Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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