http.go 12 KB

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