http.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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}
  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}
  102. handler := HttpBackend(&config)
  103. handler(ctx.ResponseWriter, ctx.Req)
  104. /* Webdav
  105. dir := models.RepoPath(username, reponame)
  106. prefix := path.Join("/", username, params["reponame"])
  107. server := webdav.NewServer(
  108. dir, prefix, true)
  109. server.ServeHTTP(ctx.ResponseWriter, ctx.Req)
  110. */
  111. }
  112. type route struct {
  113. cr *regexp.Regexp
  114. method string
  115. handler func(handler)
  116. }
  117. type Config struct {
  118. ReposRoot string
  119. GitBinPath string
  120. UploadPack bool
  121. ReceivePack bool
  122. }
  123. type handler struct {
  124. *Config
  125. w http.ResponseWriter
  126. r *http.Request
  127. Dir string
  128. File string
  129. }
  130. var routes = []route{
  131. {regexp.MustCompile("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  132. {regexp.MustCompile("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  133. {regexp.MustCompile("(.*?)/info/refs$"), "GET", getInfoRefs},
  134. {regexp.MustCompile("(.*?)/HEAD$"), "GET", getTextFile},
  135. {regexp.MustCompile("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  136. {regexp.MustCompile("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  137. {regexp.MustCompile("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  138. {regexp.MustCompile("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  139. {regexp.MustCompile("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  140. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  141. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
  142. }
  143. // Request handling function
  144. func HttpBackend(config *Config) http.HandlerFunc {
  145. return func(w http.ResponseWriter, r *http.Request) {
  146. //log.Printf("%s %s %s %s", r.RemoteAddr, r.Method, r.URL.Path, r.Proto)
  147. for _, route := range routes {
  148. if m := route.cr.FindStringSubmatch(r.URL.Path); m != nil {
  149. if route.method != r.Method {
  150. renderMethodNotAllowed(w, r)
  151. return
  152. }
  153. file := strings.Replace(r.URL.Path, m[1]+"/", "", 1)
  154. dir, err := getGitDir(config, m[1])
  155. if err != nil {
  156. log.Print(err)
  157. renderNotFound(w)
  158. return
  159. }
  160. hr := handler{config, w, r, dir, file}
  161. route.handler(hr)
  162. return
  163. }
  164. }
  165. renderNotFound(w)
  166. return
  167. }
  168. }
  169. // Actual command handling functions
  170. func serviceUploadPack(hr handler) {
  171. serviceRpc("upload-pack", hr)
  172. }
  173. func serviceReceivePack(hr handler) {
  174. serviceRpc("receive-pack", hr)
  175. }
  176. func serviceRpc(rpc string, hr handler) {
  177. w, r, dir := hr.w, hr.r, hr.Dir
  178. access := hasAccess(r, hr.Config, dir, rpc, true)
  179. if access == false {
  180. renderNoAccess(w)
  181. return
  182. }
  183. input, _ := ioutil.ReadAll(r.Body)
  184. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", rpc))
  185. w.WriteHeader(http.StatusOK)
  186. args := []string{rpc, "--stateless-rpc", dir}
  187. cmd := exec.Command(hr.Config.GitBinPath, args...)
  188. cmd.Dir = dir
  189. in, err := cmd.StdinPipe()
  190. if err != nil {
  191. log.Print(err)
  192. }
  193. stdout, err := cmd.StdoutPipe()
  194. if err != nil {
  195. log.Print(err)
  196. }
  197. err = cmd.Start()
  198. if err != nil {
  199. log.Print(err)
  200. }
  201. in.Write(input)
  202. io.Copy(w, stdout)
  203. cmd.Wait()
  204. }
  205. func getInfoRefs(hr handler) {
  206. w, r, dir := hr.w, hr.r, hr.Dir
  207. serviceName := getServiceType(r)
  208. access := hasAccess(r, hr.Config, dir, serviceName, false)
  209. if access {
  210. args := []string{serviceName, "--stateless-rpc", "--advertise-refs", "."}
  211. refs := gitCommand(hr.Config.GitBinPath, dir, args...)
  212. hdrNocache(w)
  213. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", serviceName))
  214. w.WriteHeader(http.StatusOK)
  215. w.Write(packetWrite("# service=git-" + serviceName + "\n"))
  216. w.Write(packetFlush())
  217. w.Write(refs)
  218. } else {
  219. updateServerInfo(hr.Config.GitBinPath, dir)
  220. hdrNocache(w)
  221. sendFile("text/plain; charset=utf-8", hr)
  222. }
  223. }
  224. func getInfoPacks(hr handler) {
  225. hdrCacheForever(hr.w)
  226. sendFile("text/plain; charset=utf-8", hr)
  227. }
  228. func getLooseObject(hr handler) {
  229. hdrCacheForever(hr.w)
  230. sendFile("application/x-git-loose-object", hr)
  231. }
  232. func getPackFile(hr handler) {
  233. hdrCacheForever(hr.w)
  234. sendFile("application/x-git-packed-objects", hr)
  235. }
  236. func getIdxFile(hr handler) {
  237. hdrCacheForever(hr.w)
  238. sendFile("application/x-git-packed-objects-toc", hr)
  239. }
  240. func getTextFile(hr handler) {
  241. hdrNocache(hr.w)
  242. sendFile("text/plain", hr)
  243. }
  244. // Logic helping functions
  245. func sendFile(contentType string, hr handler) {
  246. w, r := hr.w, hr.r
  247. reqFile := path.Join(hr.Dir, hr.File)
  248. //fmt.Println("sendFile:", reqFile)
  249. f, err := os.Stat(reqFile)
  250. if os.IsNotExist(err) {
  251. renderNotFound(w)
  252. return
  253. }
  254. w.Header().Set("Content-Type", contentType)
  255. w.Header().Set("Content-Length", fmt.Sprintf("%d", f.Size()))
  256. w.Header().Set("Last-Modified", f.ModTime().Format(http.TimeFormat))
  257. http.ServeFile(w, r, reqFile)
  258. }
  259. func getGitDir(config *Config, filePath string) (string, error) {
  260. root := config.ReposRoot
  261. if root == "" {
  262. cwd, err := os.Getwd()
  263. if err != nil {
  264. log.Print(err)
  265. return "", err
  266. }
  267. root = cwd
  268. }
  269. f := path.Join(root, filePath)
  270. if _, err := os.Stat(f); os.IsNotExist(err) {
  271. return "", err
  272. }
  273. return f, nil
  274. }
  275. func getServiceType(r *http.Request) string {
  276. serviceType := r.FormValue("service")
  277. if s := strings.HasPrefix(serviceType, "git-"); !s {
  278. return ""
  279. }
  280. return strings.Replace(serviceType, "git-", "", 1)
  281. }
  282. func hasAccess(r *http.Request, config *Config, dir string, rpc string, checkContentType bool) bool {
  283. if checkContentType {
  284. if r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", rpc) {
  285. return false
  286. }
  287. }
  288. if !(rpc == "upload-pack" || rpc == "receive-pack") {
  289. return false
  290. }
  291. if rpc == "receive-pack" {
  292. return config.ReceivePack
  293. }
  294. if rpc == "upload-pack" {
  295. return config.UploadPack
  296. }
  297. return getConfigSetting(config.GitBinPath, rpc, dir)
  298. }
  299. func getConfigSetting(gitBinPath, serviceName string, dir string) bool {
  300. serviceName = strings.Replace(serviceName, "-", "", -1)
  301. setting := getGitConfig(gitBinPath, "http."+serviceName, dir)
  302. if serviceName == "uploadpack" {
  303. return setting != "false"
  304. }
  305. return setting == "true"
  306. }
  307. func getGitConfig(gitBinPath, configName string, dir string) string {
  308. args := []string{"config", configName}
  309. out := string(gitCommand(gitBinPath, dir, args...))
  310. return out[0 : len(out)-1]
  311. }
  312. func updateServerInfo(gitBinPath, dir string) []byte {
  313. args := []string{"update-server-info"}
  314. return gitCommand(gitBinPath, dir, args...)
  315. }
  316. func gitCommand(gitBinPath, dir string, args ...string) []byte {
  317. command := exec.Command(gitBinPath, args...)
  318. command.Dir = dir
  319. out, err := command.Output()
  320. if err != nil {
  321. log.Print(err)
  322. }
  323. return out
  324. }
  325. // HTTP error response handling functions
  326. func renderMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  327. if r.Proto == "HTTP/1.1" {
  328. w.WriteHeader(http.StatusMethodNotAllowed)
  329. w.Write([]byte("Method Not Allowed"))
  330. } else {
  331. w.WriteHeader(http.StatusBadRequest)
  332. w.Write([]byte("Bad Request"))
  333. }
  334. }
  335. func renderNotFound(w http.ResponseWriter) {
  336. w.WriteHeader(http.StatusNotFound)
  337. w.Write([]byte("Not Found"))
  338. }
  339. func renderNoAccess(w http.ResponseWriter) {
  340. w.WriteHeader(http.StatusForbidden)
  341. w.Write([]byte("Forbidden"))
  342. }
  343. // Packet-line handling function
  344. func packetFlush() []byte {
  345. return []byte("0000")
  346. }
  347. func packetWrite(str string) []byte {
  348. s := strconv.FormatInt(int64(len(str)+4), 16)
  349. if len(s)%4 != 0 {
  350. s = strings.Repeat("0", 4-len(s)%4) + s
  351. }
  352. return []byte(s + str)
  353. }
  354. // Header writing functions
  355. func hdrNocache(w http.ResponseWriter) {
  356. w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  357. w.Header().Set("Pragma", "no-cache")
  358. w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  359. }
  360. func hdrCacheForever(w http.ResponseWriter) {
  361. now := time.Now().Unix()
  362. expires := now + 31536000
  363. w.Header().Set("Date", fmt.Sprintf("%d", now))
  364. w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  365. w.Header().Set("Cache-Control", "public, max-age=31536000")
  366. }
  367. // Main
  368. /*
  369. func main() {
  370. http.HandleFunc("/", requestHandler())
  371. err := http.ListenAndServe(":8080", nil)
  372. if err != nil {
  373. log.Fatal("ListenAndServe: ", err)
  374. }
  375. }*/