client.py 14 KB

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