web.go 20 KB

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