web.go 26 KB

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