web.go 27 KB

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