web.go 19 KB

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