web.go 26 KB

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