web.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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.4"},
  81. {"github.com/gogits/git-module", git.Version, "0.3.3"},
  82. {"github.com/gogits/go-gogs-client", gogs.Version, "0.10.1"},
  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.CacheInternal,
  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. /* BEGIN notabug patch */
  199. m.Get("/about", ignSignIn, routers.About)
  200. m.Get("/help", ignSignIn, routers.Help)
  201. m.Get("/outages", ignSignIn, routers.Outages)
  202. m.Get("/tos", ignSignIn, routers.Tos)
  203. /* END notabug patch */
  204. // ***** START: User *****
  205. m.Group("/user", func() {
  206. m.Get("/login", user.SignIn)
  207. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  208. m.Get("/sign_up", user.SignUp)
  209. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  210. m.Get("/reset_password", user.ResetPasswd)
  211. m.Post("/reset_password", user.ResetPasswdPost)
  212. }, reqSignOut)
  213. m.Group("/user/settings", func() {
  214. m.Get("", user.Settings)
  215. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  216. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
  217. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  218. m.Combo("/email").Get(user.SettingsEmails).
  219. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  220. m.Post("/email/delete", user.DeleteEmail)
  221. m.Get("/password", user.SettingsPassword)
  222. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  223. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  224. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  225. m.Post("/ssh/delete", user.DeleteSSHKey)
  226. m.Combo("/applications").Get(user.SettingsApplications).
  227. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  228. m.Post("/applications/delete", user.SettingsDeleteApplication)
  229. m.Route("/delete", "GET,POST", user.SettingsDelete)
  230. }, reqSignIn, func(ctx *context.Context) {
  231. ctx.Data["PageIsUserSettings"] = true
  232. })
  233. m.Group("/user", func() {
  234. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  235. m.Any("/activate", user.Activate)
  236. m.Any("/activate_email", user.ActivateEmail)
  237. m.Get("/email2user", user.Email2User)
  238. m.Get("/forget_password", user.ForgotPasswd)
  239. m.Post("/forget_password", user.ForgotPasswdPost)
  240. m.Get("/logout", user.SignOut)
  241. })
  242. // ***** END: User *****
  243. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  244. // ***** START: Admin *****
  245. m.Group("/admin", func() {
  246. m.Get("", adminReq, admin.Dashboard)
  247. m.Get("/config", admin.Config)
  248. m.Post("/config/test_mail", admin.SendTestMail)
  249. m.Get("/monitor", admin.Monitor)
  250. m.Group("/users", func() {
  251. m.Get("", admin.Users)
  252. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  253. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  254. m.Post("/:userid/delete", admin.DeleteUser)
  255. })
  256. m.Group("/orgs", func() {
  257. m.Get("", admin.Organizations)
  258. })
  259. m.Group("/repos", func() {
  260. m.Get("", admin.Repos)
  261. m.Post("/delete", admin.DeleteRepo)
  262. })
  263. m.Group("/auths", func() {
  264. m.Get("", admin.Authentications)
  265. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  266. m.Combo("/:authid").Get(admin.EditAuthSource).
  267. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  268. m.Post("/:authid/delete", admin.DeleteAuthSource)
  269. })
  270. m.Group("/notices", func() {
  271. m.Get("", admin.Notices)
  272. m.Post("/delete", admin.DeleteNotices)
  273. m.Get("/empty", admin.EmptyNotices)
  274. })
  275. }, adminReq)
  276. // ***** END: Admin *****
  277. m.Group("", func() {
  278. m.Group("/:username", func() {
  279. m.Get("", user.Profile)
  280. m.Get("/followers", user.Followers)
  281. m.Get("/following", user.Following)
  282. m.Get("/stars", user.Stars)
  283. })
  284. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  285. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  286. if err != nil {
  287. if models.IsErrAttachmentNotExist(err) {
  288. ctx.Error(404)
  289. } else {
  290. ctx.Handle(500, "GetAttachmentByUUID", err)
  291. }
  292. return
  293. }
  294. fr, err := os.Open(attach.LocalPath())
  295. if err != nil {
  296. ctx.Handle(500, "Open", err)
  297. return
  298. }
  299. defer fr.Close()
  300. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  301. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  302. // We must put the name in " manually.
  303. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  304. ctx.Handle(500, "ServeData", err)
  305. return
  306. }
  307. })
  308. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  309. }, ignSignIn)
  310. m.Group("/:username", func() {
  311. m.Get("/action/:action", user.Action)
  312. }, reqSignIn)
  313. if macaron.Env == macaron.DEV {
  314. m.Get("/template/*", dev.TemplatePreview)
  315. }
  316. reqRepoAdmin := context.RequireRepoAdmin()
  317. reqRepoWriter := context.RequireRepoWriter()
  318. // ***** START: Organization *****
  319. m.Group("/org", func() {
  320. m.Get("/create", org.Create)
  321. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  322. m.Group("/:org", func() {
  323. m.Get("/dashboard", user.Dashboard)
  324. m.Get("/^:type(issues|pulls)$", user.Issues)
  325. m.Get("/members", org.Members)
  326. m.Get("/members/action/:action", org.MembersAction)
  327. m.Get("/teams", org.Teams)
  328. }, context.OrgAssignment(true))
  329. m.Group("/:org", func() {
  330. m.Get("/teams/:team", org.TeamMembers)
  331. m.Get("/teams/:team/repositories", org.TeamRepositories)
  332. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  333. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  334. }, context.OrgAssignment(true, false, true))
  335. m.Group("/:org", func() {
  336. m.Get("/teams/new", org.NewTeam)
  337. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  338. m.Get("/teams/:team/edit", org.EditTeam)
  339. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  340. m.Post("/teams/:team/delete", org.DeleteTeam)
  341. m.Group("/settings", func() {
  342. m.Combo("").Get(org.Settings).
  343. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  344. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), org.SettingsAvatar)
  345. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  346. m.Group("/hooks", func() {
  347. m.Get("", org.Webhooks)
  348. m.Post("/delete", org.DeleteWebhook)
  349. m.Get("/:type/new", repo.WebhooksNew)
  350. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  351. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  352. m.Get("/:id", repo.WebHooksEdit)
  353. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  354. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  355. })
  356. m.Route("/delete", "GET,POST", org.SettingsDelete)
  357. })
  358. m.Route("/invitations/new", "GET,POST", org.Invitation)
  359. }, context.OrgAssignment(true, true))
  360. }, reqSignIn)
  361. // ***** END: Organization *****
  362. // ***** START: Repository *****
  363. m.Group("/repo", func() {
  364. m.Get("/create", repo.Create)
  365. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  366. m.Get("/migrate", repo.Migrate)
  367. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  368. m.Combo("/fork/:repoid").Get(repo.Fork).
  369. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  370. }, reqSignIn)
  371. m.Group("/:username/:reponame", func() {
  372. m.Group("/settings", func() {
  373. m.Combo("").Get(repo.Settings).
  374. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  375. m.Group("/collaboration", func() {
  376. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  377. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  378. m.Post("/delete", repo.DeleteCollaboration)
  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(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  385. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  386. m.Get("/:id", repo.WebHooksEdit)
  387. m.Post("/:id/test", repo.TestWebhook)
  388. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  389. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  390. m.Group("/git", func() {
  391. m.Get("", repo.GitHooks)
  392. m.Combo("/:name").Get(repo.GitHooksEdit).
  393. Post(repo.GitHooksEditPost)
  394. }, context.GitHookService())
  395. })
  396. m.Group("/keys", func() {
  397. m.Combo("").Get(repo.DeployKeys).
  398. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  399. m.Post("/delete", repo.DeleteDeployKey)
  400. })
  401. }, func(ctx *context.Context) {
  402. ctx.Data["PageIsSettings"] = true
  403. })
  404. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  405. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  406. m.Group("/:username/:reponame", func() {
  407. m.Group("/issues", func() {
  408. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  409. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  410. m.Combo("/:index/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  411. m.Group("/:index", func() {
  412. m.Post("/label", repo.UpdateIssueLabel)
  413. m.Post("/milestone", repo.UpdateIssueMilestone)
  414. m.Post("/assignee", repo.UpdateIssueAssignee)
  415. }, reqRepoWriter)
  416. m.Group("/:index", func() {
  417. m.Post("/title", repo.UpdateIssueTitle)
  418. m.Post("/content", repo.UpdateIssueContent)
  419. })
  420. })
  421. m.Group("/comments/:id", func() {
  422. m.Post("", repo.UpdateCommentContent)
  423. m.Post("/delete", repo.DeleteComment)
  424. })
  425. m.Group("/labels", func() {
  426. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  427. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  428. m.Post("/delete", repo.DeleteLabel)
  429. }, reqRepoWriter, context.RepoRef())
  430. m.Group("/milestones", func() {
  431. m.Combo("/new").Get(repo.NewMilestone).
  432. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  433. m.Get("/:id/edit", repo.EditMilestone)
  434. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  435. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  436. m.Post("/delete", repo.DeleteMilestone)
  437. }, reqRepoWriter, context.RepoRef())
  438. m.Group("/releases", func() {
  439. m.Get("/new", repo.NewRelease)
  440. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  441. m.Get("/edit/:tagname", repo.EditRelease)
  442. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  443. m.Post("/delete", repo.DeleteRelease)
  444. }, reqRepoWriter, context.RepoRef())
  445. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  446. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  447. }, reqSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  448. m.Group("/:username/:reponame", func() {
  449. m.Group("", func() {
  450. m.Get("/releases", repo.Releases)
  451. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  452. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  453. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  454. m.Get("/milestones", repo.Milestones)
  455. }, context.RepoRef())
  456. // m.Get("/branches", repo.Branches)
  457. m.Group("/wiki", func() {
  458. m.Get("/?:page", repo.Wiki)
  459. m.Get("/_pages", repo.WikiPages)
  460. m.Group("", func() {
  461. m.Combo("/_new").Get(repo.NewWiki).
  462. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  463. m.Combo("/:page/_edit").Get(repo.EditWiki).
  464. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  465. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  466. }, reqSignIn, reqRepoWriter)
  467. }, repo.MustEnableWiki, context.RepoRef())
  468. m.Get("/archive/*", repo.Download)
  469. m.Group("/pulls/:index", func() {
  470. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  471. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  472. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  473. }, repo.MustAllowPulls)
  474. m.Group("", func() {
  475. m.Get("/src/*", repo.Home)
  476. m.Get("/raw/*", repo.SingleDownload)
  477. m.Get("/commits/*", repo.RefCommits)
  478. m.Get("/commit/:sha([a-z0-9]{40})$", repo.Diff)
  479. m.Get("/forks", repo.Forks)
  480. }, context.RepoRef())
  481. m.Get("/commit/:sha([a-z0-9]{40})\\.:ext(patch|diff)", repo.RawDiff)
  482. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.CompareDiff)
  483. }, ignSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  484. m.Group("/:username/:reponame", func() {
  485. m.Get("/stars", repo.Stars)
  486. m.Get("/watchers", repo.Watchers)
  487. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  488. m.Group("/:username", func() {
  489. m.Group("/:reponame", func() {
  490. m.Get("", repo.Home)
  491. m.Get("\\.git$", repo.Home)
  492. }, ignSignIn, context.RepoAssignment(true), context.RepoRef())
  493. m.Group("/:reponame", func() {
  494. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  495. m.Head("/tasks/trigger", repo.TriggerTask)
  496. })
  497. })
  498. // ***** END: Repository *****
  499. m.Group("/api", func() {
  500. apiv1.RegisterRoutes(m)
  501. }, ignSignIn)
  502. // robots.txt
  503. m.Get("/robots.txt", func(ctx *context.Context) {
  504. if setting.HasRobotsTxt {
  505. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  506. } else {
  507. ctx.Error(404)
  508. }
  509. })
  510. // Not found handler.
  511. m.NotFound(routers.NotFound)
  512. // Flag for port number in case first time run conflict.
  513. if ctx.IsSet("port") {
  514. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HttpPort, ctx.String("port"), 1)
  515. setting.HttpPort = ctx.String("port")
  516. }
  517. var err error
  518. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  519. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  520. switch setting.Protocol {
  521. case setting.HTTP:
  522. err = http.ListenAndServe(listenAddr, m)
  523. case setting.HTTPS:
  524. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  525. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  526. case setting.FCGI:
  527. err = fcgi.Serve(nil, m)
  528. default:
  529. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  530. }
  531. if err != nil {
  532. log.Fatal(4, "Fail to start server: %v", err)
  533. }
  534. return nil
  535. }