web.go 27 KB

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