client.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 not new_sha1 in (have, 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. progress(pkt)
  222. else:
  223. raise AssertionError("Invalid sideband channel %d" % channel)
  224. return refs
  225. class TCPGitClient(GitClient):
  226. """A Git Client that works over TCP directly (i.e. git://)."""
  227. def __init__(self, host, port=None, *args, **kwargs):
  228. self._socket = socket.socket(type=socket.SOCK_STREAM)
  229. if port is None:
  230. port = TCP_GIT_PORT
  231. self._socket.connect((host, port))
  232. self.rfile = self._socket.makefile('rb', -1)
  233. self.wfile = self._socket.makefile('wb', 0)
  234. self.host = host
  235. super(TCPGitClient, self).__init__(lambda: _fileno_can_read(self._socket.fileno()), self.rfile.read, self.wfile.write, *args, **kwargs)
  236. def send_pack(self, path, changed_refs, generate_pack_contents):
  237. """Send a pack to a remote host.
  238. :param path: Path of the repository on the remote host
  239. """
  240. self.proto.send_cmd("git-receive-pack", path, "host=%s" % self.host)
  241. return super(TCPGitClient, self).send_pack(path, changed_refs, generate_pack_contents)
  242. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  243. """Fetch a pack from the remote host.
  244. :param path: Path of the reposiutory on the remote host
  245. :param determine_wants: Callback that receives available refs dict and
  246. should return list of sha's to fetch.
  247. :param graph_walker: GraphWalker instance used to find missing shas
  248. :param pack_data: Callback for writing pack data
  249. :param progress: Callback for writing progress
  250. """
  251. self.proto.send_cmd("git-upload-pack", path, "host=%s" % self.host)
  252. return super(TCPGitClient, self).fetch_pack(path, determine_wants,
  253. graph_walker, pack_data, progress)
  254. class SubprocessGitClient(GitClient):
  255. """Git client that talks to a server using a subprocess."""
  256. def __init__(self, *args, **kwargs):
  257. self.proc = None
  258. self._args = args
  259. self._kwargs = kwargs
  260. def _connect(self, service, *args, **kwargs):
  261. argv = [service] + list(args)
  262. self.proc = subprocess.Popen(argv, bufsize=0,
  263. stdin=subprocess.PIPE,
  264. stdout=subprocess.PIPE)
  265. def read_fn(size):
  266. return self.proc.stdout.read(size)
  267. def write_fn(data):
  268. self.proc.stdin.write(data)
  269. self.proc.stdin.flush()
  270. return GitClient(lambda: _fileno_can_read(self.proc.stdout.fileno()), read_fn, write_fn, *args, **kwargs)
  271. def send_pack(self, path, changed_refs, generate_pack_contents):
  272. """Upload a pack to the server.
  273. :param path: Path to the git repository on the server
  274. :param changed_refs: Dictionary with new values for the refs
  275. :param generate_pack_contents: Function that returns an iterator over
  276. objects to send
  277. """
  278. client = self._connect("git-receive-pack", path)
  279. return client.send_pack(path, changed_refs, generate_pack_contents)
  280. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  281. progress):
  282. """Retrieve a pack from the server
  283. :param path: Path to the git repository on the server
  284. :param determine_wants: Function that receives existing refs
  285. on the server and returns a list of desired shas
  286. :param graph_walker: GraphWalker instance
  287. :param pack_data: Function that can write pack data
  288. :param progress: Function that can write progress texts
  289. """
  290. client = self._connect("git-upload-pack", path)
  291. return client.fetch_pack(path, determine_wants, graph_walker, pack_data,
  292. progress)
  293. class SSHSubprocess(object):
  294. """A socket-like object that talks to an ssh subprocess via pipes."""
  295. def __init__(self, proc):
  296. self.proc = proc
  297. self.read = self.recv = proc.stdout.read
  298. self.write = self.send = proc.stdin.write
  299. def close(self):
  300. self.proc.stdin.close()
  301. self.proc.stdout.close()
  302. self.proc.wait()
  303. class SSHVendor(object):
  304. def connect_ssh(self, host, command, username=None, port=None):
  305. #FIXME: This has no way to deal with passwords..
  306. args = ['ssh', '-x']
  307. if port is not None:
  308. args.extend(['-p', str(port)])
  309. if username is not None:
  310. host = "%s@%s" % (username, host)
  311. args.append(host)
  312. proc = subprocess.Popen(args + command,
  313. stdin=subprocess.PIPE,
  314. stdout=subprocess.PIPE)
  315. return SSHSubprocess(proc)
  316. # Can be overridden by users
  317. get_ssh_vendor = SSHVendor
  318. class SSHGitClient(GitClient):
  319. def __init__(self, host, port=None, username=None, *args, **kwargs):
  320. self.host = host
  321. self.port = port
  322. self.username = username
  323. self._args = args
  324. self._kwargs = kwargs
  325. def send_pack(self, path, determine_wants, generate_pack_contents):
  326. remote = get_ssh_vendor().connect_ssh(
  327. self.host, ["git-receive-pack '%s'" % path],
  328. port=self.port, username=self.username)
  329. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, *self._args, **self._kwargs)
  330. return client.send_pack(path, determine_wants, generate_pack_contents)
  331. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  332. progress):
  333. remote = get_ssh_vendor().connect_ssh(self.host, ["git-upload-pack '%s'" % path], port=self.port, username=self.username)
  334. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, *self._args, **self._kwargs)
  335. return client.fetch_pack(path, determine_wants, graph_walker, pack_data,
  336. progress)
  337. def get_transport_and_path(uri):
  338. """Obtain a git client from a URI or path.
  339. :param uri: URI or path
  340. :return: Tuple with client instance and relative path.
  341. """
  342. from dulwich.client import TCPGitClient, SSHGitClient, SubprocessGitClient
  343. for handler, transport in (("git://", TCPGitClient), ("git+ssh://", SSHGitClient)):
  344. if uri.startswith(handler):
  345. host, path = uri[len(handler):].split("/", 1)
  346. return transport(host), "/"+path
  347. # if its not git or git+ssh, try a local url..
  348. return SubprocessGitClient(), uri