web.go 25 KB

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