web.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cmd
  5. import (
  6. "crypto/tls"
  7. "fmt"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "net/http/fcgi"
  12. "os"
  13. "path"
  14. "strings"
  15. "github.com/go-macaron/binding"
  16. "github.com/go-macaron/cache"
  17. "github.com/go-macaron/captcha"
  18. "github.com/go-macaron/csrf"
  19. "github.com/go-macaron/gzip"
  20. "github.com/go-macaron/i18n"
  21. "github.com/go-macaron/session"
  22. "github.com/go-macaron/toolbox"
  23. "github.com/go-xorm/xorm"
  24. "github.com/mcuadros/go-version"
  25. "github.com/urfave/cli"
  26. log "gopkg.in/clog.v1"
  27. "gopkg.in/ini.v1"
  28. "gopkg.in/macaron.v1"
  29. "github.com/gogits/git-module"
  30. "github.com/gogits/go-gogs-client"
  31. "github.com/gogits/gogs/models"
  32. "github.com/gogits/gogs/modules/auth"
  33. "github.com/gogits/gogs/modules/bindata"
  34. "github.com/gogits/gogs/modules/context"
  35. "github.com/gogits/gogs/modules/mailer"
  36. "github.com/gogits/gogs/modules/setting"
  37. "github.com/gogits/gogs/modules/template"
  38. "github.com/gogits/gogs/routers"
  39. "github.com/gogits/gogs/routers/admin"
  40. apiv1 "github.com/gogits/gogs/routers/api/v1"
  41. "github.com/gogits/gogs/routers/dev"
  42. "github.com/gogits/gogs/routers/org"
  43. "github.com/gogits/gogs/routers/repo"
  44. "github.com/gogits/gogs/routers/user"
  45. )
  46. var CmdWeb = cli.Command{
  47. Name: "web",
  48. Usage: "Start Gogs web server",
  49. Description: `Gogs web server is the only thing you need to run,
  50. and it takes care of all the other things for you`,
  51. Action: runWeb,
  52. Flags: []cli.Flag{
  53. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  54. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  55. },
  56. }
  57. type VerChecker struct {
  58. ImportPath string
  59. Version func() string
  60. Expected string
  61. }
  62. // checkVersion checks if binary matches the version of templates files.
  63. func checkVersion() {
  64. // Templates.
  65. data, err := ioutil.ReadFile(setting.StaticRootPath + "/templates/.VERSION")
  66. if err != nil {
  67. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  68. }
  69. tplVer := string(data)
  70. if tplVer != setting.AppVer {
  71. if version.Compare(tplVer, setting.AppVer, ">") {
  72. log.Fatal(4, "Binary version is lower than template file version, did you forget to recompile Gogs?")
  73. } else {
  74. log.Fatal(4, "Binary version is higher than template file version, did you forget to update template files?")
  75. }
  76. }
  77. // Check dependency version.
  78. // LEGACY [0.11]: no need to check version as we check in vendor into version control
  79. checkers := []VerChecker{
  80. {"github.com/go-xorm/xorm", func() string { return xorm.Version }, "0.6.0"},
  81. {"github.com/go-macaron/binding", binding.Version, "0.3.2"},
  82. {"github.com/go-macaron/cache", cache.Version, "0.1.2"},
  83. {"github.com/go-macaron/csrf", csrf.Version, "0.1.0"},
  84. {"github.com/go-macaron/i18n", i18n.Version, "0.3.0"},
  85. {"github.com/go-macaron/session", session.Version, "0.1.6"},
  86. {"github.com/go-macaron/toolbox", toolbox.Version, "0.1.3"},
  87. {"gopkg.in/ini.v1", ini.Version, "1.8.4"},
  88. {"gopkg.in/macaron.v1", macaron.Version, "1.1.7"},
  89. {"github.com/gogits/git-module", git.Version, "0.4.12"},
  90. {"github.com/gogits/go-gogs-client", gogs.Version, "0.12.1"},
  91. }
  92. for _, c := range checkers {
  93. if !version.Compare(c.Version(), c.Expected, ">=") {
  94. log.Fatal(4, `Dependency outdated!
  95. Package '%s' current version (%s) is below requirement (%s),
  96. please use following command to update this package and recompile Gogs:
  97. go get -u %[1]s`, c.ImportPath, c.Version(), c.Expected)
  98. }
  99. }
  100. }
  101. // newMacaron initializes Macaron instance.
  102. func newMacaron() *macaron.Macaron {
  103. m := macaron.New()
  104. if !setting.DisableRouterLog {
  105. m.Use(macaron.Logger())
  106. }
  107. m.Use(macaron.Recovery())
  108. if setting.EnableGzip {
  109. m.Use(gzip.Gziper())
  110. }
  111. if setting.Protocol == setting.SCHEME_FCGI {
  112. m.SetURLPrefix(setting.AppSubUrl)
  113. }
  114. m.Use(macaron.Static(
  115. path.Join(setting.StaticRootPath, "public"),
  116. macaron.StaticOptions{
  117. SkipLogging: setting.DisableRouterLog,
  118. },
  119. ))
  120. m.Use(macaron.Static(
  121. setting.AvatarUploadPath,
  122. macaron.StaticOptions{
  123. Prefix: "avatars",
  124. SkipLogging: setting.DisableRouterLog,
  125. },
  126. ))
  127. funcMap := template.NewFuncMap()
  128. m.Use(macaron.Renderer(macaron.RenderOptions{
  129. Directory: path.Join(setting.StaticRootPath, "templates"),
  130. AppendDirectories: []string{path.Join(setting.CustomPath, "templates")},
  131. Funcs: funcMap,
  132. IndentJSON: macaron.Env != macaron.PROD,
  133. }))
  134. mailer.InitMailRender(path.Join(setting.StaticRootPath, "templates/mail"),
  135. path.Join(setting.CustomPath, "templates/mail"), funcMap)
  136. localeNames, err := bindata.AssetDir("conf/locale")
  137. if err != nil {
  138. log.Fatal(4, "Fail to list locale files: %v", err)
  139. }
  140. localFiles := make(map[string][]byte)
  141. for _, name := range localeNames {
  142. localFiles[name] = bindata.MustAsset("conf/locale/" + name)
  143. }
  144. m.Use(i18n.I18n(i18n.Options{
  145. SubURL: setting.AppSubUrl,
  146. Files: localFiles,
  147. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  148. Langs: setting.Langs,
  149. Names: setting.Names,
  150. DefaultLang: "en-US",
  151. Redirect: true,
  152. }))
  153. m.Use(cache.Cacher(cache.Options{
  154. Adapter: setting.CacheAdapter,
  155. AdapterConfig: setting.CacheConn,
  156. Interval: setting.CacheInterval,
  157. }))
  158. m.Use(captcha.Captchaer(captcha.Options{
  159. SubURL: setting.AppSubUrl,
  160. }))
  161. m.Use(session.Sessioner(setting.SessionConfig))
  162. m.Use(csrf.Csrfer(csrf.Options{
  163. Secret: setting.SecretKey,
  164. Cookie: setting.CSRFCookieName,
  165. SetCookie: true,
  166. Header: "X-Csrf-Token",
  167. CookiePath: setting.AppSubUrl,
  168. }))
  169. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  170. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  171. &toolbox.HealthCheckFuncDesc{
  172. Desc: "Database connection",
  173. Func: models.Ping,
  174. },
  175. },
  176. }))
  177. m.Use(context.Contexter())
  178. return m
  179. }
  180. func runWeb(ctx *cli.Context) error {
  181. if ctx.IsSet("config") {
  182. setting.CustomConf = ctx.String("config")
  183. }
  184. routers.GlobalInit()
  185. checkVersion()
  186. m := newMacaron()
  187. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  188. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  189. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  190. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  191. bindIgnErr := binding.BindIgnErr
  192. // FIXME: not all routes need go through same middlewares.
  193. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  194. // Routers.
  195. m.Get("/", ignSignIn, routers.Home)
  196. m.Group("/explore", func() {
  197. m.Get("", func(ctx *context.Context) {
  198. ctx.Redirect(setting.AppSubUrl + "/explore/repos")
  199. })
  200. m.Get("/repos", routers.ExploreRepos)
  201. m.Get("/users", routers.ExploreUsers)
  202. m.Get("/organizations", routers.ExploreOrganizations)
  203. }, ignSignIn)
  204. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  205. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  206. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  207. // ***** START: User *****
  208. m.Group("/user", func() {
  209. m.Get("/login", user.SignIn)
  210. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  211. m.Get("/sign_up", user.SignUp)
  212. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  213. m.Get("/reset_password", user.ResetPasswd)
  214. m.Post("/reset_password", user.ResetPasswdPost)
  215. }, reqSignOut)
  216. m.Group("/user/settings", func() {
  217. m.Get("", user.Settings)
  218. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  219. m.Combo("/avatar").Get(user.SettingsAvatar).
  220. Post(binding.MultipartForm(auth.AvatarForm{}), user.SettingsAvatarPost)
  221. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  222. m.Combo("/email").Get(user.SettingsEmails).
  223. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  224. m.Post("/email/delete", user.DeleteEmail)
  225. m.Get("/password", user.SettingsPassword)
  226. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  227. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  228. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  229. m.Post("/ssh/delete", user.DeleteSSHKey)
  230. m.Combo("/applications").Get(user.SettingsApplications).
  231. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  232. m.Post("/applications/delete", user.SettingsDeleteApplication)
  233. m.Group("/organizations", func() {
  234. m.Get("", user.SettingsOrganizations)
  235. m.Post("/leave", user.SettingsLeaveOrganization)
  236. })
  237. m.Route("/delete", "GET,POST", user.SettingsDelete)
  238. }, reqSignIn, func(ctx *context.Context) {
  239. ctx.Data["PageIsUserSettings"] = true
  240. })
  241. m.Group("/user", func() {
  242. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  243. m.Any("/activate", user.Activate)
  244. m.Any("/activate_email", user.ActivateEmail)
  245. m.Get("/email2user", user.Email2User)
  246. m.Get("/forget_password", user.ForgotPasswd)
  247. m.Post("/forget_password", user.ForgotPasswdPost)
  248. m.Get("/logout", user.SignOut)
  249. })
  250. // ***** END: User *****
  251. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  252. // ***** START: Admin *****
  253. m.Group("/admin", func() {
  254. m.Get("", adminReq, admin.Dashboard)
  255. m.Get("/config", admin.Config)
  256. m.Post("/config/test_mail", admin.SendTestMail)
  257. m.Get("/monitor", admin.Monitor)
  258. m.Group("/users", func() {
  259. m.Get("", admin.Users)
  260. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  261. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  262. m.Post("/:userid/delete", admin.DeleteUser)
  263. })
  264. m.Group("/orgs", func() {
  265. m.Get("", admin.Organizations)
  266. })
  267. m.Group("/repos", func() {
  268. m.Get("", admin.Repos)
  269. m.Post("/delete", admin.DeleteRepo)
  270. })
  271. m.Group("/auths", func() {
  272. m.Get("", admin.Authentications)
  273. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  274. m.Combo("/:authid").Get(admin.EditAuthSource).
  275. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  276. m.Post("/:authid/delete", admin.DeleteAuthSource)
  277. })
  278. m.Group("/notices", func() {
  279. m.Get("", admin.Notices)
  280. m.Post("/delete", admin.DeleteNotices)
  281. m.Get("/empty", admin.EmptyNotices)
  282. })
  283. }, adminReq)
  284. // ***** END: Admin *****
  285. m.Group("", func() {
  286. m.Group("/:username", func() {
  287. m.Get("", user.Profile)
  288. m.Get("/followers", user.Followers)
  289. m.Get("/following", user.Following)
  290. m.Get("/stars", user.Stars)
  291. })
  292. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  293. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  294. if err != nil {
  295. if models.IsErrAttachmentNotExist(err) {
  296. ctx.Error(404)
  297. } else {
  298. ctx.Handle(500, "GetAttachmentByUUID", err)
  299. }
  300. return
  301. }
  302. fr, err := os.Open(attach.LocalPath())
  303. if err != nil {
  304. ctx.Handle(500, "Open", err)
  305. return
  306. }
  307. defer fr.Close()
  308. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  309. ctx.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name))
  310. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  311. // We must put the name in " manually.
  312. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  313. ctx.Handle(500, "ServeData", err)
  314. return
  315. }
  316. })
  317. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  318. }, ignSignIn)
  319. m.Group("/:username", func() {
  320. m.Get("/action/:action", user.Action)
  321. }, reqSignIn)
  322. if macaron.Env == macaron.DEV {
  323. m.Get("/template/*", dev.TemplatePreview)
  324. }
  325. reqRepoAdmin := context.RequireRepoAdmin()
  326. reqRepoWriter := context.RequireRepoWriter()
  327. // ***** START: Organization *****
  328. m.Group("/org", func() {
  329. m.Group("", func() {
  330. m.Get("/create", org.Create)
  331. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  332. }, func(ctx *context.Context) {
  333. if !ctx.User.CanCreateOrganization() {
  334. ctx.NotFound()
  335. }
  336. })
  337. m.Group("/:org", func() {
  338. m.Get("/dashboard", user.Dashboard)
  339. m.Get("/^:type(issues|pulls)$", user.Issues)
  340. m.Get("/members", org.Members)
  341. m.Get("/members/action/:action", org.MembersAction)
  342. m.Get("/teams", org.Teams)
  343. }, context.OrgAssignment(true))
  344. m.Group("/:org", func() {
  345. m.Get("/teams/:team", org.TeamMembers)
  346. m.Get("/teams/:team/repositories", org.TeamRepositories)
  347. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  348. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  349. }, context.OrgAssignment(true, false, true))
  350. m.Group("/:org", func() {
  351. m.Get("/teams/new", org.NewTeam)
  352. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  353. m.Get("/teams/:team/edit", org.EditTeam)
  354. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  355. m.Post("/teams/:team/delete", org.DeleteTeam)
  356. m.Group("/settings", func() {
  357. m.Combo("").Get(org.Settings).
  358. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  359. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
  360. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  361. m.Group("/hooks", func() {
  362. m.Get("", org.Webhooks)
  363. m.Post("/delete", org.DeleteWebhook)
  364. m.Get("/:type/new", repo.WebhooksNew)
  365. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  366. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  367. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  368. m.Get("/:id", repo.WebHooksEdit)
  369. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  370. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  371. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  372. })
  373. m.Route("/delete", "GET,POST", org.SettingsDelete)
  374. })
  375. m.Route("/invitations/new", "GET,POST", org.Invitation)
  376. }, context.OrgAssignment(true, true))
  377. }, reqSignIn)
  378. // ***** END: Organization *****
  379. // ***** START: Repository *****
  380. m.Group("/repo", func() {
  381. m.Get("/create", repo.Create)
  382. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  383. m.Get("/migrate", repo.Migrate)
  384. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  385. m.Combo("/fork/:repoid").Get(repo.Fork).
  386. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  387. }, reqSignIn)
  388. m.Group("/:username/:reponame", func() {
  389. m.Group("/settings", func() {
  390. m.Combo("").Get(repo.Settings).
  391. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  392. m.Group("/collaboration", func() {
  393. m.Combo("").Get(repo.SettingsCollaboration).Post(repo.SettingsCollaborationPost)
  394. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  395. m.Post("/delete", repo.DeleteCollaboration)
  396. })
  397. m.Group("/branches", func() {
  398. m.Get("", repo.SettingsBranches)
  399. m.Post("/default_branch", repo.UpdateDefaultBranch)
  400. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  401. Post(bindIgnErr(auth.ProtectBranchForm{}), repo.SettingsProtectedBranchPost)
  402. }, func(ctx *context.Context) {
  403. if ctx.Repo.Repository.IsMirror {
  404. ctx.NotFound()
  405. return
  406. }
  407. })
  408. m.Group("/hooks", func() {
  409. m.Get("", repo.Webhooks)
  410. m.Post("/delete", repo.DeleteWebhook)
  411. m.Get("/:type/new", repo.WebhooksNew)
  412. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  413. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  414. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  415. m.Get("/:id", repo.WebHooksEdit)
  416. m.Post("/:id/test", repo.TestWebhook)
  417. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  418. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  419. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  420. m.Group("/git", func() {
  421. m.Get("", repo.SettingsGitHooks)
  422. m.Combo("/:name").Get(repo.SettingsGitHooksEdit).
  423. Post(repo.SettingsGitHooksEditPost)
  424. }, context.GitHookService())
  425. })
  426. m.Group("/keys", func() {
  427. m.Combo("").Get(repo.SettingsDeployKeys).
  428. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.SettingsDeployKeysPost)
  429. m.Post("/delete", repo.DeleteDeployKey)
  430. })
  431. }, func(ctx *context.Context) {
  432. ctx.Data["PageIsSettings"] = true
  433. })
  434. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  435. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  436. m.Group("/:username/:reponame", func() {
  437. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  438. // So they can apply their own enable/disable logic on routers.
  439. m.Group("/issues", func() {
  440. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  441. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  442. m.Group("/:index", func() {
  443. m.Post("/label", repo.UpdateIssueLabel)
  444. m.Post("/milestone", repo.UpdateIssueMilestone)
  445. m.Post("/assignee", repo.UpdateIssueAssignee)
  446. }, reqRepoWriter)
  447. m.Group("/:index", func() {
  448. m.Post("/title", repo.UpdateIssueTitle)
  449. m.Post("/content", repo.UpdateIssueContent)
  450. m.Combo("/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  451. })
  452. })
  453. m.Group("/comments/:id", func() {
  454. m.Post("", repo.UpdateCommentContent)
  455. m.Post("/delete", repo.DeleteComment)
  456. })
  457. m.Group("/labels", func() {
  458. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  459. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  460. m.Post("/delete", repo.DeleteLabel)
  461. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  462. }, reqRepoWriter, context.RepoRef())
  463. m.Group("/milestones", func() {
  464. m.Combo("/new").Get(repo.NewMilestone).
  465. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  466. m.Get("/:id/edit", repo.EditMilestone)
  467. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  468. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  469. m.Post("/delete", repo.DeleteMilestone)
  470. }, reqRepoWriter, context.RepoRef())
  471. m.Group("/releases", func() {
  472. m.Get("/new", repo.NewRelease)
  473. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  474. m.Post("/delete", repo.DeleteRelease)
  475. m.Get("/edit/*", repo.EditRelease)
  476. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  477. }, reqRepoWriter, context.RepoRef())
  478. // FIXME: Should use ctx.Repo.PullRequest to unify template, currently we have inconsistent URL
  479. // for PR in same repository. After select branch on the page, the URL contains redundant head user name.
  480. // e.g. /org1/test-repo/compare/master...org1:develop
  481. // which should be /org1/test-repo/compare/master...develop
  482. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  483. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  484. m.Group("", func() {
  485. m.Combo("/_edit/*").Get(repo.EditFile).
  486. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  487. m.Combo("/_new/*").Get(repo.NewFile).
  488. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  489. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  490. m.Combo("/_delete/*").Get(repo.DeleteFile).
  491. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  492. m.Group("", func() {
  493. m.Combo("/_upload/*").Get(repo.UploadFile).
  494. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  495. m.Post("/upload-file", repo.UploadFileToServer)
  496. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  497. }, func(ctx *context.Context) {
  498. if !setting.Repository.Upload.Enabled {
  499. ctx.NotFound()
  500. return
  501. }
  502. })
  503. }, reqRepoWriter, context.RepoRef(), func(ctx *context.Context) {
  504. if !ctx.Repo.CanEnableEditor() {
  505. ctx.NotFound()
  506. return
  507. }
  508. })
  509. }, reqSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  510. m.Group("/:username/:reponame", func() {
  511. m.Group("", func() {
  512. m.Get("/releases", repo.Releases)
  513. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  514. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  515. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  516. m.Get("/milestones", repo.Milestones)
  517. }, context.RepoRef())
  518. // m.Get("/branches", repo.Branches)
  519. m.Post("/branches/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
  520. m.Group("/wiki", func() {
  521. m.Get("/?:page", repo.Wiki)
  522. m.Get("/_pages", repo.WikiPages)
  523. m.Group("", func() {
  524. m.Combo("/_new").Get(repo.NewWiki).
  525. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  526. m.Combo("/:page/_edit").Get(repo.EditWiki).
  527. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  528. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  529. }, reqSignIn, reqRepoWriter)
  530. }, repo.MustEnableWiki, context.RepoRef())
  531. m.Get("/archive/*", repo.Download)
  532. m.Group("/pulls/:index", func() {
  533. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  534. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  535. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  536. }, repo.MustAllowPulls)
  537. m.Group("", func() {
  538. m.Get("/src/*", repo.Home)
  539. m.Get("/raw/*", repo.SingleDownload)
  540. m.Get("/commits/*", repo.RefCommits)
  541. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.Diff)
  542. m.Get("/forks", repo.Forks)
  543. }, context.RepoRef())
  544. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.RawDiff)
  545. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", context.RepoRef(), repo.CompareDiff)
  546. }, ignSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  547. m.Group("/:username/:reponame", func() {
  548. m.Get("/stars", repo.Stars)
  549. m.Get("/watchers", repo.Watchers)
  550. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  551. m.Group("/:username", func() {
  552. m.Group("", func() {
  553. m.Get("/:reponame", repo.Home)
  554. }, ignSignIn, context.RepoAssignment(true), context.RepoRef())
  555. m.Group("/:reponame", func() {
  556. m.Head("/tasks/trigger", repo.TriggerTask)
  557. })
  558. // Use the regexp to match the repository name validation
  559. m.Group("/:reponame([\\d\\w-_\\.]+\\.git$)", func() {
  560. m.Get("", ignSignIn, context.RepoAssignment(true), context.RepoRef(), repo.Home)
  561. m.Route("/*", "GET,POST", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  562. })
  563. })
  564. // ***** END: Repository *****
  565. m.Group("/api", func() {
  566. apiv1.RegisterRoutes(m)
  567. }, ignSignIn)
  568. // robots.txt
  569. m.Get("/robots.txt", func(ctx *context.Context) {
  570. if setting.HasRobotsTxt {
  571. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  572. } else {
  573. ctx.Error(404)
  574. }
  575. })
  576. // Not found handler.
  577. m.NotFound(routers.NotFound)
  578. // Flag for port number in case first time run conflict.
  579. if ctx.IsSet("port") {
  580. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HTTPPort, ctx.String("port"), 1)
  581. setting.HTTPPort = ctx.String("port")
  582. }
  583. var listenAddr string
  584. if setting.Protocol == setting.SCHEME_UNIX_SOCKET {
  585. listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
  586. } else {
  587. listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
  588. }
  589. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  590. var err error
  591. switch setting.Protocol {
  592. case setting.SCHEME_HTTP:
  593. err = http.ListenAndServe(listenAddr, m)
  594. case setting.SCHEME_HTTPS:
  595. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{
  596. MinVersion: tls.VersionTLS10,
  597. CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
  598. PreferServerCipherSuites: true,
  599. CipherSuites: []uint16{
  600. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  601. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, // Required for HTTP/2 support.
  602. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  603. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  604. },
  605. }, Handler: m}
  606. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  607. case setting.SCHEME_FCGI:
  608. err = fcgi.Serve(nil, m)
  609. case setting.SCHEME_UNIX_SOCKET:
  610. os.Remove(listenAddr)
  611. var listener *net.UnixListener
  612. listener, err = net.ListenUnix("unix", &net.UnixAddr{listenAddr, "unix"})
  613. if err != nil {
  614. break // Handle error after switch
  615. }
  616. // FIXME: add proper implementation of signal capture on all protocols
  617. // execute this on SIGTERM or SIGINT: listener.Close()
  618. if err = os.Chmod(listenAddr, os.FileMode(setting.UnixSocketPermission)); err != nil {
  619. log.Fatal(4, "Failed to set permission of unix socket: %v", err)
  620. }
  621. err = http.Serve(listener, m)
  622. default:
  623. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  624. }
  625. if err != nil {
  626. log.Fatal(4, "Fail to start server: %v", err)
  627. }
  628. return nil
  629. }