web.go 23 KB

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