web.go 27 KB

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