web.go 24 KB

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