web.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. webhookRoutes := func() {
  324. m.Group("", func() {
  325. m.Get("", repo.Webhooks)
  326. m.Post("/delete", repo.DeleteWebhook)
  327. m.Get("/:type/new", repo.WebhooksNew)
  328. m.Post("/gogs/new", bindIgnErr(form.NewWebhook{}), repo.WebhooksNewPost)
  329. m.Post("/slack/new", bindIgnErr(form.NewSlackHook{}), repo.WebhooksSlackNewPost)
  330. m.Post("/discord/new", bindIgnErr(form.NewDiscordHook{}), repo.WebhooksDiscordNewPost)
  331. m.Post("/dingtalk/new", bindIgnErr(form.NewDingtalkHook{}), repo.WebhooksDingtalkNewPost)
  332. m.Get("/:id", repo.WebhooksEdit)
  333. m.Post("/gogs/:id", bindIgnErr(form.NewWebhook{}), repo.WebhooksEditPost)
  334. m.Post("/slack/:id", bindIgnErr(form.NewSlackHook{}), repo.WebhooksSlackEditPost)
  335. m.Post("/discord/:id", bindIgnErr(form.NewDiscordHook{}), repo.WebhooksDiscordEditPost)
  336. m.Post("/dingtalk/:id", bindIgnErr(form.NewDingtalkHook{}), repo.WebhooksDingtalkEditPost)
  337. }, repo.InjectOrgRepoContext())
  338. }
  339. // ***** START: Organization *****
  340. m.Group("/org", func() {
  341. m.Group("", func() {
  342. m.Get("/create", org.Create)
  343. m.Post("/create", bindIgnErr(form.CreateOrg{}), org.CreatePost)
  344. }, func(c *context.Context) {
  345. if !c.User.CanCreateOrganization() {
  346. c.NotFound()
  347. }
  348. })
  349. m.Group("/:org", func() {
  350. m.Get("/dashboard", user.Dashboard)
  351. m.Get("/^:type(issues|pulls)$", user.Issues)
  352. m.Get("/members", org.Members)
  353. m.Get("/members/action/:action", org.MembersAction)
  354. m.Get("/teams", org.Teams)
  355. }, context.OrgAssignment(true))
  356. m.Group("/:org", func() {
  357. m.Get("/teams/:team", org.TeamMembers)
  358. m.Get("/teams/:team/repositories", org.TeamRepositories)
  359. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  360. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  361. }, context.OrgAssignment(true, false, true))
  362. m.Group("/:org", func() {
  363. m.Get("/teams/new", org.NewTeam)
  364. m.Post("/teams/new", bindIgnErr(form.CreateTeam{}), org.NewTeamPost)
  365. m.Get("/teams/:team/edit", org.EditTeam)
  366. m.Post("/teams/:team/edit", bindIgnErr(form.CreateTeam{}), org.EditTeamPost)
  367. m.Post("/teams/:team/delete", org.DeleteTeam)
  368. m.Group("/settings", func() {
  369. m.Combo("").Get(org.Settings).
  370. Post(bindIgnErr(form.UpdateOrgSetting{}), org.SettingsPost)
  371. m.Post("/avatar", binding.MultipartForm(form.Avatar{}), org.SettingsAvatar)
  372. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  373. m.Group("/hooks", webhookRoutes)
  374. m.Route("/delete", "GET,POST", org.SettingsDelete)
  375. })
  376. m.Route("/invitations/new", "GET,POST", org.Invitation)
  377. }, context.OrgAssignment(true, true))
  378. }, reqSignIn)
  379. // ***** END: Organization *****
  380. // ***** START: Repository *****
  381. m.Group("/repo", func() {
  382. m.Get("/create", repo.Create)
  383. m.Post("/create", bindIgnErr(form.CreateRepo{}), repo.CreatePost)
  384. m.Get("/migrate", repo.Migrate)
  385. m.Post("/migrate", bindIgnErr(form.MigrateRepo{}), repo.MigratePost)
  386. m.Combo("/fork/:repoid").Get(repo.Fork).
  387. Post(bindIgnErr(form.CreateRepo{}), repo.ForkPost)
  388. }, reqSignIn)
  389. m.Group("/:username/:reponame", func() {
  390. m.Group("/settings", func() {
  391. m.Combo("").Get(repo.Settings).
  392. Post(bindIgnErr(form.RepoSetting{}), repo.SettingsPost)
  393. m.Combo("/avatar").Get(repo.SettingsAvatar).
  394. Post(binding.MultipartForm(form.Avatar{}), repo.SettingsAvatarPost)
  395. m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  396. m.Group("/collaboration", func() {
  397. m.Combo("").Get(repo.SettingsCollaboration).Post(repo.SettingsCollaborationPost)
  398. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  399. m.Post("/delete", repo.DeleteCollaboration)
  400. })
  401. m.Group("/branches", func() {
  402. m.Get("", repo.SettingsBranches)
  403. m.Post("/default_branch", repo.UpdateDefaultBranch)
  404. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  405. Post(bindIgnErr(form.ProtectBranch{}), repo.SettingsProtectedBranchPost)
  406. }, func(c *context.Context) {
  407. if c.Repo.Repository.IsMirror {
  408. c.NotFound()
  409. return
  410. }
  411. })
  412. m.Group("/hooks", func() {
  413. webhookRoutes()
  414. m.Group("/:id", func() {
  415. m.Post("/test", repo.TestWebhook)
  416. m.Post("/redelivery", repo.RedeliveryWebhook)
  417. })
  418. m.Group("/git", func() {
  419. m.Get("", repo.SettingsGitHooks)
  420. m.Combo("/:name").Get(repo.SettingsGitHooksEdit).
  421. Post(repo.SettingsGitHooksEditPost)
  422. }, context.GitHookService())
  423. })
  424. m.Group("/keys", func() {
  425. m.Combo("").Get(repo.SettingsDeployKeys).
  426. Post(bindIgnErr(form.AddSSHKey{}), repo.SettingsDeployKeysPost)
  427. m.Post("/delete", repo.DeleteDeployKey)
  428. })
  429. }, func(c *context.Context) {
  430. c.Data["PageIsSettings"] = true
  431. })
  432. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  433. m.Post("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  434. m.Group("/:username/:reponame", func() {
  435. m.Get("/issues", repo.RetrieveLabels, repo.Issues)
  436. m.Get("/issues/:index", repo.ViewIssue)
  437. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  438. m.Get("/milestones", repo.Milestones)
  439. }, ignSignIn, context.RepoAssignment(true))
  440. m.Group("/:username/:reponame", func() {
  441. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  442. // So they can apply their own enable/disable logic on routers.
  443. m.Group("/issues", func() {
  444. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  445. Post(bindIgnErr(form.NewIssue{}), repo.NewIssuePost)
  446. m.Group("/:index", func() {
  447. m.Post("/title", repo.UpdateIssueTitle)
  448. m.Post("/content", repo.UpdateIssueContent)
  449. m.Combo("/comments").Post(bindIgnErr(form.CreateComment{}), repo.NewComment)
  450. })
  451. })
  452. m.Group("/comments/:id", func() {
  453. m.Post("", repo.UpdateCommentContent)
  454. m.Post("/delete", repo.DeleteComment)
  455. })
  456. }, reqSignIn, context.RepoAssignment(true))
  457. m.Group("/:username/:reponame", func() {
  458. m.Group("/wiki", func() {
  459. m.Get("/?:page", repo.Wiki)
  460. m.Get("/_pages", repo.WikiPages)
  461. }, repo.MustEnableWiki, context.RepoRef())
  462. }, ignSignIn, context.RepoAssignment(false, true))
  463. m.Group("/:username/:reponame", func() {
  464. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  465. // So they can apply their own enable/disable logic on routers.
  466. m.Group("/issues", func() {
  467. m.Group("/:index", func() {
  468. m.Post("/label", repo.UpdateIssueLabel)
  469. m.Post("/milestone", repo.UpdateIssueMilestone)
  470. m.Post("/assignee", repo.UpdateIssueAssignee)
  471. }, reqRepoWriter)
  472. })
  473. m.Group("/labels", func() {
  474. m.Post("/new", bindIgnErr(form.CreateLabel{}), repo.NewLabel)
  475. m.Post("/edit", bindIgnErr(form.CreateLabel{}), repo.UpdateLabel)
  476. m.Post("/delete", repo.DeleteLabel)
  477. m.Post("/initialize", bindIgnErr(form.InitializeLabels{}), repo.InitializeLabels)
  478. }, reqRepoWriter, context.RepoRef())
  479. m.Group("/milestones", func() {
  480. m.Combo("/new").Get(repo.NewMilestone).
  481. Post(bindIgnErr(form.CreateMilestone{}), repo.NewMilestonePost)
  482. m.Get("/:id/edit", repo.EditMilestone)
  483. m.Post("/:id/edit", bindIgnErr(form.CreateMilestone{}), repo.EditMilestonePost)
  484. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  485. m.Post("/delete", repo.DeleteMilestone)
  486. }, reqRepoWriter, context.RepoRef())
  487. m.Group("/releases", func() {
  488. m.Get("/new", repo.NewRelease)
  489. m.Post("/new", bindIgnErr(form.NewRelease{}), repo.NewReleasePost)
  490. m.Post("/delete", repo.DeleteRelease)
  491. m.Get("/edit/*", repo.EditRelease)
  492. m.Post("/edit/*", bindIgnErr(form.EditRelease{}), repo.EditReleasePost)
  493. }, repo.MustBeNotBare, reqRepoWriter, func(c *context.Context) {
  494. c.Data["PageIsViewFiles"] = true
  495. })
  496. // FIXME: Should use c.Repo.PullRequest to unify template, currently we have inconsistent URL
  497. // for PR in same repository. After select branch on the page, the URL contains redundant head user name.
  498. // e.g. /org1/test-repo/compare/master...org1:develop
  499. // which should be /org1/test-repo/compare/master...develop
  500. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  501. Post(bindIgnErr(form.NewIssue{}), repo.CompareAndPullRequestPost)
  502. m.Group("", func() {
  503. m.Combo("/_edit/*").Get(repo.EditFile).
  504. Post(bindIgnErr(form.EditRepoFile{}), repo.EditFilePost)
  505. m.Combo("/_new/*").Get(repo.NewFile).
  506. Post(bindIgnErr(form.EditRepoFile{}), repo.NewFilePost)
  507. m.Post("/_preview/*", bindIgnErr(form.EditPreviewDiff{}), repo.DiffPreviewPost)
  508. m.Combo("/_delete/*").Get(repo.DeleteFile).
  509. Post(bindIgnErr(form.DeleteRepoFile{}), repo.DeleteFilePost)
  510. m.Group("", func() {
  511. m.Combo("/_upload/*").Get(repo.UploadFile).
  512. Post(bindIgnErr(form.UploadRepoFile{}), repo.UploadFilePost)
  513. m.Post("/upload-file", repo.UploadFileToServer)
  514. m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer)
  515. }, func(c *context.Context) {
  516. if !conf.Repository.Upload.Enabled {
  517. c.NotFound()
  518. return
  519. }
  520. })
  521. }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(c *context.Context) {
  522. if !c.Repo.CanEnableEditor() {
  523. c.NotFound()
  524. return
  525. }
  526. c.Data["PageIsViewFiles"] = true
  527. })
  528. }, reqSignIn, context.RepoAssignment())
  529. m.Group("/:username/:reponame", func() {
  530. m.Group("", func() {
  531. m.Get("/releases", repo.MustBeNotBare, repo.Releases)
  532. m.Get("/pulls", repo.RetrieveLabels, repo.Pulls)
  533. m.Get("/pulls/:index", repo.ViewPull)
  534. }, context.RepoRef())
  535. m.Group("/branches", func() {
  536. m.Get("", repo.Branches)
  537. m.Get("/all", repo.AllBranches)
  538. m.Post("/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
  539. }, repo.MustBeNotBare, func(c *context.Context) {
  540. c.Data["PageIsViewFiles"] = true
  541. })
  542. m.Group("/wiki", func() {
  543. m.Group("", func() {
  544. m.Combo("/_new").Get(repo.NewWiki).
  545. Post(bindIgnErr(form.NewWiki{}), repo.NewWikiPost)
  546. m.Combo("/:page/_edit").Get(repo.EditWiki).
  547. Post(bindIgnErr(form.NewWiki{}), repo.EditWikiPost)
  548. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  549. }, reqSignIn, reqRepoWriter)
  550. }, repo.MustEnableWiki, context.RepoRef())
  551. m.Get("/archive/*", repo.MustBeNotBare, repo.Download)
  552. m.Group("/pulls/:index", func() {
  553. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  554. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  555. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  556. }, repo.MustAllowPulls)
  557. m.Group("", func() {
  558. m.Get("/src/*", repo.Home)
  559. m.Get("/raw/*", repo.SingleDownload)
  560. m.Get("/commits/*", repo.RefCommits)
  561. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.Diff)
  562. m.Get("/forks", repo.Forks)
  563. }, repo.MustBeNotBare, context.RepoRef())
  564. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.MustBeNotBare, repo.RawDiff)
  565. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.MustBeNotBare, context.RepoRef(), repo.CompareDiff)
  566. }, ignSignIn, context.RepoAssignment())
  567. m.Group("/:username/:reponame", func() {
  568. m.Get("/stars", repo.Stars)
  569. m.Get("/watchers", repo.Watchers)
  570. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  571. m.Group("/:username", func() {
  572. m.Get("/:reponame", ignSignIn, context.RepoAssignment(), context.RepoRef(), repo.Home)
  573. m.Group("/:reponame", func() {
  574. m.Head("/tasks/trigger", repo.TriggerTask)
  575. })
  576. // Use the regexp to match the repository name
  577. // Duplicated route to enable different ways of accessing same set of URLs,
  578. // e.g. with or without ".git" suffix.
  579. m.Group("/:reponame([\\d\\w-_\\.]+\\.git$)", func() {
  580. m.Get("", ignSignIn, context.RepoAssignment(), context.RepoRef(), repo.Home)
  581. m.Options("/*", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  582. m.Route("/*", "GET,POST", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  583. })
  584. m.Options("/:reponame/*", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  585. m.Route("/:reponame/*", "GET,POST", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  586. })
  587. // ***** END: Repository *****
  588. m.Group("/api", func() {
  589. apiv1.RegisterRoutes(m)
  590. }, ignSignIn)
  591. // ***************************
  592. // ----- Internal routes -----
  593. // ***************************
  594. m.Group("/-", func() {
  595. m.Get("/metrics", app.MetricsFilter(), promhttp.Handler()) // "/-/metrics"
  596. m.Group("/api", func() {
  597. m.Post("/sanitize_ipynb", app.SanitizeIpynb()) // "/-/api/sanitize_ipynb"
  598. })
  599. })
  600. // robots.txt
  601. m.Get("/robots.txt", func(c *context.Context) {
  602. if conf.HasRobotsTxt {
  603. c.ServeFileContent(filepath.Join(conf.CustomDir(), "robots.txt"))
  604. } else {
  605. c.NotFound()
  606. }
  607. })
  608. // Not found handler.
  609. m.NotFound(route.NotFound)
  610. // Flag for port number in case first time run conflict.
  611. if c.IsSet("port") {
  612. conf.Server.URL.Host = strings.Replace(conf.Server.URL.Host, ":"+conf.Server.URL.Port(), ":"+c.String("port"), 1)
  613. conf.Server.ExternalURL = conf.Server.URL.String()
  614. conf.Server.HTTPPort = c.String("port")
  615. }
  616. var listenAddr string
  617. if conf.Server.Protocol == "unix" {
  618. listenAddr = conf.Server.HTTPAddr
  619. log.Info("Listen on %v://%s", conf.Server.Protocol, listenAddr)
  620. } else {
  621. listenAddr = fmt.Sprintf("%s:%s", conf.Server.HTTPAddr, conf.Server.HTTPPort)
  622. log.Info("Listen on %v://%s%s", conf.Server.Protocol, listenAddr, conf.Server.Subpath)
  623. }
  624. switch conf.Server.Protocol {
  625. case "http":
  626. err = http.ListenAndServe(listenAddr, m)
  627. case "https":
  628. tlsMinVersion := tls.VersionTLS12
  629. switch conf.Server.TLSMinVersion {
  630. case "TLS13":
  631. tlsMinVersion = tls.VersionTLS13
  632. case "TLS12":
  633. tlsMinVersion = tls.VersionTLS12
  634. case "TLS11":
  635. tlsMinVersion = tls.VersionTLS11
  636. case "TLS10":
  637. tlsMinVersion = tls.VersionTLS10
  638. }
  639. server := &http.Server{
  640. Addr: listenAddr,
  641. TLSConfig: &tls.Config{
  642. MinVersion: uint16(tlsMinVersion),
  643. CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384, tls.CurveP521},
  644. PreferServerCipherSuites: true,
  645. CipherSuites: []uint16{
  646. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  647. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  648. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  649. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  650. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  651. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  652. },
  653. }, Handler: m}
  654. err = server.ListenAndServeTLS(conf.Server.CertFile, conf.Server.KeyFile)
  655. case "fcgi":
  656. err = fcgi.Serve(nil, m)
  657. case "unix":
  658. if osutil.IsExist(listenAddr) {
  659. err = os.Remove(listenAddr)
  660. if err != nil {
  661. log.Fatal("Failed to remove existing Unix domain socket: %v", err)
  662. }
  663. }
  664. var listener *net.UnixListener
  665. listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"})
  666. if err != nil {
  667. log.Fatal("Failed to listen on Unix networks: %v", err)
  668. }
  669. // FIXME: add proper implementation of signal capture on all protocols
  670. // execute this on SIGTERM or SIGINT: listener.Close()
  671. if err = os.Chmod(listenAddr, conf.Server.UnixSocketMode); err != nil {
  672. log.Fatal("Failed to change permission of Unix domain socket: %v", err)
  673. }
  674. err = http.Serve(listener, m)
  675. default:
  676. log.Fatal("Unexpected server protocol: %s", conf.Server.Protocol)
  677. }
  678. if err != nil {
  679. log.Fatal("Failed to start server: %v", err)
  680. }
  681. return nil
  682. }