client.py 15 KB

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