web.go 26 KB

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