web.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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/go-macaron/binding"
  16. "github.com/go-macaron/cache"
  17. "github.com/go-macaron/captcha"
  18. "github.com/go-macaron/csrf"
  19. "github.com/go-macaron/gzip"
  20. "github.com/go-macaron/i18n"
  21. "github.com/go-macaron/session"
  22. "github.com/go-macaron/toolbox"
  23. "github.com/go-xorm/xorm"
  24. "github.com/mcuadros/go-version"
  25. "github.com/urfave/cli"
  26. log "gopkg.in/clog.v1"
  27. "gopkg.in/ini.v1"
  28. "gopkg.in/macaron.v1"
  29. "github.com/gogits/git-module"
  30. "github.com/gogits/go-gogs-client"
  31. "github.com/gogits/gogs/models"
  32. "github.com/gogits/gogs/modules/auth"
  33. "github.com/gogits/gogs/modules/bindata"
  34. "github.com/gogits/gogs/modules/context"
  35. "github.com/gogits/gogs/modules/mailer"
  36. "github.com/gogits/gogs/modules/setting"
  37. "github.com/gogits/gogs/modules/template"
  38. "github.com/gogits/gogs/routers"
  39. "github.com/gogits/gogs/routers/admin"
  40. apiv1 "github.com/gogits/gogs/routers/api/v1"
  41. "github.com/gogits/gogs/routers/dev"
  42. "github.com/gogits/gogs/routers/org"
  43. "github.com/gogits/gogs/routers/repo"
  44. "github.com/gogits/gogs/routers/user"
  45. )
  46. var CmdWeb = cli.Command{
  47. Name: "web",
  48. Usage: "Start Gogs web server",
  49. Description: `Gogs web server is the only thing you need to run,
  50. and it takes care of all the other things for you`,
  51. Action: runWeb,
  52. Flags: []cli.Flag{
  53. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  54. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  55. },
  56. }
  57. type VerChecker struct {
  58. ImportPath string
  59. Version func() string
  60. Expected string
  61. }
  62. // checkVersion checks if binary matches the version of templates files.
  63. func checkVersion() {
  64. // Templates.
  65. data, err := ioutil.ReadFile(setting.StaticRootPath + "/templates/.VERSION")
  66. if err != nil {
  67. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  68. }
  69. tplVer := string(data)
  70. if tplVer != setting.AppVer {
  71. if version.Compare(tplVer, setting.AppVer, ">") {
  72. log.Fatal(4, "Binary version is lower than template file version, did you forget to recompile Gogs?")
  73. } else {
  74. log.Fatal(4, "Binary version is higher than template file version, did you forget to update template files?")
  75. }
  76. }
  77. // Check dependency version.
  78. // LEGACY [0.11]: no need to check version as we check in vendor into version control
  79. checkers := []VerChecker{
  80. {"github.com/go-xorm/xorm", func() string { return xorm.Version }, "0.6.0"},
  81. {"github.com/go-macaron/binding", binding.Version, "0.3.2"},
  82. {"github.com/go-macaron/cache", cache.Version, "0.1.2"},
  83. {"github.com/go-macaron/csrf", csrf.Version, "0.1.0"},
  84. {"github.com/go-macaron/i18n", i18n.Version, "0.3.0"},
  85. {"github.com/go-macaron/session", session.Version, "0.1.6"},
  86. {"github.com/go-macaron/toolbox", toolbox.Version, "0.1.0"},
  87. {"gopkg.in/ini.v1", ini.Version, "1.8.4"},
  88. {"gopkg.in/macaron.v1", macaron.Version, "1.1.7"},
  89. {"github.com/gogits/git-module", git.Version, "0.4.10"},
  90. {"github.com/gogits/go-gogs-client", gogs.Version, "0.12.1"},
  91. }
  92. for _, c := range checkers {
  93. if !version.Compare(c.Version(), c.Expected, ">=") {
  94. log.Fatal(4, `Dependency outdated!
  95. Package '%s' current version (%s) is below requirement (%s),
  96. please use following command to update this package and recompile Gogs:
  97. go get -u %[1]s`, c.ImportPath, c.Version(), c.Expected)
  98. }
  99. }
  100. }
  101. // newMacaron initializes Macaron instance.
  102. func newMacaron() *macaron.Macaron {
  103. m := macaron.New()
  104. if !setting.DisableRouterLog {
  105. m.Use(macaron.Logger())
  106. }
  107. m.Use(macaron.Recovery())
  108. if setting.EnableGzip {
  109. m.Use(gzip.Gziper())
  110. }
  111. if setting.Protocol == setting.SCHEME_FCGI {
  112. m.SetURLPrefix(setting.AppSubUrl)
  113. }
  114. m.Use(macaron.Static(
  115. path.Join(setting.StaticRootPath, "public"),
  116. macaron.StaticOptions{
  117. SkipLogging: setting.DisableRouterLog,
  118. },
  119. ))
  120. m.Use(macaron.Static(
  121. setting.AvatarUploadPath,
  122. macaron.StaticOptions{
  123. Prefix: "avatars",
  124. SkipLogging: setting.DisableRouterLog,
  125. },
  126. ))
  127. funcMap := template.NewFuncMap()
  128. m.Use(macaron.Renderer(macaron.RenderOptions{
  129. Directory: path.Join(setting.StaticRootPath, "templates"),
  130. AppendDirectories: []string{path.Join(setting.CustomPath, "templates")},
  131. Funcs: funcMap,
  132. IndentJSON: macaron.Env != macaron.PROD,
  133. }))
  134. mailer.InitMailRender(path.Join(setting.StaticRootPath, "templates/mail"),
  135. path.Join(setting.CustomPath, "templates/mail"), funcMap)
  136. localeNames, err := bindata.AssetDir("conf/locale")
  137. if err != nil {
  138. log.Fatal(4, "Fail to list locale files: %v", err)
  139. }
  140. localFiles := make(map[string][]byte)
  141. for _, name := range localeNames {
  142. localFiles[name] = bindata.MustAsset("conf/locale/" + name)
  143. }
  144. m.Use(i18n.I18n(i18n.Options{
  145. SubURL: setting.AppSubUrl,
  146. Files: localFiles,
  147. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  148. Langs: setting.Langs,
  149. Names: setting.Names,
  150. DefaultLang: "en-US",
  151. Redirect: true,
  152. }))
  153. m.Use(cache.Cacher(cache.Options{
  154. Adapter: setting.CacheAdapter,
  155. AdapterConfig: setting.CacheConn,
  156. Interval: setting.CacheInterval,
  157. }))
  158. m.Use(captcha.Captchaer(captcha.Options{
  159. SubURL: setting.AppSubUrl,
  160. }))
  161. m.Use(session.Sessioner(setting.SessionConfig))
  162. m.Use(csrf.Csrfer(csrf.Options{
  163. Secret: setting.SecretKey,
  164. Cookie: setting.CSRFCookieName,
  165. SetCookie: true,
  166. Header: "X-Csrf-Token",
  167. CookiePath: setting.AppSubUrl,
  168. }))
  169. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  170. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  171. &toolbox.HealthCheckFuncDesc{
  172. Desc: "Database connection",
  173. Func: models.Ping,
  174. },
  175. },
  176. }))
  177. m.Use(context.Contexter())
  178. return m
  179. }
  180. func runWeb(ctx *cli.Context) error {
  181. if ctx.IsSet("config") {
  182. setting.CustomConf = ctx.String("config")
  183. }
  184. routers.GlobalInit()
  185. checkVersion()
  186. m := newMacaron()
  187. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  188. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  189. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  190. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  191. bindIgnErr := binding.BindIgnErr
  192. // FIXME: not all routes need go through same middlewares.
  193. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  194. // Routers.
  195. m.Get("/", ignSignIn, routers.Home)
  196. m.Group("/explore", func() {
  197. m.Get("", func(ctx *context.Context) {
  198. ctx.Redirect(setting.AppSubUrl + "/explore/repos")
  199. })
  200. m.Get("/repos", routers.ExploreRepos)
  201. m.Get("/users", routers.ExploreUsers)
  202. m.Get("/organizations", routers.ExploreOrganizations)
  203. }, ignSignIn)
  204. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  205. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  206. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  207. // ***** START: User *****
  208. m.Group("/user", func() {
  209. m.Get("/login", user.SignIn)
  210. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  211. m.Get("/sign_up", user.SignUp)
  212. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  213. m.Get("/reset_password", user.ResetPasswd)
  214. m.Post("/reset_password", user.ResetPasswdPost)
  215. }, reqSignOut)
  216. m.Group("/user/settings", func() {
  217. m.Get("", user.Settings)
  218. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  219. m.Combo("/avatar").Get(user.SettingsAvatar).
  220. Post(binding.MultipartForm(auth.AvatarForm{}), user.SettingsAvatarPost)
  221. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  222. m.Combo("/email").Get(user.SettingsEmails).
  223. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  224. m.Post("/email/delete", user.DeleteEmail)
  225. m.Get("/password", user.SettingsPassword)
  226. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  227. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  228. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  229. m.Post("/ssh/delete", user.DeleteSSHKey)
  230. m.Combo("/applications").Get(user.SettingsApplications).
  231. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  232. m.Post("/applications/delete", user.SettingsDeleteApplication)
  233. m.Group("/organizations", func() {
  234. m.Get("", user.SettingsOrganizations)
  235. m.Post("/leave", user.SettingsLeaveOrganization)
  236. })
  237. m.Route("/delete", "GET,POST", user.SettingsDelete)
  238. }, reqSignIn, func(ctx *context.Context) {
  239. ctx.Data["PageIsUserSettings"] = true
  240. })
  241. m.Group("/user", func() {
  242. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  243. m.Any("/activate", user.Activate)
  244. m.Any("/activate_email", user.ActivateEmail)
  245. m.Get("/email2user", user.Email2User)
  246. m.Get("/forget_password", user.ForgotPasswd)
  247. m.Post("/forget_password", user.ForgotPasswdPost)
  248. m.Get("/logout", user.SignOut)
  249. })
  250. // ***** END: User *****
  251. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  252. // ***** START: Admin *****
  253. m.Group("/admin", func() {
  254. m.Get("", adminReq, admin.Dashboard)
  255. m.Get("/config", admin.Config)
  256. m.Post("/config/test_mail", admin.SendTestMail)
  257. m.Get("/monitor", admin.Monitor)
  258. m.Group("/users", func() {
  259. m.Get("", admin.Users)
  260. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  261. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  262. m.Post("/:userid/delete", admin.DeleteUser)
  263. })
  264. m.Group("/orgs", func() {
  265. m.Get("", admin.Organizations)
  266. })
  267. m.Group("/repos", func() {
  268. m.Get("", admin.Repos)
  269. m.Post("/delete", admin.DeleteRepo)
  270. })
  271. m.Group("/auths", func() {
  272. m.Get("", admin.Authentications)
  273. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  274. m.Combo("/:authid").Get(admin.EditAuthSource).
  275. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  276. m.Post("/:authid/delete", admin.DeleteAuthSource)
  277. })
  278. m.Group("/notices", func() {
  279. m.Get("", admin.Notices)
  280. m.Post("/delete", admin.DeleteNotices)
  281. m.Get("/empty", admin.EmptyNotices)
  282. })
  283. }, adminReq)
  284. // ***** END: Admin *****
  285. m.Group("", func() {
  286. m.Group("/:username", func() {
  287. m.Get("", user.Profile)
  288. m.Get("/followers", user.Followers)
  289. m.Get("/following", user.Following)
  290. m.Get("/stars", user.Stars)
  291. })
  292. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  293. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  294. if err != nil {
  295. if models.IsErrAttachmentNotExist(err) {
  296. ctx.Error(404)
  297. } else {
  298. ctx.Handle(500, "GetAttachmentByUUID", err)
  299. }
  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. ctx.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name))
  310. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  311. // We must put the name in " manually.
  312. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  313. ctx.Handle(500, "ServeData", err)
  314. return
  315. }
  316. })
  317. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  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(auth.CreateOrgForm{}), 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(auth.CreateTeamForm{}), org.NewTeamPost)
  353. m.Get("/teams/:team/edit", org.EditTeam)
  354. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  355. m.Post("/teams/:team/delete", org.DeleteTeam)
  356. m.Group("/settings", func() {
  357. m.Combo("").Get(org.Settings).
  358. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  359. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), 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(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  366. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  367. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  368. m.Get("/:id", repo.WebHooksEdit)
  369. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  370. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  371. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), 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(auth.CreateRepoForm{}), repo.CreatePost)
  383. m.Get("/migrate", repo.Migrate)
  384. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  385. m.Combo("/fork/:repoid").Get(repo.Fork).
  386. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  387. }, reqSignIn)
  388. m.Group("/:username/:reponame", func() {
  389. m.Group("/settings", func() {
  390. m.Combo("").Get(repo.Settings).
  391. Post(bindIgnErr(auth.RepoSettingForm{}), 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(auth.ProtectBranchForm{}), 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(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  413. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  414. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  415. m.Get("/:id", repo.WebHooksEdit)
  416. m.Post("/:id/test", repo.TestWebhook)
  417. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  418. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  419. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), 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(auth.AddSSHKeyForm{}), 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(auth.CreateIssueForm{}), 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(auth.CreateCommentForm{}), 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(auth.CreateLabelForm{}), repo.NewLabel)
  459. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  460. m.Post("/delete", repo.DeleteLabel)
  461. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  462. }, reqRepoWriter, context.RepoRef())
  463. m.Group("/milestones", func() {
  464. m.Combo("/new").Get(repo.NewMilestone).
  465. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  466. m.Get("/:id/edit", repo.EditMilestone)
  467. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), 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(auth.NewReleaseForm{}), repo.NewReleasePost)
  474. m.Post("/delete", repo.DeleteRelease)
  475. }, reqRepoWriter, context.RepoRef())
  476. m.Group("/releases", func() {
  477. m.Get("/edit/*", repo.EditRelease)
  478. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  479. }, reqRepoWriter, func(ctx *context.Context) {
  480. var err error
  481. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  482. if err != nil {
  483. ctx.Handle(500, "GetBranchCommit", err)
  484. return
  485. }
  486. ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
  487. if err != nil {
  488. ctx.Handle(500, "CommitsCount", err)
  489. return
  490. }
  491. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  492. })
  493. // FIXME: Should use ctx.Repo.PullRequest to unify template, currently we have inconsistent URL
  494. // for PR in same repository. After select branch on the page, the URL contains redundant head user name.
  495. // e.g. /org1/test-repo/compare/master...org1:develop
  496. // which should be /org1/test-repo/compare/master...develop
  497. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  498. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  499. m.Group("", func() {
  500. m.Combo("/_edit/*").Get(repo.EditFile).
  501. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  502. m.Combo("/_new/*").Get(repo.NewFile).
  503. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  504. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  505. m.Combo("/_delete/*").Get(repo.DeleteFile).
  506. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  507. m.Group("", func() {
  508. m.Combo("/_upload/*").Get(repo.UploadFile).
  509. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  510. m.Post("/upload-file", repo.UploadFileToServer)
  511. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  512. }, func(ctx *context.Context) {
  513. if !setting.Repository.Upload.Enabled {
  514. ctx.NotFound()
  515. return
  516. }
  517. })
  518. }, reqRepoWriter, context.RepoRef(), func(ctx *context.Context) {
  519. if !ctx.Repo.CanEnableEditor() {
  520. ctx.NotFound()
  521. return
  522. }
  523. })
  524. }, reqSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  525. m.Group("/:username/:reponame", func() {
  526. m.Group("", func() {
  527. m.Get("/releases", repo.Releases)
  528. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  529. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  530. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  531. m.Get("/milestones", repo.Milestones)
  532. }, context.RepoRef())
  533. // m.Get("/branches", repo.Branches)
  534. m.Post("/branches/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
  535. m.Group("/wiki", func() {
  536. m.Get("/?:page", repo.Wiki)
  537. m.Get("/_pages", repo.WikiPages)
  538. m.Group("", func() {
  539. m.Combo("/_new").Get(repo.NewWiki).
  540. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  541. m.Combo("/:page/_edit").Get(repo.EditWiki).
  542. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  543. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  544. }, reqSignIn, reqRepoWriter)
  545. }, repo.MustEnableWiki, context.RepoRef())
  546. m.Get("/archive/*", repo.Download)
  547. m.Group("/pulls/:index", func() {
  548. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  549. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  550. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  551. }, repo.MustAllowPulls)
  552. m.Group("", func() {
  553. m.Get("/src/*", repo.Home)
  554. m.Get("/raw/*", repo.SingleDownload)
  555. m.Get("/commits/*", repo.RefCommits)
  556. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.Diff)
  557. m.Get("/forks", repo.Forks)
  558. }, context.RepoRef())
  559. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.RawDiff)
  560. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", context.RepoRef(), repo.CompareDiff)
  561. }, ignSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  562. m.Group("/:username/:reponame", func() {
  563. m.Get("/stars", repo.Stars)
  564. m.Get("/watchers", repo.Watchers)
  565. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  566. m.Group("/:username", func() {
  567. m.Group("/:reponame", func() {
  568. m.Get("", repo.Home)
  569. m.Get("\\.git$", repo.Home)
  570. }, ignSignIn, context.RepoAssignment(true), context.RepoRef())
  571. m.Group("/:reponame", func() {
  572. m.Head("/tasks/trigger", repo.TriggerTask)
  573. m.Route("\\.git/*", "GET,POST", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  574. })
  575. })
  576. // ***** END: Repository *****
  577. m.Group("/api", func() {
  578. apiv1.RegisterRoutes(m)
  579. }, ignSignIn)
  580. // robots.txt
  581. m.Get("/robots.txt", func(ctx *context.Context) {
  582. if setting.HasRobotsTxt {
  583. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  584. } else {
  585. ctx.Error(404)
  586. }
  587. })
  588. // Not found handler.
  589. m.NotFound(routers.NotFound)
  590. // Flag for port number in case first time run conflict.
  591. if ctx.IsSet("port") {
  592. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HTTPPort, ctx.String("port"), 1)
  593. setting.HTTPPort = ctx.String("port")
  594. }
  595. var listenAddr string
  596. if setting.Protocol == setting.SCHEME_UNIX_SOCKET {
  597. listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
  598. } else {
  599. listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
  600. }
  601. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  602. var err error
  603. switch setting.Protocol {
  604. case setting.SCHEME_HTTP:
  605. err = http.ListenAndServe(listenAddr, m)
  606. case setting.SCHEME_HTTPS:
  607. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{
  608. MinVersion: tls.VersionTLS10,
  609. CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
  610. PreferServerCipherSuites: true,
  611. CipherSuites: []uint16{
  612. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  613. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, // Required for HTTP/2 support.
  614. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  615. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  616. },
  617. }, Handler: m}
  618. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  619. case setting.SCHEME_FCGI:
  620. err = fcgi.Serve(nil, m)
  621. case setting.SCHEME_UNIX_SOCKET:
  622. os.Remove(listenAddr)
  623. var listener *net.UnixListener
  624. listener, err = net.ListenUnix("unix", &net.UnixAddr{listenAddr, "unix"})
  625. if err != nil {
  626. break // Handle error after switch
  627. }
  628. // FIXME: add proper implementation of signal capture on all protocols
  629. // execute this on SIGTERM or SIGINT: listener.Close()
  630. if err = os.Chmod(listenAddr, os.FileMode(setting.UnixSocketPermission)); err != nil {
  631. log.Fatal(4, "Failed to set permission of unix socket: %v", err)
  632. }
  633. err = http.Serve(listener, m)
  634. default:
  635. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  636. }
  637. if err != nil {
  638. log.Fatal(4, "Fail to start server: %v", err)
  639. }
  640. return nil
  641. }