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