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.

http.go 16KB

10 years ago
9 years ago
10 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
4 years ago
10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
4 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "bytes"
  8. "compress/gzip"
  9. gocontext "context"
  10. "fmt"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "code.gitea.io/gitea/models"
  20. "code.gitea.io/gitea/modules/auth/sso"
  21. "code.gitea.io/gitea/modules/base"
  22. "code.gitea.io/gitea/modules/context"
  23. "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/process"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/modules/timeutil"
  28. )
  29. // HTTP implmentation git smart HTTP protocol
  30. func HTTP(ctx *context.Context) {
  31. if len(setting.Repository.AccessControlAllowOrigin) > 0 {
  32. allowedOrigin := setting.Repository.AccessControlAllowOrigin
  33. // Set CORS headers for browser-based git clients
  34. ctx.Resp.Header().Set("Access-Control-Allow-Origin", allowedOrigin)
  35. ctx.Resp.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, User-Agent")
  36. // Handle preflight OPTIONS request
  37. if ctx.Req.Method == "OPTIONS" {
  38. if allowedOrigin == "*" {
  39. ctx.Status(http.StatusOK)
  40. } else if allowedOrigin == "null" {
  41. ctx.Status(http.StatusForbidden)
  42. } else {
  43. origin := ctx.Req.Header.Get("Origin")
  44. if len(origin) > 0 && origin == allowedOrigin {
  45. ctx.Status(http.StatusOK)
  46. } else {
  47. ctx.Status(http.StatusForbidden)
  48. }
  49. }
  50. return
  51. }
  52. }
  53. username := ctx.Params(":username")
  54. reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
  55. if ctx.Query("go-get") == "1" {
  56. context.EarlyResponseForGoGetMeta(ctx)
  57. return
  58. }
  59. var isPull bool
  60. service := ctx.Query("service")
  61. if service == "git-receive-pack" ||
  62. strings.HasSuffix(ctx.Req.URL.Path, "git-receive-pack") {
  63. isPull = false
  64. } else if service == "git-upload-pack" ||
  65. strings.HasSuffix(ctx.Req.URL.Path, "git-upload-pack") {
  66. isPull = true
  67. } else if service == "git-upload-archive" ||
  68. strings.HasSuffix(ctx.Req.URL.Path, "git-upload-archive") {
  69. isPull = true
  70. } else {
  71. isPull = (ctx.Req.Method == "GET")
  72. }
  73. var accessMode models.AccessMode
  74. if isPull {
  75. accessMode = models.AccessModeRead
  76. } else {
  77. accessMode = models.AccessModeWrite
  78. }
  79. isWiki := false
  80. var unitType = models.UnitTypeCode
  81. if strings.HasSuffix(reponame, ".wiki") {
  82. isWiki = true
  83. unitType = models.UnitTypeWiki
  84. reponame = reponame[:len(reponame)-5]
  85. }
  86. owner, err := models.GetUserByName(username)
  87. if err != nil {
  88. ctx.NotFoundOrServerError("GetUserByName", models.IsErrUserNotExist, err)
  89. return
  90. }
  91. repo, err := models.GetRepositoryByName(owner.ID, reponame)
  92. if err != nil {
  93. if models.IsErrRepoNotExist(err) {
  94. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, reponame)
  95. if err == nil {
  96. context.RedirectToRepo(ctx, redirectRepoID)
  97. } else {
  98. ctx.NotFoundOrServerError("GetRepositoryByName", models.IsErrRepoRedirectNotExist, err)
  99. }
  100. } else {
  101. ctx.ServerError("GetRepositoryByName", err)
  102. }
  103. return
  104. }
  105. // Don't allow pushing if the repo is archived
  106. if repo.IsArchived && !isPull {
  107. ctx.HandleText(http.StatusForbidden, "This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.")
  108. return
  109. }
  110. // Only public pull don't need auth.
  111. isPublicPull := !repo.IsPrivate && isPull
  112. var (
  113. askAuth = !isPublicPull || setting.Service.RequireSignInView
  114. authUser *models.User
  115. authUsername string
  116. authPasswd string
  117. environ []string
  118. )
  119. // check access
  120. if askAuth {
  121. authUsername = ctx.Req.Header.Get(setting.ReverseProxyAuthUser)
  122. if setting.Service.EnableReverseProxyAuth && len(authUsername) > 0 {
  123. authUser, err = models.GetUserByName(authUsername)
  124. if err != nil {
  125. ctx.HandleText(401, "reverse proxy login error, got error while running GetUserByName")
  126. return
  127. }
  128. } else {
  129. authHead := ctx.Req.Header.Get("Authorization")
  130. if len(authHead) == 0 {
  131. ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=\".\"")
  132. ctx.Error(http.StatusUnauthorized)
  133. return
  134. }
  135. auths := strings.Fields(authHead)
  136. // currently check basic auth
  137. // TODO: support digit auth
  138. // FIXME: middlewares/context.go did basic auth check already,
  139. // maybe could use that one.
  140. if len(auths) != 2 || auths[0] != "Basic" {
  141. ctx.HandleText(http.StatusUnauthorized, "no basic auth and digit auth")
  142. return
  143. }
  144. authUsername, authPasswd, err = base.BasicAuthDecode(auths[1])
  145. if err != nil {
  146. ctx.HandleText(http.StatusUnauthorized, "no basic auth and digit auth")
  147. return
  148. }
  149. // Check if username or password is a token
  150. isUsernameToken := len(authPasswd) == 0 || authPasswd == "x-oauth-basic"
  151. // Assume username is token
  152. authToken := authUsername
  153. if !isUsernameToken {
  154. // Assume password is token
  155. authToken = authPasswd
  156. }
  157. uid := sso.CheckOAuthAccessToken(authToken)
  158. if uid != 0 {
  159. ctx.Data["IsApiToken"] = true
  160. authUser, err = models.GetUserByID(uid)
  161. if err != nil {
  162. ctx.ServerError("GetUserByID", err)
  163. return
  164. }
  165. }
  166. // Assume password is a token.
  167. token, err := models.GetAccessTokenBySHA(authToken)
  168. if err == nil {
  169. if isUsernameToken {
  170. authUser, err = models.GetUserByID(token.UID)
  171. if err != nil {
  172. ctx.ServerError("GetUserByID", err)
  173. return
  174. }
  175. } else {
  176. authUser, err = models.GetUserByName(authUsername)
  177. if err != nil {
  178. if models.IsErrUserNotExist(err) {
  179. ctx.HandleText(http.StatusUnauthorized, "invalid credentials")
  180. } else {
  181. ctx.ServerError("GetUserByName", err)
  182. }
  183. return
  184. }
  185. if authUser.ID != token.UID {
  186. ctx.HandleText(http.StatusUnauthorized, "invalid credentials")
  187. return
  188. }
  189. }
  190. token.UpdatedUnix = timeutil.TimeStampNow()
  191. if err = models.UpdateAccessToken(token); err != nil {
  192. ctx.ServerError("UpdateAccessToken", err)
  193. }
  194. } else if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) {
  195. log.Error("GetAccessTokenBySha: %v", err)
  196. }
  197. if authUser == nil {
  198. // Check username and password
  199. authUser, err = models.UserSignIn(authUsername, authPasswd)
  200. if err != nil {
  201. if models.IsErrUserProhibitLogin(err) {
  202. ctx.HandleText(http.StatusForbidden, "User is not permitted to login")
  203. return
  204. } else if !models.IsErrUserNotExist(err) {
  205. ctx.ServerError("UserSignIn error: %v", err)
  206. return
  207. }
  208. }
  209. if authUser == nil {
  210. ctx.HandleText(http.StatusUnauthorized, "invalid credentials")
  211. return
  212. }
  213. _, err = models.GetTwoFactorByUID(authUser.ID)
  214. if err == nil {
  215. // TODO: This response should be changed to "invalid credentials" for security reasons once the expectation behind it (creating an app token to authenticate) is properly documented
  216. ctx.HandleText(http.StatusUnauthorized, "Users with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password. Please create and use a personal access token on the user settings page")
  217. return
  218. } else if !models.IsErrTwoFactorNotEnrolled(err) {
  219. ctx.ServerError("IsErrTwoFactorNotEnrolled", err)
  220. return
  221. }
  222. }
  223. }
  224. perm, err := models.GetUserRepoPermission(repo, authUser)
  225. if err != nil {
  226. ctx.ServerError("GetUserRepoPermission", err)
  227. return
  228. }
  229. if !perm.CanAccess(accessMode, unitType) {
  230. ctx.HandleText(http.StatusForbidden, "User permission denied")
  231. return
  232. }
  233. if !isPull && repo.IsMirror {
  234. ctx.HandleText(http.StatusForbidden, "mirror repository is read-only")
  235. return
  236. }
  237. environ = []string{
  238. models.EnvRepoUsername + "=" + username,
  239. models.EnvRepoName + "=" + reponame,
  240. models.EnvPusherName + "=" + authUser.Name,
  241. models.EnvPusherID + fmt.Sprintf("=%d", authUser.ID),
  242. models.ProtectedBranchRepoID + fmt.Sprintf("=%d", repo.ID),
  243. models.EnvIsDeployKey + "=false",
  244. }
  245. if !authUser.KeepEmailPrivate {
  246. environ = append(environ, models.EnvPusherEmail+"="+authUser.Email)
  247. }
  248. if isWiki {
  249. environ = append(environ, models.EnvRepoIsWiki+"=true")
  250. } else {
  251. environ = append(environ, models.EnvRepoIsWiki+"=false")
  252. }
  253. }
  254. w := ctx.Resp
  255. r := ctx.Req.Request
  256. cfg := &serviceConfig{
  257. UploadPack: true,
  258. ReceivePack: true,
  259. Env: environ,
  260. }
  261. for _, route := range routes {
  262. r.URL.Path = strings.ToLower(r.URL.Path) // blue: In case some repo name has upper case name
  263. if m := route.reg.FindStringSubmatch(r.URL.Path); m != nil {
  264. if setting.Repository.DisableHTTPGit {
  265. w.WriteHeader(http.StatusForbidden)
  266. _, err := w.Write([]byte("Interacting with repositories by HTTP protocol is not allowed"))
  267. if err != nil {
  268. log.Error(err.Error())
  269. }
  270. return
  271. }
  272. if route.method != r.Method {
  273. if r.Proto == "HTTP/1.1" {
  274. w.WriteHeader(http.StatusMethodNotAllowed)
  275. _, err := w.Write([]byte("Method Not Allowed"))
  276. if err != nil {
  277. log.Error(err.Error())
  278. }
  279. } else {
  280. w.WriteHeader(http.StatusBadRequest)
  281. _, err := w.Write([]byte("Bad Request"))
  282. if err != nil {
  283. log.Error(err.Error())
  284. }
  285. }
  286. return
  287. }
  288. file := strings.Replace(r.URL.Path, m[1]+"/", "", 1)
  289. dir, err := getGitRepoPath(m[1])
  290. if err != nil {
  291. log.Error(err.Error())
  292. ctx.NotFound("Smart Git HTTP", err)
  293. return
  294. }
  295. route.handler(serviceHandler{cfg, w, r, dir, file, cfg.Env})
  296. return
  297. }
  298. }
  299. ctx.NotFound("Smart Git HTTP", nil)
  300. }
  301. type serviceConfig struct {
  302. UploadPack bool
  303. ReceivePack bool
  304. Env []string
  305. }
  306. type serviceHandler struct {
  307. cfg *serviceConfig
  308. w http.ResponseWriter
  309. r *http.Request
  310. dir string
  311. file string
  312. environ []string
  313. }
  314. func (h *serviceHandler) setHeaderNoCache() {
  315. h.w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  316. h.w.Header().Set("Pragma", "no-cache")
  317. h.w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  318. }
  319. func (h *serviceHandler) setHeaderCacheForever() {
  320. now := time.Now().Unix()
  321. expires := now + 31536000
  322. h.w.Header().Set("Date", fmt.Sprintf("%d", now))
  323. h.w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  324. h.w.Header().Set("Cache-Control", "public, max-age=31536000")
  325. }
  326. func (h *serviceHandler) sendFile(contentType string) {
  327. reqFile := path.Join(h.dir, h.file)
  328. fi, err := os.Stat(reqFile)
  329. if os.IsNotExist(err) {
  330. h.w.WriteHeader(http.StatusNotFound)
  331. return
  332. }
  333. h.w.Header().Set("Content-Type", contentType)
  334. h.w.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size()))
  335. h.w.Header().Set("Last-Modified", fi.ModTime().Format(http.TimeFormat))
  336. http.ServeFile(h.w, h.r, reqFile)
  337. }
  338. type route struct {
  339. reg *regexp.Regexp
  340. method string
  341. handler func(serviceHandler)
  342. }
  343. var routes = []route{
  344. {regexp.MustCompile(`(.*?)/git-upload-pack$`), "POST", serviceUploadPack},
  345. {regexp.MustCompile(`(.*?)/git-receive-pack$`), "POST", serviceReceivePack},
  346. {regexp.MustCompile(`(.*?)/info/refs$`), "GET", getInfoRefs},
  347. {regexp.MustCompile(`(.*?)/HEAD$`), "GET", getTextFile},
  348. {regexp.MustCompile(`(.*?)/objects/info/alternates$`), "GET", getTextFile},
  349. {regexp.MustCompile(`(.*?)/objects/info/http-alternates$`), "GET", getTextFile},
  350. {regexp.MustCompile(`(.*?)/objects/info/packs$`), "GET", getInfoPacks},
  351. {regexp.MustCompile(`(.*?)/objects/info/[^/]*$`), "GET", getTextFile},
  352. {regexp.MustCompile(`(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$`), "GET", getLooseObject},
  353. {regexp.MustCompile(`(.*?)/objects/pack/pack-[0-9a-f]{40}\.pack$`), "GET", getPackFile},
  354. {regexp.MustCompile(`(.*?)/objects/pack/pack-[0-9a-f]{40}\.idx$`), "GET", getIdxFile},
  355. }
  356. func getGitConfig(option, dir string) string {
  357. out, err := git.NewCommand("config", option).RunInDir(dir)
  358. if err != nil {
  359. log.Error("%v - %s", err, out)
  360. }
  361. return out[0 : len(out)-1]
  362. }
  363. func getConfigSetting(service, dir string) bool {
  364. service = strings.Replace(service, "-", "", -1)
  365. setting := getGitConfig("http."+service, dir)
  366. if service == "uploadpack" {
  367. return setting != "false"
  368. }
  369. return setting == "true"
  370. }
  371. func hasAccess(service string, h serviceHandler, checkContentType bool) bool {
  372. if checkContentType {
  373. if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) {
  374. return false
  375. }
  376. }
  377. if !(service == "upload-pack" || service == "receive-pack") {
  378. return false
  379. }
  380. if service == "receive-pack" {
  381. return h.cfg.ReceivePack
  382. }
  383. if service == "upload-pack" {
  384. return h.cfg.UploadPack
  385. }
  386. return getConfigSetting(service, h.dir)
  387. }
  388. func serviceRPC(h serviceHandler, service string) {
  389. defer func() {
  390. if err := h.r.Body.Close(); err != nil {
  391. log.Error("serviceRPC: Close: %v", err)
  392. }
  393. }()
  394. if !hasAccess(service, h, true) {
  395. h.w.WriteHeader(http.StatusUnauthorized)
  396. return
  397. }
  398. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service))
  399. var err error
  400. var reqBody = h.r.Body
  401. // Handle GZIP.
  402. if h.r.Header.Get("Content-Encoding") == "gzip" {
  403. reqBody, err = gzip.NewReader(reqBody)
  404. if err != nil {
  405. log.Error("Fail to create gzip reader: %v", err)
  406. h.w.WriteHeader(http.StatusInternalServerError)
  407. return
  408. }
  409. }
  410. // set this for allow pre-receive and post-receive execute
  411. h.environ = append(h.environ, "SSH_ORIGINAL_COMMAND="+service)
  412. ctx, cancel := gocontext.WithCancel(git.DefaultContext)
  413. defer cancel()
  414. var stderr bytes.Buffer
  415. cmd := exec.CommandContext(ctx, git.GitExecutable, service, "--stateless-rpc", h.dir)
  416. cmd.Dir = h.dir
  417. if service == "receive-pack" {
  418. cmd.Env = append(os.Environ(), h.environ...)
  419. }
  420. cmd.Stdout = h.w
  421. cmd.Stdin = reqBody
  422. cmd.Stderr = &stderr
  423. pid := process.GetManager().Add(fmt.Sprintf("%s %s %s [repo_path: %s]", git.GitExecutable, service, "--stateless-rpc", h.dir), cancel)
  424. defer process.GetManager().Remove(pid)
  425. if err := cmd.Run(); err != nil {
  426. log.Error("Fail to serve RPC(%s): %v - %s", service, err, stderr.String())
  427. return
  428. }
  429. }
  430. func serviceUploadPack(h serviceHandler) {
  431. serviceRPC(h, "upload-pack")
  432. }
  433. func serviceReceivePack(h serviceHandler) {
  434. serviceRPC(h, "receive-pack")
  435. }
  436. func getServiceType(r *http.Request) string {
  437. serviceType := r.FormValue("service")
  438. if !strings.HasPrefix(serviceType, "git-") {
  439. return ""
  440. }
  441. return strings.Replace(serviceType, "git-", "", 1)
  442. }
  443. func updateServerInfo(dir string) []byte {
  444. out, err := git.NewCommand("update-server-info").RunInDirBytes(dir)
  445. if err != nil {
  446. log.Error(fmt.Sprintf("%v - %s", err, string(out)))
  447. }
  448. return out
  449. }
  450. func packetWrite(str string) []byte {
  451. s := strconv.FormatInt(int64(len(str)+4), 16)
  452. if len(s)%4 != 0 {
  453. s = strings.Repeat("0", 4-len(s)%4) + s
  454. }
  455. return []byte(s + str)
  456. }
  457. func getInfoRefs(h serviceHandler) {
  458. h.setHeaderNoCache()
  459. if hasAccess(getServiceType(h.r), h, false) {
  460. service := getServiceType(h.r)
  461. refs, err := git.NewCommand(service, "--stateless-rpc", "--advertise-refs", ".").RunInDirBytes(h.dir)
  462. if err != nil {
  463. log.Error(fmt.Sprintf("%v - %s", err, string(refs)))
  464. }
  465. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
  466. h.w.WriteHeader(http.StatusOK)
  467. _, _ = h.w.Write(packetWrite("# service=git-" + service + "\n"))
  468. _, _ = h.w.Write([]byte("0000"))
  469. _, _ = h.w.Write(refs)
  470. } else {
  471. updateServerInfo(h.dir)
  472. h.sendFile("text/plain; charset=utf-8")
  473. }
  474. }
  475. func getTextFile(h serviceHandler) {
  476. h.setHeaderNoCache()
  477. h.sendFile("text/plain")
  478. }
  479. func getInfoPacks(h serviceHandler) {
  480. h.setHeaderCacheForever()
  481. h.sendFile("text/plain; charset=utf-8")
  482. }
  483. func getLooseObject(h serviceHandler) {
  484. h.setHeaderCacheForever()
  485. h.sendFile("application/x-git-loose-object")
  486. }
  487. func getPackFile(h serviceHandler) {
  488. h.setHeaderCacheForever()
  489. h.sendFile("application/x-git-packed-objects")
  490. }
  491. func getIdxFile(h serviceHandler) {
  492. h.setHeaderCacheForever()
  493. h.sendFile("application/x-git-packed-objects-toc")
  494. }
  495. func getGitRepoPath(subdir string) (string, error) {
  496. if !strings.HasSuffix(subdir, ".git") {
  497. subdir += ".git"
  498. }
  499. fpath := path.Join(setting.RepoRootPath, subdir)
  500. if _, err := os.Stat(fpath); os.IsNotExist(err) {
  501. return "", err
  502. }
  503. return fpath, nil
  504. }