web.go 27 KB

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