web.go 26 KB

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