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 25KB

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