client.py 14 KB

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