You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

web.go 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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.Get("/create", org.Create)
  309. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  310. m.Group("/:org", func() {
  311. m.Get("/dashboard", user.Dashboard)
  312. m.Get("/^:type(issues|pulls)$", user.Issues)
  313. m.Get("/members", org.Members)
  314. m.Get("/members/action/:action", org.MembersAction)
  315. m.Get("/teams", org.Teams)
  316. }, context.OrgAssignment(true))
  317. m.Group("/:org", func() {
  318. m.Get("/teams/:team", org.TeamMembers)
  319. m.Get("/teams/:team/repositories", org.TeamRepositories)
  320. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  321. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  322. }, context.OrgAssignment(true, false, true))
  323. m.Group("/:org", func() {
  324. m.Get("/teams/new", org.NewTeam)
  325. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  326. m.Get("/teams/:team/edit", org.EditTeam)
  327. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  328. m.Post("/teams/:team/delete", org.DeleteTeam)
  329. m.Group("/settings", func() {
  330. m.Combo("").Get(org.Settings).
  331. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  332. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
  333. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  334. m.Group("/hooks", func() {
  335. m.Get("", org.Webhooks)
  336. m.Post("/delete", org.DeleteWebhook)
  337. m.Get("/:type/new", repo.WebhooksNew)
  338. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  339. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  340. m.Get("/:id", repo.WebHooksEdit)
  341. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  342. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  343. })
  344. m.Route("/delete", "GET,POST", org.SettingsDelete)
  345. })
  346. m.Route("/invitations/new", "GET,POST", org.Invitation)
  347. }, context.OrgAssignment(true, true))
  348. }, reqSignIn)
  349. // ***** END: Organization *****
  350. // ***** START: Repository *****
  351. m.Group("/repo", func() {
  352. m.Get("/create", repo.Create)
  353. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  354. m.Get("/migrate", repo.Migrate)
  355. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  356. m.Combo("/fork/:repoid").Get(repo.Fork).
  357. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  358. }, reqSignIn)
  359. m.Group("/:username/:reponame", func() {
  360. m.Group("/settings", func() {
  361. m.Combo("").Get(repo.Settings).
  362. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  363. m.Group("/collaboration", func() {
  364. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  365. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  366. m.Post("/delete", repo.DeleteCollaboration)
  367. })
  368. m.Group("/hooks", func() {
  369. m.Get("", repo.Webhooks)
  370. m.Post("/delete", repo.DeleteWebhook)
  371. m.Get("/:type/new", repo.WebhooksNew)
  372. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  373. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  374. m.Get("/:id", repo.WebHooksEdit)
  375. m.Post("/:id/test", repo.TestWebhook)
  376. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  377. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  378. m.Group("/git", func() {
  379. m.Get("", repo.GitHooks)
  380. m.Combo("/:name").Get(repo.GitHooksEdit).
  381. Post(repo.GitHooksEditPost)
  382. }, context.GitHookService())
  383. })
  384. m.Group("/keys", func() {
  385. m.Combo("").Get(repo.DeployKeys).
  386. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  387. m.Post("/delete", repo.DeleteDeployKey)
  388. })
  389. }, func(ctx *context.Context) {
  390. ctx.Data["PageIsSettings"] = true
  391. }, context.UnitTypes())
  392. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  393. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  394. m.Group("/:username/:reponame", func() {
  395. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  396. // So they can apply their own enable/disable logic on routers.
  397. m.Group("/issues", func() {
  398. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  399. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  400. m.Group("/:index", func() {
  401. m.Post("/label", repo.UpdateIssueLabel)
  402. m.Post("/milestone", repo.UpdateIssueMilestone)
  403. m.Post("/assignee", repo.UpdateIssueAssignee)
  404. }, reqRepoWriter)
  405. m.Group("/:index", func() {
  406. m.Post("/title", repo.UpdateIssueTitle)
  407. m.Post("/content", repo.UpdateIssueContent)
  408. m.Combo("/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  409. })
  410. })
  411. m.Group("/comments/:id", func() {
  412. m.Post("", repo.UpdateCommentContent)
  413. m.Post("/delete", repo.DeleteComment)
  414. })
  415. m.Group("/labels", func() {
  416. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  417. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  418. m.Post("/delete", repo.DeleteLabel)
  419. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  420. }, reqRepoWriter, context.RepoRef())
  421. m.Group("/milestones", func() {
  422. m.Combo("/new").Get(repo.NewMilestone).
  423. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  424. m.Get("/:id/edit", repo.EditMilestone)
  425. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  426. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  427. m.Post("/delete", repo.DeleteMilestone)
  428. }, reqRepoWriter, context.RepoRef())
  429. m.Group("/releases", func() {
  430. m.Get("/new", repo.NewRelease)
  431. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  432. m.Post("/delete", repo.DeleteRelease)
  433. }, reqRepoWriter, context.RepoRef())
  434. m.Group("/releases", func() {
  435. m.Get("/edit/*", repo.EditRelease)
  436. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  437. }, reqRepoWriter, func(ctx *context.Context) {
  438. var err error
  439. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  440. if err != nil {
  441. ctx.Handle(500, "GetBranchCommit", err)
  442. return
  443. }
  444. ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
  445. if err != nil {
  446. ctx.Handle(500, "CommitsCount", err)
  447. return
  448. }
  449. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  450. })
  451. m.Combo("/compare/*", repo.MustAllowPulls, repo.SetEditorconfigIfExists).
  452. Get(repo.CompareAndPullRequest).
  453. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  454. m.Group("", func() {
  455. m.Combo("/_edit/*").Get(repo.EditFile).
  456. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  457. m.Combo("/_new/*").Get(repo.NewFile).
  458. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  459. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  460. m.Combo("/_delete/*").Get(repo.DeleteFile).
  461. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  462. m.Group("", func() {
  463. m.Combo("/_upload/*").Get(repo.UploadFile).
  464. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  465. m.Post("/upload-file", repo.UploadFileToServer)
  466. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  467. }, func(ctx *context.Context) {
  468. if !setting.Repository.Upload.Enabled {
  469. ctx.Handle(404, "", nil)
  470. return
  471. }
  472. })
  473. }, reqRepoWriter, context.RepoRef(), func(ctx *context.Context) {
  474. if !ctx.Repo.Repository.CanEnableEditor() || ctx.Repo.IsViewCommit {
  475. ctx.Handle(404, "", nil)
  476. return
  477. }
  478. })
  479. }, reqSignIn, context.RepoAssignment(), repo.MustBeNotBare, context.UnitTypes())
  480. m.Group("/:username/:reponame", func() {
  481. m.Group("", func() {
  482. m.Get("/releases", repo.Releases)
  483. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  484. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  485. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  486. m.Get("/milestones", repo.Milestones)
  487. }, context.RepoRef())
  488. // m.Get("/branches", repo.Branches)
  489. m.Post("/branches/:name/delete", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
  490. m.Group("/wiki", func() {
  491. m.Get("/?:page", repo.Wiki)
  492. m.Get("/_pages", repo.WikiPages)
  493. m.Group("", func() {
  494. m.Combo("/_new").Get(repo.NewWiki).
  495. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  496. m.Combo("/:page/_edit").Get(repo.EditWiki).
  497. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  498. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  499. }, reqSignIn, reqRepoWriter)
  500. }, repo.MustEnableWiki, context.RepoRef())
  501. m.Get("/archive/*", repo.Download)
  502. m.Group("/pulls/:index", func() {
  503. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  504. m.Get("/files", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ViewPullFiles)
  505. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  506. }, repo.MustAllowPulls)
  507. m.Group("", func() {
  508. m.Get("/src/*", repo.SetEditorconfigIfExists, repo.Home)
  509. m.Get("/raw/*", repo.SingleDownload)
  510. m.Get("/commits/*", repo.RefCommits)
  511. m.Get("/graph", repo.Graph)
  512. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
  513. m.Get("/forks", repo.Forks)
  514. }, context.RepoRef())
  515. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.RawDiff)
  516. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.CompareDiff)
  517. }, ignSignIn, context.RepoAssignment(), repo.MustBeNotBare, context.UnitTypes())
  518. m.Group("/:username/:reponame", func() {
  519. m.Get("/stars", repo.Stars)
  520. m.Get("/watchers", repo.Watchers)
  521. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  522. m.Group("/:username", func() {
  523. m.Group("/:reponame", func() {
  524. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  525. m.Get("\\.git$", repo.SetEditorconfigIfExists, repo.Home)
  526. }, ignSignIn, context.RepoAssignment(true), context.RepoRef(), context.UnitTypes())
  527. m.Group("/:reponame", func() {
  528. m.Group("/info/lfs", func() {
  529. m.Post("/objects/batch", lfs.BatchHandler)
  530. m.Get("/objects/:oid/:filename", lfs.ObjectOidHandler)
  531. m.Any("/objects/:oid", lfs.ObjectOidHandler)
  532. m.Post("/objects", lfs.PostHandler)
  533. }, ignSignInAndCsrf)
  534. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  535. m.Head("/tasks/trigger", repo.TriggerTask)
  536. })
  537. })
  538. // ***** END: Repository *****
  539. m.Group("/notifications", func() {
  540. m.Get("", user.Notifications)
  541. m.Post("/status", user.NotificationStatusPost)
  542. }, reqSignIn)
  543. m.Group("/api", func() {
  544. apiv1.RegisterRoutes(m)
  545. }, ignSignIn)
  546. // robots.txt
  547. m.Get("/robots.txt", func(ctx *context.Context) {
  548. if setting.HasRobotsTxt {
  549. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  550. } else {
  551. ctx.Error(404)
  552. }
  553. })
  554. // Not found handler.
  555. m.NotFound(routers.NotFound)
  556. // Flag for port number in case first time run conflict.
  557. if ctx.IsSet("port") {
  558. setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, ctx.String("port"), 1)
  559. setting.HTTPPort = ctx.String("port")
  560. }
  561. var listenAddr string
  562. if setting.Protocol == setting.UnixSocket {
  563. listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
  564. } else {
  565. listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
  566. }
  567. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  568. if setting.LFS.StartServer {
  569. log.Info("LFS server enabled")
  570. }
  571. if setting.EnablePprof {
  572. go func() {
  573. log.Info("%v", http.ListenAndServe("localhost:6060", nil))
  574. }()
  575. }
  576. var err error
  577. switch setting.Protocol {
  578. case setting.HTTP:
  579. err = runHTTP(listenAddr, m)
  580. case setting.HTTPS:
  581. err = runHTTPS(listenAddr, setting.CertFile, setting.KeyFile, m)
  582. case setting.FCGI:
  583. err = fcgi.Serve(nil, m)
  584. case setting.UnixSocket:
  585. if err := os.Remove(listenAddr); err != nil && !os.IsNotExist(err) {
  586. log.Fatal(4, "Failed to remove unix socket directory %s: %v", listenAddr, err)
  587. }
  588. var listener *net.UnixListener
  589. listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"})
  590. if err != nil {
  591. break // Handle error after switch
  592. }
  593. // FIXME: add proper implementation of signal capture on all protocols
  594. // execute this on SIGTERM or SIGINT: listener.Close()
  595. if err = os.Chmod(listenAddr, os.FileMode(setting.UnixSocketPermission)); err != nil {
  596. log.Fatal(4, "Failed to set permission of unix socket: %v", err)
  597. }
  598. err = http.Serve(listener, m)
  599. default:
  600. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  601. }
  602. if err != nil {
  603. log.Fatal(4, "Failed to start server: %v", err)
  604. }
  605. return nil
  606. }