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.

web.go 23KB

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