web.go 26 KB

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