web.go 26 KB

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