web.go 26 KB

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