web.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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. "crypto/tls"
  7. "fmt"
  8. "io"
  9. "net"
  10. "net/http"
  11. "net/http/fcgi"
  12. "os"
  13. "path/filepath"
  14. "strings"
  15. "github.com/go-macaron/binding"
  16. "github.com/go-macaron/cache"
  17. "github.com/go-macaron/captcha"
  18. "github.com/go-macaron/csrf"
  19. "github.com/go-macaron/gzip"
  20. "github.com/go-macaron/i18n"
  21. "github.com/go-macaron/session"
  22. "github.com/go-macaron/toolbox"
  23. "github.com/prometheus/client_golang/prometheus/promhttp"
  24. "github.com/unknwon/com"
  25. "github.com/urfave/cli"
  26. "gopkg.in/macaron.v1"
  27. log "unknwon.dev/clog/v2"
  28. "gogs.io/gogs/internal/app"
  29. "gogs.io/gogs/internal/assets/public"
  30. "gogs.io/gogs/internal/assets/templates"
  31. "gogs.io/gogs/internal/conf"
  32. "gogs.io/gogs/internal/context"
  33. "gogs.io/gogs/internal/db"
  34. "gogs.io/gogs/internal/form"
  35. "gogs.io/gogs/internal/osutil"
  36. "gogs.io/gogs/internal/route"
  37. "gogs.io/gogs/internal/route/admin"
  38. apiv1 "gogs.io/gogs/internal/route/api/v1"
  39. "gogs.io/gogs/internal/route/dev"
  40. "gogs.io/gogs/internal/route/org"
  41. "gogs.io/gogs/internal/route/repo"
  42. "gogs.io/gogs/internal/route/user"
  43. "gogs.io/gogs/internal/template"
  44. )
  45. var Web = cli.Command{
  46. Name: "web",
  47. Usage: "Start web server",
  48. Description: `Gogs 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. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  53. stringFlag("config, c", "", "Custom configuration file path"),
  54. },
  55. }
  56. // newMacaron initializes Macaron instance.
  57. func newMacaron() *macaron.Macaron {
  58. m := macaron.New()
  59. if !conf.Server.DisableRouterLog {
  60. m.Use(macaron.Logger())
  61. }
  62. m.Use(macaron.Recovery())
  63. if conf.Server.EnableGzip {
  64. m.Use(gzip.Gziper())
  65. }
  66. if conf.Server.Protocol == "fcgi" {
  67. m.SetURLPrefix(conf.Server.Subpath)
  68. }
  69. // Register custom middleware first to make it possible to override files under "public".
  70. m.Use(macaron.Static(
  71. filepath.Join(conf.CustomDir(), "public"),
  72. macaron.StaticOptions{
  73. SkipLogging: conf.Server.DisableRouterLog,
  74. },
  75. ))
  76. var publicFs http.FileSystem
  77. if !conf.Server.LoadAssetsFromDisk {
  78. publicFs = public.NewFileSystem()
  79. }
  80. m.Use(macaron.Static(
  81. filepath.Join(conf.WorkDir(), "public"),
  82. macaron.StaticOptions{
  83. SkipLogging: conf.Server.DisableRouterLog,
  84. FileSystem: publicFs,
  85. },
  86. ))
  87. m.Use(macaron.Static(
  88. conf.Picture.AvatarUploadPath,
  89. macaron.StaticOptions{
  90. Prefix: db.USER_AVATAR_URL_PREFIX,
  91. SkipLogging: conf.Server.DisableRouterLog,
  92. },
  93. ))
  94. m.Use(macaron.Static(
  95. conf.Picture.RepositoryAvatarUploadPath,
  96. macaron.StaticOptions{
  97. Prefix: db.REPO_AVATAR_URL_PREFIX,
  98. SkipLogging: conf.Server.DisableRouterLog,
  99. },
  100. ))
  101. renderOpt := macaron.RenderOptions{
  102. Directory: filepath.Join(conf.WorkDir(), "templates"),
  103. AppendDirectories: []string{filepath.Join(conf.CustomDir(), "templates")},
  104. Funcs: template.FuncMap(),
  105. IndentJSON: macaron.Env != macaron.PROD,
  106. }
  107. if !conf.Server.LoadAssetsFromDisk {
  108. renderOpt.TemplateFileSystem = templates.NewTemplateFileSystem("", renderOpt.AppendDirectories[0])
  109. }
  110. m.Use(macaron.Renderer(renderOpt))
  111. localeNames, err := conf.AssetDir("conf/locale")
  112. if err != nil {
  113. log.Fatal("Failed to list locale files: %v", err)
  114. }
  115. localeFiles := make(map[string][]byte)
  116. for _, name := range localeNames {
  117. localeFiles[name] = conf.MustAsset("conf/locale/" + name)
  118. }
  119. m.Use(i18n.I18n(i18n.Options{
  120. SubURL: conf.Server.Subpath,
  121. Files: localeFiles,
  122. CustomDirectory: filepath.Join(conf.CustomDir(), "conf", "locale"),
  123. Langs: conf.I18n.Langs,
  124. Names: conf.I18n.Names,
  125. DefaultLang: "en-US",
  126. Redirect: true,
  127. }))
  128. m.Use(cache.Cacher(cache.Options{
  129. Adapter: conf.Cache.Adapter,
  130. AdapterConfig: conf.Cache.Host,
  131. Interval: conf.Cache.Interval,
  132. }))
  133. m.Use(captcha.Captchaer(captcha.Options{
  134. SubURL: conf.Server.Subpath,
  135. }))
  136. m.Use(session.Sessioner(session.Options{
  137. Provider: conf.Session.Provider,
  138. ProviderConfig: conf.Session.ProviderConfig,
  139. CookieName: conf.Session.CookieName,
  140. CookiePath: conf.Server.Subpath,
  141. Gclifetime: conf.Session.GCInterval,
  142. Maxlifetime: conf.Session.MaxLifeTime,
  143. Secure: conf.Session.CookieSecure,
  144. }))
  145. m.Use(csrf.Csrfer(csrf.Options{
  146. Secret: conf.Security.SecretKey,
  147. Header: "X-CSRF-Token",
  148. Cookie: conf.Session.CSRFCookieName,
  149. CookieDomain: conf.Server.URL.Hostname(),
  150. CookiePath: conf.Server.Subpath,
  151. CookieHttpOnly: true,
  152. SetCookie: true,
  153. Secure: conf.Server.URL.Scheme == "https",
  154. }))
  155. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  156. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  157. &toolbox.HealthCheckFuncDesc{
  158. Desc: "Database connection",
  159. Func: db.Ping,
  160. },
  161. },
  162. }))
  163. m.Use(context.Contexter())
  164. return m
  165. }
  166. func runWeb(c *cli.Context) error {
  167. err := route.GlobalInit(c.String("config"))
  168. if err != nil {
  169. log.Fatal("Failed to initialize application: %v", err)
  170. }
  171. m := newMacaron()
  172. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  173. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: conf.Auth.RequireSigninView})
  174. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  175. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  176. bindIgnErr := binding.BindIgnErr
  177. m.SetAutoHead(true)
  178. // FIXME: not all route need go through same middlewares.
  179. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  180. // Routers.
  181. m.Get("/", ignSignIn, route.Home)
  182. m.Group("/explore", func() {
  183. m.Get("", func(c *context.Context) {
  184. c.Redirect(conf.Server.Subpath + "/explore/repos")
  185. })
  186. m.Get("/repos", route.ExploreRepos)
  187. m.Get("/users", route.ExploreUsers)
  188. m.Get("/organizations", route.ExploreOrganizations)
  189. }, ignSignIn)
  190. m.Combo("/install", route.InstallInit).Get(route.Install).
  191. Post(bindIgnErr(form.Install{}), route.InstallPost)
  192. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  193. // ***** START: User *****
  194. m.Group("/user", func() {
  195. m.Group("/login", func() {
  196. m.Combo("").Get(user.Login).
  197. Post(bindIgnErr(form.SignIn{}), user.LoginPost)
  198. m.Combo("/two_factor").Get(user.LoginTwoFactor).Post(user.LoginTwoFactorPost)
  199. m.Combo("/two_factor_recovery_code").Get(user.LoginTwoFactorRecoveryCode).Post(user.LoginTwoFactorRecoveryCodePost)
  200. })
  201. m.Get("/sign_up", user.SignUp)
  202. m.Post("/sign_up", bindIgnErr(form.Register{}), user.SignUpPost)
  203. m.Get("/reset_password", user.ResetPasswd)
  204. m.Post("/reset_password", user.ResetPasswdPost)
  205. }, reqSignOut)
  206. m.Group("/user/settings", func() {
  207. m.Get("", user.Settings)
  208. m.Post("", bindIgnErr(form.UpdateProfile{}), user.SettingsPost)
  209. m.Combo("/avatar").Get(user.SettingsAvatar).
  210. Post(binding.MultipartForm(form.Avatar{}), user.SettingsAvatarPost)
  211. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  212. m.Combo("/email").Get(user.SettingsEmails).
  213. Post(bindIgnErr(form.AddEmail{}), user.SettingsEmailPost)
  214. m.Post("/email/delete", user.DeleteEmail)
  215. m.Get("/password", user.SettingsPassword)
  216. m.Post("/password", bindIgnErr(form.ChangePassword{}), user.SettingsPasswordPost)
  217. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  218. Post(bindIgnErr(form.AddSSHKey{}), user.SettingsSSHKeysPost)
  219. m.Post("/ssh/delete", user.DeleteSSHKey)
  220. m.Group("/security", func() {
  221. m.Get("", user.SettingsSecurity)
  222. m.Combo("/two_factor_enable").Get(user.SettingsTwoFactorEnable).
  223. Post(user.SettingsTwoFactorEnablePost)
  224. m.Combo("/two_factor_recovery_codes").Get(user.SettingsTwoFactorRecoveryCodes).
  225. Post(user.SettingsTwoFactorRecoveryCodesPost)
  226. m.Post("/two_factor_disable", user.SettingsTwoFactorDisable)
  227. })
  228. m.Group("/repositories", func() {
  229. m.Get("", user.SettingsRepos)
  230. m.Post("/leave", user.SettingsLeaveRepo)
  231. })
  232. m.Group("/organizations", func() {
  233. m.Get("", user.SettingsOrganizations)
  234. m.Post("/leave", user.SettingsLeaveOrganization)
  235. })
  236. m.Combo("/applications").Get(user.SettingsApplications).
  237. Post(bindIgnErr(form.NewAccessToken{}), user.SettingsApplicationsPost)
  238. m.Post("/applications/delete", user.SettingsDeleteApplication)
  239. m.Route("/delete", "GET,POST", user.SettingsDelete)
  240. }, reqSignIn, func(c *context.Context) {
  241. c.Data["PageIsUserSettings"] = true
  242. })
  243. m.Group("/user", func() {
  244. m.Any("/activate", user.Activate)
  245. m.Any("/activate_email", user.ActivateEmail)
  246. m.Get("/email2user", user.Email2User)
  247. m.Get("/forget_password", user.ForgotPasswd)
  248. m.Post("/forget_password", user.ForgotPasswdPost)
  249. m.Post("/logout", user.SignOut)
  250. })
  251. // ***** END: User *****
  252. reqAdmin := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  253. // ***** START: Admin *****
  254. m.Group("/admin", func() {
  255. m.Combo("").Get(admin.Dashboard).Post(admin.Operation) // "/admin"
  256. m.Get("/config", admin.Config)
  257. m.Post("/config/test_mail", admin.SendTestMail)
  258. m.Get("/monitor", admin.Monitor)
  259. m.Group("/users", func() {
  260. m.Get("", admin.Users)
  261. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(form.AdminCrateUser{}), admin.NewUserPost)
  262. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(form.AdminEditUser{}), admin.EditUserPost)
  263. m.Post("/:userid/delete", admin.DeleteUser)
  264. })
  265. m.Group("/orgs", func() {
  266. m.Get("", admin.Organizations)
  267. })
  268. m.Group("/repos", func() {
  269. m.Get("", admin.Repos)
  270. m.Post("/delete", admin.DeleteRepo)
  271. })
  272. m.Group("/auths", func() {
  273. m.Get("", admin.Authentications)
  274. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(form.Authentication{}), admin.NewAuthSourcePost)
  275. m.Combo("/:authid").Get(admin.EditAuthSource).
  276. Post(bindIgnErr(form.Authentication{}), admin.EditAuthSourcePost)
  277. m.Post("/:authid/delete", admin.DeleteAuthSource)
  278. })
  279. m.Group("/notices", func() {
  280. m.Get("", admin.Notices)
  281. m.Post("/delete", admin.DeleteNotices)
  282. m.Get("/empty", admin.EmptyNotices)
  283. })
  284. }, reqAdmin)
  285. // ***** END: Admin *****
  286. m.Group("", func() {
  287. m.Group("/:username", func() {
  288. m.Get("", user.Profile)
  289. m.Get("/followers", user.Followers)
  290. m.Get("/following", user.Following)
  291. m.Get("/stars", user.Stars)
  292. }, context.InjectParamsUser())
  293. m.Get("/attachments/:uuid", func(c *context.Context) {
  294. attach, err := db.GetAttachmentByUUID(c.Params(":uuid"))
  295. if err != nil {
  296. c.NotFoundOrError(err, "get attachment by UUID")
  297. return
  298. } else if !com.IsFile(attach.LocalPath()) {
  299. c.NotFound()
  300. return
  301. }
  302. fr, err := os.Open(attach.LocalPath())
  303. if err != nil {
  304. c.Error(err, "open attachment file")
  305. return
  306. }
  307. defer fr.Close()
  308. c.Header().Set("Cache-Control", "public,max-age=86400")
  309. c.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name))
  310. if _, err = io.Copy(c.Resp, fr); err != nil {
  311. c.Error(err, "copy from file to response")
  312. return
  313. }
  314. })
  315. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  316. m.Post("/releases/attachments", repo.UploadReleaseAttachment)
  317. }, ignSignIn)
  318. m.Group("/:username", func() {
  319. m.Post("/action/:action", user.Action)
  320. }, reqSignIn, context.InjectParamsUser())
  321. if macaron.Env == macaron.DEV {
  322. m.Get("/template/*", dev.TemplatePreview)
  323. }
  324. reqRepoAdmin := context.RequireRepoAdmin()
  325. reqRepoWriter := context.RequireRepoWriter()
  326. webhookRoutes := func() {
  327. m.Group("", func() {
  328. m.Get("", repo.Webhooks)
  329. m.Post("/delete", repo.DeleteWebhook)
  330. m.Get("/:type/new", repo.WebhooksNew)
  331. m.Post("/gogs/new", bindIgnErr(form.NewWebhook{}), repo.WebhooksNewPost)
  332. m.Post("/slack/new", bindIgnErr(form.NewSlackHook{}), repo.WebhooksSlackNewPost)
  333. m.Post("/discord/new", bindIgnErr(form.NewDiscordHook{}), repo.WebhooksDiscordNewPost)
  334. m.Post("/dingtalk/new", bindIgnErr(form.NewDingtalkHook{}), repo.WebhooksDingtalkNewPost)
  335. m.Get("/:id", repo.WebhooksEdit)
  336. m.Post("/gogs/:id", bindIgnErr(form.NewWebhook{}), repo.WebhooksEditPost)
  337. m.Post("/slack/:id", bindIgnErr(form.NewSlackHook{}), repo.WebhooksSlackEditPost)
  338. m.Post("/discord/:id", bindIgnErr(form.NewDiscordHook{}), repo.WebhooksDiscordEditPost)
  339. m.Post("/dingtalk/:id", bindIgnErr(form.NewDingtalkHook{}), repo.WebhooksDingtalkEditPost)
  340. }, repo.InjectOrgRepoContext())
  341. }
  342. // ***** START: Organization *****
  343. m.Group("/org", func() {
  344. m.Group("", func() {
  345. m.Get("/create", org.Create)
  346. m.Post("/create", bindIgnErr(form.CreateOrg{}), org.CreatePost)
  347. }, func(c *context.Context) {
  348. if !c.User.CanCreateOrganization() {
  349. c.NotFound()
  350. }
  351. })
  352. m.Group("/:org", func() {
  353. m.Get("/dashboard", user.Dashboard)
  354. m.Get("/^:type(issues|pulls)$", user.Issues)
  355. m.Get("/members", org.Members)
  356. m.Get("/members/action/:action", org.MembersAction)
  357. m.Get("/teams", org.Teams)
  358. }, context.OrgAssignment(true))
  359. m.Group("/:org", func() {
  360. m.Get("/teams/:team", org.TeamMembers)
  361. m.Get("/teams/:team/repositories", org.TeamRepositories)
  362. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  363. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  364. }, context.OrgAssignment(true, false, true))
  365. m.Group("/:org", func() {
  366. m.Get("/teams/new", org.NewTeam)
  367. m.Post("/teams/new", bindIgnErr(form.CreateTeam{}), org.NewTeamPost)
  368. m.Get("/teams/:team/edit", org.EditTeam)
  369. m.Post("/teams/:team/edit", bindIgnErr(form.CreateTeam{}), org.EditTeamPost)
  370. m.Post("/teams/:team/delete", org.DeleteTeam)
  371. m.Group("/settings", func() {
  372. m.Combo("").Get(org.Settings).
  373. Post(bindIgnErr(form.UpdateOrgSetting{}), org.SettingsPost)
  374. m.Post("/avatar", binding.MultipartForm(form.Avatar{}), org.SettingsAvatar)
  375. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  376. m.Group("/hooks", webhookRoutes)
  377. m.Route("/delete", "GET,POST", org.SettingsDelete)
  378. })
  379. m.Route("/invitations/new", "GET,POST", org.Invitation)
  380. }, context.OrgAssignment(true, true))
  381. }, reqSignIn)
  382. // ***** END: Organization *****
  383. // ***** START: Repository *****
  384. m.Group("/repo", func() {
  385. m.Get("/create", repo.Create)
  386. m.Post("/create", bindIgnErr(form.CreateRepo{}), repo.CreatePost)
  387. m.Get("/migrate", repo.Migrate)
  388. m.Post("/migrate", bindIgnErr(form.MigrateRepo{}), repo.MigratePost)
  389. m.Combo("/fork/:repoid").Get(repo.Fork).
  390. Post(bindIgnErr(form.CreateRepo{}), repo.ForkPost)
  391. }, reqSignIn)
  392. m.Group("/:username/:reponame", func() {
  393. m.Group("/settings", func() {
  394. m.Combo("").Get(repo.Settings).
  395. Post(bindIgnErr(form.RepoSetting{}), repo.SettingsPost)
  396. m.Combo("/avatar").Get(repo.SettingsAvatar).
  397. Post(binding.MultipartForm(form.Avatar{}), repo.SettingsAvatarPost)
  398. m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  399. m.Group("/collaboration", func() {
  400. m.Combo("").Get(repo.SettingsCollaboration).Post(repo.SettingsCollaborationPost)
  401. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  402. m.Post("/delete", repo.DeleteCollaboration)
  403. })
  404. m.Group("/branches", func() {
  405. m.Get("", repo.SettingsBranches)
  406. m.Post("/default_branch", repo.UpdateDefaultBranch)
  407. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  408. Post(bindIgnErr(form.ProtectBranch{}), repo.SettingsProtectedBranchPost)
  409. }, func(c *context.Context) {
  410. if c.Repo.Repository.IsMirror {
  411. c.NotFound()
  412. return
  413. }
  414. })
  415. m.Group("/hooks", func() {
  416. webhookRoutes()
  417. m.Group("/:id", func() {
  418. m.Post("/test", repo.TestWebhook)
  419. m.Post("/redelivery", repo.RedeliveryWebhook)
  420. })
  421. m.Group("/git", func() {
  422. m.Get("", repo.SettingsGitHooks)
  423. m.Combo("/:name").Get(repo.SettingsGitHooksEdit).
  424. Post(repo.SettingsGitHooksEditPost)
  425. }, context.GitHookService())
  426. })
  427. m.Group("/keys", func() {
  428. m.Combo("").Get(repo.SettingsDeployKeys).
  429. Post(bindIgnErr(form.AddSSHKey{}), repo.SettingsDeployKeysPost)
  430. m.Post("/delete", repo.DeleteDeployKey)
  431. })
  432. }, func(c *context.Context) {
  433. c.Data["PageIsSettings"] = true
  434. })
  435. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  436. m.Post("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  437. m.Group("/:username/:reponame", func() {
  438. m.Get("/issues", repo.RetrieveLabels, repo.Issues)
  439. m.Get("/issues/:index", repo.ViewIssue)
  440. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  441. m.Get("/milestones", repo.Milestones)
  442. }, ignSignIn, context.RepoAssignment(true))
  443. m.Group("/:username/:reponame", func() {
  444. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  445. // So they can apply their own enable/disable logic on routers.
  446. m.Group("/issues", func() {
  447. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  448. Post(bindIgnErr(form.NewIssue{}), repo.NewIssuePost)
  449. m.Group("/:index", func() {
  450. m.Post("/title", repo.UpdateIssueTitle)
  451. m.Post("/content", repo.UpdateIssueContent)
  452. m.Combo("/comments").Post(bindIgnErr(form.CreateComment{}), repo.NewComment)
  453. })
  454. })
  455. m.Group("/comments/:id", func() {
  456. m.Post("", repo.UpdateCommentContent)
  457. m.Post("/delete", repo.DeleteComment)
  458. })
  459. }, reqSignIn, context.RepoAssignment(true))
  460. m.Group("/:username/:reponame", func() {
  461. m.Group("/wiki", func() {
  462. m.Get("/?:page", repo.Wiki)
  463. m.Get("/_pages", repo.WikiPages)
  464. }, repo.MustEnableWiki, context.RepoRef())
  465. }, ignSignIn, context.RepoAssignment(false, true))
  466. m.Group("/:username/:reponame", func() {
  467. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  468. // So they can apply their own enable/disable logic on routers.
  469. m.Group("/issues", func() {
  470. m.Group("/:index", func() {
  471. m.Post("/label", repo.UpdateIssueLabel)
  472. m.Post("/milestone", repo.UpdateIssueMilestone)
  473. m.Post("/assignee", repo.UpdateIssueAssignee)
  474. }, reqRepoWriter)
  475. })
  476. m.Group("/labels", func() {
  477. m.Post("/new", bindIgnErr(form.CreateLabel{}), repo.NewLabel)
  478. m.Post("/edit", bindIgnErr(form.CreateLabel{}), repo.UpdateLabel)
  479. m.Post("/delete", repo.DeleteLabel)
  480. m.Post("/initialize", bindIgnErr(form.InitializeLabels{}), repo.InitializeLabels)
  481. }, reqRepoWriter, context.RepoRef())
  482. m.Group("/milestones", func() {
  483. m.Combo("/new").Get(repo.NewMilestone).
  484. Post(bindIgnErr(form.CreateMilestone{}), repo.NewMilestonePost)
  485. m.Get("/:id/edit", repo.EditMilestone)
  486. m.Post("/:id/edit", bindIgnErr(form.CreateMilestone{}), repo.EditMilestonePost)
  487. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  488. m.Post("/delete", repo.DeleteMilestone)
  489. }, reqRepoWriter, context.RepoRef())
  490. m.Group("/releases", func() {
  491. m.Get("/new", repo.NewRelease)
  492. m.Post("/new", bindIgnErr(form.NewRelease{}), repo.NewReleasePost)
  493. m.Post("/delete", repo.DeleteRelease)
  494. m.Get("/edit/*", repo.EditRelease)
  495. m.Post("/edit/*", bindIgnErr(form.EditRelease{}), repo.EditReleasePost)
  496. }, repo.MustBeNotBare, reqRepoWriter, func(c *context.Context) {
  497. c.Data["PageIsViewFiles"] = true
  498. })
  499. // FIXME: Should use c.Repo.PullRequest to unify template, currently we have inconsistent URL
  500. // for PR in same repository. After select branch on the page, the URL contains redundant head user name.
  501. // e.g. /org1/test-repo/compare/master...org1:develop
  502. // which should be /org1/test-repo/compare/master...develop
  503. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  504. Post(bindIgnErr(form.NewIssue{}), repo.CompareAndPullRequestPost)
  505. m.Group("", func() {
  506. m.Combo("/_edit/*").Get(repo.EditFile).
  507. Post(bindIgnErr(form.EditRepoFile{}), repo.EditFilePost)
  508. m.Combo("/_new/*").Get(repo.NewFile).
  509. Post(bindIgnErr(form.EditRepoFile{}), repo.NewFilePost)
  510. m.Post("/_preview/*", bindIgnErr(form.EditPreviewDiff{}), repo.DiffPreviewPost)
  511. m.Combo("/_delete/*").Get(repo.DeleteFile).
  512. Post(bindIgnErr(form.DeleteRepoFile{}), repo.DeleteFilePost)
  513. m.Group("", func() {
  514. m.Combo("/_upload/*").Get(repo.UploadFile).
  515. Post(bindIgnErr(form.UploadRepoFile{}), repo.UploadFilePost)
  516. m.Post("/upload-file", repo.UploadFileToServer)
  517. m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer)
  518. }, func(c *context.Context) {
  519. if !conf.Repository.Upload.Enabled {
  520. c.NotFound()
  521. return
  522. }
  523. })
  524. }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(c *context.Context) {
  525. if !c.Repo.CanEnableEditor() {
  526. c.NotFound()
  527. return
  528. }
  529. c.Data["PageIsViewFiles"] = true
  530. })
  531. }, reqSignIn, context.RepoAssignment())
  532. m.Group("/:username/:reponame", func() {
  533. m.Group("", func() {
  534. m.Get("/releases", repo.MustBeNotBare, repo.Releases)
  535. m.Get("/pulls", repo.RetrieveLabels, repo.Pulls)
  536. m.Get("/pulls/:index", repo.ViewPull)
  537. }, context.RepoRef())
  538. m.Group("/branches", func() {
  539. m.Get("", repo.Branches)
  540. m.Get("/all", repo.AllBranches)
  541. m.Post("/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
  542. }, repo.MustBeNotBare, func(c *context.Context) {
  543. c.Data["PageIsViewFiles"] = true
  544. })
  545. m.Group("/wiki", func() {
  546. m.Group("", func() {
  547. m.Combo("/_new").Get(repo.NewWiki).
  548. Post(bindIgnErr(form.NewWiki{}), repo.NewWikiPost)
  549. m.Combo("/:page/_edit").Get(repo.EditWiki).
  550. Post(bindIgnErr(form.NewWiki{}), repo.EditWikiPost)
  551. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  552. }, reqSignIn, reqRepoWriter)
  553. }, repo.MustEnableWiki, context.RepoRef())
  554. m.Get("/archive/*", repo.MustBeNotBare, repo.Download)
  555. m.Group("/pulls/:index", func() {
  556. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  557. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  558. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  559. }, repo.MustAllowPulls)
  560. m.Group("", func() {
  561. m.Get("/src/*", repo.Home)
  562. m.Get("/raw/*", repo.SingleDownload)
  563. m.Get("/commits/*", repo.RefCommits)
  564. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.Diff)
  565. m.Get("/forks", repo.Forks)
  566. }, repo.MustBeNotBare, context.RepoRef())
  567. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.MustBeNotBare, repo.RawDiff)
  568. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.MustBeNotBare, context.RepoRef(), repo.CompareDiff)
  569. }, ignSignIn, context.RepoAssignment())
  570. m.Group("/:username/:reponame", func() {
  571. m.Get("/stars", repo.Stars)
  572. m.Get("/watchers", repo.Watchers)
  573. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  574. m.Group("/:username", func() {
  575. m.Get("/:reponame", ignSignIn, context.RepoAssignment(), context.RepoRef(), repo.Home)
  576. m.Group("/:reponame", func() {
  577. m.Head("/tasks/trigger", repo.TriggerTask)
  578. })
  579. // Use the regexp to match the repository name
  580. // Duplicated route to enable different ways of accessing same set of URLs,
  581. // e.g. with or without ".git" suffix.
  582. m.Group("/:reponame([\\d\\w-_\\.]+\\.git$)", func() {
  583. m.Get("", ignSignIn, context.RepoAssignment(), context.RepoRef(), repo.Home)
  584. m.Options("/*", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  585. m.Route("/*", "GET,POST", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  586. })
  587. m.Options("/:reponame/*", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  588. m.Route("/:reponame/*", "GET,POST", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  589. })
  590. // ***** END: Repository *****
  591. m.Group("/api", func() {
  592. apiv1.RegisterRoutes(m)
  593. }, ignSignIn)
  594. // ***************************
  595. // ----- Internal routes -----
  596. // ***************************
  597. m.Group("/-", func() {
  598. m.Get("/metrics", app.MetricsFilter(), promhttp.Handler()) // "/-/metrics"
  599. m.Group("/api", func() {
  600. m.Post("/sanitize_ipynb", app.SanitizeIpynb()) // "/-/api/sanitize_ipynb"
  601. })
  602. })
  603. // robots.txt
  604. m.Get("/robots.txt", func(c *context.Context) {
  605. if conf.HasRobotsTxt {
  606. c.ServeFileContent(filepath.Join(conf.CustomDir(), "robots.txt"))
  607. } else {
  608. c.NotFound()
  609. }
  610. })
  611. // Not found handler.
  612. m.NotFound(route.NotFound)
  613. // Flag for port number in case first time run conflict.
  614. if c.IsSet("port") {
  615. conf.Server.URL.Host = strings.Replace(conf.Server.URL.Host, ":"+conf.Server.URL.Port(), ":"+c.String("port"), 1)
  616. conf.Server.ExternalURL = conf.Server.URL.String()
  617. conf.Server.HTTPPort = c.String("port")
  618. }
  619. var listenAddr string
  620. if conf.Server.Protocol == "unix" {
  621. listenAddr = conf.Server.HTTPAddr
  622. log.Info("Listen on %v://%s", conf.Server.Protocol, listenAddr)
  623. } else {
  624. listenAddr = fmt.Sprintf("%s:%s", conf.Server.HTTPAddr, conf.Server.HTTPPort)
  625. log.Info("Listen on %v://%s%s", conf.Server.Protocol, listenAddr, conf.Server.Subpath)
  626. }
  627. switch conf.Server.Protocol {
  628. case "http":
  629. err = http.ListenAndServe(listenAddr, m)
  630. case "https":
  631. tlsMinVersion := tls.VersionTLS12
  632. switch conf.Server.TLSMinVersion {
  633. case "TLS13":
  634. tlsMinVersion = tls.VersionTLS13
  635. case "TLS12":
  636. tlsMinVersion = tls.VersionTLS12
  637. case "TLS11":
  638. tlsMinVersion = tls.VersionTLS11
  639. case "TLS10":
  640. tlsMinVersion = tls.VersionTLS10
  641. }
  642. server := &http.Server{
  643. Addr: listenAddr,
  644. TLSConfig: &tls.Config{
  645. MinVersion: uint16(tlsMinVersion),
  646. CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384, tls.CurveP521},
  647. PreferServerCipherSuites: true,
  648. CipherSuites: []uint16{
  649. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  650. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  651. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  652. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  653. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  654. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  655. },
  656. }, Handler: m}
  657. err = server.ListenAndServeTLS(conf.Server.CertFile, conf.Server.KeyFile)
  658. case "fcgi":
  659. err = fcgi.Serve(nil, m)
  660. case "unix":
  661. if osutil.IsExist(listenAddr) {
  662. err = os.Remove(listenAddr)
  663. if err != nil {
  664. log.Fatal("Failed to remove existing Unix domain socket: %v", err)
  665. }
  666. }
  667. var listener *net.UnixListener
  668. listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"})
  669. if err != nil {
  670. log.Fatal("Failed to listen on Unix networks: %v", err)
  671. }
  672. // FIXME: add proper implementation of signal capture on all protocols
  673. // execute this on SIGTERM or SIGINT: listener.Close()
  674. if err = os.Chmod(listenAddr, conf.Server.UnixSocketMode); err != nil {
  675. log.Fatal("Failed to change permission of Unix domain socket: %v", err)
  676. }
  677. err = http.Serve(listener, m)
  678. default:
  679. log.Fatal("Unexpected server protocol: %s", conf.Server.Protocol)
  680. }
  681. if err != nil {
  682. log.Fatal("Failed to start server: %v", err)
  683. }
  684. return nil
  685. }
PANIC: session(release): write data/sessions/c/b/cb5f1f6191727abb: no space left on device

PANIC

session(release): write data/sessions/c/b/cb5f1f6191727abb: no space left on device
github.com/go-macaron/session@v0.0.0-20190805070824-1a3cdc6f5659/session.go:199 (0x8b2934)
gopkg.in/macaron.v1@v1.3.9/context.go:79 (0x83d0a0)
github.com/go-macaron/inject@v0.0.0-20160627170012-d8a0b8677191/inject.go:157 (0x80ab07)
github.com/go-macaron/inject@v0.0.0-20160627170012-d8a0b8677191/inject.go:135 (0x80a8a8)
gopkg.in/macaron.v1@v1.3.9/context.go:121 (0x83d1f8)
gopkg.in/macaron.v1@v1.3.9/context.go:112 (0x84fdb5)
gopkg.in/macaron.v1@v1.3.9/recovery.go:161 (0x84fda8)
gopkg.in/macaron.v1@v1.3.9/logger.go:40 (0x840c73)
github.com/go-macaron/inject@v0.0.0-20160627170012-d8a0b8677191/inject.go:157 (0x80ab07)
github.com/go-macaron/inject@v0.0.0-20160627170012-d8a0b8677191/inject.go:135 (0x80a8a8)
gopkg.in/macaron.v1@v1.3.9/context.go:121 (0x83d1f8)
gopkg.in/macaron.v1@v1.3.9/router.go:187 (0x850fc6)
gopkg.in/macaron.v1@v1.3.9/router.go:303 (0x8493e5)
gopkg.in/macaron.v1@v1.3.9/macaron.go:220 (0x841fca)
net/http/server.go:2836 (0x7a79b2)
net/http/server.go:1924 (0x7a341b)
runtime/asm_amd64.s:1373 (0x46f9f0)