您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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. if setting.EnableOpenIDSignIn {
  182. m.Combo("/login/openid").
  183. Get(user.SignInOpenID).
  184. Post(bindIgnErr(auth.SignInOpenIDForm{}), user.SignInOpenIDPost)
  185. m.Group("/openid", func() {
  186. m.Combo("/connect").
  187. Get(user.ConnectOpenID).
  188. Post(bindIgnErr(auth.ConnectOpenIDForm{}), user.ConnectOpenIDPost)
  189. m.Combo("/register").
  190. Get(user.RegisterOpenID).
  191. Post(bindIgnErr(auth.SignUpOpenIDForm{}), user.RegisterOpenIDPost)
  192. })
  193. }
  194. m.Get("/sign_up", user.SignUp)
  195. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  196. m.Get("/reset_password", user.ResetPasswd)
  197. m.Post("/reset_password", user.ResetPasswdPost)
  198. m.Group("/oauth2", func() {
  199. m.Get("/:provider", user.SignInOAuth)
  200. m.Get("/:provider/callback", user.SignInOAuthCallback)
  201. })
  202. m.Get("/link_account", user.LinkAccount)
  203. m.Post("/link_account_signin", bindIgnErr(auth.SignInForm{}), user.LinkAccountPostSignIn)
  204. m.Post("/link_account_signup", bindIgnErr(auth.RegisterForm{}), user.LinkAccountPostRegister)
  205. m.Group("/two_factor", func() {
  206. m.Get("", user.TwoFactor)
  207. m.Post("", bindIgnErr(auth.TwoFactorAuthForm{}), user.TwoFactorPost)
  208. m.Get("/scratch", user.TwoFactorScratch)
  209. m.Post("/scratch", bindIgnErr(auth.TwoFactorScratchAuthForm{}), user.TwoFactorScratchPost)
  210. })
  211. }, reqSignOut)
  212. m.Group("/user/settings", func() {
  213. m.Get("", user.Settings)
  214. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  215. m.Combo("/avatar").Get(user.SettingsAvatar).
  216. Post(binding.MultipartForm(auth.AvatarForm{}), user.SettingsAvatarPost)
  217. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  218. m.Combo("/email").Get(user.SettingsEmails).
  219. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  220. m.Post("/email/delete", user.DeleteEmail)
  221. m.Get("/password", user.SettingsPassword)
  222. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  223. if setting.EnableOpenIDSignIn {
  224. m.Group("/openid", func() {
  225. m.Combo("").Get(user.SettingsOpenID).
  226. Post(bindIgnErr(auth.AddOpenIDForm{}), user.SettingsOpenIDPost)
  227. m.Post("/delete", user.DeleteOpenID)
  228. m.Post("/toggle_visibility", user.ToggleOpenIDVisibility)
  229. })
  230. }
  231. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  232. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  233. m.Post("/ssh/delete", user.DeleteSSHKey)
  234. m.Combo("/applications").Get(user.SettingsApplications).
  235. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  236. m.Post("/applications/delete", user.SettingsDeleteApplication)
  237. m.Route("/delete", "GET,POST", user.SettingsDelete)
  238. m.Combo("/account_link").Get(user.SettingsAccountLinks).Post(user.SettingsDeleteAccountLink)
  239. m.Group("/two_factor", func() {
  240. m.Get("", user.SettingsTwoFactor)
  241. m.Post("/regenerate_scratch", user.SettingsTwoFactorRegenerateScratch)
  242. m.Post("/disable", user.SettingsTwoFactorDisable)
  243. m.Get("/enroll", user.SettingsTwoFactorEnroll)
  244. m.Post("/enroll", bindIgnErr(auth.TwoFactorAuthForm{}), user.SettingsTwoFactorEnrollPost)
  245. })
  246. }, reqSignIn, func(ctx *context.Context) {
  247. ctx.Data["PageIsUserSettings"] = true
  248. })
  249. m.Group("/user", func() {
  250. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  251. m.Any("/activate", user.Activate)
  252. m.Any("/activate_email", user.ActivateEmail)
  253. m.Get("/email2user", user.Email2User)
  254. m.Get("/forgot_password", user.ForgotPasswd)
  255. m.Post("/forgot_password", user.ForgotPasswdPost)
  256. m.Get("/logout", user.SignOut)
  257. })
  258. // ***** END: User *****
  259. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  260. // ***** START: Admin *****
  261. m.Group("/admin", func() {
  262. m.Get("", adminReq, admin.Dashboard)
  263. m.Get("/config", admin.Config)
  264. m.Post("/config/test_mail", admin.SendTestMail)
  265. m.Get("/monitor", admin.Monitor)
  266. m.Group("/users", func() {
  267. m.Get("", admin.Users)
  268. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost)
  269. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  270. m.Post("/:userid/delete", admin.DeleteUser)
  271. })
  272. m.Group("/orgs", func() {
  273. m.Get("", admin.Organizations)
  274. })
  275. m.Group("/repos", func() {
  276. m.Get("", admin.Repos)
  277. m.Post("/delete", admin.DeleteRepo)
  278. })
  279. m.Group("/auths", func() {
  280. m.Get("", admin.Authentications)
  281. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  282. m.Combo("/:authid").Get(admin.EditAuthSource).
  283. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  284. m.Post("/:authid/delete", admin.DeleteAuthSource)
  285. })
  286. m.Group("/notices", func() {
  287. m.Get("", admin.Notices)
  288. m.Post("/delete", admin.DeleteNotices)
  289. m.Get("/empty", admin.EmptyNotices)
  290. })
  291. }, adminReq)
  292. // ***** END: Admin *****
  293. m.Group("", func() {
  294. m.Group("/:username", func() {
  295. m.Get("", user.Profile)
  296. m.Get("/followers", user.Followers)
  297. m.Get("/following", user.Following)
  298. })
  299. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  300. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  301. if err != nil {
  302. if models.IsErrAttachmentNotExist(err) {
  303. ctx.Error(404)
  304. } else {
  305. ctx.Handle(500, "GetAttachmentByUUID", err)
  306. }
  307. return
  308. }
  309. fr, err := os.Open(attach.LocalPath())
  310. if err != nil {
  311. ctx.Handle(500, "Open", err)
  312. return
  313. }
  314. defer fr.Close()
  315. if err = repo.ServeData(ctx, attach.Name, fr); err != nil {
  316. ctx.Handle(500, "ServeData", err)
  317. return
  318. }
  319. })
  320. m.Post("/attachments", repo.UploadAttachment)
  321. }, ignSignIn)
  322. m.Group("/:username", func() {
  323. m.Get("/action/:action", user.Action)
  324. }, reqSignIn)
  325. if macaron.Env == macaron.DEV {
  326. m.Get("/template/*", dev.TemplatePreview)
  327. }
  328. reqRepoAdmin := context.RequireRepoAdmin()
  329. reqRepoWriter := context.RequireRepoWriter()
  330. // ***** START: Organization *****
  331. m.Group("/org", func() {
  332. m.Group("", func() {
  333. m.Get("/create", org.Create)
  334. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  335. }, func(ctx *context.Context) {
  336. if !ctx.User.CanCreateOrganization() {
  337. ctx.NotFound()
  338. }
  339. })
  340. m.Group("/:org", func() {
  341. m.Get("/dashboard", user.Dashboard)
  342. m.Get("/^:type(issues|pulls)$", user.Issues)
  343. m.Get("/members", org.Members)
  344. m.Get("/members/action/:action", org.MembersAction)
  345. m.Get("/teams", org.Teams)
  346. }, context.OrgAssignment(true))
  347. m.Group("/:org", func() {
  348. m.Get("/teams/:team", org.TeamMembers)
  349. m.Get("/teams/:team/repositories", org.TeamRepositories)
  350. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  351. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  352. }, context.OrgAssignment(true, false, true))
  353. m.Group("/:org", func() {
  354. m.Get("/teams/new", org.NewTeam)
  355. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  356. m.Get("/teams/:team/edit", org.EditTeam)
  357. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  358. m.Post("/teams/:team/delete", org.DeleteTeam)
  359. m.Group("/settings", func() {
  360. m.Combo("").Get(org.Settings).
  361. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  362. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
  363. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  364. m.Group("/hooks", func() {
  365. m.Get("", org.Webhooks)
  366. m.Post("/delete", org.DeleteWebhook)
  367. m.Get("/:type/new", repo.WebhooksNew)
  368. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  369. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  370. m.Get("/:id", repo.WebHooksEdit)
  371. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  372. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  373. })
  374. m.Route("/delete", "GET,POST", org.SettingsDelete)
  375. })
  376. m.Route("/invitations/new", "GET,POST", org.Invitation)
  377. }, context.OrgAssignment(true, true))
  378. }, reqSignIn)
  379. // ***** END: Organization *****
  380. // ***** START: Repository *****
  381. m.Group("/repo", func() {
  382. m.Get("/create", repo.Create)
  383. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  384. m.Get("/migrate", repo.Migrate)
  385. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  386. m.Combo("/fork/:repoid").Get(repo.Fork).
  387. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  388. }, reqSignIn)
  389. m.Group("/:username/:reponame", func() {
  390. m.Group("/settings", func() {
  391. m.Combo("").Get(repo.Settings).
  392. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  393. m.Group("/collaboration", func() {
  394. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  395. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  396. m.Post("/delete", repo.DeleteCollaboration)
  397. })
  398. m.Group("/branches", func() {
  399. m.Combo("").Get(repo.ProtectedBranch).Post(repo.ProtectedBranchPost)
  400. m.Post("/can_push", repo.ChangeProtectedBranch)
  401. m.Post("/delete", repo.DeleteProtectedBranch)
  402. }, repo.MustBeNotBare)
  403. m.Group("/hooks", func() {
  404. m.Get("", repo.Webhooks)
  405. m.Post("/delete", repo.DeleteWebhook)
  406. m.Get("/:type/new", repo.WebhooksNew)
  407. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  408. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  409. m.Get("/:id", repo.WebHooksEdit)
  410. m.Post("/:id/test", repo.TestWebhook)
  411. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  412. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  413. m.Group("/git", func() {
  414. m.Get("", repo.GitHooks)
  415. m.Combo("/:name").Get(repo.GitHooksEdit).
  416. Post(repo.GitHooksEditPost)
  417. }, context.GitHookService())
  418. })
  419. m.Group("/keys", func() {
  420. m.Combo("").Get(repo.DeployKeys).
  421. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  422. m.Post("/delete", repo.DeleteDeployKey)
  423. })
  424. }, func(ctx *context.Context) {
  425. ctx.Data["PageIsSettings"] = true
  426. }, context.UnitTypes())
  427. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  428. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  429. m.Group("/:username/:reponame", func() {
  430. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  431. // So they can apply their own enable/disable logic on routers.
  432. m.Group("/issues", func() {
  433. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  434. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  435. m.Group("/:index", func() {
  436. m.Post("/title", repo.UpdateIssueTitle)
  437. m.Post("/content", repo.UpdateIssueContent)
  438. m.Combo("/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  439. })
  440. m.Post("/labels", repo.UpdateIssueLabel, reqRepoWriter)
  441. m.Post("/milestone", repo.UpdateIssueMilestone, reqRepoWriter)
  442. m.Post("/assignee", repo.UpdateIssueAssignee, reqRepoWriter)
  443. m.Post("/status", repo.UpdateIssueStatus, reqRepoWriter)
  444. })
  445. m.Group("/comments/:id", func() {
  446. m.Post("", repo.UpdateCommentContent)
  447. m.Post("/delete", repo.DeleteComment)
  448. })
  449. m.Group("/labels", func() {
  450. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  451. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  452. m.Post("/delete", repo.DeleteLabel)
  453. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  454. }, reqRepoWriter, context.RepoRef())
  455. m.Group("/milestones", func() {
  456. m.Combo("/new").Get(repo.NewMilestone).
  457. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  458. m.Get("/:id/edit", repo.EditMilestone)
  459. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  460. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  461. m.Post("/delete", repo.DeleteMilestone)
  462. }, reqRepoWriter, context.RepoRef())
  463. m.Group("/releases", func() {
  464. m.Get("/new", repo.NewRelease)
  465. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  466. m.Post("/delete", repo.DeleteRelease)
  467. }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef())
  468. m.Group("/releases", func() {
  469. m.Get("/edit/*", repo.EditRelease)
  470. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  471. }, repo.MustBeNotBare, reqRepoWriter, func(ctx *context.Context) {
  472. var err error
  473. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  474. if err != nil {
  475. ctx.Handle(500, "GetBranchCommit", err)
  476. return
  477. }
  478. ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
  479. if err != nil {
  480. ctx.Handle(500, "CommitsCount", err)
  481. return
  482. }
  483. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  484. })
  485. m.Combo("/compare/*", repo.MustAllowPulls, repo.SetEditorconfigIfExists).
  486. Get(repo.CompareAndPullRequest).
  487. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  488. m.Group("", func() {
  489. m.Combo("/_edit/*").Get(repo.EditFile).
  490. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  491. m.Combo("/_new/*").Get(repo.NewFile).
  492. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  493. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  494. m.Combo("/_delete/*").Get(repo.DeleteFile).
  495. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  496. m.Group("", func() {
  497. m.Combo("/_upload/*").Get(repo.UploadFile).
  498. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  499. m.Post("/upload-file", repo.UploadFileToServer)
  500. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  501. }, func(ctx *context.Context) {
  502. if !setting.Repository.Upload.Enabled {
  503. ctx.Handle(404, "", nil)
  504. return
  505. }
  506. })
  507. }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(ctx *context.Context) {
  508. if !ctx.Repo.Repository.CanEnableEditor() || ctx.Repo.IsViewCommit {
  509. ctx.Handle(404, "", nil)
  510. return
  511. }
  512. })
  513. }, reqSignIn, context.RepoAssignment(), context.UnitTypes())
  514. m.Group("/:username/:reponame", func() {
  515. m.Group("", func() {
  516. m.Get("/releases", repo.MustBeNotBare, repo.Releases)
  517. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  518. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  519. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  520. m.Get("/milestones", repo.Milestones)
  521. }, context.RepoRef())
  522. // m.Get("/branches", repo.Branches)
  523. m.Post("/branches/:name/delete", reqSignIn, reqRepoWriter, repo.MustBeNotBare, repo.DeleteBranchPost)
  524. m.Group("/wiki", func() {
  525. m.Get("/?:page", repo.Wiki)
  526. m.Get("/_pages", repo.WikiPages)
  527. m.Group("", func() {
  528. m.Combo("/_new").Get(repo.NewWiki).
  529. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  530. m.Combo("/:page/_edit").Get(repo.EditWiki).
  531. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  532. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  533. }, reqSignIn, reqRepoWriter)
  534. }, repo.MustEnableWiki, context.RepoRef())
  535. m.Group("/wiki", func() {
  536. m.Get("/raw/*", repo.WikiRaw)
  537. m.Get("/*", repo.WikiRaw)
  538. }, repo.MustEnableWiki)
  539. m.Get("/archive/*", repo.MustBeNotBare, repo.Download)
  540. m.Group("/pulls/:index", func() {
  541. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  542. m.Get("/files", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ViewPullFiles)
  543. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  544. }, repo.MustAllowPulls)
  545. m.Group("", func() {
  546. m.Get("/src/*", repo.SetEditorconfigIfExists, repo.Home)
  547. m.Get("/raw/*", repo.SingleDownload)
  548. m.Get("/commits/*", repo.RefCommits)
  549. m.Get("/graph", repo.Graph)
  550. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
  551. m.Get("/forks", repo.Forks)
  552. }, context.RepoRef())
  553. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.MustBeNotBare, repo.RawDiff)
  554. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.MustBeNotBare, repo.CompareDiff)
  555. }, ignSignIn, context.RepoAssignment(), context.UnitTypes())
  556. m.Group("/:username/:reponame", func() {
  557. m.Get("/stars", repo.Stars)
  558. m.Get("/watchers", repo.Watchers)
  559. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
  560. m.Group("/:username", func() {
  561. m.Group("/:reponame", func() {
  562. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  563. m.Get("\\.git$", repo.SetEditorconfigIfExists, repo.Home)
  564. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
  565. m.Group("/:reponame", func() {
  566. m.Group("/info/lfs", func() {
  567. m.Post("/objects/batch", lfs.BatchHandler)
  568. m.Get("/objects/:oid/:filename", lfs.ObjectOidHandler)
  569. m.Any("/objects/:oid", lfs.ObjectOidHandler)
  570. m.Post("/objects", lfs.PostHandler)
  571. }, ignSignInAndCsrf)
  572. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  573. m.Head("/tasks/trigger", repo.TriggerTask)
  574. })
  575. })
  576. // ***** END: Repository *****
  577. m.Group("/notifications", func() {
  578. m.Get("", user.Notifications)
  579. m.Post("/status", user.NotificationStatusPost)
  580. }, reqSignIn)
  581. m.Group("/api", func() {
  582. apiv1.RegisterRoutes(m)
  583. }, ignSignIn)
  584. // robots.txt
  585. m.Get("/robots.txt", func(ctx *context.Context) {
  586. if setting.HasRobotsTxt {
  587. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  588. } else {
  589. ctx.Error(404)
  590. }
  591. })
  592. // Not found handler.
  593. m.NotFound(routers.NotFound)
  594. // Flag for port number in case first time run conflict.
  595. if ctx.IsSet("port") {
  596. setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, ctx.String("port"), 1)
  597. setting.HTTPPort = ctx.String("port")
  598. }
  599. var listenAddr string
  600. if setting.Protocol == setting.UnixSocket {
  601. listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
  602. } else {
  603. listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
  604. }
  605. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  606. if setting.LFS.StartServer {
  607. log.Info("LFS server enabled")
  608. }
  609. if setting.EnablePprof {
  610. go func() {
  611. log.Info("%v", http.ListenAndServe("localhost:6060", nil))
  612. }()
  613. }
  614. var err error
  615. switch setting.Protocol {
  616. case setting.HTTP:
  617. err = runHTTP(listenAddr, context2.ClearHandler(m))
  618. case setting.HTTPS:
  619. err = runHTTPS(listenAddr, setting.CertFile, setting.KeyFile, context2.ClearHandler(m))
  620. case setting.FCGI:
  621. err = fcgi.Serve(nil, context2.ClearHandler(m))
  622. case setting.UnixSocket:
  623. if err := os.Remove(listenAddr); err != nil && !os.IsNotExist(err) {
  624. log.Fatal(4, "Failed to remove unix socket directory %s: %v", listenAddr, err)
  625. }
  626. var listener *net.UnixListener
  627. listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"})
  628. if err != nil {
  629. break // Handle error after switch
  630. }
  631. // FIXME: add proper implementation of signal capture on all protocols
  632. // execute this on SIGTERM or SIGINT: listener.Close()
  633. if err = os.Chmod(listenAddr, os.FileMode(setting.UnixSocketPermission)); err != nil {
  634. log.Fatal(4, "Failed to set permission of unix socket: %v", err)
  635. }
  636. err = http.Serve(listener, context2.ClearHandler(m))
  637. default:
  638. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  639. }
  640. if err != nil {
  641. log.Fatal(4, "Failed to start server: %v", err)
  642. }
  643. return nil
  644. }