web.go 26 KB

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