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

http.go 11KB

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