web.go 27 KB

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