web.go 26 KB

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