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

web.go 23KB

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