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