You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

477 lines
16 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. "html/template"
  9. "io/ioutil"
  10. "net/http"
  11. "net/http/fcgi"
  12. "os"
  13. "path"
  14. "strings"
  15. "github.com/Unknwon/macaron"
  16. "github.com/codegangsta/cli"
  17. "github.com/macaron-contrib/binding"
  18. "github.com/macaron-contrib/cache"
  19. "github.com/macaron-contrib/captcha"
  20. "github.com/macaron-contrib/csrf"
  21. "github.com/macaron-contrib/i18n"
  22. "github.com/macaron-contrib/oauth2"
  23. "github.com/macaron-contrib/session"
  24. "github.com/macaron-contrib/toolbox"
  25. api "github.com/gogits/go-gogs-client"
  26. "github.com/gogits/gogs/models"
  27. "github.com/gogits/gogs/modules/auth"
  28. "github.com/gogits/gogs/modules/auth/apiv1"
  29. "github.com/gogits/gogs/modules/avatar"
  30. "github.com/gogits/gogs/modules/base"
  31. "github.com/gogits/gogs/modules/git"
  32. "github.com/gogits/gogs/modules/log"
  33. "github.com/gogits/gogs/modules/middleware"
  34. "github.com/gogits/gogs/modules/setting"
  35. "github.com/gogits/gogs/routers"
  36. "github.com/gogits/gogs/routers/admin"
  37. "github.com/gogits/gogs/routers/api/v1"
  38. "github.com/gogits/gogs/routers/dev"
  39. "github.com/gogits/gogs/routers/org"
  40. "github.com/gogits/gogs/routers/repo"
  41. "github.com/gogits/gogs/routers/user"
  42. )
  43. var CmdWeb = cli.Command{
  44. Name: "web",
  45. Usage: "Start Gogs web server",
  46. Description: `Gogs web server is the only thing you need to run,
  47. and it takes care of all the other things for you`,
  48. Action: runWeb,
  49. Flags: []cli.Flag{},
  50. }
  51. type VerChecker struct {
  52. ImportPath string
  53. Version func() string
  54. Expected string
  55. }
  56. // checkVersion checks if binary matches the version of templates files.
  57. func checkVersion() {
  58. // Templates.
  59. data, err := ioutil.ReadFile(path.Join(setting.StaticRootPath, "templates/.VERSION"))
  60. if err != nil {
  61. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  62. }
  63. if string(data) != setting.AppVer {
  64. log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
  65. }
  66. // Check dependency version.
  67. checkers := []VerChecker{
  68. {"github.com/Unknwon/macaron", macaron.Version, "0.4.7"},
  69. {"github.com/macaron-contrib/binding", binding.Version, "0.0.2"},
  70. {"github.com/macaron-contrib/i18n", i18n.Version, "0.0.3"},
  71. {"github.com/macaron-contrib/session", session.Version, "0.0.5"},
  72. }
  73. for _, c := range checkers {
  74. ver := strings.Join(strings.Split(c.Version(), ".")[:3], ".")
  75. if git.MustParseVersion(ver).LessThan(git.MustParseVersion(c.Expected)) {
  76. log.Fatal(4, "Package '%s' version is too old(%s -> %s), did you forget to update?", c.ImportPath, ver, c.Expected)
  77. }
  78. }
  79. }
  80. // newMacaron initializes Macaron instance.
  81. func newMacaron() *macaron.Macaron {
  82. m := macaron.New()
  83. m.Use(macaron.Logger())
  84. m.Use(macaron.Recovery())
  85. if setting.EnableGzip {
  86. m.Use(macaron.Gziper())
  87. }
  88. if setting.Protocol == setting.FCGI {
  89. m.SetURLPrefix(setting.AppSubUrl)
  90. }
  91. m.Use(macaron.Static(
  92. path.Join(setting.StaticRootPath, "public"),
  93. macaron.StaticOptions{
  94. SkipLogging: !setting.DisableRouterLog,
  95. },
  96. ))
  97. m.Use(macaron.Static(
  98. setting.AvatarUploadPath,
  99. macaron.StaticOptions{
  100. Prefix: "avatars",
  101. SkipLogging: !setting.DisableRouterLog,
  102. },
  103. ))
  104. m.Use(macaron.Renderer(macaron.RenderOptions{
  105. Directory: path.Join(setting.StaticRootPath, "templates"),
  106. Funcs: []template.FuncMap{base.TemplateFuncs},
  107. IndentJSON: macaron.Env != macaron.PROD,
  108. }))
  109. m.Use(i18n.I18n(i18n.Options{
  110. SubURL: setting.AppSubUrl,
  111. Directory: path.Join(setting.ConfRootPath, "locale"),
  112. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  113. Langs: setting.Langs,
  114. Names: setting.Names,
  115. Redirect: true,
  116. }))
  117. m.Use(cache.Cacher(cache.Options{
  118. Adapter: setting.CacheAdapter,
  119. Interval: setting.CacheInternal,
  120. Conn: setting.CacheConn,
  121. }))
  122. m.Use(captcha.Captchaer(captcha.Options{
  123. SubURL: setting.AppSubUrl,
  124. }))
  125. m.Use(session.Sessioner(session.Options{
  126. Provider: setting.SessionProvider,
  127. Config: *setting.SessionConfig,
  128. }))
  129. m.Use(csrf.Generate(csrf.Options{
  130. Secret: setting.SecretKey,
  131. SetCookie: true,
  132. Header: "X-Csrf-Token",
  133. CookiePath: setting.AppSubUrl,
  134. }))
  135. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  136. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  137. &toolbox.HealthCheckFuncDesc{
  138. Desc: "Database connection",
  139. Func: models.Ping,
  140. },
  141. },
  142. }))
  143. // OAuth 2.
  144. if setting.OauthService != nil {
  145. for _, info := range setting.OauthService.OauthInfos {
  146. m.Use(oauth2.NewOAuth2Provider(info.Options, info.AuthUrl, info.TokenUrl))
  147. }
  148. }
  149. m.Use(middleware.Contexter())
  150. return m
  151. }
  152. func runWeb(*cli.Context) {
  153. routers.GlobalInit()
  154. checkVersion()
  155. m := newMacaron()
  156. reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
  157. ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: setting.Service.RequireSignInView})
  158. ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})
  159. reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})
  160. bind := binding.Bind
  161. bindIgnErr := binding.BindIgnErr
  162. // Routers.
  163. m.Get("/", ignSignIn, routers.Home)
  164. m.Get("/explore", ignSignIn, routers.Explore)
  165. // FIXME: when i'm binding form here???
  166. m.Get("/install", bindIgnErr(auth.InstallForm{}), routers.Install)
  167. m.Post("/install", bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  168. m.Group("", func() {
  169. m.Get("/pulls", user.Pulls)
  170. m.Get("/issues", user.Issues)
  171. }, reqSignIn)
  172. // API.
  173. // FIXME: custom form error response.
  174. m.Group("/api", func() {
  175. m.Group("/v1", func() {
  176. // Miscellaneous.
  177. m.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
  178. m.Post("/markdown/raw", v1.MarkdownRaw)
  179. // Users.
  180. m.Group("/users", func() {
  181. m.Get("/search", v1.SearchUsers)
  182. m.Group("/:username", func() {
  183. m.Get("", v1.GetUserInfo)
  184. m.Group("/tokens", func() {
  185. m.Combo("").Get(v1.ListAccessTokens).Post(bind(v1.CreateAccessTokenForm{}), v1.CreateAccessToken)
  186. }, middleware.ApiReqBasicAuth())
  187. })
  188. })
  189. // Repositories.
  190. m.Combo("/user/repos", middleware.ApiReqToken()).Get(v1.ListMyRepos).Post(bind(api.CreateRepoOption{}), v1.CreateRepo)
  191. m.Post("/org/:org/repos", middleware.ApiReqToken(), bind(api.CreateRepoOption{}), v1.CreateOrgRepo)
  192. m.Group("/repos", func() {
  193. m.Get("/search", v1.SearchRepos)
  194. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), v1.MigrateRepo)
  195. m.Group("/:username/:reponame", func() {
  196. m.Combo("/hooks").Get(v1.ListRepoHooks).Post(bind(api.CreateHookOption{}), v1.CreateRepoHook)
  197. m.Patch("/hooks/:id:int", bind(api.EditHookOption{}), v1.EditRepoHook)
  198. m.Get("/raw/*", middleware.RepoRef(), v1.GetRepoRawFile)
  199. }, middleware.ApiRepoAssignment(), middleware.ApiReqToken())
  200. })
  201. m.Any("/*", func(ctx *middleware.Context) {
  202. ctx.JSON(404, &base.ApiJsonErr{"Not Found", base.DOC_URL})
  203. })
  204. })
  205. })
  206. // User.
  207. m.Group("/user", func() {
  208. m.Get("/login", user.SignIn)
  209. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  210. m.Get("/info/:name", user.SocialSignIn)
  211. m.Get("/sign_up", user.SignUp)
  212. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  213. m.Get("/reset_password", user.ResetPasswd)
  214. m.Post("/reset_password", user.ResetPasswdPost)
  215. }, reqSignOut)
  216. m.Group("/user/settings", func() {
  217. m.Get("", user.Settings)
  218. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  219. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
  220. m.Get("/password", user.SettingsPassword)
  221. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  222. m.Get("/ssh", user.SettingsSSHKeys)
  223. m.Post("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  224. m.Get("/social", user.SettingsSocial)
  225. m.Combo("/applications").Get(user.SettingsApplications).Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  226. m.Route("/delete", "GET,POST", user.SettingsDelete)
  227. }, reqSignIn)
  228. m.Group("/user", func() {
  229. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  230. m.Any("/activate", user.Activate)
  231. m.Get("/email2user", user.Email2User)
  232. m.Get("/forget_password", user.ForgotPasswd)
  233. m.Post("/forget_password", user.ForgotPasswdPost)
  234. m.Get("/logout", user.SignOut)
  235. })
  236. // Gravatar service.
  237. avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
  238. os.MkdirAll("public/img/avatar/", os.ModePerm)
  239. m.Get("/avatar/:hash", avt.ServeHTTP)
  240. adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
  241. m.Group("/admin", func() {
  242. m.Get("", adminReq, admin.Dashboard)
  243. m.Get("/config", admin.Config)
  244. m.Get("/monitor", admin.Monitor)
  245. m.Group("/users", func() {
  246. m.Get("", admin.Users)
  247. m.Get("/new", admin.NewUser)
  248. m.Post("/new", bindIgnErr(auth.RegisterForm{}), admin.NewUserPost)
  249. m.Get("/:userid", admin.EditUser)
  250. m.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  251. m.Post("/:userid/delete", admin.DeleteUser)
  252. })
  253. m.Group("/orgs", func() {
  254. m.Get("", admin.Organizations)
  255. })
  256. m.Group("/repos", func() {
  257. m.Get("", admin.Repositories)
  258. })
  259. m.Group("/auths", func() {
  260. m.Get("", admin.Authentications)
  261. m.Get("/new", admin.NewAuthSource)
  262. m.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  263. m.Get("/:authid", admin.EditAuthSource)
  264. m.Post("/:authid", bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  265. m.Post("/:authid/delete", admin.DeleteAuthSource)
  266. })
  267. m.Group("/notices", func() {
  268. m.Get("", admin.Notices)
  269. m.Get("/:id:int/delete", admin.DeleteNotice)
  270. })
  271. }, adminReq)
  272. m.Get("/:username", ignSignIn, user.Profile)
  273. if macaron.Env == macaron.DEV {
  274. m.Get("/template/*", dev.TemplatePreview)
  275. }
  276. reqTrueOwner := middleware.RequireTrueOwner()
  277. // Organization.
  278. m.Group("/org", func() {
  279. m.Get("/create", org.Create)
  280. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  281. m.Group("/:org", func() {
  282. m.Get("/dashboard", user.Dashboard)
  283. m.Get("/members", org.Members)
  284. m.Get("/members/action/:action", org.MembersAction)
  285. m.Get("/teams", org.Teams)
  286. m.Get("/teams/:team", org.TeamMembers)
  287. m.Get("/teams/:team/repositories", org.TeamRepositories)
  288. m.Get("/teams/:team/action/:action", org.TeamsAction)
  289. m.Get("/teams/:team/action/repo/:action", org.TeamsRepoAction)
  290. }, middleware.OrgAssignment(true, true))
  291. m.Group("/:org", func() {
  292. m.Get("/teams/new", org.NewTeam)
  293. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  294. m.Get("/teams/:team/edit", org.EditTeam)
  295. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  296. m.Post("/teams/:team/delete", org.DeleteTeam)
  297. m.Group("/settings", func() {
  298. m.Get("", org.Settings)
  299. m.Post("", bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  300. m.Get("/hooks", org.SettingsHooks)
  301. m.Get("/hooks/new", repo.WebHooksNew)
  302. m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  303. m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  304. m.Get("/hooks/:id", repo.WebHooksEdit)
  305. m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  306. m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  307. m.Route("/delete", "GET,POST", org.SettingsDelete)
  308. })
  309. m.Route("/invitations/new", "GET,POST", org.Invitation)
  310. }, middleware.OrgAssignment(true, true, true))
  311. }, reqSignIn)
  312. m.Group("/org", func() {
  313. m.Get("/:org", org.Home)
  314. }, middleware.OrgAssignment(true))
  315. // Repository.
  316. m.Group("/repo", func() {
  317. m.Get("/create", repo.Create)
  318. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  319. m.Get("/migrate", repo.Migrate)
  320. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  321. m.Get("/fork", repo.Fork)
  322. m.Post("/fork", bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  323. }, reqSignIn)
  324. m.Group("/:username/:reponame", func() {
  325. m.Get("/settings", repo.Settings)
  326. m.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  327. m.Group("/settings", func() {
  328. m.Route("/collaboration", "GET,POST", repo.SettingsCollaboration)
  329. m.Get("/hooks", repo.Webhooks)
  330. m.Get("/hooks/new", repo.WebHooksNew)
  331. m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  332. m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  333. m.Get("/hooks/:id", repo.WebHooksEdit)
  334. m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  335. m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  336. m.Group("/hooks/git", func() {
  337. m.Get("", repo.GitHooks)
  338. m.Get("/:name", repo.GitHooksEdit)
  339. m.Post("/:name", repo.GitHooksEditPost)
  340. }, middleware.GitHookService())
  341. })
  342. }, reqSignIn, middleware.RepoAssignment(true), reqTrueOwner)
  343. m.Group("/:username/:reponame", func() {
  344. m.Get("/action/:action", repo.Action)
  345. m.Group("/issues", func() {
  346. m.Get("/new", repo.CreateIssue)
  347. m.Post("/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost)
  348. m.Post("/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
  349. m.Post("/:index/label", repo.UpdateIssueLabel)
  350. m.Post("/:index/milestone", repo.UpdateIssueMilestone)
  351. m.Post("/:index/assignee", repo.UpdateAssignee)
  352. m.Get("/:index/attachment/:id", repo.IssueGetAttachment)
  353. m.Post("/labels/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  354. m.Post("/labels/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  355. m.Post("/labels/delete", repo.DeleteLabel)
  356. m.Get("/milestones/new", repo.NewMilestone)
  357. m.Post("/milestones/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  358. m.Get("/milestones/:index/edit", repo.UpdateMilestone)
  359. m.Post("/milestones/:index/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.UpdateMilestonePost)
  360. m.Get("/milestones/:index/:action", repo.UpdateMilestone)
  361. })
  362. m.Post("/comment/:action", repo.Comment)
  363. m.Group("/releases", func() {
  364. m.Get("/new", repo.NewRelease)
  365. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  366. m.Get("/edit/:tagname", repo.EditRelease)
  367. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  368. }, middleware.RepoRef())
  369. }, reqSignIn, middleware.RepoAssignment(true))
  370. m.Group("/:username/:reponame", func() {
  371. m.Get("/releases", middleware.RepoRef(), repo.Releases)
  372. m.Get("/issues", repo.Issues)
  373. m.Get("/issues/:index", repo.ViewIssue)
  374. m.Get("/issues/milestones", repo.Milestones)
  375. m.Get("/pulls", repo.Pulls)
  376. m.Get("/branches", repo.Branches)
  377. m.Get("/archive/*", repo.Download)
  378. m.Get("/issues2/", repo.Issues2)
  379. m.Get("/pulls2/", repo.PullRequest2)
  380. m.Get("/labels2/", repo.Labels2)
  381. m.Get("/milestone2/", repo.Milestones2)
  382. m.Group("", func() {
  383. m.Get("/src/*", repo.Home)
  384. m.Get("/raw/*", repo.SingleDownload)
  385. m.Get("/commits/*", repo.RefCommits)
  386. m.Get("/commit/*", repo.Diff)
  387. }, middleware.RepoRef())
  388. m.Get("/compare/:before([a-z0-9]+)...:after([a-z0-9]+)", repo.CompareDiff)
  389. }, ignSignIn, middleware.RepoAssignment(true))
  390. m.Group("/:username", func() {
  391. m.Get("/:reponame", ignSignIn, middleware.RepoAssignment(true, true), middleware.RepoRef(), repo.Home)
  392. m.Any("/:reponame/*", ignSignInAndCsrf, repo.Http)
  393. })
  394. // robots.txt
  395. m.Get("/robots.txt", func(ctx *middleware.Context) {
  396. if setting.HasRobotsTxt {
  397. ctx.ServeFile(path.Join(setting.CustomPath, "robots.txt"))
  398. } else {
  399. ctx.Error(404)
  400. }
  401. })
  402. // Not found handler.
  403. m.NotFound(routers.NotFound)
  404. var err error
  405. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  406. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  407. switch setting.Protocol {
  408. case setting.HTTP:
  409. err = http.ListenAndServe(listenAddr, m)
  410. case setting.HTTPS:
  411. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  412. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  413. case setting.FCGI:
  414. err = fcgi.Serve(nil, m)
  415. default:
  416. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  417. }
  418. if err != nil {
  419. log.Fatal(4, "Fail to start server: %v", err)
  420. }
  421. }