2
0

client.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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. The Dulwich client supports the following capabilities:
  21. * thin-pack
  22. * multi_ack_detailed
  23. * multi_ack
  24. * side-band-64k
  25. * ofs-delta
  26. * report-status
  27. * delete-refs
  28. Known capabilities that are not supported:
  29. * shallow
  30. * no-progress
  31. * include-tag
  32. """
  33. __docformat__ = 'restructuredText'
  34. from cStringIO import StringIO
  35. import select
  36. import socket
  37. import subprocess
  38. import urllib2
  39. import urlparse
  40. from dulwich.errors import (
  41. GitProtocolError,
  42. NotGitRepository,
  43. SendPackError,
  44. UpdateRefsError,
  45. )
  46. from dulwich.protocol import (
  47. _RBUFSIZE,
  48. PktLineParser,
  49. Protocol,
  50. TCP_GIT_PORT,
  51. ZERO_SHA,
  52. extract_capabilities,
  53. )
  54. from dulwich.pack import (
  55. write_pack_objects,
  56. )
  57. # Python 2.6.6 included these in urlparse.uses_netloc upstream. Do
  58. # monkeypatching to enable similar behaviour in earlier Pythons:
  59. for scheme in ('git', 'git+ssh'):
  60. if scheme not in urlparse.uses_netloc:
  61. urlparse.uses_netloc.append(scheme)
  62. def _fileno_can_read(fileno):
  63. """Check if a file descriptor is readable."""
  64. return len(select.select([fileno], [], [], 0)[0]) > 0
  65. COMMON_CAPABILITIES = ['ofs-delta', 'side-band-64k']
  66. FETCH_CAPABILITIES = ['thin-pack', 'multi_ack', 'multi_ack_detailed'] + COMMON_CAPABILITIES
  67. SEND_CAPABILITIES = ['report-status'] + COMMON_CAPABILITIES
  68. class ReportStatusParser(object):
  69. """Handle status as reported by servers with the 'report-status' capability.
  70. """
  71. def __init__(self):
  72. self._done = False
  73. self._pack_status = None
  74. self._ref_status_ok = True
  75. self._ref_statuses = []
  76. def check(self):
  77. """Check if there were any errors and, if so, raise exceptions.
  78. :raise SendPackError: Raised when the server could not unpack
  79. :raise UpdateRefsError: Raised when refs could not be updated
  80. """
  81. if self._pack_status not in ('unpack ok', None):
  82. raise SendPackError(self._pack_status)
  83. if not self._ref_status_ok:
  84. ref_status = {}
  85. ok = set()
  86. for status in self._ref_statuses:
  87. if ' ' not in status:
  88. # malformed response, move on to the next one
  89. continue
  90. status, ref = status.split(' ', 1)
  91. if status == 'ng':
  92. if ' ' in ref:
  93. ref, status = ref.split(' ', 1)
  94. else:
  95. ok.add(ref)
  96. ref_status[ref] = status
  97. raise UpdateRefsError('%s failed to update' %
  98. ', '.join([ref for ref in ref_status
  99. if ref not in ok]),
  100. ref_status=ref_status)
  101. def handle_packet(self, pkt):
  102. """Handle a packet.
  103. :raise GitProtocolError: Raised when packets are received after a
  104. flush packet.
  105. """
  106. if self._done:
  107. raise GitProtocolError("received more data after status report")
  108. if pkt is None:
  109. self._done = True
  110. return
  111. if self._pack_status is None:
  112. self._pack_status = pkt.strip()
  113. else:
  114. ref_status = pkt.strip()
  115. self._ref_statuses.append(ref_status)
  116. if not ref_status.startswith('ok '):
  117. self._ref_status_ok = False
  118. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  119. # support some capabilities. This should work properly with servers
  120. # that don't support multi_ack.
  121. class GitClient(object):
  122. """Git smart server client.
  123. """
  124. def __init__(self, thin_packs=True, report_activity=None):
  125. """Create a new GitClient instance.
  126. :param thin_packs: Whether or not thin packs should be retrieved
  127. :param report_activity: Optional callback for reporting transport
  128. activity.
  129. """
  130. self._report_activity = report_activity
  131. self._report_status_parser = None
  132. self._fetch_capabilities = set(FETCH_CAPABILITIES)
  133. self._send_capabilities = set(SEND_CAPABILITIES)
  134. if not thin_packs:
  135. self._fetch_capabilities.remove('thin-pack')
  136. def _read_refs(self, proto):
  137. server_capabilities = None
  138. refs = {}
  139. # Receive refs from server
  140. for pkt in proto.read_pkt_seq():
  141. (sha, ref) = pkt.rstrip('\n').split(' ', 1)
  142. if sha == 'ERR':
  143. raise GitProtocolError(ref)
  144. if server_capabilities is None:
  145. (ref, server_capabilities) = extract_capabilities(ref)
  146. refs[ref] = sha
  147. if len(refs) == 0:
  148. return None, set([])
  149. return refs, set(server_capabilities)
  150. def send_pack(self, path, determine_wants, generate_pack_contents,
  151. progress=None):
  152. """Upload a pack to a remote repository.
  153. :param path: Repository path
  154. :param generate_pack_contents: Function that can return a sequence of the
  155. shas of the objects to upload.
  156. :param progress: Optional progress function
  157. :raises SendPackError: if server rejects the pack data
  158. :raises UpdateRefsError: if the server supports report-status
  159. and rejects ref updates
  160. """
  161. raise NotImplementedError(self.send_pack)
  162. def fetch(self, path, target, determine_wants=None, progress=None):
  163. """Fetch into a target repository.
  164. :param path: Path to fetch from
  165. :param target: Target repository to fetch into
  166. :param determine_wants: Optional function to determine what refs
  167. to fetch
  168. :param progress: Optional progress function
  169. :return: remote refs as dictionary
  170. """
  171. if determine_wants is None:
  172. determine_wants = target.object_store.determine_wants_all
  173. f, commit = target.object_store.add_pack()
  174. result = self.fetch_pack(path, determine_wants,
  175. target.get_graph_walker(), f.write, progress)
  176. commit()
  177. return result
  178. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  179. progress=None):
  180. """Retrieve a pack from a git smart server.
  181. :param determine_wants: Callback that returns list of commits to fetch
  182. :param graph_walker: Object with next() and ack().
  183. :param pack_data: Callback called for each bit of data in the pack
  184. :param progress: Callback for progress reports (strings)
  185. """
  186. raise NotImplementedError(self.fetch_pack)
  187. def _parse_status_report(self, proto):
  188. unpack = proto.read_pkt_line().strip()
  189. if unpack != 'unpack ok':
  190. st = True
  191. # flush remaining error data
  192. while st is not None:
  193. st = proto.read_pkt_line()
  194. raise SendPackError(unpack)
  195. statuses = []
  196. errs = False
  197. ref_status = proto.read_pkt_line()
  198. while ref_status:
  199. ref_status = ref_status.strip()
  200. statuses.append(ref_status)
  201. if not ref_status.startswith('ok '):
  202. errs = True
  203. ref_status = proto.read_pkt_line()
  204. if errs:
  205. ref_status = {}
  206. ok = set()
  207. for status in statuses:
  208. if ' ' not in status:
  209. # malformed response, move on to the next one
  210. continue
  211. status, ref = status.split(' ', 1)
  212. if status == 'ng':
  213. if ' ' in ref:
  214. ref, status = ref.split(' ', 1)
  215. else:
  216. ok.add(ref)
  217. ref_status[ref] = status
  218. raise UpdateRefsError('%s failed to update' %
  219. ', '.join([ref for ref in ref_status
  220. if ref not in ok]),
  221. ref_status=ref_status)
  222. def _read_side_band64k_data(self, proto, channel_callbacks):
  223. """Read per-channel data.
  224. This requires the side-band-64k capability.
  225. :param proto: Protocol object to read from
  226. :param channel_callbacks: Dictionary mapping channels to packet
  227. handlers to use. None for a callback discards channel data.
  228. """
  229. for pkt in proto.read_pkt_seq():
  230. channel = ord(pkt[0])
  231. pkt = pkt[1:]
  232. try:
  233. cb = channel_callbacks[channel]
  234. except KeyError:
  235. raise AssertionError('Invalid sideband channel %d' % channel)
  236. else:
  237. if cb is not None:
  238. cb(pkt)
  239. def _handle_receive_pack_head(self, proto, capabilities, old_refs, new_refs):
  240. """Handle the head of a 'git-receive-pack' request.
  241. :param proto: Protocol object to read from
  242. :param capabilities: List of negotiated capabilities
  243. :param old_refs: Old refs, as received from the server
  244. :param new_refs: New refs
  245. :return: (have, want) tuple
  246. """
  247. want = []
  248. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  249. sent_capabilities = False
  250. for refname in set(new_refs.keys() + old_refs.keys()):
  251. old_sha1 = old_refs.get(refname, ZERO_SHA)
  252. new_sha1 = new_refs.get(refname, ZERO_SHA)
  253. if old_sha1 != new_sha1:
  254. if sent_capabilities:
  255. proto.write_pkt_line('%s %s %s' % (old_sha1, new_sha1,
  256. refname))
  257. else:
  258. proto.write_pkt_line(
  259. '%s %s %s\0%s' % (old_sha1, new_sha1, refname,
  260. ' '.join(capabilities)))
  261. sent_capabilities = True
  262. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  263. want.append(new_sha1)
  264. proto.write_pkt_line(None)
  265. return (have, want)
  266. def _handle_receive_pack_tail(self, proto, capabilities, progress=None):
  267. """Handle the tail of a 'git-receive-pack' request.
  268. :param proto: Protocol object to read from
  269. :param capabilities: List of negotiated capabilities
  270. :param progress: Optional progress reporting function
  271. """
  272. if "side-band-64k" in capabilities:
  273. if progress is None:
  274. progress = lambda x: None
  275. channel_callbacks = { 2: progress }
  276. if 'report-status' in capabilities:
  277. channel_callbacks[1] = PktLineParser(
  278. self._report_status_parser.handle_packet).parse
  279. self._read_side_band64k_data(proto, channel_callbacks)
  280. else:
  281. if 'report-status' in capabilities:
  282. for pkt in proto.read_pkt_seq():
  283. self._report_status_parser.handle_packet(pkt)
  284. if self._report_status_parser is not None:
  285. self._report_status_parser.check()
  286. # wait for EOF before returning
  287. data = proto.read()
  288. if data:
  289. raise SendPackError('Unexpected response %r' % data)
  290. def _handle_upload_pack_head(self, proto, capabilities, graph_walker,
  291. wants, can_read):
  292. """Handle the head of a 'git-upload-pack' request.
  293. :param proto: Protocol object to read from
  294. :param capabilities: List of negotiated capabilities
  295. :param graph_walker: GraphWalker instance to call .ack() on
  296. :param wants: List of commits to fetch
  297. :param can_read: function that returns a boolean that indicates
  298. whether there is extra graph data to read on proto
  299. """
  300. assert isinstance(wants, list) and type(wants[0]) == str
  301. proto.write_pkt_line('want %s %s\n' % (
  302. wants[0], ' '.join(capabilities)))
  303. for want in wants[1:]:
  304. proto.write_pkt_line('want %s\n' % want)
  305. proto.write_pkt_line(None)
  306. have = graph_walker.next()
  307. while have:
  308. proto.write_pkt_line('have %s\n' % have)
  309. if can_read():
  310. pkt = proto.read_pkt_line()
  311. parts = pkt.rstrip('\n').split(' ')
  312. if parts[0] == 'ACK':
  313. graph_walker.ack(parts[1])
  314. if parts[2] in ('continue', 'common'):
  315. pass
  316. elif parts[2] == 'ready':
  317. break
  318. else:
  319. raise AssertionError(
  320. "%s not in ('continue', 'ready', 'common)" %
  321. parts[2])
  322. have = graph_walker.next()
  323. proto.write_pkt_line('done\n')
  324. def _handle_upload_pack_tail(self, proto, capabilities, graph_walker,
  325. pack_data, progress=None, rbufsize=_RBUFSIZE):
  326. """Handle the tail of a 'git-upload-pack' request.
  327. :param proto: Protocol object to read from
  328. :param capabilities: List of negotiated capabilities
  329. :param graph_walker: GraphWalker instance to call .ack() on
  330. :param pack_data: Function to call with pack data
  331. :param progress: Optional progress reporting function
  332. :param rbufsize: Read buffer size
  333. """
  334. pkt = proto.read_pkt_line()
  335. while pkt:
  336. parts = pkt.rstrip('\n').split(' ')
  337. if parts[0] == 'ACK':
  338. graph_walker.ack(pkt.split(' ')[1])
  339. if len(parts) < 3 or parts[2] not in (
  340. 'ready', 'continue', 'common'):
  341. break
  342. pkt = proto.read_pkt_line()
  343. if "side-band-64k" in capabilities:
  344. if progress is None:
  345. # Just ignore progress data
  346. progress = lambda x: None
  347. self._read_side_band64k_data(proto, {1: pack_data, 2: progress})
  348. # wait for EOF before returning
  349. data = proto.read()
  350. if data:
  351. raise Exception('Unexpected response %r' % data)
  352. else:
  353. while True:
  354. data = proto.read(rbufsize)
  355. if data == "":
  356. break
  357. pack_data(data)
  358. class TraditionalGitClient(GitClient):
  359. """Traditional Git client."""
  360. def _connect(self, cmd, path):
  361. """Create a connection to the server.
  362. This method is abstract - concrete implementations should
  363. implement their own variant which connects to the server and
  364. returns an initialized Protocol object with the service ready
  365. for use and a can_read function which may be used to see if
  366. reads would block.
  367. :param cmd: The git service name to which we should connect.
  368. :param path: The path we should pass to the service.
  369. """
  370. raise NotImplementedError()
  371. def send_pack(self, path, determine_wants, generate_pack_contents,
  372. progress=None):
  373. """Upload a pack to a remote repository.
  374. :param path: Repository path
  375. :param generate_pack_contents: Function that can return a sequence of the
  376. shas of the objects to upload.
  377. :param progress: Optional callback called with progress updates
  378. :raises SendPackError: if server rejects the pack data
  379. :raises UpdateRefsError: if the server supports report-status
  380. and rejects ref updates
  381. """
  382. proto, unused_can_read = self._connect('receive-pack', path)
  383. old_refs, server_capabilities = self._read_refs(proto)
  384. negotiated_capabilities = self._send_capabilities & server_capabilities
  385. if 'report-status' in negotiated_capabilities:
  386. self._report_status_parser = ReportStatusParser()
  387. report_status_parser = self._report_status_parser
  388. try:
  389. new_refs = orig_new_refs = determine_wants(dict(old_refs))
  390. except:
  391. proto.write_pkt_line(None)
  392. raise
  393. if not 'delete-refs' in server_capabilities:
  394. # Server does not support deletions. Fail later.
  395. def remove_del(pair):
  396. if pair[1] == ZERO_SHA:
  397. if 'report-status' in negotiated_capabilities:
  398. report_status_parser._ref_statuses.append(
  399. 'ng %s remote does not support deleting refs'
  400. % pair[1])
  401. report_status_parser._ref_status_ok = False
  402. return False
  403. else:
  404. return True
  405. new_refs = dict(
  406. filter(
  407. remove_del,
  408. [(ref, sha) for ref, sha in new_refs.iteritems()]))
  409. if new_refs is None:
  410. proto.write_pkt_line(None)
  411. return old_refs
  412. if len(new_refs) == 0 and len(orig_new_refs):
  413. # NOOP - Original new refs filtered out by policy
  414. proto.write_pkt_line(None)
  415. if self._report_status_parser is not None:
  416. self._report_status_parser.check()
  417. return old_refs
  418. (have, want) = self._handle_receive_pack_head(proto,
  419. negotiated_capabilities, old_refs, new_refs)
  420. if not want and old_refs == new_refs:
  421. return new_refs
  422. objects = generate_pack_contents(have, want)
  423. if len(objects) > 0:
  424. entries, sha = write_pack_objects(proto.write_file(), objects)
  425. elif len(set(new_refs.values()) - set([ZERO_SHA])) > 0:
  426. # Check for valid create/update refs
  427. filtered_new_refs = \
  428. dict([(ref, sha) for ref, sha in new_refs.iteritems()
  429. if sha != ZERO_SHA])
  430. if len(set(filtered_new_refs.iteritems()) -
  431. set(old_refs.iteritems())) > 0:
  432. entries, sha = write_pack_objects(proto.write_file(), objects)
  433. self._handle_receive_pack_tail(proto, negotiated_capabilities,
  434. progress)
  435. return new_refs
  436. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  437. progress=None):
  438. """Retrieve a pack from a git smart server.
  439. :param determine_wants: Callback that returns list of commits to fetch
  440. :param graph_walker: Object with next() and ack().
  441. :param pack_data: Callback called for each bit of data in the pack
  442. :param progress: Callback for progress reports (strings)
  443. """
  444. proto, can_read = self._connect('upload-pack', path)
  445. refs, server_capabilities = self._read_refs(proto)
  446. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  447. if refs is None:
  448. proto.write_pkt_line(None)
  449. return refs
  450. try:
  451. wants = determine_wants(refs)
  452. except:
  453. proto.write_pkt_line(None)
  454. raise
  455. if wants is not None:
  456. wants = [cid for cid in wants if cid != ZERO_SHA]
  457. if not wants:
  458. proto.write_pkt_line(None)
  459. return refs
  460. self._handle_upload_pack_head(proto, negotiated_capabilities,
  461. graph_walker, wants, can_read)
  462. self._handle_upload_pack_tail(proto, negotiated_capabilities,
  463. graph_walker, pack_data, progress)
  464. return refs
  465. def archive(self, path, committish, write_data, progress=None):
  466. proto, can_read = self._connect('upload-archive', path)
  467. proto.write_pkt_line("argument %s" % committish)
  468. proto.write_pkt_line(None)
  469. pkt = proto.read_pkt_line()
  470. if pkt == "NACK\n":
  471. return
  472. elif pkt == "ACK\n":
  473. pass
  474. elif pkt.startswith("ERR "):
  475. raise GitProtocolError(pkt[4:].rstrip("\n"))
  476. else:
  477. raise AssertionError("invalid response %r" % pkt)
  478. ret = proto.read_pkt_line()
  479. if ret is not None:
  480. raise AssertionError("expected pkt tail")
  481. self._read_side_band64k_data(proto, {1: write_data, 2: progress})
  482. class TCPGitClient(TraditionalGitClient):
  483. """A Git Client that works over TCP directly (i.e. git://)."""
  484. def __init__(self, host, port=None, *args, **kwargs):
  485. if port is None:
  486. port = TCP_GIT_PORT
  487. self._host = host
  488. self._port = port
  489. TraditionalGitClient.__init__(self, *args, **kwargs)
  490. def _connect(self, cmd, path):
  491. sockaddrs = socket.getaddrinfo(self._host, self._port,
  492. socket.AF_UNSPEC, socket.SOCK_STREAM)
  493. s = None
  494. err = socket.error("no address found for %s" % self._host)
  495. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  496. s = socket.socket(family, socktype, proto)
  497. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  498. try:
  499. s.connect(sockaddr)
  500. break
  501. except socket.error, err:
  502. if s is not None:
  503. s.close()
  504. s = None
  505. if s is None:
  506. raise err
  507. # -1 means system default buffering
  508. rfile = s.makefile('rb', -1)
  509. # 0 means unbuffered
  510. wfile = s.makefile('wb', 0)
  511. proto = Protocol(rfile.read, wfile.write,
  512. report_activity=self._report_activity)
  513. if path.startswith("/~"):
  514. path = path[1:]
  515. proto.send_cmd('git-%s' % cmd, path, 'host=%s' % self._host)
  516. return proto, lambda: _fileno_can_read(s)
  517. class SubprocessWrapper(object):
  518. """A socket-like object that talks to a subprocess via pipes."""
  519. def __init__(self, proc):
  520. self.proc = proc
  521. self.read = proc.stdout.read
  522. self.write = proc.stdin.write
  523. def can_read(self):
  524. if subprocess.mswindows:
  525. from msvcrt import get_osfhandle
  526. from win32pipe import PeekNamedPipe
  527. handle = get_osfhandle(self.proc.stdout.fileno())
  528. return PeekNamedPipe(handle, 0)[2] != 0
  529. else:
  530. return _fileno_can_read(self.proc.stdout.fileno())
  531. def close(self):
  532. self.proc.stdin.close()
  533. self.proc.stdout.close()
  534. self.proc.wait()
  535. class SubprocessGitClient(TraditionalGitClient):
  536. """Git client that talks to a server using a subprocess."""
  537. def __init__(self, *args, **kwargs):
  538. self._connection = None
  539. self._stderr = None
  540. self._stderr = kwargs.get('stderr')
  541. if 'stderr' in kwargs:
  542. del kwargs['stderr']
  543. TraditionalGitClient.__init__(self, *args, **kwargs)
  544. def _connect(self, service, path):
  545. import subprocess
  546. argv = ['git', service, path]
  547. p = SubprocessWrapper(
  548. subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  549. stdout=subprocess.PIPE,
  550. stderr=self._stderr))
  551. return Protocol(p.read, p.write,
  552. report_activity=self._report_activity), p.can_read
  553. class SSHVendor(object):
  554. """A client side SSH implementation."""
  555. def connect_ssh(self, host, command, username=None, port=None):
  556. """Connect to an SSH server.
  557. Run a command remotely and return a file-like object for interaction
  558. with the remote command.
  559. :param host: Host name
  560. :param command: Command to run
  561. :param username: Optional ame of user to log in as
  562. :param port: Optional SSH port to use
  563. """
  564. raise NotImplementedError(self.connect_ssh)
  565. class SubprocessSSHVendor(SSHVendor):
  566. """SSH vendor that shells out to the local 'ssh' command."""
  567. def connect_ssh(self, host, command, username=None, port=None):
  568. import subprocess
  569. #FIXME: This has no way to deal with passwords..
  570. args = ['ssh', '-x']
  571. if port is not None:
  572. args.extend(['-p', str(port)])
  573. if username is not None:
  574. host = '%s@%s' % (username, host)
  575. args.append(host)
  576. proc = subprocess.Popen(args + command,
  577. stdin=subprocess.PIPE,
  578. stdout=subprocess.PIPE)
  579. return SubprocessWrapper(proc)
  580. # Can be overridden by users
  581. get_ssh_vendor = SubprocessSSHVendor
  582. class SSHGitClient(TraditionalGitClient):
  583. def __init__(self, host, port=None, username=None, *args, **kwargs):
  584. self.host = host
  585. self.port = port
  586. self.username = username
  587. TraditionalGitClient.__init__(self, *args, **kwargs)
  588. self.alternative_paths = {}
  589. def _get_cmd_path(self, cmd):
  590. return self.alternative_paths.get(cmd, 'git-%s' % cmd)
  591. def _connect(self, cmd, path):
  592. if path.startswith("/~"):
  593. path = path[1:]
  594. con = get_ssh_vendor().connect_ssh(
  595. self.host, ["%s '%s'" % (self._get_cmd_path(cmd), path)],
  596. port=self.port, username=self.username)
  597. return (Protocol(con.read, con.write, report_activity=self._report_activity),
  598. con.can_read)
  599. class HttpGitClient(GitClient):
  600. def __init__(self, base_url, dumb=None, *args, **kwargs):
  601. self.base_url = base_url.rstrip("/") + "/"
  602. self.dumb = dumb
  603. GitClient.__init__(self, *args, **kwargs)
  604. def _get_url(self, path):
  605. return urlparse.urljoin(self.base_url, path).rstrip("/") + "/"
  606. def _http_request(self, url, headers={}, data=None):
  607. req = urllib2.Request(url, headers=headers, data=data)
  608. try:
  609. resp = self._perform(req)
  610. except urllib2.HTTPError as e:
  611. if e.code == 404:
  612. raise NotGitRepository()
  613. if e.code != 200:
  614. raise GitProtocolError("unexpected http response %d" % e.code)
  615. return resp
  616. def _perform(self, req):
  617. """Perform a HTTP request.
  618. This is provided so subclasses can provide their own version.
  619. :param req: urllib2.Request instance
  620. :return: matching response
  621. """
  622. return urllib2.urlopen(req)
  623. def _discover_references(self, service, url):
  624. assert url[-1] == "/"
  625. url = urlparse.urljoin(url, "info/refs")
  626. headers = {}
  627. if self.dumb != False:
  628. url += "?service=%s" % service
  629. headers["Content-Type"] = "application/x-%s-request" % service
  630. resp = self._http_request(url, headers)
  631. self.dumb = (not resp.info().gettype().startswith("application/x-git-"))
  632. proto = Protocol(resp.read, None)
  633. if not self.dumb:
  634. # The first line should mention the service
  635. pkts = list(proto.read_pkt_seq())
  636. if pkts != [('# service=%s\n' % service)]:
  637. raise GitProtocolError(
  638. "unexpected first line %r from smart server" % pkts)
  639. return self._read_refs(proto)
  640. def _smart_request(self, service, url, data):
  641. assert url[-1] == "/"
  642. url = urlparse.urljoin(url, service)
  643. headers = {"Content-Type": "application/x-%s-request" % service}
  644. resp = self._http_request(url, headers, data)
  645. if resp.info().gettype() != ("application/x-%s-result" % service):
  646. raise GitProtocolError("Invalid content-type from server: %s"
  647. % resp.info().gettype())
  648. return resp
  649. def send_pack(self, path, determine_wants, generate_pack_contents,
  650. progress=None):
  651. """Upload a pack to a remote repository.
  652. :param path: Repository path
  653. :param generate_pack_contents: Function that can return a sequence of the
  654. shas of the objects to upload.
  655. :param progress: Optional progress function
  656. :raises SendPackError: if server rejects the pack data
  657. :raises UpdateRefsError: if the server supports report-status
  658. and rejects ref updates
  659. """
  660. url = self._get_url(path)
  661. old_refs, server_capabilities = self._discover_references(
  662. "git-receive-pack", url)
  663. negotiated_capabilities = self._send_capabilities & server_capabilities
  664. if 'report-status' in negotiated_capabilities:
  665. self._report_status_parser = ReportStatusParser()
  666. new_refs = determine_wants(dict(old_refs))
  667. if new_refs is None:
  668. return old_refs
  669. if self.dumb:
  670. raise NotImplementedError(self.fetch_pack)
  671. req_data = StringIO()
  672. req_proto = Protocol(None, req_data.write)
  673. (have, want) = self._handle_receive_pack_head(
  674. req_proto, negotiated_capabilities, old_refs, new_refs)
  675. if not want and old_refs == new_refs:
  676. return new_refs
  677. objects = generate_pack_contents(have, want)
  678. if len(objects) > 0:
  679. entries, sha = write_pack_objects(req_proto.write_file(), objects)
  680. resp = self._smart_request("git-receive-pack", url,
  681. data=req_data.getvalue())
  682. resp_proto = Protocol(resp.read, None)
  683. self._handle_receive_pack_tail(resp_proto, negotiated_capabilities,
  684. progress)
  685. return new_refs
  686. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  687. progress=None):
  688. """Retrieve a pack from a git smart server.
  689. :param determine_wants: Callback that returns list of commits to fetch
  690. :param graph_walker: Object with next() and ack().
  691. :param pack_data: Callback called for each bit of data in the pack
  692. :param progress: Callback for progress reports (strings)
  693. :return: Dictionary with the refs of the remote repository
  694. """
  695. url = self._get_url(path)
  696. refs, server_capabilities = self._discover_references(
  697. "git-upload-pack", url)
  698. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  699. wants = determine_wants(refs)
  700. if wants is not None:
  701. wants = [cid for cid in wants if cid != ZERO_SHA]
  702. if not wants:
  703. return refs
  704. if self.dumb:
  705. raise NotImplementedError(self.send_pack)
  706. req_data = StringIO()
  707. req_proto = Protocol(None, req_data.write)
  708. self._handle_upload_pack_head(req_proto,
  709. negotiated_capabilities, graph_walker, wants,
  710. lambda: False)
  711. resp = self._smart_request("git-upload-pack", url,
  712. data=req_data.getvalue())
  713. resp_proto = Protocol(resp.read, None)
  714. self._handle_upload_pack_tail(resp_proto, negotiated_capabilities,
  715. graph_walker, pack_data, progress)
  716. return refs
  717. def get_transport_and_path(uri, **kwargs):
  718. """Obtain a git client from a URI or path.
  719. :param uri: URI or path
  720. :param thin_packs: Whether or not thin packs should be retrieved
  721. :param report_activity: Optional callback for reporting transport
  722. activity.
  723. :return: Tuple with client instance and relative path.
  724. """
  725. parsed = urlparse.urlparse(uri)
  726. if parsed.scheme == 'git':
  727. return (TCPGitClient(parsed.hostname, port=parsed.port, **kwargs),
  728. parsed.path)
  729. elif parsed.scheme == 'git+ssh':
  730. path = parsed.path
  731. if path.startswith('/'):
  732. path = parsed.path[1:]
  733. return SSHGitClient(parsed.hostname, port=parsed.port,
  734. username=parsed.username, **kwargs), path
  735. elif parsed.scheme in ('http', 'https'):
  736. return HttpGitClient(urlparse.urlunparse(parsed), **kwargs), parsed.path
  737. if parsed.scheme and not parsed.netloc:
  738. # SSH with no user@, zero or one leading slash.
  739. return SSHGitClient(parsed.scheme, **kwargs), parsed.path
  740. elif parsed.scheme:
  741. raise ValueError('Unknown git protocol scheme: %s' % parsed.scheme)
  742. elif '@' in parsed.path and ':' in parsed.path:
  743. # SSH with user@host:foo.
  744. user_host, path = parsed.path.split(':')
  745. user, host = user_host.rsplit('@')
  746. return SSHGitClient(host, username=user, **kwargs), path
  747. # Otherwise, assume it's a local path.
  748. return SubprocessGitClient(**kwargs), uri