1
0

web.go 25 KB

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