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