client.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # client.py -- Implementation of the server side git protocols
  2. # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
  3. # Copyright (C) 2008 John Carr
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # or (at your option) a later version of the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """Client side support for the Git protocol."""
  20. __docformat__ = 'restructuredText'
  21. import os
  22. import select
  23. import socket
  24. import subprocess
  25. from dulwich.errors import (
  26. ChecksumMismatch,
  27. )
  28. from dulwich.protocol import (
  29. Protocol,
  30. TCP_GIT_PORT,
  31. extract_capabilities,
  32. )
  33. from dulwich.pack import (
  34. write_pack_data,
  35. )
  36. def _fileno_can_read(fileno):
  37. """Check if a file descriptor is readable."""
  38. return len(select.select([fileno], [], [], 0)[0]) > 0
  39. CAPABILITIES = ["multi_ack", "side-band-64k", "ofs-delta"]
  40. class GitClient(object):
  41. """Git smart server client.
  42. """
  43. def __init__(self, can_read, read, write, thin_packs=True,
  44. report_activity=None):
  45. """Create a new GitClient instance.
  46. :param can_read: Function that returns True if there is data available
  47. to be read.
  48. :param read: Callback for reading data, takes number of bytes to read
  49. :param write: Callback for writing data
  50. :param thin_packs: Whether or not thin packs should be retrieved
  51. :param report_activity: Optional callback for reporting transport
  52. activity.
  53. """
  54. self.proto = Protocol(read, write, report_activity)
  55. self._can_read = can_read
  56. self._capabilities = list(CAPABILITIES)
  57. if thin_packs:
  58. self._capabilities.append("thin-pack")
  59. def capabilities(self):
  60. return " ".join(self._capabilities)
  61. def read_refs(self):
  62. server_capabilities = None
  63. refs = {}
  64. # Receive refs from server
  65. for pkt in self.proto.read_pkt_seq():
  66. (sha, ref) = pkt.rstrip("\n").split(" ", 1)
  67. if server_capabilities is None:
  68. (ref, server_capabilities) = extract_capabilities(ref)
  69. refs[ref] = sha
  70. return refs, server_capabilities
  71. def send_pack(self, path, determine_wants, generate_pack_contents):
  72. """Upload a pack to a remote repository.
  73. :param path: Repository path
  74. :param generate_pack_contents: Function that can return the shas of the
  75. objects to upload.
  76. """
  77. old_refs, server_capabilities = self.read_refs()
  78. new_refs = determine_wants(old_refs)
  79. if not new_refs:
  80. self.proto.write_pkt_line(None)
  81. return {}
  82. want = []
  83. have = [x for x in old_refs.values() if not x == "0" * 40]
  84. sent_capabilities = False
  85. for refname in set(new_refs.keys() + old_refs.keys()):
  86. old_sha1 = old_refs.get(refname, "0" * 40)
  87. new_sha1 = new_refs.get(refname, "0" * 40)
  88. if sent_capabilities:
  89. self.proto.write_pkt_line("%s %s %s" % (old_sha1, new_sha1, refname))
  90. else:
  91. self.proto.write_pkt_line("%s %s %s\0%s" % (old_sha1, new_sha1, refname, self.capabilities()))
  92. sent_capabilities = True
  93. if not new_sha1 in (have, "0" * 40):
  94. want.append(new_sha1)
  95. self.proto.write_pkt_line(None)
  96. objects = generate_pack_contents(have, want)
  97. (entries, sha) = write_pack_data(self.proto.write_file(), objects,
  98. len(objects))
  99. # read the final confirmation sha
  100. client_sha = self.proto.read(20)
  101. if not client_sha in (None, "", sha):
  102. raise ChecksumMismatch(sha, client_sha)
  103. return new_refs
  104. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  105. progress):
  106. """Retrieve a pack from a git smart server.
  107. :param determine_wants: Callback that returns list of commits to fetch
  108. :param graph_walker: Object with next() and ack().
  109. :param pack_data: Callback called for each bit of data in the pack
  110. :param progress: Callback for progress reports (strings)
  111. """
  112. (refs, server_capabilities) = self.read_refs()
  113. wants = determine_wants(refs)
  114. if not wants:
  115. self.proto.write_pkt_line(None)
  116. return refs
  117. assert isinstance(wants, list) and type(wants[0]) == str
  118. self.proto.write_pkt_line("want %s %s\n" % (wants[0], self.capabilities()))
  119. for want in wants[1:]:
  120. self.proto.write_pkt_line("want %s\n" % want)
  121. self.proto.write_pkt_line(None)
  122. have = graph_walker.next()
  123. while have:
  124. self.proto.write_pkt_line("have %s\n" % have)
  125. if self._can_read():
  126. pkt = self.proto.read_pkt_line()
  127. parts = pkt.rstrip("\n").split(" ")
  128. if parts[0] == "ACK":
  129. graph_walker.ack(parts[1])
  130. assert parts[2] == "continue"
  131. have = graph_walker.next()
  132. self.proto.write_pkt_line("done\n")
  133. pkt = self.proto.read_pkt_line()
  134. while pkt:
  135. parts = pkt.rstrip("\n").split(" ")
  136. if parts[0] == "ACK":
  137. graph_walker.ack(pkt.split(" ")[1])
  138. if len(parts) < 3 or parts[2] != "continue":
  139. break
  140. pkt = self.proto.read_pkt_line()
  141. for pkt in self.proto.read_pkt_seq():
  142. channel = ord(pkt[0])
  143. pkt = pkt[1:]
  144. if channel == 1:
  145. pack_data(pkt)
  146. elif channel == 2:
  147. progress(pkt)
  148. else:
  149. raise AssertionError("Invalid sideband channel %d" % channel)
  150. return refs
  151. class TCPGitClient(GitClient):
  152. """A Git Client that works over TCP directly (i.e. git://)."""
  153. def __init__(self, host, port=None, *args, **kwargs):
  154. self._socket = socket.socket(type=socket.SOCK_STREAM)
  155. if port is None:
  156. port = TCP_GIT_PORT
  157. self._socket.connect((host, port))
  158. self.rfile = self._socket.makefile('rb', -1)
  159. self.wfile = self._socket.makefile('wb', 0)
  160. self.host = host
  161. super(TCPGitClient, self).__init__(lambda: _fileno_can_read(self._socket.fileno()), self.rfile.read, self.wfile.write, *args, **kwargs)
  162. def send_pack(self, path, changed_refs, generate_pack_contents):
  163. """Send a pack to a remote host.
  164. :param path: Path of the repository on the remote host
  165. """
  166. self.proto.send_cmd("git-receive-pack", path, "host=%s" % self.host)
  167. return super(TCPGitClient, self).send_pack(path, changed_refs, generate_pack_contents)
  168. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  169. """Fetch a pack from the remote host.
  170. :param path: Path of the reposiutory on the remote host
  171. :param determine_wants: Callback that receives available refs dict and
  172. should return list of sha's to fetch.
  173. :param graph_walker: GraphWalker instance used to find missing shas
  174. :param pack_data: Callback for writing pack data
  175. :param progress: Callback for writing progress
  176. """
  177. self.proto.send_cmd("git-upload-pack", path, "host=%s" % self.host)
  178. return super(TCPGitClient, self).fetch_pack(path, determine_wants,
  179. graph_walker, pack_data, progress)
  180. class SubprocessGitClient(GitClient):
  181. """Git client that talks to a server using a subprocess."""
  182. def __init__(self, *args, **kwargs):
  183. self.proc = None
  184. self._args = args
  185. self._kwargs = kwargs
  186. def _connect(self, service, *args, **kwargs):
  187. argv = [service] + list(args)
  188. self.proc = subprocess.Popen(argv, bufsize=0,
  189. stdin=subprocess.PIPE,
  190. stdout=subprocess.PIPE)
  191. def read_fn(size):
  192. return self.proc.stdout.read(size)
  193. def write_fn(data):
  194. self.proc.stdin.write(data)
  195. self.proc.stdin.flush()
  196. return GitClient(lambda: _fileno_can_read(self.proc.stdout.fileno()), read_fn, write_fn, *args, **kwargs)
  197. def send_pack(self, path, changed_refs, generate_pack_contents):
  198. """Upload a pack to the server.
  199. :param path: Path to the git repository on the server
  200. :param changed_refs: Dictionary with new values for the refs
  201. :param generate_pack_contents: Function that returns an iterator over
  202. objects to send
  203. """
  204. client = self._connect("git-receive-pack", path)
  205. return client.send_pack(path, changed_refs, generate_pack_contents)
  206. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  207. progress):
  208. """Retrieve a pack from the server
  209. :param path: Path to the git repository on the server
  210. :param determine_wants: Function that receives existing refs
  211. on the server and returns a list of desired shas
  212. :param graph_walker: GraphWalker instance
  213. :param pack_data: Function that can write pack data
  214. :param progress: Function that can write progress texts
  215. """
  216. client = self._connect("git-upload-pack", path)
  217. return client.fetch_pack(path, determine_wants, graph_walker, pack_data,
  218. progress)
  219. class SSHSubprocess(object):
  220. """A socket-like object that talks to an ssh subprocess via pipes."""
  221. def __init__(self, proc):
  222. self.proc = proc
  223. def send(self, data):
  224. return os.write(self.proc.stdin.fileno(), data)
  225. def recv(self, count):
  226. return self.proc.stdout.read(count)
  227. def close(self):
  228. self.proc.stdin.close()
  229. self.proc.stdout.close()
  230. self.proc.wait()
  231. class SSHVendor(object):
  232. def connect_ssh(self, host, command, username=None, port=None):
  233. #FIXME: This has no way to deal with passwords..
  234. args = ['ssh', '-x']
  235. if port is not None:
  236. args.extend(['-p', str(port)])
  237. if username is not None:
  238. host = "%s@%s" % (username, host)
  239. args.append(host)
  240. proc = subprocess.Popen(args + command,
  241. stdin=subprocess.PIPE,
  242. stdout=subprocess.PIPE)
  243. return SSHSubprocess(proc)
  244. # Can be overridden by users
  245. get_ssh_vendor = SSHVendor
  246. class SSHGitClient(GitClient):
  247. def __init__(self, host, port=None, *args, **kwargs):
  248. self.host = host
  249. self.port = port
  250. self._args = args
  251. self._kwargs = kwargs
  252. def send_pack(self, path, determine_wants, generate_pack_contents):
  253. remote = get_ssh_vendor().connect_ssh(self.host, ["git-receive-pack %s" % path], port=self.port)
  254. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, *self._args, **self._kwargs)
  255. return client.send_pack(path, determine_wants, generate_pack_contents)
  256. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  257. progress):
  258. remote = get_ssh_vendor().connect_ssh(self.host, ["git-upload-pack %s" % path], port=self.port)
  259. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, *self._args, **self._kwargs)
  260. return client.fetch_pack(path, determine_wants, graph_walker, pack_data,
  261. progress)