http.go 12 KB

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