web.go 26 KB

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