client.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. HangupException,
  28. )
  29. from dulwich.protocol import (
  30. Protocol,
  31. TCP_GIT_PORT,
  32. ZERO_SHA,
  33. extract_capabilities,
  34. )
  35. from dulwich.pack import (
  36. write_pack_data,
  37. )
  38. def _fileno_can_read(fileno):
  39. """Check if a file descriptor is readable."""
  40. return len(select.select([fileno], [], [], 0)[0]) > 0
  41. CAPABILITIES = ["multi_ack", "side-band-64k", "ofs-delta"]
  42. class GitClient(object):
  43. """Git smart server client.
  44. """
  45. def __init__(self, can_read, read, write, thin_packs=True,
  46. report_activity=None):
  47. """Create a new GitClient instance.
  48. :param can_read: Function that returns True if there is data available
  49. to be read.
  50. :param read: Callback for reading data, takes number of bytes to read
  51. :param write: Callback for writing data
  52. :param thin_packs: Whether or not thin packs should be retrieved
  53. :param report_activity: Optional callback for reporting transport
  54. activity.
  55. """
  56. self.proto = Protocol(read, write, report_activity)
  57. self._can_read = can_read
  58. self._capabilities = list(CAPABILITIES)
  59. if thin_packs:
  60. self._capabilities.append("thin-pack")
  61. def capabilities(self):
  62. return " ".join(self._capabilities)
  63. def read_refs(self):
  64. server_capabilities = None
  65. refs = {}
  66. # Receive refs from server
  67. for pkt in self.proto.read_pkt_seq():
  68. (sha, ref) = pkt.rstrip("\n").split(" ", 1)
  69. if server_capabilities is None:
  70. (ref, server_capabilities) = extract_capabilities(ref)
  71. refs[ref] = sha
  72. return refs, server_capabilities
  73. def send_pack(self, path, determine_wants, generate_pack_contents):
  74. """Upload a pack to a remote repository.
  75. :param path: Repository path
  76. :param generate_pack_contents: Function that can return the shas of the
  77. objects to upload.
  78. """
  79. old_refs, server_capabilities = self.read_refs()
  80. new_refs = determine_wants(old_refs)
  81. if not new_refs:
  82. self.proto.write_pkt_line(None)
  83. return {}
  84. want = []
  85. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  86. sent_capabilities = False
  87. for refname in set(new_refs.keys() + old_refs.keys()):
  88. old_sha1 = old_refs.get(refname, ZERO_SHA)
  89. new_sha1 = new_refs.get(refname, ZERO_SHA)
  90. if old_sha1 != new_sha1:
  91. if sent_capabilities:
  92. self.proto.write_pkt_line("%s %s %s" % (old_sha1, new_sha1, refname))
  93. else:
  94. self.proto.write_pkt_line("%s %s %s\0%s" % (old_sha1, new_sha1, refname, self.capabilities()))
  95. sent_capabilities = True
  96. if not new_sha1 in (have, ZERO_SHA):
  97. want.append(new_sha1)
  98. self.proto.write_pkt_line(None)
  99. if not want:
  100. return new_refs
  101. objects = generate_pack_contents(have, want)
  102. (entries, sha) = write_pack_data(self.proto.write_file(), objects,
  103. len(objects))
  104. # read the final confirmation sha
  105. try:
  106. client_sha = self.proto.read_pkt_line()
  107. except HangupException:
  108. # for git-daemon versions before v1.6.6.1-26-g38a81b4, there is
  109. # nothing to read; catch this and hide from the user.
  110. pass
  111. else:
  112. if not client_sha in (None, "", sha):
  113. raise ChecksumMismatch(sha, client_sha)
  114. return new_refs
  115. def fetch(self, path, target, determine_wants=None, progress=None):
  116. """Fetch into a target repository.
  117. :param path: Path to fetch from
  118. :param target: Target repository to fetch into
  119. :param determine_wants: Optional function to determine what refs
  120. to fetch
  121. :param progress: Optional progress function
  122. :return: remote refs
  123. """
  124. if determine_wants is None:
  125. determine_wants = target.object_store.determine_wants_all
  126. f, commit = target.object_store.add_pack()
  127. try:
  128. return self.fetch_pack(path, determine_wants,
  129. target.get_graph_walker(), f.write, progress)
  130. finally:
  131. commit()
  132. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  133. progress):
  134. """Retrieve a pack from a git smart server.
  135. :param determine_wants: Callback that returns list of commits to fetch
  136. :param graph_walker: Object with next() and ack().
  137. :param pack_data: Callback called for each bit of data in the pack
  138. :param progress: Callback for progress reports (strings)
  139. """
  140. (refs, server_capabilities) = self.read_refs()
  141. wants = determine_wants(refs)
  142. if not wants:
  143. self.proto.write_pkt_line(None)
  144. return refs
  145. assert isinstance(wants, list) and type(wants[0]) == str
  146. self.proto.write_pkt_line("want %s %s\n" % (wants[0], self.capabilities()))
  147. for want in wants[1:]:
  148. self.proto.write_pkt_line("want %s\n" % want)
  149. self.proto.write_pkt_line(None)
  150. have = graph_walker.next()
  151. while have:
  152. self.proto.write_pkt_line("have %s\n" % have)
  153. if self._can_read():
  154. pkt = self.proto.read_pkt_line()
  155. parts = pkt.rstrip("\n").split(" ")
  156. if parts[0] == "ACK":
  157. graph_walker.ack(parts[1])
  158. assert parts[2] == "continue"
  159. have = graph_walker.next()
  160. self.proto.write_pkt_line("done\n")
  161. pkt = self.proto.read_pkt_line()
  162. while pkt:
  163. parts = pkt.rstrip("\n").split(" ")
  164. if parts[0] == "ACK":
  165. graph_walker.ack(pkt.split(" ")[1])
  166. if len(parts) < 3 or parts[2] != "continue":
  167. break
  168. pkt = self.proto.read_pkt_line()
  169. for pkt in self.proto.read_pkt_seq():
  170. channel = ord(pkt[0])
  171. pkt = pkt[1:]
  172. if channel == 1:
  173. pack_data(pkt)
  174. elif channel == 2:
  175. progress(pkt)
  176. else:
  177. raise AssertionError("Invalid sideband channel %d" % channel)
  178. return refs
  179. class TCPGitClient(GitClient):
  180. """A Git Client that works over TCP directly (i.e. git://)."""
  181. def __init__(self, host, port=None, *args, **kwargs):
  182. self._socket = socket.socket(type=socket.SOCK_STREAM)
  183. if port is None:
  184. port = TCP_GIT_PORT
  185. self._socket.connect((host, port))
  186. self.rfile = self._socket.makefile('rb', -1)
  187. self.wfile = self._socket.makefile('wb', 0)
  188. self.host = host
  189. super(TCPGitClient, self).__init__(lambda: _fileno_can_read(self._socket.fileno()), self.rfile.read, self.wfile.write, *args, **kwargs)
  190. def send_pack(self, path, changed_refs, generate_pack_contents):
  191. """Send a pack to a remote host.
  192. :param path: Path of the repository on the remote host
  193. """
  194. self.proto.send_cmd("git-receive-pack", path, "host=%s" % self.host)
  195. return super(TCPGitClient, self).send_pack(path, changed_refs, generate_pack_contents)
  196. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  197. """Fetch a pack from the remote host.
  198. :param path: Path of the reposiutory on the remote host
  199. :param determine_wants: Callback that receives available refs dict and
  200. should return list of sha's to fetch.
  201. :param graph_walker: GraphWalker instance used to find missing shas
  202. :param pack_data: Callback for writing pack data
  203. :param progress: Callback for writing progress
  204. """
  205. self.proto.send_cmd("git-upload-pack", path, "host=%s" % self.host)
  206. return super(TCPGitClient, self).fetch_pack(path, determine_wants,
  207. graph_walker, pack_data, progress)
  208. class SubprocessGitClient(GitClient):
  209. """Git client that talks to a server using a subprocess."""
  210. def __init__(self, *args, **kwargs):
  211. self.proc = None
  212. self._args = args
  213. self._kwargs = kwargs
  214. def _connect(self, service, *args, **kwargs):
  215. argv = [service] + list(args)
  216. self.proc = subprocess.Popen(argv, bufsize=0,
  217. stdin=subprocess.PIPE,
  218. stdout=subprocess.PIPE)
  219. def read_fn(size):
  220. return self.proc.stdout.read(size)
  221. def write_fn(data):
  222. self.proc.stdin.write(data)
  223. self.proc.stdin.flush()
  224. return GitClient(lambda: _fileno_can_read(self.proc.stdout.fileno()), read_fn, write_fn, *args, **kwargs)
  225. def send_pack(self, path, changed_refs, generate_pack_contents):
  226. """Upload a pack to the server.
  227. :param path: Path to the git repository on the server
  228. :param changed_refs: Dictionary with new values for the refs
  229. :param generate_pack_contents: Function that returns an iterator over
  230. objects to send
  231. """
  232. client = self._connect("git-receive-pack", path)
  233. return client.send_pack(path, changed_refs, generate_pack_contents)
  234. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  235. progress):
  236. """Retrieve a pack from the server
  237. :param path: Path to the git repository on the server
  238. :param determine_wants: Function that receives existing refs
  239. on the server and returns a list of desired shas
  240. :param graph_walker: GraphWalker instance
  241. :param pack_data: Function that can write pack data
  242. :param progress: Function that can write progress texts
  243. """
  244. client = self._connect("git-upload-pack", path)
  245. return client.fetch_pack(path, determine_wants, graph_walker, pack_data,
  246. progress)
  247. class SSHSubprocess(object):
  248. """A socket-like object that talks to an ssh subprocess via pipes."""
  249. def __init__(self, proc):
  250. self.proc = proc
  251. def send(self, data):
  252. return os.write(self.proc.stdin.fileno(), data)
  253. def recv(self, count):
  254. return self.proc.stdout.read(count)
  255. def close(self):
  256. self.proc.stdin.close()
  257. self.proc.stdout.close()
  258. self.proc.wait()
  259. class SSHVendor(object):
  260. def connect_ssh(self, host, command, username=None, port=None):
  261. #FIXME: This has no way to deal with passwords..
  262. args = ['ssh', '-x']
  263. if port is not None:
  264. args.extend(['-p', str(port)])
  265. if username is not None:
  266. host = "%s@%s" % (username, host)
  267. args.append(host)
  268. proc = subprocess.Popen(args + command,
  269. stdin=subprocess.PIPE,
  270. stdout=subprocess.PIPE)
  271. return SSHSubprocess(proc)
  272. # Can be overridden by users
  273. get_ssh_vendor = SSHVendor
  274. class SSHGitClient(GitClient):
  275. def __init__(self, host, port=None, username=None, *args, **kwargs):
  276. self.host = host
  277. self.port = port
  278. self.username = username
  279. self._args = args
  280. self._kwargs = kwargs
  281. def send_pack(self, path, determine_wants, generate_pack_contents):
  282. remote = get_ssh_vendor().connect_ssh(self.host, ["git-receive-pack '%s'" % path], port=self.port, username=self.username)
  283. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, *self._args, **self._kwargs)
  284. return client.send_pack(path, determine_wants, generate_pack_contents)
  285. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  286. progress):
  287. remote = get_ssh_vendor().connect_ssh(self.host, ["git-upload-pack '%s'" % path], port=self.port, username=self.username)
  288. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, *self._args, **self._kwargs)
  289. return client.fetch_pack(path, determine_wants, graph_walker, pack_data,
  290. progress)
  291. def get_transport_and_path(uri):
  292. """Obtain a git client from a URI or path.
  293. :param uri: URI or path
  294. :return: Tuple with client instance and relative path.
  295. """
  296. from dulwich.client import TCPGitClient, SSHGitClient, SubprocessGitClient
  297. for handler, transport in (("git://", TCPGitClient), ("git+ssh://", SSHGitClient)):
  298. if uri.startswith(handler):
  299. host, path = uri[len(handler):].split("/", 1)
  300. return transport(host), "/"+path
  301. # if its not git or git+ssh, try a local url..
  302. return SubprocessGitClient(), uri