http.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. // Copyright 2017 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 repo
  5. import (
  6. "bytes"
  7. "compress/gzip"
  8. "fmt"
  9. "net/http"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "gopkg.in/macaron.v1"
  18. log "unknwon.dev/clog/v2"
  19. "gogs.io/gogs/internal/auth"
  20. "gogs.io/gogs/internal/conf"
  21. "gogs.io/gogs/internal/db"
  22. "gogs.io/gogs/internal/lazyregexp"
  23. "gogs.io/gogs/internal/pathutil"
  24. "gogs.io/gogs/internal/tool"
  25. )
  26. type HTTPContext struct {
  27. *macaron.Context
  28. OwnerName string
  29. OwnerSalt string
  30. RepoID int64
  31. RepoName string
  32. AuthUser *db.User
  33. }
  34. // askCredentials responses HTTP header and status which informs client to provide credentials.
  35. func askCredentials(c *macaron.Context, status int, text string) {
  36. c.Header().Set("WWW-Authenticate", "Basic realm=\".\"")
  37. c.Error(status, text)
  38. }
  39. func HTTPContexter() macaron.Handler {
  40. return func(c *macaron.Context) {
  41. if len(conf.HTTP.AccessControlAllowOrigin) > 0 {
  42. // Set CORS headers for browser-based git clients
  43. c.Header().Set("Access-Control-Allow-Origin", conf.HTTP.AccessControlAllowOrigin)
  44. c.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, User-Agent")
  45. // Handle preflight OPTIONS request
  46. if c.Req.Method == "OPTIONS" {
  47. c.Status(http.StatusOK)
  48. return
  49. }
  50. }
  51. ownerName := c.Params(":username")
  52. repoName := strings.TrimSuffix(c.Params(":reponame"), ".git")
  53. repoName = strings.TrimSuffix(repoName, ".wiki")
  54. isPull := c.Query("service") == "git-upload-pack" ||
  55. strings.HasSuffix(c.Req.URL.Path, "git-upload-pack") ||
  56. c.Req.Method == "GET"
  57. owner, err := db.Users.GetByUsername(c.Req.Context(), ownerName)
  58. if err != nil {
  59. if db.IsErrUserNotExist(err) {
  60. c.Status(http.StatusNotFound)
  61. } else {
  62. c.Status(http.StatusInternalServerError)
  63. log.Error("Failed to get user [name: %s]: %v", ownerName, err)
  64. }
  65. return
  66. }
  67. repo, err := db.Repos.GetByName(c.Req.Context(), owner.ID, repoName)
  68. if err != nil {
  69. if db.IsErrRepoNotExist(err) {
  70. c.Status(http.StatusNotFound)
  71. } else {
  72. c.Status(http.StatusInternalServerError)
  73. log.Error("Failed to get repository [owner_id: %d, name: %s]: %v", owner.ID, repoName, err)
  74. }
  75. return
  76. }
  77. // Authentication is not required for pulling from public repositories.
  78. if isPull && !repo.IsPrivate && !conf.Auth.RequireSigninView {
  79. c.Map(&HTTPContext{
  80. Context: c,
  81. })
  82. return
  83. }
  84. // In case user requested a wrong URL and not intended to access Git objects.
  85. action := c.Params("*")
  86. if !strings.Contains(action, "git-") &&
  87. !strings.Contains(action, "info/") &&
  88. !strings.Contains(action, "HEAD") &&
  89. !strings.Contains(action, "objects/") {
  90. c.Error(http.StatusBadRequest, fmt.Sprintf("Unrecognized action %q", action))
  91. return
  92. }
  93. // Handle HTTP Basic Authentication
  94. authHead := c.Req.Header.Get("Authorization")
  95. if authHead == "" {
  96. askCredentials(c, http.StatusUnauthorized, "")
  97. return
  98. }
  99. auths := strings.Fields(authHead)
  100. if len(auths) != 2 || auths[0] != "Basic" {
  101. askCredentials(c, http.StatusUnauthorized, "")
  102. return
  103. }
  104. authUsername, authPassword, err := tool.BasicAuthDecode(auths[1])
  105. if err != nil {
  106. askCredentials(c, http.StatusUnauthorized, "")
  107. return
  108. }
  109. authUser, err := db.Users.Authenticate(c.Req.Context(), authUsername, authPassword, -1)
  110. if err != nil && !auth.IsErrBadCredentials(err) {
  111. c.Status(http.StatusInternalServerError)
  112. log.Error("Failed to authenticate user [name: %s]: %v", authUsername, err)
  113. return
  114. }
  115. // If username and password combination failed, try again using username as a token.
  116. if authUser == nil {
  117. token, err := db.AccessTokens.GetBySHA1(c.Req.Context(), authUsername)
  118. if err != nil {
  119. if db.IsErrAccessTokenNotExist(err) {
  120. askCredentials(c, http.StatusUnauthorized, "")
  121. } else {
  122. c.Status(http.StatusInternalServerError)
  123. log.Error("Failed to get access token [sha: %s]: %v", authUsername, err)
  124. }
  125. return
  126. }
  127. if err = db.AccessTokens.Touch(c.Req.Context(), token.ID); err != nil {
  128. log.Error("Failed to touch access token: %v", err)
  129. }
  130. authUser, err = db.Users.GetByID(c.Req.Context(), token.UserID)
  131. if err != nil {
  132. // Once we found token, we're supposed to find its related user,
  133. // thus any error is unexpected.
  134. c.Status(http.StatusInternalServerError)
  135. log.Error("Failed to get user [id: %d]: %v", token.UserID, err)
  136. return
  137. }
  138. } else if authUser.IsEnabledTwoFactor() {
  139. askCredentials(c, http.StatusUnauthorized, `User with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password
  140. Please create and use personal access token on user settings page`)
  141. return
  142. }
  143. log.Trace("[Git] Authenticated user: %s", authUser.Name)
  144. mode := db.AccessModeWrite
  145. if isPull {
  146. mode = db.AccessModeRead
  147. }
  148. if !db.Perms.Authorize(c.Req.Context(), authUser.ID, repo.ID, mode,
  149. db.AccessModeOptions{
  150. OwnerID: repo.OwnerID,
  151. Private: repo.IsPrivate,
  152. },
  153. ) {
  154. askCredentials(c, http.StatusForbidden, "User permission denied")
  155. return
  156. }
  157. if !isPull && repo.IsMirror {
  158. c.Error(http.StatusForbidden, "Mirror repository is read-only")
  159. return
  160. }
  161. c.Map(&HTTPContext{
  162. Context: c,
  163. OwnerName: ownerName,
  164. OwnerSalt: owner.Salt,
  165. RepoID: repo.ID,
  166. RepoName: repoName,
  167. AuthUser: authUser,
  168. })
  169. }
  170. }
  171. type serviceHandler struct {
  172. w http.ResponseWriter
  173. r *http.Request
  174. dir string
  175. file string
  176. authUser *db.User
  177. ownerName string
  178. ownerSalt string
  179. repoID int64
  180. repoName string
  181. }
  182. func (h *serviceHandler) setHeaderNoCache() {
  183. h.w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  184. h.w.Header().Set("Pragma", "no-cache")
  185. h.w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  186. }
  187. func (h *serviceHandler) setHeaderCacheForever() {
  188. now := time.Now().Unix()
  189. expires := now + 31536000
  190. h.w.Header().Set("Date", fmt.Sprintf("%d", now))
  191. h.w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  192. h.w.Header().Set("Cache-Control", "public, max-age=31536000")
  193. }
  194. func (h *serviceHandler) sendFile(contentType string) {
  195. reqFile := path.Join(h.dir, h.file)
  196. fi, err := os.Stat(reqFile)
  197. if os.IsNotExist(err) {
  198. h.w.WriteHeader(http.StatusNotFound)
  199. return
  200. }
  201. h.w.Header().Set("Content-Type", contentType)
  202. h.w.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size()))
  203. h.w.Header().Set("Last-Modified", fi.ModTime().Format(http.TimeFormat))
  204. http.ServeFile(h.w, h.r, reqFile)
  205. }
  206. func serviceRPC(h serviceHandler, service string) {
  207. defer h.r.Body.Close()
  208. if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) {
  209. h.w.WriteHeader(http.StatusUnauthorized)
  210. return
  211. }
  212. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service))
  213. var (
  214. reqBody = h.r.Body
  215. err error
  216. )
  217. // Handle GZIP
  218. if h.r.Header.Get("Content-Encoding") == "gzip" {
  219. reqBody, err = gzip.NewReader(reqBody)
  220. if err != nil {
  221. log.Error("HTTP.Get: fail to create gzip reader: %v", err)
  222. h.w.WriteHeader(http.StatusInternalServerError)
  223. return
  224. }
  225. }
  226. var stderr bytes.Buffer
  227. cmd := exec.Command("git", service, "--stateless-rpc", h.dir)
  228. if service == "receive-pack" {
  229. cmd.Env = append(os.Environ(), db.ComposeHookEnvs(db.ComposeHookEnvsOptions{
  230. AuthUser: h.authUser,
  231. OwnerName: h.ownerName,
  232. OwnerSalt: h.ownerSalt,
  233. RepoID: h.repoID,
  234. RepoName: h.repoName,
  235. RepoPath: h.dir,
  236. })...)
  237. }
  238. cmd.Dir = h.dir
  239. cmd.Stdout = h.w
  240. cmd.Stderr = &stderr
  241. cmd.Stdin = reqBody
  242. if err = cmd.Run(); err != nil {
  243. log.Error("HTTP.serviceRPC: fail to serve RPC '%s': %v - %s", service, err, stderr.String())
  244. h.w.WriteHeader(http.StatusInternalServerError)
  245. return
  246. }
  247. }
  248. func serviceUploadPack(h serviceHandler) {
  249. serviceRPC(h, "upload-pack")
  250. }
  251. func serviceReceivePack(h serviceHandler) {
  252. serviceRPC(h, "receive-pack")
  253. }
  254. func getServiceType(r *http.Request) string {
  255. serviceType := r.FormValue("service")
  256. if !strings.HasPrefix(serviceType, "git-") {
  257. return ""
  258. }
  259. return strings.TrimPrefix(serviceType, "git-")
  260. }
  261. // FIXME: use process module
  262. func gitCommand(dir string, args ...string) []byte {
  263. cmd := exec.Command("git", args...)
  264. cmd.Dir = dir
  265. out, err := cmd.Output()
  266. if err != nil {
  267. log.Error(fmt.Sprintf("Git: %v - %s", err, out))
  268. }
  269. return out
  270. }
  271. func updateServerInfo(dir string) []byte {
  272. return gitCommand(dir, "update-server-info")
  273. }
  274. func packetWrite(str string) []byte {
  275. s := strconv.FormatInt(int64(len(str)+4), 16)
  276. if len(s)%4 != 0 {
  277. s = strings.Repeat("0", 4-len(s)%4) + s
  278. }
  279. return []byte(s + str)
  280. }
  281. func getInfoRefs(h serviceHandler) {
  282. h.setHeaderNoCache()
  283. service := getServiceType(h.r)
  284. if service != "upload-pack" && service != "receive-pack" {
  285. updateServerInfo(h.dir)
  286. h.sendFile("text/plain; charset=utf-8")
  287. return
  288. }
  289. refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".")
  290. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
  291. h.w.WriteHeader(http.StatusOK)
  292. _, _ = h.w.Write(packetWrite("# service=git-" + service + "\n"))
  293. _, _ = h.w.Write([]byte("0000"))
  294. _, _ = h.w.Write(refs)
  295. }
  296. func getTextFile(h serviceHandler) {
  297. h.setHeaderNoCache()
  298. h.sendFile("text/plain")
  299. }
  300. func getInfoPacks(h serviceHandler) {
  301. h.setHeaderCacheForever()
  302. h.sendFile("text/plain; charset=utf-8")
  303. }
  304. func getLooseObject(h serviceHandler) {
  305. h.setHeaderCacheForever()
  306. h.sendFile("application/x-git-loose-object")
  307. }
  308. func getPackFile(h serviceHandler) {
  309. h.setHeaderCacheForever()
  310. h.sendFile("application/x-git-packed-objects")
  311. }
  312. func getIdxFile(h serviceHandler) {
  313. h.setHeaderCacheForever()
  314. h.sendFile("application/x-git-packed-objects-toc")
  315. }
  316. var routes = []struct {
  317. re *lazyregexp.Regexp
  318. method string
  319. handler func(serviceHandler)
  320. }{
  321. {lazyregexp.New("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  322. {lazyregexp.New("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  323. {lazyregexp.New("(.*?)/info/refs$"), "GET", getInfoRefs},
  324. {lazyregexp.New("(.*?)/HEAD$"), "GET", getTextFile},
  325. {lazyregexp.New("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  326. {lazyregexp.New("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  327. {lazyregexp.New("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  328. {lazyregexp.New("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  329. {lazyregexp.New("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  330. {lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  331. {lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
  332. }
  333. func getGitRepoPath(dir string) (string, error) {
  334. if !strings.HasSuffix(dir, ".git") {
  335. dir += ".git"
  336. }
  337. filename := filepath.Join(conf.Repository.Root, dir)
  338. if _, err := os.Stat(filename); os.IsNotExist(err) {
  339. return "", err
  340. }
  341. return filename, nil
  342. }
  343. func HTTP(c *HTTPContext) {
  344. for _, route := range routes {
  345. reqPath := strings.ToLower(c.Req.URL.Path)
  346. m := route.re.FindStringSubmatch(reqPath)
  347. if m == nil {
  348. continue
  349. }
  350. // We perform check here because route matched in cmd/web.go is wider than needed,
  351. // but we only want to output this message only if user is really trying to access
  352. // Git HTTP endpoints.
  353. if conf.Repository.DisableHTTPGit {
  354. c.Error(http.StatusForbidden, "Interacting with repositories by HTTP protocol is disabled")
  355. return
  356. }
  357. if route.method != c.Req.Method {
  358. c.Error(http.StatusNotFound)
  359. return
  360. }
  361. cleaned := pathutil.Clean(m[1])
  362. if m[1] != "/"+cleaned {
  363. c.Error(http.StatusBadRequest, "Request path contains suspicious characters")
  364. return
  365. }
  366. file := strings.TrimPrefix(reqPath, cleaned)
  367. dir, err := getGitRepoPath(cleaned)
  368. if err != nil {
  369. log.Warn("HTTP.getGitRepoPath: %v", err)
  370. c.Error(http.StatusNotFound)
  371. return
  372. }
  373. route.handler(serviceHandler{
  374. w: c.Resp,
  375. r: c.Req.Request,
  376. dir: dir,
  377. file: file,
  378. authUser: c.AuthUser,
  379. ownerName: c.OwnerName,
  380. ownerSalt: c.OwnerSalt,
  381. repoID: c.RepoID,
  382. repoName: c.RepoName,
  383. })
  384. return
  385. }
  386. c.Error(http.StatusNotFound)
  387. }