client.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 old_sha1 != new_sha1:
  89. if sent_capabilities:
  90. self.proto.write_pkt_line("%s %s %s" % (old_sha1, new_sha1, refname))
  91. else:
  92. self.proto.write_pkt_line("%s %s %s\0%s" % (old_sha1, new_sha1, refname, self.capabilities()))
  93. sent_capabilities = True
  94. if not new_sha1 in (have, "0" * 40):
  95. want.append(new_sha1)
  96. self.proto.write_pkt_line(None)
  97. if not want:
  98. return new_refs
  99. objects = generate_pack_contents(have, want)
  100. (entries, sha) = write_pack_data(self.proto.write_file(), objects,
  101. len(objects))
  102. # read the final confirmation sha
  103. client_sha = self.proto.read(20)
  104. if not client_sha in (None, "", sha):
  105. raise ChecksumMismatch(sha, client_sha)
  106. return new_refs
  107. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  108. progress):
  109. """Retrieve a pack from a git smart server.
  110. :param determine_wants: Callback that returns list of commits to fetch
  111. :param graph_walker: Object with next() and ack().
  112. :param pack_data: Callback called for each bit of data in the pack
  113. :param progress: Callback for progress reports (strings)
  114. """
  115. (refs, server_capabilities) = self.read_refs()
  116. wants = determine_wants(refs)
  117. if not wants:
  118. self.proto.write_pkt_line(None)
  119. return refs
  120. assert isinstance(wants, list) and type(wants[0]) == str
  121. self.proto.write_pkt_line("want %s %s\n" % (wants[0], self.capabilities()))
  122. for want in wants[1:]:
  123. self.proto.write_pkt_line("want %s\n" % want)
  124. self.proto.write_pkt_line(None)
  125. have = graph_walker.next()
  126. while have:
  127. self.proto.write_pkt_line("have %s\n" % have)
  128. if self._can_read():
  129. pkt = self.proto.read_pkt_line()
  130. parts = pkt.rstrip("\n").split(" ")
  131. if parts[0] == "ACK":
  132. graph_walker.ack(parts[1])
  133. assert parts[2] == "continue"
  134. have = graph_walker.next()
  135. self.proto.write_pkt_line("done\n")
  136. pkt = self.proto.read_pkt_line()
  137. while pkt:
  138. parts = pkt.rstrip("\n").split(" ")
  139. if parts[0] == "ACK":
  140. graph_walker.ack(pkt.split(" ")[1])
  141. if len(parts) < 3 or parts[2] != "continue":
  142. break
  143. pkt = self.proto.read_pkt_line()
  144. for pkt in self.proto.read_pkt_seq():
  145. channel = ord(pkt[0])
  146. pkt = pkt[1:]
  147. if channel == 1:
  148. pack_data(pkt)
  149. elif channel == 2:
  150. progress(pkt)
  151. else:
  152. raise AssertionError("Invalid sideband channel %d" % channel)
  153. return refs
  154. class TCPGitClient(GitClient):
  155. """A Git Client that works over TCP directly (i.e. git://)."""
  156. def __init__(self, host, port=None, *args, **kwargs):
  157. self._socket = socket.socket(type=socket.SOCK_STREAM)
  158. if port is None:
  159. port = TCP_GIT_PORT
  160. self._socket.connect((host, port))
  161. self.rfile = self._socket.makefile('rb', -1)
  162. self.wfile = self._socket.makefile('wb', 0)
  163. self.host = host
  164. super(TCPGitClient, self).__init__(lambda: _fileno_can_read(self._socket.fileno()), self.rfile.read, self.wfile.write, *args, **kwargs)
  165. def send_pack(self, path, changed_refs, generate_pack_contents):
  166. """Send a pack to a remote host.
  167. :param path: Path of the repository on the remote host
  168. """
  169. self.proto.send_cmd("git-receive-pack", path, "host=%s" % self.host)
  170. return super(TCPGitClient, self).send_pack(path, changed_refs, generate_pack_contents)
  171. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  172. """Fetch a pack from the remote host.
  173. :param path: Path of the reposiutory on the remote host
  174. :param determine_wants: Callback that receives available refs dict and
  175. should return list of sha's to fetch.
  176. :param graph_walker: GraphWalker instance used to find missing shas
  177. :param pack_data: Callback for writing pack data
  178. :param progress: Callback for writing progress
  179. """
  180. self.proto.send_cmd("git-upload-pack", path, "host=%s" % self.host)
  181. return super(TCPGitClient, self).fetch_pack(path, determine_wants,
  182. graph_walker, pack_data, progress)
  183. class SubprocessGitClient(GitClient):
  184. """Git client that talks to a server using a subprocess."""
  185. def __init__(self, *args, **kwargs):
  186. self.proc = None
  187. self._args = args
  188. self._kwargs = kwargs
  189. def _connect(self, service, *args, **kwargs):
  190. argv = [service] + list(args)
  191. self.proc = subprocess.Popen(argv, bufsize=0,
  192. stdin=subprocess.PIPE,
  193. stdout=subprocess.PIPE)
  194. def read_fn(size):
  195. return self.proc.stdout.read(size)
  196. def write_fn(data):
  197. self.proc.stdin.write(data)
  198. self.proc.stdin.flush()
  199. return GitClient(lambda: _fileno_can_read(self.proc.stdout.fileno()), read_fn, write_fn, *args, **kwargs)
  200. def send_pack(self, path, changed_refs, generate_pack_contents):
  201. """Upload a pack to the server.
  202. :param path: Path to the git repository on the server
  203. :param changed_refs: Dictionary with new values for the refs
  204. :param generate_pack_contents: Function that returns an iterator over
  205. objects to send
  206. """
  207. client = self._connect("git-receive-pack", path)
  208. return client.send_pack(path, changed_refs, generate_pack_contents)
  209. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  210. progress):
  211. """Retrieve a pack from the server
  212. :param path: Path to the git repository on the server
  213. :param determine_wants: Function that receives existing refs
  214. on the server and returns a list of desired shas
  215. :param graph_walker: GraphWalker instance
  216. :param pack_data: Function that can write pack data
  217. :param progress: Function that can write progress texts
  218. """
  219. client = self._connect("git-upload-pack", path)
  220. return client.fetch_pack(path, determine_wants, graph_walker, pack_data,
  221. progress)
  222. class SSHSubprocess(object):
  223. """A socket-like object that talks to an ssh subprocess via pipes."""
  224. def __init__(self, proc):
  225. self.proc = proc
  226. def send(self, data):
  227. return os.write(self.proc.stdin.fileno(), data)
  228. def recv(self, count):
  229. return self.proc.stdout.read(count)
  230. def close(self):
  231. self.proc.stdin.close()
  232. self.proc.stdout.close()
  233. self.proc.wait()
  234. class SSHVendor(object):
  235. def connect_ssh(self, host, command, username=None, port=None):
  236. #FIXME: This has no way to deal with passwords..
  237. args = ['ssh', '-x']
  238. if port is not None:
  239. args.extend(['-p', str(port)])
  240. if username is not None:
  241. host = "%s@%s" % (username, host)
  242. args.append(host)
  243. proc = subprocess.Popen(args + command,
  244. stdin=subprocess.PIPE,
  245. stdout=subprocess.PIPE)
  246. return SSHSubprocess(proc)
  247. # Can be overridden by users
  248. get_ssh_vendor = SSHVendor
  249. class SSHGitClient(GitClient):
  250. def __init__(self, host, port=None, username=None, *args, **kwargs):
  251. self.host = host
  252. self.port = port
  253. self.username = username
  254. self._args = args
  255. self._kwargs = kwargs
  256. def send_pack(self, path, determine_wants, generate_pack_contents):
  257. remote = get_ssh_vendor().connect_ssh(self.host, ["git-receive-pack '%s'" % path], port=self.port, username=self.username)
  258. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, *self._args, **self._kwargs)
  259. return client.send_pack(path, determine_wants, generate_pack_contents)
  260. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  261. progress):
  262. remote = get_ssh_vendor().connect_ssh(self.host, ["git-upload-pack '%s'" % path], port=self.port, username=self.username)
  263. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, *self._args, **self._kwargs)
  264. return client.fetch_pack(path, determine_wants, graph_walker, pack_data,
  265. progress)