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.

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