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

http.go 16 kB

11 years ago
10 years ago
11 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
5 years ago
11 years ago
9 years ago
11 years ago
11 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 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
5 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. "fmt"
  10. "net/http"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "regexp"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "code.gitea.io/gitea/models"
  19. "code.gitea.io/gitea/modules/auth/sso"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/context"
  22. "code.gitea.io/gitea/modules/git"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/setting"
  25. "code.gitea.io/gitea/modules/timeutil"
  26. )
  27. // HTTP implmentation git smart HTTP protocol
  28. func HTTP(ctx *context.Context) {
  29. if len(setting.Repository.AccessControlAllowOrigin) > 0 {
  30. allowedOrigin := setting.Repository.AccessControlAllowOrigin
  31. // Set CORS headers for browser-based git clients
  32. ctx.Resp.Header().Set("Access-Control-Allow-Origin", allowedOrigin)
  33. ctx.Resp.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, User-Agent")
  34. // Handle preflight OPTIONS request
  35. if ctx.Req.Method == "OPTIONS" {
  36. if allowedOrigin == "*" {
  37. ctx.Status(http.StatusOK)
  38. } else if allowedOrigin == "null" {
  39. ctx.Status(http.StatusForbidden)
  40. } else {
  41. origin := ctx.Req.Header.Get("Origin")
  42. if len(origin) > 0 && origin == allowedOrigin {
  43. ctx.Status(http.StatusOK)
  44. } else {
  45. ctx.Status(http.StatusForbidden)
  46. }
  47. }
  48. return
  49. }
  50. }
  51. username := ctx.Params(":username")
  52. reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
  53. if ctx.Query("go-get") == "1" {
  54. context.EarlyResponseForGoGetMeta(ctx)
  55. return
  56. }
  57. var isPull bool
  58. service := ctx.Query("service")
  59. if service == "git-receive-pack" ||
  60. strings.HasSuffix(ctx.Req.URL.Path, "git-receive-pack") {
  61. isPull = false
  62. } else if service == "git-upload-pack" ||
  63. strings.HasSuffix(ctx.Req.URL.Path, "git-upload-pack") {
  64. isPull = true
  65. } else if service == "git-upload-archive" ||
  66. strings.HasSuffix(ctx.Req.URL.Path, "git-upload-archive") {
  67. isPull = true
  68. } else {
  69. isPull = (ctx.Req.Method == "GET")
  70. }
  71. var accessMode models.AccessMode
  72. if isPull {
  73. accessMode = models.AccessModeRead
  74. } else {
  75. accessMode = models.AccessModeWrite
  76. }
  77. isWiki := false
  78. var unitType = models.UnitTypeCode
  79. if strings.HasSuffix(reponame, ".wiki") {
  80. isWiki = true
  81. unitType = models.UnitTypeWiki
  82. reponame = reponame[:len(reponame)-5]
  83. }
  84. owner, err := models.GetUserByName(username)
  85. if err != nil {
  86. ctx.NotFoundOrServerError("GetUserByName", models.IsErrUserNotExist, err)
  87. return
  88. }
  89. repo, err := models.GetRepositoryByName(owner.ID, reponame)
  90. if err != nil {
  91. if models.IsErrRepoNotExist(err) {
  92. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, reponame)
  93. if err == nil {
  94. context.RedirectToRepo(ctx, redirectRepoID)
  95. } else {
  96. ctx.NotFoundOrServerError("GetRepositoryByName", models.IsErrRepoRedirectNotExist, err)
  97. }
  98. } else {
  99. ctx.ServerError("GetRepositoryByName", err)
  100. }
  101. return
  102. }
  103. // Don't allow pushing if the repo is archived
  104. if repo.IsArchived && !isPull {
  105. ctx.HandleText(http.StatusForbidden, "This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.")
  106. return
  107. }
  108. // Only public pull don't need auth.
  109. isPublicPull := !repo.IsPrivate && isPull
  110. var (
  111. askAuth = !isPublicPull || setting.Service.RequireSignInView
  112. authUser *models.User
  113. authUsername string
  114. authPasswd string
  115. environ []string
  116. )
  117. // check access
  118. if askAuth {
  119. authUsername = ctx.Req.Header.Get(setting.ReverseProxyAuthUser)
  120. if setting.Service.EnableReverseProxyAuth && len(authUsername) > 0 {
  121. authUser, err = models.GetUserByName(authUsername)
  122. if err != nil {
  123. ctx.HandleText(401, "reverse proxy login error, got error while running GetUserByName")
  124. return
  125. }
  126. } else {
  127. authHead := ctx.Req.Header.Get("Authorization")
  128. if len(authHead) == 0 {
  129. ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=\".\"")
  130. ctx.Error(http.StatusUnauthorized)
  131. return
  132. }
  133. auths := strings.Fields(authHead)
  134. // currently check basic auth
  135. // TODO: support digit auth
  136. // FIXME: middlewares/context.go did basic auth check already,
  137. // maybe could use that one.
  138. if len(auths) != 2 || auths[0] != "Basic" {
  139. ctx.HandleText(http.StatusUnauthorized, "no basic auth and digit auth")
  140. return
  141. }
  142. authUsername, authPasswd, err = base.BasicAuthDecode(auths[1])
  143. if err != nil {
  144. ctx.HandleText(http.StatusUnauthorized, "no basic auth and digit auth")
  145. return
  146. }
  147. // Check if username or password is a token
  148. isUsernameToken := len(authPasswd) == 0 || authPasswd == "x-oauth-basic"
  149. // Assume username is token
  150. authToken := authUsername
  151. if !isUsernameToken {
  152. // Assume password is token
  153. authToken = authPasswd
  154. }
  155. uid := sso.CheckOAuthAccessToken(authToken)
  156. if uid != 0 {
  157. ctx.Data["IsApiToken"] = true
  158. authUser, err = models.GetUserByID(uid)
  159. if err != nil {
  160. ctx.ServerError("GetUserByID", err)
  161. return
  162. }
  163. }
  164. // Assume password is a token.
  165. token, err := models.GetAccessTokenBySHA(authToken)
  166. if err == nil {
  167. if isUsernameToken {
  168. authUser, err = models.GetUserByID(token.UID)
  169. if err != nil {
  170. ctx.ServerError("GetUserByID", err)
  171. return
  172. }
  173. } else {
  174. authUser, err = models.GetUserByName(authUsername)
  175. if err != nil {
  176. if models.IsErrUserNotExist(err) {
  177. ctx.HandleText(http.StatusUnauthorized, "invalid credentials")
  178. } else {
  179. ctx.ServerError("GetUserByName", err)
  180. }
  181. return
  182. }
  183. if authUser.ID != token.UID {
  184. ctx.HandleText(http.StatusUnauthorized, "invalid credentials")
  185. return
  186. }
  187. }
  188. token.UpdatedUnix = timeutil.TimeStampNow()
  189. if err = models.UpdateAccessToken(token); err != nil {
  190. ctx.ServerError("UpdateAccessToken", err)
  191. }
  192. } else if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) {
  193. log.Error("GetAccessTokenBySha: %v", err)
  194. }
  195. if authUser == nil {
  196. // Check username and password
  197. authUser, err = models.UserSignIn(authUsername, authPasswd)
  198. if err != nil {
  199. if models.IsErrUserProhibitLogin(err) {
  200. ctx.HandleText(http.StatusForbidden, "User is not permitted to login")
  201. return
  202. } else if !models.IsErrUserNotExist(err) {
  203. ctx.ServerError("UserSignIn error: %v", err)
  204. return
  205. }
  206. }
  207. if authUser == nil {
  208. ctx.HandleText(http.StatusUnauthorized, "invalid credentials")
  209. return
  210. }
  211. _, err = models.GetTwoFactorByUID(authUser.ID)
  212. if err == nil {
  213. // 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
  214. 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")
  215. return
  216. } else if !models.IsErrTwoFactorNotEnrolled(err) {
  217. ctx.ServerError("IsErrTwoFactorNotEnrolled", err)
  218. return
  219. }
  220. }
  221. }
  222. perm, err := models.GetUserRepoPermission(repo, authUser)
  223. if err != nil {
  224. ctx.ServerError("GetUserRepoPermission", err)
  225. return
  226. }
  227. if !perm.CanAccess(accessMode, unitType) {
  228. ctx.HandleText(http.StatusForbidden, "User permission denied")
  229. return
  230. }
  231. if !isPull && repo.IsMirror {
  232. ctx.HandleText(http.StatusForbidden, "mirror repository is read-only")
  233. return
  234. }
  235. environ = []string{
  236. models.EnvRepoUsername + "=" + username,
  237. models.EnvRepoName + "=" + reponame,
  238. models.EnvPusherName + "=" + authUser.Name,
  239. models.EnvPusherID + fmt.Sprintf("=%d", authUser.ID),
  240. models.ProtectedBranchRepoID + fmt.Sprintf("=%d", repo.ID),
  241. models.EnvIsDeployKey + "=false",
  242. }
  243. if !authUser.KeepEmailPrivate {
  244. environ = append(environ, models.EnvPusherEmail+"="+authUser.Email)
  245. }
  246. if isWiki {
  247. environ = append(environ, models.EnvRepoIsWiki+"=true")
  248. } else {
  249. environ = append(environ, models.EnvRepoIsWiki+"=false")
  250. }
  251. }
  252. w := ctx.Resp
  253. r := ctx.Req.Request
  254. cfg := &serviceConfig{
  255. UploadPack: true,
  256. ReceivePack: true,
  257. Env: environ,
  258. }
  259. for _, route := range routes {
  260. r.URL.Path = strings.ToLower(r.URL.Path) // blue: In case some repo name has upper case name
  261. if m := route.reg.FindStringSubmatch(r.URL.Path); m != nil {
  262. if setting.Repository.DisableHTTPGit {
  263. w.WriteHeader(http.StatusForbidden)
  264. _, err := w.Write([]byte("Interacting with repositories by HTTP protocol is not allowed"))
  265. if err != nil {
  266. log.Error(err.Error())
  267. }
  268. return
  269. }
  270. if route.method != r.Method {
  271. if r.Proto == "HTTP/1.1" {
  272. w.WriteHeader(http.StatusMethodNotAllowed)
  273. _, err := w.Write([]byte("Method Not Allowed"))
  274. if err != nil {
  275. log.Error(err.Error())
  276. }
  277. } else {
  278. w.WriteHeader(http.StatusBadRequest)
  279. _, err := w.Write([]byte("Bad Request"))
  280. if err != nil {
  281. log.Error(err.Error())
  282. }
  283. }
  284. return
  285. }
  286. file := strings.Replace(r.URL.Path, m[1]+"/", "", 1)
  287. dir, err := getGitRepoPath(m[1])
  288. if err != nil {
  289. log.Error(err.Error())
  290. ctx.NotFound("Smart Git HTTP", err)
  291. return
  292. }
  293. route.handler(serviceHandler{cfg, w, r, dir, file, cfg.Env})
  294. return
  295. }
  296. }
  297. ctx.NotFound("Smart Git HTTP", nil)
  298. }
  299. type serviceConfig struct {
  300. UploadPack bool
  301. ReceivePack bool
  302. Env []string
  303. }
  304. type serviceHandler struct {
  305. cfg *serviceConfig
  306. w http.ResponseWriter
  307. r *http.Request
  308. dir string
  309. file string
  310. environ []string
  311. }
  312. func (h *serviceHandler) setHeaderNoCache() {
  313. h.w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  314. h.w.Header().Set("Pragma", "no-cache")
  315. h.w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  316. }
  317. func (h *serviceHandler) setHeaderCacheForever() {
  318. now := time.Now().Unix()
  319. expires := now + 31536000
  320. h.w.Header().Set("Date", fmt.Sprintf("%d", now))
  321. h.w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  322. h.w.Header().Set("Cache-Control", "public, max-age=31536000")
  323. }
  324. func (h *serviceHandler) sendFile(contentType string) {
  325. reqFile := path.Join(h.dir, h.file)
  326. fi, err := os.Stat(reqFile)
  327. if os.IsNotExist(err) {
  328. h.w.WriteHeader(http.StatusNotFound)
  329. return
  330. }
  331. h.w.Header().Set("Content-Type", contentType)
  332. h.w.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size()))
  333. h.w.Header().Set("Last-Modified", fi.ModTime().Format(http.TimeFormat))
  334. http.ServeFile(h.w, h.r, reqFile)
  335. }
  336. type route struct {
  337. reg *regexp.Regexp
  338. method string
  339. handler func(serviceHandler)
  340. }
  341. var routes = []route{
  342. {regexp.MustCompile(`(.*?)/git-upload-pack$`), "POST", serviceUploadPack},
  343. {regexp.MustCompile(`(.*?)/git-receive-pack$`), "POST", serviceReceivePack},
  344. {regexp.MustCompile(`(.*?)/info/refs$`), "GET", getInfoRefs},
  345. {regexp.MustCompile(`(.*?)/HEAD$`), "GET", getTextFile},
  346. {regexp.MustCompile(`(.*?)/objects/info/alternates$`), "GET", getTextFile},
  347. {regexp.MustCompile(`(.*?)/objects/info/http-alternates$`), "GET", getTextFile},
  348. {regexp.MustCompile(`(.*?)/objects/info/packs$`), "GET", getInfoPacks},
  349. {regexp.MustCompile(`(.*?)/objects/info/[^/]*$`), "GET", getTextFile},
  350. {regexp.MustCompile(`(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$`), "GET", getLooseObject},
  351. {regexp.MustCompile(`(.*?)/objects/pack/pack-[0-9a-f]{40}\.pack$`), "GET", getPackFile},
  352. {regexp.MustCompile(`(.*?)/objects/pack/pack-[0-9a-f]{40}\.idx$`), "GET", getIdxFile},
  353. }
  354. func getGitConfig(option, dir string) string {
  355. out, err := git.NewCommand("config", option).RunInDir(dir)
  356. if err != nil {
  357. log.Error("%v - %s", err, out)
  358. }
  359. return out[0 : len(out)-1]
  360. }
  361. func getConfigSetting(service, dir string) bool {
  362. service = strings.Replace(service, "-", "", -1)
  363. setting := getGitConfig("http."+service, dir)
  364. if service == "uploadpack" {
  365. return setting != "false"
  366. }
  367. return setting == "true"
  368. }
  369. func hasAccess(service string, h serviceHandler, checkContentType bool) bool {
  370. if checkContentType {
  371. if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) {
  372. return false
  373. }
  374. }
  375. if !(service == "upload-pack" || service == "receive-pack") {
  376. return false
  377. }
  378. if service == "receive-pack" {
  379. return h.cfg.ReceivePack
  380. }
  381. if service == "upload-pack" {
  382. return h.cfg.UploadPack
  383. }
  384. return getConfigSetting(service, h.dir)
  385. }
  386. func serviceRPC(h serviceHandler, service string) {
  387. defer func() {
  388. if err := h.r.Body.Close(); err != nil {
  389. log.Error("serviceRPC: Close: %v", err)
  390. }
  391. }()
  392. if !hasAccess(service, h, true) {
  393. h.w.WriteHeader(http.StatusUnauthorized)
  394. return
  395. }
  396. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service))
  397. var err error
  398. var reqBody = h.r.Body
  399. // Handle GZIP.
  400. if h.r.Header.Get("Content-Encoding") == "gzip" {
  401. reqBody, err = gzip.NewReader(reqBody)
  402. if err != nil {
  403. log.Error("Fail to create gzip reader: %v", err)
  404. h.w.WriteHeader(http.StatusInternalServerError)
  405. return
  406. }
  407. }
  408. // set this for allow pre-receive and post-receive execute
  409. h.environ = append(h.environ, "SSH_ORIGINAL_COMMAND="+service)
  410. var stderr bytes.Buffer
  411. cmd := exec.Command(git.GitExecutable, service, "--stateless-rpc", h.dir)
  412. cmd.Dir = h.dir
  413. if service == "receive-pack" {
  414. cmd.Env = append(os.Environ(), h.environ...)
  415. }
  416. cmd.Stdout = h.w
  417. cmd.Stdin = reqBody
  418. cmd.Stderr = &stderr
  419. if err := cmd.Run(); err != nil {
  420. log.Error("Fail to serve RPC(%s): %v - %s", service, err, stderr.String())
  421. return
  422. }
  423. }
  424. func serviceUploadPack(h serviceHandler) {
  425. serviceRPC(h, "upload-pack")
  426. }
  427. func serviceReceivePack(h serviceHandler) {
  428. serviceRPC(h, "receive-pack")
  429. }
  430. func getServiceType(r *http.Request) string {
  431. serviceType := r.FormValue("service")
  432. if !strings.HasPrefix(serviceType, "git-") {
  433. return ""
  434. }
  435. return strings.Replace(serviceType, "git-", "", 1)
  436. }
  437. func updateServerInfo(dir string) []byte {
  438. out, err := git.NewCommand("update-server-info").RunInDirBytes(dir)
  439. if err != nil {
  440. log.Error(fmt.Sprintf("%v - %s", err, string(out)))
  441. }
  442. return out
  443. }
  444. func packetWrite(str string) []byte {
  445. s := strconv.FormatInt(int64(len(str)+4), 16)
  446. if len(s)%4 != 0 {
  447. s = strings.Repeat("0", 4-len(s)%4) + s
  448. }
  449. return []byte(s + str)
  450. }
  451. func getInfoRefs(h serviceHandler) {
  452. h.setHeaderNoCache()
  453. if hasAccess(getServiceType(h.r), h, false) {
  454. service := getServiceType(h.r)
  455. refs, err := git.NewCommand(service, "--stateless-rpc", "--advertise-refs", ".").RunInDirBytes(h.dir)
  456. if err != nil {
  457. log.Error(fmt.Sprintf("%v - %s", err, string(refs)))
  458. }
  459. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
  460. h.w.WriteHeader(http.StatusOK)
  461. _, _ = h.w.Write(packetWrite("# service=git-" + service + "\n"))
  462. _, _ = h.w.Write([]byte("0000"))
  463. _, _ = h.w.Write(refs)
  464. } else {
  465. updateServerInfo(h.dir)
  466. h.sendFile("text/plain; charset=utf-8")
  467. }
  468. }
  469. func getTextFile(h serviceHandler) {
  470. h.setHeaderNoCache()
  471. h.sendFile("text/plain")
  472. }
  473. func getInfoPacks(h serviceHandler) {
  474. h.setHeaderCacheForever()
  475. h.sendFile("text/plain; charset=utf-8")
  476. }
  477. func getLooseObject(h serviceHandler) {
  478. h.setHeaderCacheForever()
  479. h.sendFile("application/x-git-loose-object")
  480. }
  481. func getPackFile(h serviceHandler) {
  482. h.setHeaderCacheForever()
  483. h.sendFile("application/x-git-packed-objects")
  484. }
  485. func getIdxFile(h serviceHandler) {
  486. h.setHeaderCacheForever()
  487. h.sendFile("application/x-git-packed-objects-toc")
  488. }
  489. func getGitRepoPath(subdir string) (string, error) {
  490. if !strings.HasSuffix(subdir, ".git") {
  491. subdir += ".git"
  492. }
  493. fpath := path.Join(setting.RepoRootPath, subdir)
  494. if _, err := os.Stat(fpath); os.IsNotExist(err) {
  495. return "", err
  496. }
  497. return fpath, nil
  498. }