web.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cmd
  5. import (
  6. "crypto/tls"
  7. "fmt"
  8. "io"
  9. "net"
  10. "net/http"
  11. "net/http/fcgi"
  12. "os"
  13. "path/filepath"
  14. "strings"
  15. "github.com/go-macaron/binding"
  16. "github.com/go-macaron/cache"
  17. "github.com/go-macaron/captcha"
  18. "github.com/go-macaron/csrf"
  19. "github.com/go-macaron/gzip"
  20. "github.com/go-macaron/i18n"
  21. "github.com/go-macaron/session"
  22. "github.com/go-macaron/toolbox"
  23. "github.com/prometheus/client_golang/prometheus/promhttp"
  24. "github.com/unknwon/com"
  25. "github.com/urfave/cli"
  26. "gopkg.in/macaron.v1"
  27. log "unknwon.dev/clog/v2"
  28. "gogs.io/gogs/internal/app"
  29. "gogs.io/gogs/internal/assets/public"
  30. "gogs.io/gogs/internal/assets/templates"
  31. "gogs.io/gogs/internal/conf"
  32. "gogs.io/gogs/internal/context"
  33. "gogs.io/gogs/internal/db"
  34. "gogs.io/gogs/internal/form"
  35. "gogs.io/gogs/internal/osutil"
  36. "gogs.io/gogs/internal/route"
  37. "gogs.io/gogs/internal/route/admin"
  38. apiv1 "gogs.io/gogs/internal/route/api/v1"
  39. "gogs.io/gogs/internal/route/dev"
  40. "gogs.io/gogs/internal/route/lfs"
  41. "gogs.io/gogs/internal/route/org"
  42. "gogs.io/gogs/internal/route/repo"
  43. "gogs.io/gogs/internal/route/user"
  44. "gogs.io/gogs/internal/template"
  45. )
  46. var Web = cli.Command{
  47. Name: "web",
  48. Usage: "Start web server",
  49. Description: `Gogs web server is the only thing you need to run,
  50. and it takes care of all the other things for you`,
  51. Action: runWeb,
  52. Flags: []cli.Flag{
  53. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  54. stringFlag("config, c", "", "Custom configuration file path"),
  55. },
  56. }
  57. // newMacaron initializes Macaron instance.
  58. func newMacaron() *macaron.Macaron {
  59. m := macaron.New()
  60. if !conf.Server.DisableRouterLog {
  61. m.Use(macaron.Logger())
  62. }
  63. m.Use(macaron.Recovery())
  64. if conf.Server.EnableGzip {
  65. m.Use(gzip.Gziper())
  66. }
  67. if conf.Server.Protocol == "fcgi" {
  68. m.SetURLPrefix(conf.Server.Subpath)
  69. }
  70. // Register custom middleware first to make it possible to override files under "public".
  71. m.Use(macaron.Static(
  72. filepath.Join(conf.CustomDir(), "public"),
  73. macaron.StaticOptions{
  74. SkipLogging: conf.Server.DisableRouterLog,
  75. },
  76. ))
  77. var publicFs http.FileSystem
  78. if !conf.Server.LoadAssetsFromDisk {
  79. publicFs = public.NewFileSystem()
  80. }
  81. m.Use(macaron.Static(
  82. filepath.Join(conf.WorkDir(), "public"),
  83. macaron.StaticOptions{
  84. SkipLogging: conf.Server.DisableRouterLog,
  85. FileSystem: publicFs,
  86. },
  87. ))
  88. m.Use(macaron.Static(
  89. conf.Picture.AvatarUploadPath,
  90. macaron.StaticOptions{
  91. Prefix: db.USER_AVATAR_URL_PREFIX,
  92. SkipLogging: conf.Server.DisableRouterLog,
  93. },
  94. ))
  95. m.Use(macaron.Static(
  96. conf.Picture.RepositoryAvatarUploadPath,
  97. macaron.StaticOptions{
  98. Prefix: db.REPO_AVATAR_URL_PREFIX,
  99. SkipLogging: conf.Server.DisableRouterLog,
  100. },
  101. ))
  102. renderOpt := macaron.RenderOptions{
  103. Directory: filepath.Join(conf.WorkDir(), "templates"),
  104. AppendDirectories: []string{filepath.Join(conf.CustomDir(), "templates")},
  105. Funcs: template.FuncMap(),
  106. IndentJSON: macaron.Env != macaron.PROD,
  107. }
  108. if !conf.Server.LoadAssetsFromDisk {
  109. renderOpt.TemplateFileSystem = templates.NewTemplateFileSystem("", renderOpt.AppendDirectories[0])
  110. }
  111. m.Use(macaron.Renderer(renderOpt))
  112. localeNames, err := conf.AssetDir("conf/locale")
  113. if err != nil {
  114. log.Fatal("Failed to list locale files: %v", err)
  115. }
  116. localeFiles := make(map[string][]byte)
  117. for _, name := range localeNames {
  118. localeFiles[name] = conf.MustAsset("conf/locale/" + name)
  119. }
  120. m.Use(i18n.I18n(i18n.Options{
  121. SubURL: conf.Server.Subpath,
  122. Files: localeFiles,
  123. CustomDirectory: filepath.Join(conf.CustomDir(), "conf", "locale"),
  124. Langs: conf.I18n.Langs,
  125. Names: conf.I18n.Names,
  126. DefaultLang: "en-US",
  127. Redirect: true,
  128. }))
  129. m.Use(cache.Cacher(cache.Options{
  130. Adapter: conf.Cache.Adapter,
  131. AdapterConfig: conf.Cache.Host,
  132. Interval: conf.Cache.Interval,
  133. }))
  134. m.Use(captcha.Captchaer(captcha.Options{
  135. SubURL: conf.Server.Subpath,
  136. }))
  137. m.Use(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("Cache-Control", "public,max-age=86400")
  287. c.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name))
  288. if _, err = io.Copy(c.Resp, fr); err != nil {
  289. c.Error(err, "copy from file to response")
  290. return
  291. }
  292. })
  293. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  294. m.Post("/releases/attachments", repo.UploadReleaseAttachment)
  295. }, ignSignIn)
  296. m.Group("/:username", func() {
  297. m.Post("/action/:action", user.Action)
  298. }, reqSignIn, context.InjectParamsUser())
  299. if macaron.Env == macaron.DEV {
  300. m.Get("/template/*", dev.TemplatePreview)
  301. }
  302. reqRepoAdmin := context.RequireRepoAdmin()
  303. reqRepoWriter := context.RequireRepoWriter()
  304. webhookRoutes := func() {
  305. m.Group("", func() {
  306. m.Get("", repo.Webhooks)
  307. m.Post("/delete", repo.DeleteWebhook)
  308. m.Get("/:type/new", repo.WebhooksNew)
  309. m.Post("/gogs/new", bindIgnErr(form.NewWebhook{}), repo.WebhooksNewPost)
  310. m.Post("/slack/new", bindIgnErr(form.NewSlackHook{}), repo.WebhooksSlackNewPost)
  311. m.Post("/discord/new", bindIgnErr(form.NewDiscordHook{}), repo.WebhooksDiscordNewPost)
  312. m.Post("/dingtalk/new", bindIgnErr(form.NewDingtalkHook{}), repo.WebhooksDingtalkNewPost)
  313. m.Get("/:id", repo.WebhooksEdit)
  314. m.Post("/gogs/:id", bindIgnErr(form.NewWebhook{}), repo.WebhooksEditPost)
  315. m.Post("/slack/:id", bindIgnErr(form.NewSlackHook{}), repo.WebhooksSlackEditPost)
  316. m.Post("/discord/:id", bindIgnErr(form.NewDiscordHook{}), repo.WebhooksDiscordEditPost)
  317. m.Post("/dingtalk/:id", bindIgnErr(form.NewDingtalkHook{}), repo.WebhooksDingtalkEditPost)
  318. }, repo.InjectOrgRepoContext())
  319. }
  320. // ***** START: Organization *****
  321. m.Group("/org", func() {
  322. m.Group("", func() {
  323. m.Get("/create", org.Create)
  324. m.Post("/create", bindIgnErr(form.CreateOrg{}), org.CreatePost)
  325. }, func(c *context.Context) {
  326. if !c.User.CanCreateOrganization() {
  327. c.NotFound()
  328. }
  329. })
  330. m.Group("/:org", func() {
  331. m.Get("/dashboard", user.Dashboard)
  332. m.Get("/^:type(issues|pulls)$", user.Issues)
  333. m.Get("/members", org.Members)
  334. m.Get("/members/action/:action", org.MembersAction)
  335. m.Get("/teams", org.Teams)
  336. }, context.OrgAssignment(true))
  337. m.Group("/:org", func() {
  338. m.Get("/teams/:team", org.TeamMembers)
  339. m.Get("/teams/:team/repositories", org.TeamRepositories)
  340. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  341. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  342. }, context.OrgAssignment(true, false, true))
  343. m.Group("/:org", func() {
  344. m.Get("/teams/new", org.NewTeam)
  345. m.Post("/teams/new", bindIgnErr(form.CreateTeam{}), org.NewTeamPost)
  346. m.Get("/teams/:team/edit", org.EditTeam)
  347. m.Post("/teams/:team/edit", bindIgnErr(form.CreateTeam{}), org.EditTeamPost)
  348. m.Post("/teams/:team/delete", org.DeleteTeam)
  349. m.Group("/settings", func() {
  350. m.Combo("").Get(org.Settings).
  351. Post(bindIgnErr(form.UpdateOrgSetting{}), org.SettingsPost)
  352. m.Post("/avatar", binding.MultipartForm(form.Avatar{}), org.SettingsAvatar)
  353. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  354. m.Group("/hooks", webhookRoutes)
  355. m.Route("/delete", "GET,POST", org.SettingsDelete)
  356. })
  357. m.Route("/invitations/new", "GET,POST", org.Invitation)
  358. }, context.OrgAssignment(true, true))
  359. }, reqSignIn)
  360. // ***** END: Organization *****
  361. // ***** START: Repository *****
  362. m.Group("/repo", func() {
  363. m.Get("/create", repo.Create)
  364. m.Post("/create", bindIgnErr(form.CreateRepo{}), repo.CreatePost)
  365. m.Get("/migrate", repo.Migrate)
  366. m.Post("/migrate", bindIgnErr(form.MigrateRepo{}), repo.MigratePost)
  367. m.Combo("/fork/:repoid").Get(repo.Fork).
  368. Post(bindIgnErr(form.CreateRepo{}), repo.ForkPost)
  369. }, reqSignIn)
  370. m.Group("/:username/:reponame", func() {
  371. m.Group("/settings", func() {
  372. m.Combo("").Get(repo.Settings).
  373. Post(bindIgnErr(form.RepoSetting{}), repo.SettingsPost)
  374. m.Combo("/avatar").Get(repo.SettingsAvatar).
  375. Post(binding.MultipartForm(form.Avatar{}), repo.SettingsAvatarPost)
  376. m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  377. m.Group("/collaboration", func() {
  378. m.Combo("").Get(repo.SettingsCollaboration).Post(repo.SettingsCollaborationPost)
  379. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  380. m.Post("/delete", repo.DeleteCollaboration)
  381. })
  382. m.Group("/branches", func() {
  383. m.Get("", repo.SettingsBranches)
  384. m.Post("/default_branch", repo.UpdateDefaultBranch)
  385. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  386. Post(bindIgnErr(form.ProtectBranch{}), repo.SettingsProtectedBranchPost)
  387. }, func(c *context.Context) {
  388. if c.Repo.Repository.IsMirror {
  389. c.NotFound()
  390. return
  391. }
  392. })
  393. m.Group("/hooks", func() {
  394. webhookRoutes()
  395. m.Group("/:id", func() {
  396. m.Post("/test", repo.TestWebhook)
  397. m.Post("/redelivery", repo.RedeliveryWebhook)
  398. })
  399. m.Group("/git", func() {
  400. m.Get("", repo.SettingsGitHooks)
  401. m.Combo("/:name").Get(repo.SettingsGitHooksEdit).
  402. Post(repo.SettingsGitHooksEditPost)
  403. }, context.GitHookService())
  404. })
  405. m.Group("/keys", func() {
  406. m.Combo("").Get(repo.SettingsDeployKeys).
  407. Post(bindIgnErr(form.AddSSHKey{}), repo.SettingsDeployKeysPost)
  408. m.Post("/delete", repo.DeleteDeployKey)
  409. })
  410. }, func(c *context.Context) {
  411. c.Data["PageIsSettings"] = true
  412. })
  413. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  414. m.Post("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  415. m.Group("/:username/:reponame", func() {
  416. m.Get("/issues", repo.RetrieveLabels, repo.Issues)
  417. m.Get("/issues/:index", repo.ViewIssue)
  418. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  419. m.Get("/milestones", repo.Milestones)
  420. }, ignSignIn, context.RepoAssignment(true))
  421. m.Group("/:username/:reponame", func() {
  422. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  423. // So they can apply their own enable/disable logic on routers.
  424. m.Group("/issues", func() {
  425. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  426. Post(bindIgnErr(form.NewIssue{}), repo.NewIssuePost)
  427. m.Group("/:index", func() {
  428. m.Post("/title", repo.UpdateIssueTitle)
  429. m.Post("/content", repo.UpdateIssueContent)
  430. m.Combo("/comments").Post(bindIgnErr(form.CreateComment{}), repo.NewComment)
  431. })
  432. })
  433. m.Group("/comments/:id", func() {
  434. m.Post("", repo.UpdateCommentContent)
  435. m.Post("/delete", repo.DeleteComment)
  436. })
  437. }, reqSignIn, context.RepoAssignment(true))
  438. m.Group("/:username/:reponame", func() {
  439. m.Group("/wiki", func() {
  440. m.Get("/?:page", repo.Wiki)
  441. m.Get("/_pages", repo.WikiPages)
  442. }, repo.MustEnableWiki, context.RepoRef())
  443. }, ignSignIn, context.RepoAssignment(false, true))
  444. m.Group("/:username/:reponame", func() {
  445. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  446. // So they can apply their own enable/disable logic on routers.
  447. m.Group("/issues", func() {
  448. m.Group("/:index", func() {
  449. m.Post("/label", repo.UpdateIssueLabel)
  450. m.Post("/milestone", repo.UpdateIssueMilestone)
  451. m.Post("/assignee", repo.UpdateIssueAssignee)
  452. }, reqRepoWriter)
  453. })
  454. m.Group("/labels", func() {
  455. m.Post("/new", bindIgnErr(form.CreateLabel{}), repo.NewLabel)
  456. m.Post("/edit", bindIgnErr(form.CreateLabel{}), repo.UpdateLabel)
  457. m.Post("/delete", repo.DeleteLabel)
  458. m.Post("/initialize", bindIgnErr(form.InitializeLabels{}), repo.InitializeLabels)
  459. }, reqRepoWriter, context.RepoRef())
  460. m.Group("/milestones", func() {
  461. m.Combo("/new").Get(repo.NewMilestone).
  462. Post(bindIgnErr(form.CreateMilestone{}), repo.NewMilestonePost)
  463. m.Get("/:id/edit", repo.EditMilestone)
  464. m.Post("/:id/edit", bindIgnErr(form.CreateMilestone{}), repo.EditMilestonePost)
  465. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  466. m.Post("/delete", repo.DeleteMilestone)
  467. }, reqRepoWriter, context.RepoRef())
  468. m.Group("/releases", func() {
  469. m.Get("/new", repo.NewRelease)
  470. m.Post("/new", bindIgnErr(form.NewRelease{}), repo.NewReleasePost)
  471. m.Post("/delete", repo.DeleteRelease)
  472. m.Get("/edit/*", repo.EditRelease)
  473. m.Post("/edit/*", bindIgnErr(form.EditRelease{}), repo.EditReleasePost)
  474. }, repo.MustBeNotBare, reqRepoWriter, func(c *context.Context) {
  475. c.Data["PageIsViewFiles"] = true
  476. })
  477. // FIXME: Should use c.Repo.PullRequest to unify template, currently we have inconsistent URL
  478. // for PR in same repository. After select branch on the page, the URL contains redundant head user name.
  479. // e.g. /org1/test-repo/compare/master...org1:develop
  480. // which should be /org1/test-repo/compare/master...develop
  481. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  482. Post(bindIgnErr(form.NewIssue{}), repo.CompareAndPullRequestPost)
  483. m.Group("", func() {
  484. m.Combo("/_edit/*").Get(repo.EditFile).
  485. Post(bindIgnErr(form.EditRepoFile{}), repo.EditFilePost)
  486. m.Combo("/_new/*").Get(repo.NewFile).
  487. Post(bindIgnErr(form.EditRepoFile{}), repo.NewFilePost)
  488. m.Post("/_preview/*", bindIgnErr(form.EditPreviewDiff{}), repo.DiffPreviewPost)
  489. m.Combo("/_delete/*").Get(repo.DeleteFile).
  490. Post(bindIgnErr(form.DeleteRepoFile{}), repo.DeleteFilePost)
  491. m.Group("", func() {
  492. m.Combo("/_upload/*").Get(repo.UploadFile).
  493. Post(bindIgnErr(form.UploadRepoFile{}), repo.UploadFilePost)
  494. m.Post("/upload-file", repo.UploadFileToServer)
  495. m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer)
  496. }, func(c *context.Context) {
  497. if !conf.Repository.Upload.Enabled {
  498. c.NotFound()
  499. return
  500. }
  501. })
  502. }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(c *context.Context) {
  503. if !c.Repo.CanEnableEditor() {
  504. c.NotFound()
  505. return
  506. }
  507. c.Data["PageIsViewFiles"] = true
  508. })
  509. }, reqSignIn, context.RepoAssignment())
  510. m.Group("/:username/:reponame", func() {
  511. m.Group("", func() {
  512. m.Get("/releases", repo.MustBeNotBare, repo.Releases)
  513. m.Get("/pulls", repo.RetrieveLabels, repo.Pulls)
  514. m.Get("/pulls/:index", repo.ViewPull)
  515. }, context.RepoRef())
  516. m.Group("/branches", func() {
  517. m.Get("", repo.Branches)
  518. m.Get("/all", repo.AllBranches)
  519. m.Post("/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
  520. }, repo.MustBeNotBare, func(c *context.Context) {
  521. c.Data["PageIsViewFiles"] = true
  522. })
  523. m.Group("/wiki", func() {
  524. m.Group("", func() {
  525. m.Combo("/_new").Get(repo.NewWiki).
  526. Post(bindIgnErr(form.NewWiki{}), repo.NewWikiPost)
  527. m.Combo("/:page/_edit").Get(repo.EditWiki).
  528. Post(bindIgnErr(form.NewWiki{}), repo.EditWikiPost)
  529. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  530. }, reqSignIn, reqRepoWriter)
  531. }, repo.MustEnableWiki, context.RepoRef())
  532. m.Get("/archive/*", repo.MustBeNotBare, repo.Download)
  533. m.Group("/pulls/:index", func() {
  534. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  535. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  536. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  537. }, repo.MustAllowPulls)
  538. m.Group("", func() {
  539. m.Get("/src/*", repo.Home)
  540. m.Get("/raw/*", repo.SingleDownload)
  541. m.Get("/commits/*", repo.RefCommits)
  542. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.Diff)
  543. m.Get("/forks", repo.Forks)
  544. }, repo.MustBeNotBare, context.RepoRef())
  545. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.MustBeNotBare, repo.RawDiff)
  546. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.MustBeNotBare, context.RepoRef(), repo.CompareDiff)
  547. }, ignSignIn, context.RepoAssignment())
  548. m.Group("/:username/:reponame", func() {
  549. m.Get("", repo.Home)
  550. m.Get("/stars", repo.Stars)
  551. m.Get("/watchers", repo.Watchers)
  552. m.Head("/tasks/trigger", repo.TriggerTask) // TODO: Without session and CSRF
  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.Group("/info/lfs", func() {
  589. lfs.RegisterRoutes(m.Router)
  590. })
  591. m.Route("/*", "GET,POST,OPTIONS", repo.HTTPContexter(), repo.HTTP)
  592. })
  593. // ***************************
  594. // ----- Internal routes -----
  595. // ***************************
  596. m.Group("/-", func() {
  597. m.Get("/metrics", app.MetricsFilter(), promhttp.Handler()) // "/-/metrics"
  598. m.Group("/api", func() {
  599. m.Post("/sanitize_ipynb", app.SanitizeIpynb()) // "/-/api/sanitize_ipynb"
  600. })
  601. })
  602. // **********************
  603. // ----- robots.txt -----
  604. // **********************
  605. m.Get("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
  606. if conf.HasRobotsTxt {
  607. http.ServeFile(w, r, filepath.Join(conf.CustomDir(), "robots.txt"))
  608. } else {
  609. w.WriteHeader(http.StatusNotFound)
  610. }
  611. })
  612. m.NotFound(route.NotFound)
  613. // Flag for port number in case first time run conflict.
  614. if c.IsSet("port") {
  615. conf.Server.URL.Host = strings.Replace(conf.Server.URL.Host, ":"+conf.Server.URL.Port(), ":"+c.String("port"), 1)
  616. conf.Server.ExternalURL = conf.Server.URL.String()
  617. conf.Server.HTTPPort = c.String("port")
  618. }
  619. var listenAddr string
  620. if conf.Server.Protocol == "unix" {
  621. listenAddr = conf.Server.HTTPAddr
  622. log.Info("Listen on %v://%s", conf.Server.Protocol, listenAddr)
  623. } else {
  624. listenAddr = fmt.Sprintf("%s:%s", conf.Server.HTTPAddr, conf.Server.HTTPPort)
  625. log.Info("Listen on %v://%s%s", conf.Server.Protocol, listenAddr, conf.Server.Subpath)
  626. }
  627. switch conf.Server.Protocol {
  628. case "http":
  629. err = http.ListenAndServe(listenAddr, m)
  630. case "https":
  631. tlsMinVersion := tls.VersionTLS12
  632. switch conf.Server.TLSMinVersion {
  633. case "TLS13":
  634. tlsMinVersion = tls.VersionTLS13
  635. case "TLS12":
  636. tlsMinVersion = tls.VersionTLS12
  637. case "TLS11":
  638. tlsMinVersion = tls.VersionTLS11
  639. case "TLS10":
  640. tlsMinVersion = tls.VersionTLS10
  641. }
  642. server := &http.Server{
  643. Addr: listenAddr,
  644. TLSConfig: &tls.Config{
  645. MinVersion: uint16(tlsMinVersion),
  646. CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384, tls.CurveP521},
  647. PreferServerCipherSuites: true,
  648. CipherSuites: []uint16{
  649. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  650. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  651. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  652. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  653. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  654. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  655. },
  656. }, Handler: m}
  657. err = server.ListenAndServeTLS(conf.Server.CertFile, conf.Server.KeyFile)
  658. case "fcgi":
  659. err = fcgi.Serve(nil, m)
  660. case "unix":
  661. if osutil.IsExist(listenAddr) {
  662. err = os.Remove(listenAddr)
  663. if err != nil {
  664. log.Fatal("Failed to remove existing Unix domain socket: %v", err)
  665. }
  666. }
  667. var listener *net.UnixListener
  668. listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"})
  669. if err != nil {
  670. log.Fatal("Failed to listen on Unix networks: %v", err)
  671. }
  672. // FIXME: add proper implementation of signal capture on all protocols
  673. // execute this on SIGTERM or SIGINT: listener.Close()
  674. if err = os.Chmod(listenAddr, conf.Server.UnixSocketMode); err != nil {
  675. log.Fatal("Failed to change permission of Unix domain socket: %v", err)
  676. }
  677. err = http.Serve(listener, m)
  678. default:
  679. log.Fatal("Unexpected server protocol: %s", conf.Server.Protocol)
  680. }
  681. if err != nil {
  682. log.Fatal("Failed to start server: %v", err)
  683. }
  684. return nil
  685. }