web.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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. Config: session.MemoryConfig{},
  162. Cookie: session.CookieOptions{
  163. Name: conf.Session.CookieName,
  164. Path: conf.Server.Subpath,
  165. MaxAge: int(conf.Session.MaxLifeTime),
  166. Secure: conf.Session.CookieSecure,
  167. },
  168. }))
  169. f.Use(csrf.Csrfer(csrf.Options{
  170. Secret: conf.Security.SecretKey,
  171. Header: "X-CSRF-Token",
  172. }))
  173. f.Use(context.Contexter(context.NewStore()))
  174. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  175. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: conf.Auth.RequireSigninView})
  176. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  177. f.Get("/", ignSignIn, route.Home)
  178. f.Group("/explore", func() {
  179. f.Get("", func(c *context.Context) {
  180. c.Redirect(conf.Server.Subpath + "/explore/repos")
  181. })
  182. f.Get("/repos", route.ExploreRepos)
  183. f.Get("/users", route.ExploreUsers)
  184. f.Get("/organizations", route.ExploreOrganizations)
  185. }, ignSignIn)
  186. f.Combo("/install", route.InstallInit).Get(route.Install).
  187. Post(binding.Form(form.Install{}), route.InstallPost)
  188. f.Get("/<type:issues|pulls>", reqSignIn, user.Issues)
  189. // ***** START: User *****
  190. f.Group("/user", func() {
  191. f.Group("/login", func() {
  192. f.Combo("").Get(user.Login).
  193. Post(binding.Form(form.SignIn{}), user.LoginPost)
  194. f.Combo("/two_factor").Get(user.LoginTwoFactor).Post(user.LoginTwoFactorPost)
  195. f.Combo("/two_factor_recovery_code").Get(user.LoginTwoFactorRecoveryCode).Post(user.LoginTwoFactorRecoveryCodePost)
  196. })
  197. f.Get("/sign_up", user.SignUp)
  198. f.Post("/sign_up", binding.Form(form.Register{}), user.SignUpPost)
  199. f.Get("/reset_password", user.ResetPasswd)
  200. f.Post("/reset_password", user.ResetPasswdPost)
  201. }, reqSignOut)
  202. f.Group("/user/settings", func() {
  203. f.Get("", user.Settings)
  204. f.Post("", binding.Form(form.UpdateProfile{}), user.SettingsPost)
  205. f.Combo("/avatar").Get(user.SettingsAvatar).
  206. Post(binding.Form(form.Avatar{}), user.SettingsAvatarPost)
  207. f.Post("/avatar/delete", user.SettingsDeleteAvatar)
  208. f.Combo("/email").Get(user.SettingsEmails).
  209. Post(binding.Form(form.AddEmail{}), user.SettingsEmailPost)
  210. f.Post("/email/delete", user.DeleteEmail)
  211. f.Get("/password", user.SettingsPassword)
  212. f.Post("/password", binding.Form(form.ChangePassword{}), user.SettingsPasswordPost)
  213. f.Combo("/ssh").Get(user.SettingsSSHKeys).
  214. Post(binding.Form(form.AddSSHKey{}), user.SettingsSSHKeysPost)
  215. f.Post("/ssh/delete", user.DeleteSSHKey)
  216. f.Group("/security", func() {
  217. f.Get("", user.SettingsSecurity)
  218. f.Combo("/two_factor_enable").Get(user.SettingsTwoFactorEnable).
  219. Post(user.SettingsTwoFactorEnablePost)
  220. f.Combo("/two_factor_recovery_codes").Get(user.SettingsTwoFactorRecoveryCodes).
  221. Post(user.SettingsTwoFactorRecoveryCodesPost)
  222. f.Post("/two_factor_disable", user.SettingsTwoFactorDisable)
  223. })
  224. f.Group("/repositories", func() {
  225. f.Get("", user.SettingsRepos)
  226. f.Post("/leave", user.SettingsLeaveRepo)
  227. })
  228. f.Group("/organizations", func() {
  229. f.Get("", user.SettingsOrganizations)
  230. f.Post("/leave", user.SettingsLeaveOrganization)
  231. })
  232. settingsHandler := user.NewSettingsHandler(user.NewSettingsStore())
  233. f.Combo("/applications").Get(settingsHandler.Applications()).
  234. Post(binding.Form(form.NewAccessToken{}), settingsHandler.ApplicationsPost())
  235. f.Post("/applications/delete", settingsHandler.DeleteApplication())
  236. f.Route("/delete", "GET,POST", user.SettingsDelete)
  237. }, reqSignIn, func(c *context.Context) {
  238. c.Data["PageIsUserSettings"] = true
  239. })
  240. f.Group("/user", func() {
  241. f.Any("/activate", user.Activate)
  242. f.Any("/activate_email", user.ActivateEmail)
  243. f.Get("/email2user", user.Email2User)
  244. f.Get("/forget_password", user.ForgotPasswd)
  245. f.Post("/forget_password", user.ForgotPasswdPost)
  246. f.Post("/logout", user.SignOut)
  247. })
  248. // ***** END: User *****
  249. reqAdmin := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  250. // ***** START: Admin *****
  251. f.Group("/admin", func() {
  252. f.Combo("").Get(admin.Dashboard).Post(admin.Operation) // "/admin"
  253. f.Get("/config", admin.Config)
  254. f.Post("/config/test_mail", admin.SendTestMail)
  255. f.Get("/monitor", admin.Monitor)
  256. f.Group("/users", func() {
  257. f.Get("", admin.Users)
  258. f.Combo("/new").Get(admin.NewUser).Post(binding.Form(form.AdminCrateUser{}), admin.NewUserPost)
  259. f.Combo("/<userid>").Get(admin.EditUser).Post(binding.Form(form.AdminEditUser{}), admin.EditUserPost)
  260. f.Post("/<userid>/delete", admin.DeleteUser)
  261. })
  262. f.Group("/orgs", func() {
  263. f.Get("", admin.Organizations)
  264. })
  265. f.Group("/repos", func() {
  266. f.Get("", admin.Repos)
  267. f.Post("/delete", admin.DeleteRepo)
  268. })
  269. f.Group("/auths", func() {
  270. f.Get("", admin.Authentications)
  271. f.Combo("/new").Get(admin.NewAuthSource).Post(binding.Form(form.Authentication{}), admin.NewAuthSourcePost)
  272. f.Combo("/<authid>").Get(admin.EditAuthSource).
  273. Post(binding.Form(form.Authentication{}), admin.EditAuthSourcePost)
  274. f.Post("/<authid>/delete", admin.DeleteAuthSource)
  275. })
  276. f.Group("/notices", func() {
  277. f.Get("", admin.Notices)
  278. f.Post("/delete", admin.DeleteNotices)
  279. f.Get("/empty", admin.EmptyNotices)
  280. })
  281. }, reqAdmin)
  282. // ***** END: Admin *****
  283. f.Group("", func() {
  284. f.Group("/<username>", func() {
  285. f.Get("", user.Profile)
  286. f.Get("/followers", user.Followers)
  287. f.Get("/following", user.Following)
  288. f.Get("/stars", user.Stars)
  289. }, context.InjectParamsUser())
  290. f.Get("/attachments/<uuid>", func(c *context.Context) {
  291. attach, err := database.GetAttachmentByUUID(c.Param("uuid"))
  292. if err != nil {
  293. c.NotFoundOrError(err, "get attachment by UUID")
  294. return
  295. } else if !com.IsFile(attach.LocalPath()) {
  296. c.NotFound()
  297. return
  298. }
  299. fr, err := os.Open(attach.LocalPath())
  300. if err != nil {
  301. c.Error(err, "open attachment file")
  302. return
  303. }
  304. defer fr.Close()
  305. c.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox")
  306. c.Header().Set("Cache-Control", "public,max-age=86400")
  307. c.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name))
  308. if _, err = io.Copy(c.Resp, fr); err != nil {
  309. c.Error(err, "copy from file to response")
  310. return
  311. }
  312. })
  313. f.Post("/issues/attachments", repo.UploadIssueAttachment)
  314. f.Post("/releases/attachments", repo.UploadReleaseAttachment)
  315. }, ignSignIn)
  316. f.Group("/<username>", func() {
  317. f.Post("/action/<action>", user.Action)
  318. }, reqSignIn, context.InjectParamsUser())
  319. if conf.IsProdMode() {
  320. f.Get("/template/*", dev.TemplatePreview)
  321. }
  322. reqRepoAdmin := context.RequireRepoAdmin()
  323. reqRepoWriter := context.RequireRepoWriter()
  324. webhookRoutes := func() {
  325. f.Group("", func() {
  326. f.Get("", repo.Webhooks)
  327. f.Post("/delete", repo.DeleteWebhook)
  328. f.Get("/<type>/new", repo.WebhooksNew)
  329. f.Post("/gogs/new", binding.Form(form.NewWebhook{}), repo.WebhooksNewPost)
  330. f.Post("/slack/new", binding.Form(form.NewSlackHook{}), repo.WebhooksSlackNewPost)
  331. f.Post("/discord/new", binding.Form(form.NewDiscordHook{}), repo.WebhooksDiscordNewPost)
  332. f.Post("/dingtalk/new", binding.Form(form.NewDingtalkHook{}), repo.WebhooksDingtalkNewPost)
  333. f.Get("/<id>", repo.WebhooksEdit)
  334. f.Post("/gogs/<id>", binding.Form(form.NewWebhook{}), repo.WebhooksEditPost)
  335. f.Post("/slack/<id>", binding.Form(form.NewSlackHook{}), repo.WebhooksSlackEditPost)
  336. f.Post("/discord/<id>", binding.Form(form.NewDiscordHook{}), repo.WebhooksDiscordEditPost)
  337. f.Post("/dingtalk/<id>", binding.Form(form.NewDingtalkHook{}), repo.WebhooksDingtalkEditPost)
  338. }, repo.InjectOrgRepoContext())
  339. }
  340. // ***** START: Organization *****
  341. f.Group("/org", func() {
  342. f.Group("", func() {
  343. f.Get("/create", org.Create)
  344. f.Post("/create", binding.Form(form.CreateOrg{}), org.CreatePost)
  345. }, func(c *context.Context) {
  346. if !c.User.CanCreateOrganization() {
  347. c.NotFound()
  348. }
  349. })
  350. f.Group("/<org>", func() {
  351. f.Get("/dashboard", user.Dashboard)
  352. f.Get("/<type:issues|pulls>", user.Issues)
  353. f.Get("/members", org.Members)
  354. f.Get("/members/action/<action>", org.MembersAction)
  355. f.Get("/teams", org.Teams)
  356. }, context.OrgAssignment(true))
  357. f.Group("/<org>", func() {
  358. f.Get("/teams/<team>", org.TeamMembers)
  359. f.Get("/teams/<team>/repositories", org.TeamRepositories)
  360. f.Route("/teams/<team>/action/<action>", "GET,POST", org.TeamsAction)
  361. f.Route("/teams/<team>/action/repo/<action>", "GET,POST", org.TeamsRepoAction)
  362. }, context.OrgAssignment(true, false, true))
  363. f.Group("/<org>", func() {
  364. f.Get("/teams/new", org.NewTeam)
  365. f.Post("/teams/new", binding.Form(form.CreateTeam{}), org.NewTeamPost)
  366. f.Get("/teams/<team>/edit", org.EditTeam)
  367. f.Post("/teams/<team>/edit", binding.Form(form.CreateTeam{}), org.EditTeamPost)
  368. f.Post("/teams/<team>/delete", org.DeleteTeam)
  369. f.Group("/settings", func() {
  370. f.Combo("").Get(org.Settings).
  371. Post(binding.Form(form.UpdateOrgSetting{}), org.SettingsPost)
  372. f.Post("/avatar", binding.Form(form.Avatar{}), org.SettingsAvatar)
  373. f.Post("/avatar/delete", org.SettingsDeleteAvatar)
  374. f.Group("/hooks", webhookRoutes)
  375. f.Route("/delete", "GET,POST", org.SettingsDelete)
  376. })
  377. f.Route("/invitations/new", "GET,POST", org.Invitation)
  378. }, context.OrgAssignment(true, true))
  379. }, reqSignIn)
  380. // ***** END: Organization *****
  381. // ***** START: Repository *****
  382. f.Group("/repo", func() {
  383. f.Get("/create", repo.Create)
  384. f.Post("/create", binding.Form(form.CreateRepo{}), repo.CreatePost)
  385. f.Get("/migrate", repo.Migrate)
  386. f.Post("/migrate", binding.Form(form.MigrateRepo{}), repo.MigratePost)
  387. f.Combo("/fork/<repoid>").Get(repo.Fork).
  388. Post(binding.Form(form.CreateRepo{}), repo.ForkPost)
  389. }, reqSignIn)
  390. f.Group("/<username>/<reponame>", func() {
  391. f.Group("/settings", func() {
  392. f.Combo("").Get(repo.Settings).
  393. Post(binding.Form(form.RepoSetting{}), repo.SettingsPost)
  394. f.Combo("/avatar").Get(repo.SettingsAvatar).
  395. Post(binding.Form(form.Avatar{}), repo.SettingsAvatarPost)
  396. f.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  397. f.Group("/collaboration", func() {
  398. f.Combo("").Get(repo.SettingsCollaboration).Post(repo.SettingsCollaborationPost)
  399. f.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  400. f.Post("/delete", repo.DeleteCollaboration)
  401. })
  402. f.Group("/branches", func() {
  403. f.Get("", repo.SettingsBranches)
  404. f.Post("/default_branch", repo.UpdateDefaultBranch)
  405. f.Combo("/*").Get(repo.SettingsProtectedBranch).
  406. Post(binding.Form(form.ProtectBranch{}), repo.SettingsProtectedBranchPost)
  407. }, func(c *context.Context) {
  408. if c.Repo.Repository.IsMirror {
  409. c.NotFound()
  410. return
  411. }
  412. })
  413. f.Group("/hooks", func() {
  414. webhookRoutes()
  415. f.Group("/<id>", func() {
  416. f.Post("/test", repo.TestWebhook)
  417. f.Post("/redelivery", repo.RedeliveryWebhook)
  418. })
  419. f.Group("/git", func() {
  420. f.Get("", repo.SettingsGitHooks)
  421. f.Combo("/<name>").Get(repo.SettingsGitHooksEdit).
  422. Post(repo.SettingsGitHooksEditPost)
  423. }, context.GitHookService())
  424. })
  425. f.Group("/keys", func() {
  426. f.Combo("").Get(repo.SettingsDeployKeys).
  427. Post(binding.Form(form.AddSSHKey{}), repo.SettingsDeployKeysPost)
  428. f.Post("/delete", repo.DeleteDeployKey)
  429. })
  430. }, func(c *context.Context) {
  431. c.Data["PageIsSettings"] = true
  432. })
  433. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  434. f.Post("/<username>/<reponame>/action/<action>", reqSignIn, context.RepoAssignment(), repo.Action)
  435. f.Group("/<username>/<reponame>", func() {
  436. f.Get("/issues", repo.RetrieveLabels, repo.Issues)
  437. f.Get("/issues/<index>", repo.ViewIssue)
  438. f.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  439. f.Get("/milestones", repo.Milestones)
  440. }, ignSignIn, context.RepoAssignment(true))
  441. f.Group("/<username>/<reponame>", func() {
  442. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  443. // So they can apply their own enable/disable logic on routers.
  444. f.Group("/issues", func() {
  445. f.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  446. Post(binding.Form(form.NewIssue{}), repo.NewIssuePost)
  447. f.Group("/<index>", func() {
  448. f.Post("/title", repo.UpdateIssueTitle)
  449. f.Post("/content", repo.UpdateIssueContent)
  450. f.Combo("/comments").Post(binding.Form(form.CreateComment{}), repo.NewComment)
  451. })
  452. })
  453. f.Group("/comments/<id>", func() {
  454. f.Post("", repo.UpdateCommentContent)
  455. f.Post("/delete", repo.DeleteComment)
  456. })
  457. }, reqSignIn, context.RepoAssignment(true))
  458. f.Group("/<username>/<reponame>", func() {
  459. f.Group("/wiki", func() {
  460. f.Get("/?<page>", repo.Wiki)
  461. f.Get("/_pages", repo.WikiPages)
  462. }, repo.MustEnableWiki, context.RepoRef())
  463. }, ignSignIn, context.RepoAssignment(false, true))
  464. f.Group("/<username>/<reponame>", func() {
  465. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  466. // So they can apply their own enable/disable logic on routers.
  467. f.Group("/issues", func() {
  468. f.Group("/<index>", func() {
  469. f.Post("/label", repo.UpdateIssueLabel)
  470. f.Post("/milestone", repo.UpdateIssueMilestone)
  471. f.Post("/assignee", repo.UpdateIssueAssignee)
  472. }, reqRepoWriter)
  473. })
  474. f.Group("/labels", func() {
  475. f.Post("/new", binding.Form(form.CreateLabel{}), repo.NewLabel)
  476. f.Post("/edit", binding.Form(form.CreateLabel{}), repo.UpdateLabel)
  477. f.Post("/delete", repo.DeleteLabel)
  478. f.Post("/initialize", binding.Form(form.InitializeLabels{}), repo.InitializeLabels)
  479. }, reqRepoWriter, context.RepoRef())
  480. f.Group("/milestones", func() {
  481. f.Combo("/new").Get(repo.NewMilestone).
  482. Post(binding.Form(form.CreateMilestone{}), repo.NewMilestonePost)
  483. f.Get("/<id>/edit", repo.EditMilestone)
  484. f.Post("/<id>/edit", binding.Form(form.CreateMilestone{}), repo.EditMilestonePost)
  485. f.Get("/<id>/<action>", repo.ChangeMilestonStatus)
  486. f.Post("/delete", repo.DeleteMilestone)
  487. }, reqRepoWriter, context.RepoRef())
  488. f.Group("/releases", func() {
  489. f.Get("/new", repo.NewRelease)
  490. f.Post("/new", binding.Form(form.NewRelease{}), repo.NewReleasePost)
  491. f.Post("/delete", repo.DeleteRelease)
  492. f.Get("/edit/*", repo.EditRelease)
  493. f.Post("/edit/*", binding.Form(form.EditRelease{}), repo.EditReleasePost)
  494. }, repo.MustBeNotBare, reqRepoWriter, func(c *context.Context) {
  495. c.Data["PageIsViewFiles"] = true
  496. })
  497. // FIXME: Should use c.Repo.PullRequest to unify template, currently we have inconsistent URL
  498. // for PR in same repository. After select branch on the page, the URL contains redundant head user name.
  499. // e.g. /org1/test-repo/compare/master...org1:develop
  500. // which should be /org1/test-repo/compare/master...develop
  501. f.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  502. Post(binding.Form(form.NewIssue{}), repo.CompareAndPullRequestPost)
  503. f.Group("", func() {
  504. f.Combo("/_edit/*").Get(repo.EditFile).
  505. Post(binding.Form(form.EditRepoFile{}), repo.EditFilePost)
  506. f.Combo("/_new/*").Get(repo.NewFile).
  507. Post(binding.Form(form.EditRepoFile{}), repo.NewFilePost)
  508. f.Post("/_preview/*", binding.Form(form.EditPreviewDiff{}), repo.DiffPreviewPost)
  509. f.Combo("/_delete/*").Get(repo.DeleteFile).
  510. Post(binding.Form(form.DeleteRepoFile{}), repo.DeleteFilePost)
  511. f.Group("", func() {
  512. f.Combo("/_upload/*").Get(repo.UploadFile).
  513. Post(binding.Form(form.UploadRepoFile{}), repo.UploadFilePost)
  514. f.Post("/upload-file", repo.UploadFileToServer)
  515. f.Post("/upload-remove", binding.Form(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer)
  516. }, func(c *context.Context) {
  517. if !conf.Repository.Upload.Enabled {
  518. c.NotFound()
  519. return
  520. }
  521. })
  522. }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(c *context.Context) {
  523. if !c.Repo.CanEnableEditor() {
  524. c.NotFound()
  525. return
  526. }
  527. c.Data["PageIsViewFiles"] = true
  528. })
  529. }, reqSignIn, context.RepoAssignment())
  530. f.Group("/<username>/<reponame>", func() {
  531. f.Group("", func() {
  532. f.Get("/releases", repo.MustBeNotBare, repo.Releases)
  533. f.Get("/pulls", repo.RetrieveLabels, repo.Pulls)
  534. f.Get("/pulls/<index>", repo.ViewPull)
  535. }, context.RepoRef())
  536. f.Group("/branches", func() {
  537. f.Get("", repo.Branches)
  538. f.Get("/all", repo.AllBranches)
  539. f.Post("/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
  540. }, repo.MustBeNotBare, func(c *context.Context) {
  541. c.Data["PageIsViewFiles"] = true
  542. })
  543. f.Group("/wiki", func() {
  544. f.Group("", func() {
  545. f.Combo("/_new").Get(repo.NewWiki).
  546. Post(binding.Form(form.NewWiki{}), repo.NewWikiPost)
  547. f.Combo("/<page>/_edit").Get(repo.EditWiki).
  548. Post(binding.Form(form.NewWiki{}), repo.EditWikiPost)
  549. f.Post("/<page>/delete", repo.DeleteWikiPagePost)
  550. }, reqSignIn, reqRepoWriter)
  551. }, repo.MustEnableWiki, context.RepoRef())
  552. f.Get("/archive/*", repo.MustBeNotBare, repo.Download)
  553. f.Group("/pulls/<index>", func() {
  554. f.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  555. f.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  556. f.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  557. }, repo.MustAllowPulls)
  558. f.Group("", func() {
  559. f.Get("/src/*", repo.Home)
  560. f.Get("/raw/*", repo.SingleDownload)
  561. f.Get("/commits/*", repo.RefCommits)
  562. f.Get("/commit/<sha:[a-f0-9]{7,40}>", repo.Diff)
  563. f.Get("/forks", repo.Forks)
  564. }, repo.MustBeNotBare, context.RepoRef())
  565. f.Get("/commit/<sha:[a-f0-9]{7,40}>.<ext:patch|diff>", repo.MustBeNotBare, repo.RawDiff)
  566. f.Get("/compare/<before>([a-z0-9]{40})\\.\\.\\.<after>([a-z0-9]{40})", repo.MustBeNotBare, context.RepoRef(), repo.CompareDiff)
  567. }, ignSignIn, context.RepoAssignment())
  568. f.Group("/<username>/<reponame>", func() {
  569. f.Get("", repo.Home)
  570. f.Get("/stars", repo.Stars)
  571. f.Get("/watchers", repo.Watchers)
  572. }, context.ServeGoGet(), ignSignIn, context.RepoAssignment(), context.RepoRef())
  573. // ***** END: Repository *****
  574. // **********************
  575. // ----- API routes -----
  576. // **********************
  577. // TODO: Without session and CSRF
  578. f.Group("/api", func() {
  579. apiv1.RegisterRoutes(f)
  580. }, ignSignIn)
  581. // ***************************
  582. // ----- HTTP Git routes -----
  583. // ***************************
  584. f.Group("/<username>/<reponame>", func() {
  585. f.Get("/tasks/trigger", repo.TriggerTask)
  586. f.Group("/info/lfs", func() {
  587. lfs.RegisterRoutes(f)
  588. })
  589. f.Route("/*", "GET,POST,OPTIONS", context.ServeGoGet(), repo.HTTPContexter(repo.NewStore()), repo.HTTP)
  590. })
  591. // ***************************
  592. // ----- Internal routes -----
  593. // ***************************
  594. f.Group("/-", func() {
  595. f.Get("/metrics", app.MetricsFilter(), promhttp.Handler()) // "/-/metrics"
  596. f.Group("/api", func() {
  597. f.Post("/sanitize_ipynb", app.SanitizeIpynb()) // "/-/api/sanitize_ipynb"
  598. })
  599. })
  600. // **********************
  601. // ----- robots.txt -----
  602. // **********************
  603. f.Get("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
  604. if conf.HasRobotsTxt {
  605. http.ServeFile(w, r, filepath.Join(conf.CustomDir(), "robots.txt"))
  606. } else {
  607. w.WriteHeader(http.StatusNotFound)
  608. }
  609. })
  610. f.NotFound(route.NotFound)
  611. // Flag for port number in case first time run conflict.
  612. if c.IsSet("port") {
  613. conf.Server.URL.Host = strings.Replace(conf.Server.URL.Host, ":"+conf.Server.URL.Port(), ":"+c.String("port"), 1)
  614. conf.Server.ExternalURL = conf.Server.URL.String()
  615. conf.Server.HTTPPort = c.String("port")
  616. }
  617. var listenAddr string
  618. if conf.Server.Protocol == "unix" {
  619. listenAddr = conf.Server.HTTPAddr
  620. } else {
  621. listenAddr = fmt.Sprintf("%s:%s", conf.Server.HTTPAddr, conf.Server.HTTPPort)
  622. }
  623. log.Info("Available on %s", conf.Server.ExternalURL)
  624. switch conf.Server.Protocol {
  625. case "http":
  626. err = http.ListenAndServe(listenAddr, f)
  627. case "https":
  628. tlsMinVersion := tls.VersionTLS12
  629. switch conf.Server.TLSMinVersion {
  630. case "TLS13":
  631. tlsMinVersion = tls.VersionTLS13
  632. case "TLS12":
  633. tlsMinVersion = tls.VersionTLS12
  634. case "TLS11":
  635. tlsMinVersion = tls.VersionTLS11
  636. case "TLS10":
  637. tlsMinVersion = tls.VersionTLS10
  638. }
  639. server := &http.Server{
  640. Addr: listenAddr,
  641. TLSConfig: &tls.Config{
  642. MinVersion: uint16(tlsMinVersion),
  643. CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384, tls.CurveP521},
  644. PreferServerCipherSuites: true,
  645. CipherSuites: []uint16{
  646. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  647. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  648. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  649. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  650. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  651. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  652. },
  653. }, Handler: f,
  654. }
  655. err = server.ListenAndServeTLS(conf.Server.CertFile, conf.Server.KeyFile)
  656. case "fcgi":
  657. err = fcgi.Serve(nil, f)
  658. case "unix":
  659. if osutil.Exist(listenAddr) {
  660. err = os.Remove(listenAddr)
  661. if err != nil {
  662. log.Fatal("Failed to remove existing Unix domain socket: %v", err)
  663. }
  664. }
  665. var listener *net.UnixListener
  666. listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"})
  667. if err != nil {
  668. log.Fatal("Failed to listen on Unix networks: %v", err)
  669. }
  670. // FIXME: add proper implementation of signal capture on all protocols
  671. // execute this on SIGTERM or SIGINT: listener.Close()
  672. if err = os.Chmod(listenAddr, conf.Server.UnixSocketMode); err != nil {
  673. log.Fatal("Failed to change permission of Unix domain socket: %v", err)
  674. }
  675. err = http.Serve(listener, f)
  676. default:
  677. log.Fatal("Unexpected server protocol: %s", conf.Server.Protocol)
  678. }
  679. if err != nil {
  680. log.Fatal("Failed to start server: %v", err)
  681. }
  682. return nil
  683. }