web.go 26 KB

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