web.go 26 KB

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