web.go 27 KB

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