client.py 16 KB

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