You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

web.go 19KB

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