web.go 27 KB

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