web.go 26 KB

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