web.go 27 KB

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