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

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