http.go 10 KB

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