web.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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/ioutil"
  9. "net"
  10. "net/http"
  11. "net/http/fcgi"
  12. "os"
  13. "path"
  14. "strings"
  15. "github.com/go-macaron/binding"
  16. "github.com/go-macaron/cache"
  17. "github.com/go-macaron/captcha"
  18. "github.com/go-macaron/csrf"
  19. "github.com/go-macaron/gzip"
  20. "github.com/go-macaron/i18n"
  21. "github.com/go-macaron/session"
  22. "github.com/go-macaron/toolbox"
  23. "github.com/go-xorm/xorm"
  24. "github.com/mcuadros/go-version"
  25. "github.com/urfave/cli"
  26. "gopkg.in/ini.v1"
  27. "gopkg.in/macaron.v1"
  28. "github.com/gogits/git-module"
  29. "github.com/gogits/go-gogs-client"
  30. "github.com/gogits/gogs/models"
  31. "github.com/gogits/gogs/modules/auth"
  32. "github.com/gogits/gogs/modules/bindata"
  33. "github.com/gogits/gogs/modules/context"
  34. "github.com/gogits/gogs/modules/log"
  35. "github.com/gogits/gogs/modules/setting"
  36. "github.com/gogits/gogs/modules/template"
  37. "github.com/gogits/gogs/routers"
  38. "github.com/gogits/gogs/routers/admin"
  39. apiv1 "github.com/gogits/gogs/routers/api/v1"
  40. "github.com/gogits/gogs/routers/dev"
  41. "github.com/gogits/gogs/routers/org"
  42. "github.com/gogits/gogs/routers/repo"
  43. "github.com/gogits/gogs/routers/user"
  44. )
  45. var CmdWeb = cli.Command{
  46. Name: "web",
  47. Usage: "Start Gogs web server",
  48. Description: `Gogs web server is the only thing you need to run,
  49. and it takes care of all the other things for you`,
  50. Action: runWeb,
  51. Flags: []cli.Flag{
  52. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  53. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  54. },
  55. }
  56. type VerChecker struct {
  57. ImportPath string
  58. Version func() string
  59. Expected string
  60. }
  61. // checkVersion checks if binary matches the version of templates files.
  62. func checkVersion() {
  63. // Templates.
  64. data, err := ioutil.ReadFile(setting.StaticRootPath + "/templates/.VERSION")
  65. if err != nil {
  66. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  67. }
  68. if string(data) != setting.AppVer {
  69. log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
  70. }
  71. // Check dependency version.
  72. checkers := []VerChecker{
  73. {"github.com/go-xorm/xorm", func() string { return xorm.Version }, "0.5.5"},
  74. {"github.com/go-macaron/binding", binding.Version, "0.3.2"},
  75. {"github.com/go-macaron/cache", cache.Version, "0.1.2"},
  76. {"github.com/go-macaron/csrf", csrf.Version, "0.1.0"},
  77. {"github.com/go-macaron/i18n", i18n.Version, "0.3.0"},
  78. {"github.com/go-macaron/session", session.Version, "0.1.6"},
  79. {"github.com/go-macaron/toolbox", toolbox.Version, "0.1.0"},
  80. {"gopkg.in/ini.v1", ini.Version, "1.8.4"},
  81. {"gopkg.in/macaron.v1", macaron.Version, "1.1.7"},
  82. {"github.com/gogits/git-module", git.Version, "0.4.1"},
  83. {"github.com/gogits/go-gogs-client", gogs.Version, "0.12.1"},
  84. }
  85. for _, c := range checkers {
  86. if !version.Compare(c.Version(), c.Expected, ">=") {
  87. log.Fatal(4, `Dependency outdated!
  88. Package '%s' current version (%s) is below requirement (%s),
  89. please use following command to update this package and recompile Gogs:
  90. go get -u %[1]s`, c.ImportPath, c.Version(), c.Expected)
  91. }
  92. }
  93. }
  94. // newMacaron initializes Macaron instance.
  95. func newMacaron() *macaron.Macaron {
  96. m := macaron.New()
  97. if !setting.DisableRouterLog {
  98. m.Use(macaron.Logger())
  99. }
  100. m.Use(macaron.Recovery())
  101. if setting.EnableGzip {
  102. m.Use(gzip.Gziper())
  103. }
  104. if setting.Protocol == setting.FCGI {
  105. m.SetURLPrefix(setting.AppSubUrl)
  106. }
  107. m.Use(macaron.Static(
  108. path.Join(setting.StaticRootPath, "public"),
  109. macaron.StaticOptions{
  110. SkipLogging: setting.DisableRouterLog,
  111. },
  112. ))
  113. m.Use(macaron.Static(
  114. setting.AvatarUploadPath,
  115. macaron.StaticOptions{
  116. Prefix: "avatars",
  117. SkipLogging: setting.DisableRouterLog,
  118. },
  119. ))
  120. funcMap := template.NewFuncMap()
  121. m.Use(macaron.Renderer(macaron.RenderOptions{
  122. Directory: path.Join(setting.StaticRootPath, "templates"),
  123. AppendDirectories: []string{path.Join(setting.CustomPath, "templates")},
  124. Funcs: funcMap,
  125. IndentJSON: macaron.Env != macaron.PROD,
  126. }))
  127. models.InitMailRender(path.Join(setting.StaticRootPath, "templates/mail"),
  128. path.Join(setting.CustomPath, "templates/mail"), funcMap)
  129. localeNames, err := bindata.AssetDir("conf/locale")
  130. if err != nil {
  131. log.Fatal(4, "Fail to list locale files: %v", err)
  132. }
  133. localFiles := make(map[string][]byte)
  134. for _, name := range localeNames {
  135. localFiles[name] = bindata.MustAsset("conf/locale/" + name)
  136. }
  137. m.Use(i18n.I18n(i18n.Options{
  138. SubURL: setting.AppSubUrl,
  139. Files: localFiles,
  140. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  141. Langs: setting.Langs,
  142. Names: setting.Names,
  143. DefaultLang: "en-US",
  144. Redirect: true,
  145. }))
  146. m.Use(cache.Cacher(cache.Options{
  147. Adapter: setting.CacheAdapter,
  148. AdapterConfig: setting.CacheConn,
  149. Interval: setting.CacheInterval,
  150. }))
  151. m.Use(captcha.Captchaer(captcha.Options{
  152. SubURL: setting.AppSubUrl,
  153. }))
  154. m.Use(session.Sessioner(setting.SessionConfig))
  155. m.Use(csrf.Csrfer(csrf.Options{
  156. Secret: setting.SecretKey,
  157. Cookie: setting.CSRFCookieName,
  158. SetCookie: true,
  159. Header: "X-Csrf-Token",
  160. CookiePath: setting.AppSubUrl,
  161. }))
  162. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  163. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  164. &toolbox.HealthCheckFuncDesc{
  165. Desc: "Database connection",
  166. Func: models.Ping,
  167. },
  168. },
  169. }))
  170. m.Use(context.Contexter())
  171. return m
  172. }
  173. func runWeb(ctx *cli.Context) error {
  174. if ctx.IsSet("config") {
  175. setting.CustomConf = ctx.String("config")
  176. }
  177. routers.GlobalInit()
  178. checkVersion()
  179. m := newMacaron()
  180. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  181. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  182. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  183. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  184. bindIgnErr := binding.BindIgnErr
  185. // FIXME: not all routes need go through same middlewares.
  186. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  187. // Routers.
  188. m.Get("/", ignSignIn, routers.Home)
  189. m.Group("/explore", func() {
  190. m.Get("", func(ctx *context.Context) {
  191. ctx.Redirect(setting.AppSubUrl + "/explore/repos")
  192. })
  193. m.Get("/repos", routers.ExploreRepos)
  194. m.Get("/users", routers.ExploreUsers)
  195. }, ignSignIn)
  196. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  197. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  198. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  199. // ***** START: User *****
  200. m.Group("/user", func() {
  201. m.Get("/login", user.SignIn)
  202. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  203. m.Get("/sign_up", user.SignUp)
  204. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), 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(auth.UpdateProfileForm{}), user.SettingsPost)
  211. m.Combo("/avatar").Get(user.SettingsAvatar).
  212. Post(binding.MultipartForm(auth.AvatarForm{}), user.SettingsAvatarPost)
  213. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  214. m.Combo("/email").Get(user.SettingsEmails).
  215. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  216. m.Post("/email/delete", user.DeleteEmail)
  217. m.Get("/password", user.SettingsPassword)
  218. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  219. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  220. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  221. m.Post("/ssh/delete", user.DeleteSSHKey)
  222. m.Combo("/applications").Get(user.SettingsApplications).
  223. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  224. m.Post("/applications/delete", user.SettingsDeleteApplication)
  225. m.Route("/delete", "GET,POST", user.SettingsDelete)
  226. }, reqSignIn, func(ctx *context.Context) {
  227. ctx.Data["PageIsUserSettings"] = true
  228. })
  229. m.Group("/user", func() {
  230. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  231. m.Any("/activate", user.Activate)
  232. m.Any("/activate_email", user.ActivateEmail)
  233. m.Get("/email2user", user.Email2User)
  234. m.Get("/forget_password", user.ForgotPasswd)
  235. m.Post("/forget_password", user.ForgotPasswdPost)
  236. m.Get("/logout", user.SignOut)
  237. })
  238. // ***** END: User *****
  239. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  240. // ***** START: Admin *****
  241. m.Group("/admin", func() {
  242. m.Get("", adminReq, admin.Dashboard)
  243. m.Get("/config", admin.Config)
  244. m.Post("/config/test_mail", admin.SendTestMail)
  245. m.Get("/monitor", admin.Monitor)
  246. m.Group("/users", func() {
  247. m.Get("", admin.Users)
  248. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  249. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  250. m.Post("/:userid/delete", admin.DeleteUser)
  251. })
  252. m.Group("/orgs", func() {
  253. m.Get("", admin.Organizations)
  254. })
  255. m.Group("/repos", func() {
  256. m.Get("", admin.Repos)
  257. m.Post("/delete", admin.DeleteRepo)
  258. })
  259. m.Group("/auths", func() {
  260. m.Get("", admin.Authentications)
  261. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  262. m.Combo("/:authid").Get(admin.EditAuthSource).
  263. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  264. m.Post("/:authid/delete", admin.DeleteAuthSource)
  265. })
  266. m.Group("/notices", func() {
  267. m.Get("", admin.Notices)
  268. m.Post("/delete", admin.DeleteNotices)
  269. m.Get("/empty", admin.EmptyNotices)
  270. })
  271. }, adminReq)
  272. // ***** END: Admin *****
  273. m.Group("", func() {
  274. m.Group("/:username", func() {
  275. m.Get("", user.Profile)
  276. m.Get("/followers", user.Followers)
  277. m.Get("/following", user.Following)
  278. m.Get("/stars", user.Stars)
  279. })
  280. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  281. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  282. if err != nil {
  283. if models.IsErrAttachmentNotExist(err) {
  284. ctx.Error(404)
  285. } else {
  286. ctx.Handle(500, "GetAttachmentByUUID", err)
  287. }
  288. return
  289. }
  290. fr, err := os.Open(attach.LocalPath())
  291. if err != nil {
  292. ctx.Handle(500, "Open", err)
  293. return
  294. }
  295. defer fr.Close()
  296. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  297. ctx.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name))
  298. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  299. // We must put the name in " manually.
  300. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  301. ctx.Handle(500, "ServeData", err)
  302. return
  303. }
  304. })
  305. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  306. }, ignSignIn)
  307. m.Group("/:username", func() {
  308. m.Get("/action/:action", user.Action)
  309. }, reqSignIn)
  310. if macaron.Env == macaron.DEV {
  311. m.Get("/template/*", dev.TemplatePreview)
  312. }
  313. reqRepoAdmin := context.RequireRepoAdmin()
  314. reqRepoWriter := context.RequireRepoWriter()
  315. // ***** START: Organization *****
  316. m.Group("/org", func() {
  317. m.Get("/create", org.Create)
  318. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  319. m.Group("/:org", func() {
  320. m.Get("/dashboard", user.Dashboard)
  321. m.Get("/^:type(issues|pulls)$", user.Issues)
  322. m.Get("/members", org.Members)
  323. m.Get("/members/action/:action", org.MembersAction)
  324. m.Get("/teams", org.Teams)
  325. }, context.OrgAssignment(true))
  326. m.Group("/:org", func() {
  327. m.Get("/teams/:team", org.TeamMembers)
  328. m.Get("/teams/:team/repositories", org.TeamRepositories)
  329. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  330. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  331. }, context.OrgAssignment(true, false, true))
  332. m.Group("/:org", func() {
  333. m.Get("/teams/new", org.NewTeam)
  334. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  335. m.Get("/teams/:team/edit", org.EditTeam)
  336. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  337. m.Post("/teams/:team/delete", org.DeleteTeam)
  338. m.Group("/settings", func() {
  339. m.Combo("").Get(org.Settings).
  340. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  341. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
  342. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  343. m.Group("/hooks", func() {
  344. m.Get("", org.Webhooks)
  345. m.Post("/delete", org.DeleteWebhook)
  346. m.Get("/:type/new", repo.WebhooksNew)
  347. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  348. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  349. m.Get("/:id", repo.WebHooksEdit)
  350. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  351. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  352. })
  353. m.Route("/delete", "GET,POST", org.SettingsDelete)
  354. })
  355. m.Route("/invitations/new", "GET,POST", org.Invitation)
  356. }, context.OrgAssignment(true, true))
  357. }, reqSignIn)
  358. // ***** END: Organization *****
  359. // ***** START: Repository *****
  360. m.Group("/repo", func() {
  361. m.Get("/create", repo.Create)
  362. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  363. m.Get("/migrate", repo.Migrate)
  364. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  365. m.Combo("/fork/:repoid").Get(repo.Fork).
  366. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  367. }, reqSignIn)
  368. m.Group("/:username/:reponame", func() {
  369. m.Group("/settings", func() {
  370. m.Combo("").Get(repo.Settings).
  371. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  372. m.Group("/collaboration", func() {
  373. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  374. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  375. m.Post("/delete", repo.DeleteCollaboration)
  376. })
  377. m.Group("/hooks", func() {
  378. m.Get("", repo.Webhooks)
  379. m.Post("/delete", repo.DeleteWebhook)
  380. m.Get("/:type/new", repo.WebhooksNew)
  381. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  382. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  383. m.Get("/:id", repo.WebHooksEdit)
  384. m.Post("/:id/test", repo.TestWebhook)
  385. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  386. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  387. m.Group("/git", func() {
  388. m.Get("", repo.GitHooks)
  389. m.Combo("/:name").Get(repo.GitHooksEdit).
  390. Post(repo.GitHooksEditPost)
  391. }, context.GitHookService())
  392. })
  393. m.Group("/keys", func() {
  394. m.Combo("").Get(repo.DeployKeys).
  395. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  396. m.Post("/delete", repo.DeleteDeployKey)
  397. })
  398. }, func(ctx *context.Context) {
  399. ctx.Data["PageIsSettings"] = true
  400. })
  401. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  402. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  403. m.Group("/:username/:reponame", func() {
  404. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  405. // So they can apply their own enable/disable logic on routers.
  406. m.Group("/issues", func() {
  407. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  408. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  409. m.Group("/:index", func() {
  410. m.Post("/label", repo.UpdateIssueLabel)
  411. m.Post("/milestone", repo.UpdateIssueMilestone)
  412. m.Post("/assignee", repo.UpdateIssueAssignee)
  413. }, reqRepoWriter)
  414. m.Group("/:index", func() {
  415. m.Post("/title", repo.UpdateIssueTitle)
  416. m.Post("/content", repo.UpdateIssueContent)
  417. m.Combo("/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  418. })
  419. })
  420. m.Group("/comments/:id", func() {
  421. m.Post("", repo.UpdateCommentContent)
  422. m.Post("/delete", repo.DeleteComment)
  423. })
  424. m.Group("/labels", func() {
  425. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  426. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  427. m.Post("/delete", repo.DeleteLabel)
  428. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  429. }, reqRepoWriter, context.RepoRef())
  430. m.Group("/milestones", func() {
  431. m.Combo("/new").Get(repo.NewMilestone).
  432. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  433. m.Get("/:id/edit", repo.EditMilestone)
  434. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  435. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  436. m.Post("/delete", repo.DeleteMilestone)
  437. }, reqRepoWriter, context.RepoRef())
  438. m.Group("/releases", func() {
  439. m.Get("/new", repo.NewRelease)
  440. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  441. m.Get("/edit/*", repo.EditRelease)
  442. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  443. m.Post("/delete", repo.DeleteRelease)
  444. }, reqRepoWriter, context.RepoRef())
  445. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  446. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  447. m.Group("", func() {
  448. m.Combo("/_edit/*").Get(repo.EditFile).
  449. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  450. m.Combo("/_new/*").Get(repo.NewFile).
  451. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  452. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  453. m.Combo("/_delete/*").Get(repo.DeleteFile).
  454. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  455. m.Group("", func() {
  456. m.Combo("/_upload/*").Get(repo.UploadFile).
  457. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  458. m.Post("/upload-file", repo.UploadFileToServer)
  459. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  460. }, func(ctx *context.Context) {
  461. if !setting.Repository.Upload.Enabled {
  462. ctx.Handle(404, "", nil)
  463. return
  464. }
  465. })
  466. }, reqRepoWriter, context.RepoRef(), func(ctx *context.Context) {
  467. if !ctx.Repo.Repository.CanEnableEditor() || ctx.Repo.IsViewCommit {
  468. ctx.Handle(404, "", nil)
  469. return
  470. }
  471. })
  472. }, reqSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  473. m.Group("/:username/:reponame", func() {
  474. m.Group("", func() {
  475. m.Get("/releases", repo.Releases)
  476. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  477. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  478. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  479. m.Get("/milestones", repo.Milestones)
  480. }, context.RepoRef())
  481. // m.Get("/branches", repo.Branches)
  482. m.Group("/wiki", func() {
  483. m.Get("/?:page", repo.Wiki)
  484. m.Get("/_pages", repo.WikiPages)
  485. m.Group("", func() {
  486. m.Combo("/_new").Get(repo.NewWiki).
  487. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  488. m.Combo("/:page/_edit").Get(repo.EditWiki).
  489. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  490. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  491. }, reqSignIn, reqRepoWriter)
  492. }, repo.MustEnableWiki, context.RepoRef())
  493. m.Get("/archive/*", repo.Download)
  494. m.Group("/pulls/:index", func() {
  495. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  496. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  497. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  498. }, repo.MustAllowPulls)
  499. m.Group("", func() {
  500. m.Get("/src/*", repo.Home)
  501. m.Get("/raw/*", repo.SingleDownload)
  502. m.Get("/commits/*", repo.RefCommits)
  503. m.Get("/commit/:sha([a-z0-9]{7,40})$", repo.Diff)
  504. m.Get("/forks", repo.Forks)
  505. }, context.RepoRef())
  506. m.Get("/commit/:sha([a-z0-9]{7,40})\\.:ext(patch|diff)", repo.RawDiff)
  507. m.Get("/compare/:before([a-z0-9]{7,40})\\.\\.\\.:after([a-z0-9]{7,40})", repo.CompareDiff)
  508. }, ignSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  509. m.Group("/:username/:reponame", func() {
  510. m.Get("/stars", repo.Stars)
  511. m.Get("/watchers", repo.Watchers)
  512. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  513. m.Group("/:username", func() {
  514. m.Group("/:reponame", func() {
  515. m.Get("", repo.Home)
  516. m.Get("\\.git$", repo.Home)
  517. }, ignSignIn, context.RepoAssignment(true), context.RepoRef())
  518. m.Group("/:reponame", func() {
  519. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  520. m.Head("/tasks/trigger", repo.TriggerTask)
  521. })
  522. })
  523. // ***** END: Repository *****
  524. m.Group("/api", func() {
  525. apiv1.RegisterRoutes(m)
  526. }, ignSignIn)
  527. // robots.txt
  528. m.Get("/robots.txt", func(ctx *context.Context) {
  529. if setting.HasRobotsTxt {
  530. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  531. } else {
  532. ctx.Error(404)
  533. }
  534. })
  535. // Not found handler.
  536. m.NotFound(routers.NotFound)
  537. // Flag for port number in case first time run conflict.
  538. if ctx.IsSet("port") {
  539. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HTTPPort, ctx.String("port"), 1)
  540. setting.HTTPPort = ctx.String("port")
  541. }
  542. var listenAddr string
  543. if setting.Protocol == setting.UNIX_SOCKET {
  544. listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
  545. } else {
  546. listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
  547. }
  548. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  549. var err error
  550. switch setting.Protocol {
  551. case setting.HTTP:
  552. err = http.ListenAndServe(listenAddr, m)
  553. case setting.HTTPS:
  554. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  555. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  556. case setting.FCGI:
  557. err = fcgi.Serve(nil, m)
  558. case setting.UNIX_SOCKET:
  559. os.Remove(listenAddr)
  560. var listener *net.UnixListener
  561. listener, err = net.ListenUnix("unix", &net.UnixAddr{listenAddr, "unix"})
  562. if err != nil {
  563. break // Handle error after switch
  564. }
  565. // FIXME: add proper implementation of signal capture on all protocols
  566. // execute this on SIGTERM or SIGINT: listener.Close()
  567. if err = os.Chmod(listenAddr, os.FileMode(setting.UnixSocketPermission)); err != nil {
  568. log.Fatal(4, "Failed to set permission of unix socket: %v", err)
  569. }
  570. err = http.Serve(listener, m)
  571. default:
  572. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  573. }
  574. if err != nil {
  575. log.Fatal(4, "Fail to start server: %v", err)
  576. }
  577. return nil
  578. }