client.py 13 KB

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