http.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. package repo
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/go-martini/martini"
  17. "github.com/gogits/gogs/models"
  18. "github.com/gogits/gogs/modules/base"
  19. "github.com/gogits/gogs/modules/middleware"
  20. )
  21. func Http(ctx *middleware.Context, params martini.Params) {
  22. username := params["username"]
  23. reponame := params["reponame"]
  24. if strings.HasSuffix(reponame, ".git") {
  25. reponame = reponame[:len(reponame)-4]
  26. }
  27. var isPull bool
  28. service := ctx.Query("service")
  29. if service == "git-receive-pack" ||
  30. strings.HasSuffix(ctx.Req.URL.Path, "git-receive-pack") {
  31. isPull = false
  32. } else if service == "git-upload-pack" ||
  33. strings.HasSuffix(ctx.Req.URL.Path, "git-upload-pack") {
  34. isPull = true
  35. } else {
  36. isPull = (ctx.Req.Method == "GET")
  37. }
  38. repoUser, err := models.GetUserByName(username)
  39. if err != nil {
  40. ctx.Handle(500, "repo.GetUserByName", nil)
  41. return
  42. }
  43. repo, err := models.GetRepositoryByName(repoUser.Id, reponame)
  44. if err != nil {
  45. ctx.Handle(500, "repo.GetRepositoryByName", nil)
  46. return
  47. }
  48. // only public pull don't need auth
  49. var askAuth = !(!repo.IsPrivate && isPull)
  50. var authUser *models.User
  51. // check access
  52. if askAuth {
  53. baHead := ctx.Req.Header.Get("Authorization")
  54. if baHead == "" {
  55. // ask auth
  56. authRequired(ctx)
  57. return
  58. }
  59. auths := strings.Fields(baHead)
  60. // currently check basic auth
  61. // TODO: support digit auth
  62. if len(auths) != 2 || auths[0] != "Basic" {
  63. ctx.Handle(401, "no basic auth and digit auth", nil)
  64. return
  65. }
  66. authUsername, passwd, err := basicDecode(auths[1])
  67. if err != nil {
  68. ctx.Handle(401, "no basic auth and digit auth", nil)
  69. return
  70. }
  71. authUser, err = models.GetUserByName(authUsername)
  72. if err != nil {
  73. ctx.Handle(401, "no basic auth and digit auth", nil)
  74. return
  75. }
  76. newUser := &models.User{Passwd: passwd, Salt: authUser.Salt}
  77. newUser.EncodePasswd()
  78. if authUser.Passwd != newUser.Passwd {
  79. ctx.Handle(401, "no basic auth and digit auth", nil)
  80. return
  81. }
  82. var tp = models.AU_WRITABLE
  83. if isPull {
  84. tp = models.AU_READABLE
  85. }
  86. has, err := models.HasAccess(authUsername, username+"/"+reponame, tp)
  87. if err != nil {
  88. ctx.Handle(401, "no basic auth and digit auth", nil)
  89. return
  90. } else if !has {
  91. if tp == models.AU_READABLE {
  92. has, err = models.HasAccess(authUsername, username+"/"+reponame, models.AU_WRITABLE)
  93. if err != nil || !has {
  94. ctx.Handle(401, "no basic auth and digit auth", nil)
  95. return
  96. }
  97. } else {
  98. ctx.Handle(401, "no basic auth and digit auth", nil)
  99. return
  100. }
  101. }
  102. }
  103. config := Config{base.RepoRootPath, "git", true, true, func(rpc string, input []byte) {
  104. if rpc == "receive-pack" {
  105. firstLine := bytes.IndexRune(input, '\n')
  106. if firstLine > -1 {
  107. fields := strings.Fields(string(input[:firstLine]))
  108. if len(fields) > 3 {
  109. oldCommitId := fields[0][4:]
  110. newCommitId := fields[1]
  111. refName := fields[2]
  112. models.Update(refName, oldCommitId, newCommitId, username, reponame, authUser.Id)
  113. }
  114. }
  115. }
  116. }}
  117. handler := HttpBackend(&config)
  118. handler(ctx.ResponseWriter, ctx.Req)
  119. /* Webdav
  120. dir := models.RepoPath(username, reponame)
  121. prefix := path.Join("/", username, params["reponame"])
  122. server := webdav.NewServer(
  123. dir, prefix, true)
  124. server.ServeHTTP(ctx.ResponseWriter, ctx.Req)
  125. */
  126. }
  127. type route struct {
  128. cr *regexp.Regexp
  129. method string
  130. handler func(handler)
  131. }
  132. type Config struct {
  133. ReposRoot string
  134. GitBinPath string
  135. UploadPack bool
  136. ReceivePack bool
  137. OnSucceed func(rpc string, input []byte)
  138. }
  139. type handler struct {
  140. *Config
  141. w http.ResponseWriter
  142. r *http.Request
  143. Dir string
  144. File string
  145. }
  146. var routes = []route{
  147. {regexp.MustCompile("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  148. {regexp.MustCompile("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  149. {regexp.MustCompile("(.*?)/info/refs$"), "GET", getInfoRefs},
  150. {regexp.MustCompile("(.*?)/HEAD$"), "GET", getTextFile},
  151. {regexp.MustCompile("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  152. {regexp.MustCompile("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  153. {regexp.MustCompile("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  154. {regexp.MustCompile("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  155. {regexp.MustCompile("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  156. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  157. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
  158. }
  159. // Request handling function
  160. func HttpBackend(config *Config) http.HandlerFunc {
  161. return func(w http.ResponseWriter, r *http.Request) {
  162. //log.Printf("%s %s %s %s", r.RemoteAddr, r.Method, r.URL.Path, r.Proto)
  163. for _, route := range routes {
  164. if m := route.cr.FindStringSubmatch(r.URL.Path); m != nil {
  165. if route.method != r.Method {
  166. renderMethodNotAllowed(w, r)
  167. return
  168. }
  169. file := strings.Replace(r.URL.Path, m[1]+"/", "", 1)
  170. dir, err := getGitDir(config, m[1])
  171. if err != nil {
  172. log.Print(err)
  173. renderNotFound(w)
  174. return
  175. }
  176. hr := handler{config, w, r, dir, file}
  177. route.handler(hr)
  178. return
  179. }
  180. }
  181. renderNotFound(w)
  182. return
  183. }
  184. }
  185. // Actual command handling functions
  186. func serviceUploadPack(hr handler) {
  187. serviceRpc("upload-pack", hr)
  188. }
  189. func serviceReceivePack(hr handler) {
  190. serviceRpc("receive-pack", hr)
  191. }
  192. func serviceRpc(rpc string, hr handler) {
  193. w, r, dir := hr.w, hr.r, hr.Dir
  194. access := hasAccess(r, hr.Config, dir, rpc, true)
  195. if access == false {
  196. renderNoAccess(w)
  197. return
  198. }
  199. input, _ := ioutil.ReadAll(r.Body)
  200. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", rpc))
  201. w.WriteHeader(http.StatusOK)
  202. args := []string{rpc, "--stateless-rpc", dir}
  203. cmd := exec.Command(hr.Config.GitBinPath, args...)
  204. cmd.Dir = dir
  205. in, err := cmd.StdinPipe()
  206. if err != nil {
  207. log.Print(err)
  208. return
  209. }
  210. stdout, err := cmd.StdoutPipe()
  211. if err != nil {
  212. log.Print(err)
  213. return
  214. }
  215. err = cmd.Start()
  216. if err != nil {
  217. log.Print(err)
  218. return
  219. }
  220. in.Write(input)
  221. io.Copy(w, stdout)
  222. cmd.Wait()
  223. if hr.Config.OnSucceed != nil {
  224. hr.Config.OnSucceed(rpc, input)
  225. }
  226. }
  227. func getInfoRefs(hr handler) {
  228. w, r, dir := hr.w, hr.r, hr.Dir
  229. serviceName := getServiceType(r)
  230. access := hasAccess(r, hr.Config, dir, serviceName, false)
  231. if access {
  232. args := []string{serviceName, "--stateless-rpc", "--advertise-refs", "."}
  233. refs := gitCommand(hr.Config.GitBinPath, dir, args...)
  234. hdrNocache(w)
  235. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", serviceName))
  236. w.WriteHeader(http.StatusOK)
  237. w.Write(packetWrite("# service=git-" + serviceName + "\n"))
  238. w.Write(packetFlush())
  239. w.Write(refs)
  240. } else {
  241. updateServerInfo(hr.Config.GitBinPath, dir)
  242. hdrNocache(w)
  243. sendFile("text/plain; charset=utf-8", hr)
  244. }
  245. }
  246. func getInfoPacks(hr handler) {
  247. hdrCacheForever(hr.w)
  248. sendFile("text/plain; charset=utf-8", hr)
  249. }
  250. func getLooseObject(hr handler) {
  251. hdrCacheForever(hr.w)
  252. sendFile("application/x-git-loose-object", hr)
  253. }
  254. func getPackFile(hr handler) {
  255. hdrCacheForever(hr.w)
  256. sendFile("application/x-git-packed-objects", hr)
  257. }
  258. func getIdxFile(hr handler) {
  259. hdrCacheForever(hr.w)
  260. sendFile("application/x-git-packed-objects-toc", hr)
  261. }
  262. func getTextFile(hr handler) {
  263. hdrNocache(hr.w)
  264. sendFile("text/plain", hr)
  265. }
  266. // Logic helping functions
  267. func sendFile(contentType string, hr handler) {
  268. w, r := hr.w, hr.r
  269. reqFile := path.Join(hr.Dir, hr.File)
  270. //fmt.Println("sendFile:", reqFile)
  271. f, err := os.Stat(reqFile)
  272. if os.IsNotExist(err) {
  273. renderNotFound(w)
  274. return
  275. }
  276. w.Header().Set("Content-Type", contentType)
  277. w.Header().Set("Content-Length", fmt.Sprintf("%d", f.Size()))
  278. w.Header().Set("Last-Modified", f.ModTime().Format(http.TimeFormat))
  279. http.ServeFile(w, r, reqFile)
  280. }
  281. func getGitDir(config *Config, filePath string) (string, error) {
  282. root := config.ReposRoot
  283. if root == "" {
  284. cwd, err := os.Getwd()
  285. if err != nil {
  286. log.Print(err)
  287. return "", err
  288. }
  289. root = cwd
  290. }
  291. f := path.Join(root, filePath)
  292. if _, err := os.Stat(f); os.IsNotExist(err) {
  293. return "", err
  294. }
  295. return f, nil
  296. }
  297. func getServiceType(r *http.Request) string {
  298. serviceType := r.FormValue("service")
  299. if s := strings.HasPrefix(serviceType, "git-"); !s {
  300. return ""
  301. }
  302. return strings.Replace(serviceType, "git-", "", 1)
  303. }
  304. func hasAccess(r *http.Request, config *Config, dir string, rpc string, checkContentType bool) bool {
  305. if checkContentType {
  306. if r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", rpc) {
  307. return false
  308. }
  309. }
  310. if !(rpc == "upload-pack" || rpc == "receive-pack") {
  311. return false
  312. }
  313. if rpc == "receive-pack" {
  314. return config.ReceivePack
  315. }
  316. if rpc == "upload-pack" {
  317. return config.UploadPack
  318. }
  319. return getConfigSetting(config.GitBinPath, rpc, dir)
  320. }
  321. func getConfigSetting(gitBinPath, serviceName string, dir string) bool {
  322. serviceName = strings.Replace(serviceName, "-", "", -1)
  323. setting := getGitConfig(gitBinPath, "http."+serviceName, dir)
  324. if serviceName == "uploadpack" {
  325. return setting != "false"
  326. }
  327. return setting == "true"
  328. }
  329. func getGitConfig(gitBinPath, configName string, dir string) string {
  330. args := []string{"config", configName}
  331. out := string(gitCommand(gitBinPath, dir, args...))
  332. return out[0 : len(out)-1]
  333. }
  334. func updateServerInfo(gitBinPath, dir string) []byte {
  335. args := []string{"update-server-info"}
  336. return gitCommand(gitBinPath, dir, args...)
  337. }
  338. func gitCommand(gitBinPath, dir string, args ...string) []byte {
  339. command := exec.Command(gitBinPath, args...)
  340. command.Dir = dir
  341. out, err := command.Output()
  342. if err != nil {
  343. log.Print(err)
  344. }
  345. return out
  346. }
  347. // HTTP error response handling functions
  348. func renderMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  349. if r.Proto == "HTTP/1.1" {
  350. w.WriteHeader(http.StatusMethodNotAllowed)
  351. w.Write([]byte("Method Not Allowed"))
  352. } else {
  353. w.WriteHeader(http.StatusBadRequest)
  354. w.Write([]byte("Bad Request"))
  355. }
  356. }
  357. func renderNotFound(w http.ResponseWriter) {
  358. w.WriteHeader(http.StatusNotFound)
  359. w.Write([]byte("Not Found"))
  360. }
  361. func renderNoAccess(w http.ResponseWriter) {
  362. w.WriteHeader(http.StatusForbidden)
  363. w.Write([]byte("Forbidden"))
  364. }
  365. // Packet-line handling function
  366. func packetFlush() []byte {
  367. return []byte("0000")
  368. }
  369. func packetWrite(str string) []byte {
  370. s := strconv.FormatInt(int64(len(str)+4), 16)
  371. if len(s)%4 != 0 {
  372. s = strings.Repeat("0", 4-len(s)%4) + s
  373. }
  374. return []byte(s + str)
  375. }
  376. // Header writing functions
  377. func hdrNocache(w http.ResponseWriter) {
  378. w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  379. w.Header().Set("Pragma", "no-cache")
  380. w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  381. }
  382. func hdrCacheForever(w http.ResponseWriter) {
  383. now := time.Now().Unix()
  384. expires := now + 31536000
  385. w.Header().Set("Date", fmt.Sprintf("%d", now))
  386. w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  387. w.Header().Set("Cache-Control", "public, max-age=31536000")
  388. }
  389. // Main
  390. /*
  391. func main() {
  392. http.HandleFunc("/", requestHandler())
  393. err := http.ListenAndServe(":8080", nil)
  394. if err != nil {
  395. log.Fatal("ListenAndServe: ", err)
  396. }
  397. }*/