You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

http.go 11 kB

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