Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

web.go 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. "fmt"
  7. "net"
  8. "net/http"
  9. "net/http/fcgi"
  10. "os"
  11. "path"
  12. "strings"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/auth"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/lfs"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/options"
  19. "code.gitea.io/gitea/modules/public"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/templates"
  22. "code.gitea.io/gitea/routers"
  23. "code.gitea.io/gitea/routers/admin"
  24. apiv1 "code.gitea.io/gitea/routers/api/v1"
  25. "code.gitea.io/gitea/routers/dev"
  26. "code.gitea.io/gitea/routers/org"
  27. "code.gitea.io/gitea/routers/repo"
  28. "code.gitea.io/gitea/routers/user"
  29. "github.com/go-macaron/binding"
  30. "github.com/go-macaron/cache"
  31. "github.com/go-macaron/captcha"
  32. "github.com/go-macaron/csrf"
  33. "github.com/go-macaron/gzip"
  34. "github.com/go-macaron/i18n"
  35. "github.com/go-macaron/session"
  36. "github.com/go-macaron/toolbox"
  37. "github.com/urfave/cli"
  38. macaron "gopkg.in/macaron.v1"
  39. )
  40. // CmdWeb represents the available web sub-command.
  41. var CmdWeb = cli.Command{
  42. Name: "web",
  43. Usage: "Start Gitea web server",
  44. Description: `Gitea web server is the only thing you need to run,
  45. and it takes care of all the other things for you`,
  46. Action: runWeb,
  47. Flags: []cli.Flag{
  48. cli.StringFlag{
  49. Name: "port, p",
  50. Value: "3000",
  51. Usage: "Temporary port number to prevent conflict",
  52. },
  53. cli.StringFlag{
  54. Name: "config, c",
  55. Value: "custom/conf/app.ini",
  56. Usage: "Custom configuration file path",
  57. },
  58. cli.StringFlag{
  59. Name: "pid, P",
  60. Value: "/var/run/gitea.pid",
  61. Usage: "Custom pid file path",
  62. },
  63. },
  64. }
  65. // VerChecker is a listing of required dependency versions.
  66. type VerChecker struct {
  67. ImportPath string
  68. Version func() string
  69. Expected string
  70. }
  71. // newMacaron initializes Macaron instance.
  72. func newMacaron() *macaron.Macaron {
  73. m := macaron.New()
  74. if !setting.DisableRouterLog {
  75. m.Use(macaron.Logger())
  76. }
  77. m.Use(macaron.Recovery())
  78. if setting.EnableGzip {
  79. m.Use(gzip.Gziper())
  80. }
  81. if setting.Protocol == setting.FCGI {
  82. m.SetURLPrefix(setting.AppSubURL)
  83. }
  84. m.Use(public.Custom(
  85. &public.Options{
  86. SkipLogging: setting.DisableRouterLog,
  87. },
  88. ))
  89. m.Use(public.Static(
  90. &public.Options{
  91. Directory: path.Join(setting.StaticRootPath, "public"),
  92. SkipLogging: setting.DisableRouterLog,
  93. },
  94. ))
  95. m.Use(macaron.Static(
  96. setting.AvatarUploadPath,
  97. macaron.StaticOptions{
  98. Prefix: "avatars",
  99. SkipLogging: setting.DisableRouterLog,
  100. ETag: true,
  101. },
  102. ))
  103. m.Use(templates.Renderer())
  104. models.InitMailRender(templates.Mailer())
  105. localeNames, err := options.Dir("locale")
  106. if err != nil {
  107. log.Fatal(4, "Failed to list locale files: %v", err)
  108. }
  109. localFiles := make(map[string][]byte)
  110. for _, name := range localeNames {
  111. localFiles[name], err = options.Locale(name)
  112. if err != nil {
  113. log.Fatal(4, "Failed to load %s locale file. %v", name, err)
  114. }
  115. }
  116. m.Use(i18n.I18n(i18n.Options{
  117. SubURL: setting.AppSubURL,
  118. Files: localFiles,
  119. Langs: setting.Langs,
  120. Names: setting.Names,
  121. DefaultLang: "en-US",
  122. Redirect: true,
  123. }))
  124. m.Use(cache.Cacher(cache.Options{
  125. Adapter: setting.CacheAdapter,
  126. AdapterConfig: setting.CacheConn,
  127. Interval: setting.CacheInterval,
  128. }))
  129. m.Use(captcha.Captchaer(captcha.Options{
  130. SubURL: setting.AppSubURL,
  131. }))
  132. m.Use(session.Sessioner(setting.SessionConfig))
  133. m.Use(csrf.Csrfer(csrf.Options{
  134. Secret: setting.SecretKey,
  135. Cookie: setting.CSRFCookieName,
  136. SetCookie: true,
  137. Header: "X-Csrf-Token",
  138. CookiePath: setting.AppSubURL,
  139. }))
  140. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  141. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  142. {
  143. Desc: "Database connection",
  144. Func: models.Ping,
  145. },
  146. },
  147. }))
  148. m.Use(context.Contexter())
  149. return m
  150. }
  151. func runWeb(ctx *cli.Context) error {
  152. if ctx.IsSet("config") {
  153. setting.CustomConf = ctx.String("config")
  154. }
  155. if ctx.IsSet("pid") {
  156. setting.CustomPID = ctx.String("pid")
  157. }
  158. routers.GlobalInit()
  159. m := newMacaron()
  160. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  161. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  162. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  163. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  164. bindIgnErr := binding.BindIgnErr
  165. m.Use(user.GetNotificationCount)
  166. // FIXME: not all routes need go through same middlewares.
  167. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  168. // Routers.
  169. m.Get("/", ignSignIn, routers.Home)
  170. m.Group("/explore", func() {
  171. m.Get("", func(ctx *context.Context) {
  172. ctx.Redirect(setting.AppSubURL + "/explore/repos")
  173. })
  174. m.Get("/repos", routers.ExploreRepos)
  175. m.Get("/users", routers.ExploreUsers)
  176. m.Get("/organizations", routers.ExploreOrganizations)
  177. }, ignSignIn)
  178. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  179. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  180. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  181. // ***** START: User *****
  182. m.Group("/user", func() {
  183. m.Get("/login", user.SignIn)
  184. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  185. m.Get("/sign_up", user.SignUp)
  186. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  187. m.Get("/reset_password", user.ResetPasswd)
  188. m.Post("/reset_password", user.ResetPasswdPost)
  189. m.Group("/two_factor", func() {
  190. m.Get("", user.TwoFactor)
  191. m.Post("", bindIgnErr(auth.TwoFactorAuthForm{}), user.TwoFactorPost)
  192. m.Get("/scratch", user.TwoFactorScratch)
  193. m.Post("/scratch", bindIgnErr(auth.TwoFactorScratchAuthForm{}), user.TwoFactorScratchPost)
  194. })
  195. }, reqSignOut)
  196. m.Group("/user/settings", func() {
  197. m.Get("", user.Settings)
  198. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  199. m.Combo("/avatar").Get(user.SettingsAvatar).
  200. Post(binding.MultipartForm(auth.AvatarForm{}), user.SettingsAvatarPost)
  201. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  202. m.Combo("/email").Get(user.SettingsEmails).
  203. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  204. m.Post("/email/delete", user.DeleteEmail)
  205. m.Get("/password", user.SettingsPassword)
  206. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  207. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  208. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  209. m.Post("/ssh/delete", user.DeleteSSHKey)
  210. m.Combo("/applications").Get(user.SettingsApplications).
  211. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  212. m.Post("/applications/delete", user.SettingsDeleteApplication)
  213. m.Route("/delete", "GET,POST", user.SettingsDelete)
  214. m.Group("/two_factor", func() {
  215. m.Get("", user.SettingsTwoFactor)
  216. m.Post("/regenerate_scratch", user.SettingsTwoFactorRegenerateScratch)
  217. m.Post("/disable", user.SettingsTwoFactorDisable)
  218. m.Get("/enroll", user.SettingsTwoFactorEnroll)
  219. m.Post("/enroll", bindIgnErr(auth.TwoFactorAuthForm{}), user.SettingsTwoFactorEnrollPost)
  220. })
  221. }, reqSignIn, func(ctx *context.Context) {
  222. ctx.Data["PageIsUserSettings"] = true
  223. })
  224. m.Group("/user", func() {
  225. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  226. m.Any("/activate", user.Activate)
  227. m.Any("/activate_email", user.ActivateEmail)
  228. m.Get("/email2user", user.Email2User)
  229. m.Get("/forget_password", user.ForgotPasswd)
  230. m.Post("/forget_password", user.ForgotPasswdPost)
  231. m.Get("/logout", user.SignOut)
  232. })
  233. // ***** END: User *****
  234. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  235. // ***** START: Admin *****
  236. m.Group("/admin", func() {
  237. m.Get("", adminReq, admin.Dashboard)
  238. m.Get("/config", admin.Config)
  239. m.Post("/config/test_mail", admin.SendTestMail)
  240. m.Get("/monitor", admin.Monitor)
  241. m.Group("/users", func() {
  242. m.Get("", admin.Users)
  243. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost)
  244. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  245. m.Post("/:userid/delete", admin.DeleteUser)
  246. })
  247. m.Group("/orgs", func() {
  248. m.Get("", admin.Organizations)
  249. })
  250. m.Group("/repos", func() {
  251. m.Get("", admin.Repos)
  252. m.Post("/delete", admin.DeleteRepo)
  253. })
  254. m.Group("/auths", func() {
  255. m.Get("", admin.Authentications)
  256. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  257. m.Combo("/:authid").Get(admin.EditAuthSource).
  258. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  259. m.Post("/:authid/delete", admin.DeleteAuthSource)
  260. })
  261. m.Group("/notices", func() {
  262. m.Get("", admin.Notices)
  263. m.Post("/delete", admin.DeleteNotices)
  264. m.Get("/empty", admin.EmptyNotices)
  265. })
  266. }, adminReq)
  267. // ***** END: Admin *****
  268. m.Group("", func() {
  269. m.Group("/:username", func() {
  270. m.Get("", user.Profile)
  271. m.Get("/followers", user.Followers)
  272. m.Get("/following", user.Following)
  273. })
  274. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  275. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  276. if err != nil {
  277. if models.IsErrAttachmentNotExist(err) {
  278. ctx.Error(404)
  279. } else {
  280. ctx.Handle(500, "GetAttachmentByUUID", err)
  281. }
  282. return
  283. }
  284. fr, err := os.Open(attach.LocalPath())
  285. if err != nil {
  286. ctx.Handle(500, "Open", err)
  287. return
  288. }
  289. defer fr.Close()
  290. if err = repo.ServeData(ctx, attach.Name, fr); err != nil {
  291. ctx.Handle(500, "ServeData", err)
  292. return
  293. }
  294. })
  295. m.Post("/attachments", repo.UploadAttachment)
  296. }, ignSignIn)
  297. m.Group("/:username", func() {
  298. m.Get("/action/:action", user.Action)
  299. }, reqSignIn)
  300. if macaron.Env == macaron.DEV {
  301. m.Get("/template/*", dev.TemplatePreview)
  302. }
  303. reqRepoAdmin := context.RequireRepoAdmin()
  304. reqRepoWriter := context.RequireRepoWriter()
  305. // ***** START: Organization *****
  306. m.Group("/org", func() {
  307. m.Get("/create", org.Create)
  308. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  309. m.Group("/:org", func() {
  310. m.Get("/dashboard", user.Dashboard)
  311. m.Get("/^:type(issues|pulls)$", user.Issues)
  312. m.Get("/members", org.Members)
  313. m.Get("/members/action/:action", org.MembersAction)
  314. m.Get("/teams", org.Teams)
  315. }, context.OrgAssignment(true))
  316. m.Group("/:org", func() {
  317. m.Get("/teams/:team", org.TeamMembers)
  318. m.Get("/teams/:team/repositories", org.TeamRepositories)
  319. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  320. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  321. }, context.OrgAssignment(true, false, true))
  322. m.Group("/:org", func() {
  323. m.Get("/teams/new", org.NewTeam)
  324. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  325. m.Get("/teams/:team/edit", org.EditTeam)
  326. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  327. m.Post("/teams/:team/delete", org.DeleteTeam)
  328. m.Group("/settings", func() {
  329. m.Combo("").Get(org.Settings).
  330. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  331. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
  332. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  333. m.Group("/hooks", func() {
  334. m.Get("", org.Webhooks)
  335. m.Post("/delete", org.DeleteWebhook)
  336. m.Get("/:type/new", repo.WebhooksNew)
  337. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  338. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  339. m.Get("/:id", repo.WebHooksEdit)
  340. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  341. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  342. })
  343. m.Route("/delete", "GET,POST", org.SettingsDelete)
  344. })
  345. m.Route("/invitations/new", "GET,POST", org.Invitation)
  346. }, context.OrgAssignment(true, true))
  347. }, reqSignIn)
  348. // ***** END: Organization *****
  349. // ***** START: Repository *****
  350. m.Group("/repo", func() {
  351. m.Get("/create", repo.Create)
  352. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  353. m.Get("/migrate", repo.Migrate)
  354. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  355. m.Combo("/fork/:repoid").Get(repo.Fork).
  356. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  357. }, reqSignIn)
  358. m.Group("/:username/:reponame", func() {
  359. m.Group("/settings", func() {
  360. m.Combo("").Get(repo.Settings).
  361. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  362. m.Group("/collaboration", func() {
  363. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  364. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  365. m.Post("/delete", repo.DeleteCollaboration)
  366. })
  367. m.Group("/hooks", func() {
  368. m.Get("", repo.Webhooks)
  369. m.Post("/delete", repo.DeleteWebhook)
  370. m.Get("/:type/new", repo.WebhooksNew)
  371. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  372. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  373. m.Get("/:id", repo.WebHooksEdit)
  374. m.Post("/:id/test", repo.TestWebhook)
  375. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  376. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  377. m.Group("/git", func() {
  378. m.Get("", repo.GitHooks)
  379. m.Combo("/:name").Get(repo.GitHooksEdit).
  380. Post(repo.GitHooksEditPost)
  381. }, context.GitHookService())
  382. })
  383. m.Group("/keys", func() {
  384. m.Combo("").Get(repo.DeployKeys).
  385. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  386. m.Post("/delete", repo.DeleteDeployKey)
  387. })
  388. }, func(ctx *context.Context) {
  389. ctx.Data["PageIsSettings"] = true
  390. })
  391. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  392. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  393. m.Group("/:username/:reponame", func() {
  394. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  395. // So they can apply their own enable/disable logic on routers.
  396. m.Group("/issues", func() {
  397. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  398. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  399. m.Group("/:index", func() {
  400. m.Post("/label", repo.UpdateIssueLabel)
  401. m.Post("/milestone", repo.UpdateIssueMilestone)
  402. m.Post("/assignee", repo.UpdateIssueAssignee)
  403. }, reqRepoWriter)
  404. m.Group("/:index", func() {
  405. m.Post("/title", repo.UpdateIssueTitle)
  406. m.Post("/content", repo.UpdateIssueContent)
  407. m.Combo("/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  408. })
  409. })
  410. m.Group("/comments/:id", func() {
  411. m.Post("", repo.UpdateCommentContent)
  412. m.Post("/delete", repo.DeleteComment)
  413. })
  414. m.Group("/labels", func() {
  415. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  416. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  417. m.Post("/delete", repo.DeleteLabel)
  418. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  419. }, reqRepoWriter, context.RepoRef())
  420. m.Group("/milestones", func() {
  421. m.Combo("/new").Get(repo.NewMilestone).
  422. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  423. m.Get("/:id/edit", repo.EditMilestone)
  424. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  425. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  426. m.Post("/delete", repo.DeleteMilestone)
  427. }, reqRepoWriter, context.RepoRef())
  428. m.Group("/releases", func() {
  429. m.Get("/new", repo.NewRelease)
  430. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  431. m.Post("/delete", repo.DeleteRelease)
  432. }, reqRepoWriter, context.RepoRef())
  433. m.Group("/releases", func() {
  434. m.Get("/edit/*", repo.EditRelease)
  435. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  436. }, reqRepoWriter, func(ctx *context.Context) {
  437. var err error
  438. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  439. if err != nil {
  440. ctx.Handle(500, "GetBranchCommit", err)
  441. return
  442. }
  443. ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
  444. if err != nil {
  445. ctx.Handle(500, "CommitsCount", err)
  446. return
  447. }
  448. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  449. })
  450. m.Combo("/compare/*", repo.MustAllowPulls, repo.SetEditorconfigIfExists).
  451. Get(repo.CompareAndPullRequest).
  452. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  453. m.Group("", func() {
  454. m.Combo("/_edit/*").Get(repo.EditFile).
  455. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  456. m.Combo("/_new/*").Get(repo.NewFile).
  457. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  458. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  459. m.Combo("/_delete/*").Get(repo.DeleteFile).
  460. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  461. m.Group("", func() {
  462. m.Combo("/_upload/*").Get(repo.UploadFile).
  463. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  464. m.Post("/upload-file", repo.UploadFileToServer)
  465. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  466. }, func(ctx *context.Context) {
  467. if !setting.Repository.Upload.Enabled {
  468. ctx.Handle(404, "", nil)
  469. return
  470. }
  471. })
  472. }, reqRepoWriter, context.RepoRef(), func(ctx *context.Context) {
  473. if !ctx.Repo.Repository.CanEnableEditor() || ctx.Repo.IsViewCommit {
  474. ctx.Handle(404, "", nil)
  475. return
  476. }
  477. })
  478. }, reqSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  479. m.Group("/:username/:reponame", func() {
  480. m.Group("", func() {
  481. m.Get("/releases", repo.Releases)
  482. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  483. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  484. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  485. m.Get("/milestones", repo.Milestones)
  486. }, context.RepoRef())
  487. // m.Get("/branches", repo.Branches)
  488. m.Post("/branches/:name/delete", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
  489. m.Group("/wiki", func() {
  490. m.Get("/?:page", repo.Wiki)
  491. m.Get("/_pages", repo.WikiPages)
  492. m.Group("", func() {
  493. m.Combo("/_new").Get(repo.NewWiki).
  494. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  495. m.Combo("/:page/_edit").Get(repo.EditWiki).
  496. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  497. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  498. }, reqSignIn, reqRepoWriter)
  499. }, repo.MustEnableWiki, context.RepoRef())
  500. m.Get("/archive/*", repo.Download)
  501. m.Group("/pulls/:index", func() {
  502. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  503. m.Get("/files", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ViewPullFiles)
  504. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  505. }, repo.MustAllowPulls)
  506. m.Group("", func() {
  507. m.Get("/src/*", repo.SetEditorconfigIfExists, repo.Home)
  508. m.Get("/raw/*", repo.SingleDownload)
  509. m.Get("/commits/*", repo.RefCommits)
  510. m.Get("/graph", repo.Graph)
  511. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
  512. m.Get("/forks", repo.Forks)
  513. }, context.RepoRef())
  514. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.RawDiff)
  515. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.CompareDiff)
  516. }, ignSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  517. m.Group("/:username/:reponame", func() {
  518. m.Get("/stars", repo.Stars)
  519. m.Get("/watchers", repo.Watchers)
  520. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  521. m.Group("/:username", func() {
  522. m.Group("/:reponame", func() {
  523. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  524. m.Get("\\.git$", repo.SetEditorconfigIfExists, repo.Home)
  525. }, ignSignIn, context.RepoAssignment(true), context.RepoRef())
  526. m.Group("/:reponame", func() {
  527. m.Group("/info/lfs", func() {
  528. m.Post("/objects/batch", lfs.BatchHandler)
  529. m.Get("/objects/:oid/:filename", lfs.ObjectOidHandler)
  530. m.Any("/objects/:oid", lfs.ObjectOidHandler)
  531. m.Post("/objects", lfs.PostHandler)
  532. }, ignSignInAndCsrf)
  533. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  534. m.Head("/tasks/trigger", repo.TriggerTask)
  535. })
  536. })
  537. // ***** END: Repository *****
  538. m.Group("/notifications", func() {
  539. m.Get("", user.Notifications)
  540. m.Post("/status", user.NotificationStatusPost)
  541. }, reqSignIn)
  542. m.Group("/api", func() {
  543. apiv1.RegisterRoutes(m)
  544. }, ignSignIn)
  545. // robots.txt
  546. m.Get("/robots.txt", func(ctx *context.Context) {
  547. if setting.HasRobotsTxt {
  548. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  549. } else {
  550. ctx.Error(404)
  551. }
  552. })
  553. // Not found handler.
  554. m.NotFound(routers.NotFound)
  555. // Flag for port number in case first time run conflict.
  556. if ctx.IsSet("port") {
  557. setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, ctx.String("port"), 1)
  558. setting.HTTPPort = ctx.String("port")
  559. }
  560. var listenAddr string
  561. if setting.Protocol == setting.UnixSocket {
  562. listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
  563. } else {
  564. listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
  565. }
  566. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  567. if setting.LFS.StartServer {
  568. log.Info("LFS server enabled")
  569. }
  570. var err error
  571. switch setting.Protocol {
  572. case setting.HTTP:
  573. err = runHTTP(listenAddr, m)
  574. case setting.HTTPS:
  575. err = runHTTPS(listenAddr, setting.CertFile, setting.KeyFile, m)
  576. case setting.FCGI:
  577. err = fcgi.Serve(nil, m)
  578. case setting.UnixSocket:
  579. if err := os.Remove(listenAddr); err != nil {
  580. log.Fatal(4, "Failed to remove unix socket directory %s: %v", listenAddr, err)
  581. }
  582. var listener *net.UnixListener
  583. listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"})
  584. if err != nil {
  585. break // Handle error after switch
  586. }
  587. // FIXME: add proper implementation of signal capture on all protocols
  588. // execute this on SIGTERM or SIGINT: listener.Close()
  589. if err = os.Chmod(listenAddr, os.FileMode(setting.UnixSocketPermission)); err != nil {
  590. log.Fatal(4, "Failed to set permission of unix socket: %v", err)
  591. }
  592. err = http.Serve(listener, m)
  593. default:
  594. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  595. }
  596. if err != nil {
  597. log.Fatal(4, "Failed to start server: %v", err)
  598. }
  599. return nil
  600. }