client.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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, abort = target.object_store.add_pack()
  174. try:
  175. result = self.fetch_pack(path, determine_wants,
  176. target.get_graph_walker(), f.write, progress)
  177. except:
  178. abort()
  179. raise
  180. else:
  181. commit()
  182. return result
  183. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  184. progress=None):
  185. """Retrieve a pack from a git smart server.
  186. :param determine_wants: Callback that returns list of commits to fetch
  187. :param graph_walker: Object with next() and ack().
  188. :param pack_data: Callback called for each bit of data in the pack
  189. :param progress: Callback for progress reports (strings)
  190. """
  191. raise NotImplementedError(self.fetch_pack)
  192. def _parse_status_report(self, proto):
  193. unpack = proto.read_pkt_line().strip()
  194. if unpack != 'unpack ok':
  195. st = True
  196. # flush remaining error data
  197. while st is not None:
  198. st = proto.read_pkt_line()
  199. raise SendPackError(unpack)
  200. statuses = []
  201. errs = False
  202. ref_status = proto.read_pkt_line()
  203. while ref_status:
  204. ref_status = ref_status.strip()
  205. statuses.append(ref_status)
  206. if not ref_status.startswith('ok '):
  207. errs = True
  208. ref_status = proto.read_pkt_line()
  209. if errs:
  210. ref_status = {}
  211. ok = set()
  212. for status in statuses:
  213. if ' ' not in status:
  214. # malformed response, move on to the next one
  215. continue
  216. status, ref = status.split(' ', 1)
  217. if status == 'ng':
  218. if ' ' in ref:
  219. ref, status = ref.split(' ', 1)
  220. else:
  221. ok.add(ref)
  222. ref_status[ref] = status
  223. raise UpdateRefsError('%s failed to update' %
  224. ', '.join([ref for ref in ref_status
  225. if ref not in ok]),
  226. ref_status=ref_status)
  227. def _read_side_band64k_data(self, proto, channel_callbacks):
  228. """Read per-channel data.
  229. This requires the side-band-64k capability.
  230. :param proto: Protocol object to read from
  231. :param channel_callbacks: Dictionary mapping channels to packet
  232. handlers to use. None for a callback discards channel data.
  233. """
  234. for pkt in proto.read_pkt_seq():
  235. channel = ord(pkt[0])
  236. pkt = pkt[1:]
  237. try:
  238. cb = channel_callbacks[channel]
  239. except KeyError:
  240. raise AssertionError('Invalid sideband channel %d' % channel)
  241. else:
  242. if cb is not None:
  243. cb(pkt)
  244. def _handle_receive_pack_head(self, proto, capabilities, old_refs, new_refs):
  245. """Handle the head of a 'git-receive-pack' request.
  246. :param proto: Protocol object to read from
  247. :param capabilities: List of negotiated capabilities
  248. :param old_refs: Old refs, as received from the server
  249. :param new_refs: New refs
  250. :return: (have, want) tuple
  251. """
  252. want = []
  253. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  254. sent_capabilities = False
  255. for refname in set(new_refs.keys() + old_refs.keys()):
  256. old_sha1 = old_refs.get(refname, ZERO_SHA)
  257. new_sha1 = new_refs.get(refname, ZERO_SHA)
  258. if old_sha1 != new_sha1:
  259. if sent_capabilities:
  260. proto.write_pkt_line('%s %s %s' % (old_sha1, new_sha1,
  261. refname))
  262. else:
  263. proto.write_pkt_line(
  264. '%s %s %s\0%s' % (old_sha1, new_sha1, refname,
  265. ' '.join(capabilities)))
  266. sent_capabilities = True
  267. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  268. want.append(new_sha1)
  269. proto.write_pkt_line(None)
  270. return (have, want)
  271. def _handle_receive_pack_tail(self, proto, capabilities, progress=None):
  272. """Handle the tail of a 'git-receive-pack' request.
  273. :param proto: Protocol object to read from
  274. :param capabilities: List of negotiated capabilities
  275. :param progress: Optional progress reporting function
  276. """
  277. if "side-band-64k" in capabilities:
  278. if progress is None:
  279. progress = lambda x: None
  280. channel_callbacks = { 2: progress }
  281. if 'report-status' in capabilities:
  282. channel_callbacks[1] = PktLineParser(
  283. self._report_status_parser.handle_packet).parse
  284. self._read_side_band64k_data(proto, channel_callbacks)
  285. else:
  286. if 'report-status' in capabilities:
  287. for pkt in proto.read_pkt_seq():
  288. self._report_status_parser.handle_packet(pkt)
  289. if self._report_status_parser is not None:
  290. self._report_status_parser.check()
  291. # wait for EOF before returning
  292. data = proto.read()
  293. if data:
  294. raise SendPackError('Unexpected response %r' % data)
  295. def _handle_upload_pack_head(self, proto, capabilities, graph_walker,
  296. wants, can_read):
  297. """Handle the head of a 'git-upload-pack' request.
  298. :param proto: Protocol object to read from
  299. :param capabilities: List of negotiated capabilities
  300. :param graph_walker: GraphWalker instance to call .ack() on
  301. :param wants: List of commits to fetch
  302. :param can_read: function that returns a boolean that indicates
  303. whether there is extra graph data to read on proto
  304. """
  305. assert isinstance(wants, list) and type(wants[0]) == str
  306. proto.write_pkt_line('want %s %s\n' % (
  307. wants[0], ' '.join(capabilities)))
  308. for want in wants[1:]:
  309. proto.write_pkt_line('want %s\n' % want)
  310. proto.write_pkt_line(None)
  311. have = graph_walker.next()
  312. while have:
  313. proto.write_pkt_line('have %s\n' % have)
  314. if can_read():
  315. pkt = proto.read_pkt_line()
  316. parts = pkt.rstrip('\n').split(' ')
  317. if parts[0] == 'ACK':
  318. graph_walker.ack(parts[1])
  319. if parts[2] in ('continue', 'common'):
  320. pass
  321. elif parts[2] == 'ready':
  322. break
  323. else:
  324. raise AssertionError(
  325. "%s not in ('continue', 'ready', 'common)" %
  326. parts[2])
  327. have = graph_walker.next()
  328. proto.write_pkt_line('done\n')
  329. def _handle_upload_pack_tail(self, proto, capabilities, graph_walker,
  330. pack_data, progress=None, rbufsize=_RBUFSIZE):
  331. """Handle the tail of a 'git-upload-pack' request.
  332. :param proto: Protocol object to read from
  333. :param capabilities: List of negotiated capabilities
  334. :param graph_walker: GraphWalker instance to call .ack() on
  335. :param pack_data: Function to call with pack data
  336. :param progress: Optional progress reporting function
  337. :param rbufsize: Read buffer size
  338. """
  339. pkt = proto.read_pkt_line()
  340. while pkt:
  341. parts = pkt.rstrip('\n').split(' ')
  342. if parts[0] == 'ACK':
  343. graph_walker.ack(pkt.split(' ')[1])
  344. if len(parts) < 3 or parts[2] not in (
  345. 'ready', 'continue', 'common'):
  346. break
  347. pkt = proto.read_pkt_line()
  348. if "side-band-64k" in capabilities:
  349. if progress is None:
  350. # Just ignore progress data
  351. progress = lambda x: None
  352. self._read_side_band64k_data(proto, {1: pack_data, 2: progress})
  353. # wait for EOF before returning
  354. data = proto.read()
  355. if data:
  356. raise Exception('Unexpected response %r' % data)
  357. else:
  358. while True:
  359. data = proto.read(rbufsize)
  360. if data == "":
  361. break
  362. pack_data(data)
  363. class TraditionalGitClient(GitClient):
  364. """Traditional Git client."""
  365. def _connect(self, cmd, path):
  366. """Create a connection to the server.
  367. This method is abstract - concrete implementations should
  368. implement their own variant which connects to the server and
  369. returns an initialized Protocol object with the service ready
  370. for use and a can_read function which may be used to see if
  371. reads would block.
  372. :param cmd: The git service name to which we should connect.
  373. :param path: The path we should pass to the service.
  374. """
  375. raise NotImplementedError()
  376. def send_pack(self, path, determine_wants, generate_pack_contents,
  377. progress=None):
  378. """Upload a pack to a remote repository.
  379. :param path: Repository path
  380. :param generate_pack_contents: Function that can return a sequence of the
  381. shas of the objects to upload.
  382. :param progress: Optional callback called with progress updates
  383. :raises SendPackError: if server rejects the pack data
  384. :raises UpdateRefsError: if the server supports report-status
  385. and rejects ref updates
  386. """
  387. proto, unused_can_read = self._connect('receive-pack', path)
  388. old_refs, server_capabilities = self._read_refs(proto)
  389. negotiated_capabilities = self._send_capabilities & server_capabilities
  390. if 'report-status' in negotiated_capabilities:
  391. self._report_status_parser = ReportStatusParser()
  392. report_status_parser = self._report_status_parser
  393. try:
  394. new_refs = orig_new_refs = determine_wants(dict(old_refs))
  395. except:
  396. proto.write_pkt_line(None)
  397. raise
  398. if not 'delete-refs' in server_capabilities:
  399. # Server does not support deletions. Fail later.
  400. def remove_del(pair):
  401. if pair[1] == ZERO_SHA:
  402. if 'report-status' in negotiated_capabilities:
  403. report_status_parser._ref_statuses.append(
  404. 'ng %s remote does not support deleting refs'
  405. % pair[1])
  406. report_status_parser._ref_status_ok = False
  407. return False
  408. else:
  409. return True
  410. new_refs = dict(
  411. filter(
  412. remove_del,
  413. [(ref, sha) for ref, sha in new_refs.iteritems()]))
  414. if new_refs is None:
  415. proto.write_pkt_line(None)
  416. return old_refs
  417. if len(new_refs) == 0 and len(orig_new_refs):
  418. # NOOP - Original new refs filtered out by policy
  419. proto.write_pkt_line(None)
  420. if self._report_status_parser is not None:
  421. self._report_status_parser.check()
  422. return old_refs
  423. (have, want) = self._handle_receive_pack_head(proto,
  424. negotiated_capabilities, old_refs, new_refs)
  425. if not want and old_refs == new_refs:
  426. return new_refs
  427. objects = generate_pack_contents(have, want)
  428. if len(objects) > 0:
  429. entries, sha = write_pack_objects(proto.write_file(), objects)
  430. elif len(set(new_refs.values()) - set([ZERO_SHA])) > 0:
  431. # Check for valid create/update refs
  432. filtered_new_refs = \
  433. dict([(ref, sha) for ref, sha in new_refs.iteritems()
  434. if sha != ZERO_SHA])
  435. if len(set(filtered_new_refs.iteritems()) -
  436. set(old_refs.iteritems())) > 0:
  437. entries, sha = write_pack_objects(proto.write_file(), objects)
  438. self._handle_receive_pack_tail(proto, negotiated_capabilities,
  439. progress)
  440. return new_refs
  441. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  442. progress=None):
  443. """Retrieve a pack from a git smart server.
  444. :param determine_wants: Callback that returns list of commits to fetch
  445. :param graph_walker: Object with next() and ack().
  446. :param pack_data: Callback called for each bit of data in the pack
  447. :param progress: Callback for progress reports (strings)
  448. """
  449. proto, can_read = self._connect('upload-pack', path)
  450. refs, server_capabilities = self._read_refs(proto)
  451. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  452. if refs is None:
  453. proto.write_pkt_line(None)
  454. return refs
  455. try:
  456. wants = determine_wants(refs)
  457. except:
  458. proto.write_pkt_line(None)
  459. raise
  460. if wants is not None:
  461. wants = [cid for cid in wants if cid != ZERO_SHA]
  462. if not wants:
  463. proto.write_pkt_line(None)
  464. return refs
  465. self._handle_upload_pack_head(proto, negotiated_capabilities,
  466. graph_walker, wants, can_read)
  467. self._handle_upload_pack_tail(proto, negotiated_capabilities,
  468. graph_walker, pack_data, progress)
  469. return refs
  470. def archive(self, path, committish, write_data, progress=None):
  471. proto, can_read = self._connect('upload-archive', path)
  472. proto.write_pkt_line("argument %s" % committish)
  473. proto.write_pkt_line(None)
  474. pkt = proto.read_pkt_line()
  475. if pkt == "NACK\n":
  476. return
  477. elif pkt == "ACK\n":
  478. pass
  479. elif pkt.startswith("ERR "):
  480. raise GitProtocolError(pkt[4:].rstrip("\n"))
  481. else:
  482. raise AssertionError("invalid response %r" % pkt)
  483. ret = proto.read_pkt_line()
  484. if ret is not None:
  485. raise AssertionError("expected pkt tail")
  486. self._read_side_band64k_data(proto, {1: write_data, 2: progress})
  487. class TCPGitClient(TraditionalGitClient):
  488. """A Git Client that works over TCP directly (i.e. git://)."""
  489. def __init__(self, host, port=None, *args, **kwargs):
  490. if port is None:
  491. port = TCP_GIT_PORT
  492. self._host = host
  493. self._port = port
  494. TraditionalGitClient.__init__(self, *args, **kwargs)
  495. def _connect(self, cmd, path):
  496. sockaddrs = socket.getaddrinfo(self._host, self._port,
  497. socket.AF_UNSPEC, socket.SOCK_STREAM)
  498. s = None
  499. err = socket.error("no address found for %s" % self._host)
  500. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  501. s = socket.socket(family, socktype, proto)
  502. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  503. try:
  504. s.connect(sockaddr)
  505. break
  506. except socket.error, err:
  507. if s is not None:
  508. s.close()
  509. s = None
  510. if s is None:
  511. raise err
  512. # -1 means system default buffering
  513. rfile = s.makefile('rb', -1)
  514. # 0 means unbuffered
  515. wfile = s.makefile('wb', 0)
  516. proto = Protocol(rfile.read, wfile.write,
  517. report_activity=self._report_activity)
  518. if path.startswith("/~"):
  519. path = path[1:]
  520. proto.send_cmd('git-%s' % cmd, path, 'host=%s' % self._host)
  521. return proto, lambda: _fileno_can_read(s)
  522. class SubprocessWrapper(object):
  523. """A socket-like object that talks to a subprocess via pipes."""
  524. def __init__(self, proc):
  525. self.proc = proc
  526. self.read = proc.stdout.read
  527. self.write = proc.stdin.write
  528. def can_read(self):
  529. if subprocess.mswindows:
  530. from msvcrt import get_osfhandle
  531. from win32pipe import PeekNamedPipe
  532. handle = get_osfhandle(self.proc.stdout.fileno())
  533. return PeekNamedPipe(handle, 0)[2] != 0
  534. else:
  535. return _fileno_can_read(self.proc.stdout.fileno())
  536. def close(self):
  537. self.proc.stdin.close()
  538. self.proc.stdout.close()
  539. self.proc.wait()
  540. class SubprocessGitClient(TraditionalGitClient):
  541. """Git client that talks to a server using a subprocess."""
  542. def __init__(self, *args, **kwargs):
  543. self._connection = None
  544. self._stderr = None
  545. self._stderr = kwargs.get('stderr')
  546. if 'stderr' in kwargs:
  547. del kwargs['stderr']
  548. TraditionalGitClient.__init__(self, *args, **kwargs)
  549. def _connect(self, service, path):
  550. import subprocess
  551. argv = ['git', service, path]
  552. p = SubprocessWrapper(
  553. subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  554. stdout=subprocess.PIPE,
  555. stderr=self._stderr))
  556. return Protocol(p.read, p.write,
  557. report_activity=self._report_activity), p.can_read
  558. class SSHVendor(object):
  559. """A client side SSH implementation."""
  560. def connect_ssh(self, host, command, username=None, port=None):
  561. import warnings
  562. warnings.warn(
  563. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  564. DeprecationWarning)
  565. return self.run_command(host, command, username=username, port=port)
  566. def run_command(self, host, command, username=None, port=None):
  567. """Connect to an SSH server.
  568. Run a command remotely and return a file-like object for interaction
  569. with the remote command.
  570. :param host: Host name
  571. :param command: Command to run
  572. :param username: Optional ame of user to log in as
  573. :param port: Optional SSH port to use
  574. """
  575. raise NotImplementedError(self.run_command)
  576. class SubprocessSSHVendor(SSHVendor):
  577. """SSH vendor that shells out to the local 'ssh' command."""
  578. def run_command(self, host, command, username=None, port=None):
  579. import subprocess
  580. #FIXME: This has no way to deal with passwords..
  581. args = ['ssh', '-x']
  582. if port is not None:
  583. args.extend(['-p', str(port)])
  584. if username is not None:
  585. host = '%s@%s' % (username, host)
  586. args.append(host)
  587. proc = subprocess.Popen(args + command,
  588. stdin=subprocess.PIPE,
  589. stdout=subprocess.PIPE)
  590. return SubprocessWrapper(proc)
  591. try:
  592. import paramiko
  593. except ImportError:
  594. pass
  595. else:
  596. import threading
  597. class ParamikoWrapper(object):
  598. STDERR_READ_N = 2048 # 2k
  599. def __init__(self, client, channel, progress_stderr=None):
  600. self.client = client
  601. self.channel = channel
  602. self.progress_stderr = progress_stderr
  603. self.should_monitor = bool(progress_stderr) or True
  604. self.monitor_thread = None
  605. self.stderr = ''
  606. # Channel must block
  607. self.channel.setblocking(True)
  608. # Start
  609. if self.should_monitor:
  610. self.monitor_thread = threading.Thread(target=self.monitor_stderr)
  611. self.monitor_thread.start()
  612. def monitor_stderr(self):
  613. while self.should_monitor:
  614. # Block and read
  615. data = self.read_stderr(self.STDERR_READ_N)
  616. # Socket closed
  617. if not data:
  618. self.should_monitor = False
  619. break
  620. # Emit data
  621. if self.progress_stderr:
  622. self.progress_stderr(data)
  623. # Append to buffer
  624. self.stderr += data
  625. def stop_monitoring(self):
  626. # Stop StdErr thread
  627. if self.should_monitor:
  628. self.should_monitor = False
  629. self.monitor_thread.join()
  630. # Get left over data
  631. data = self.channel.in_stderr_buffer.empty()
  632. self.stderr += data
  633. def can_read(self):
  634. return self.channel.recv_ready()
  635. def write(self, data):
  636. return self.channel.sendall(data)
  637. def read_stderr(self, n):
  638. return self.channel.recv_stderr(n)
  639. def read(self, n=None):
  640. data = self.channel.recv(n)
  641. data_len = len(data)
  642. # Closed socket
  643. if not data:
  644. return
  645. # Read more if needed
  646. if n and data_len < n:
  647. diff_len = n - data_len
  648. return data + self.read(diff_len)
  649. return data
  650. def close(self):
  651. self.channel.close()
  652. self.stop_monitoring()
  653. def __del__(self):
  654. self.close()
  655. class ParamikoSSHVendor(object):
  656. def run_command(self, host, command, username=None, port=None,
  657. progress_stderr=None, **kwargs):
  658. client = paramiko.SSHClient()
  659. policy = paramiko.client.MissingHostKeyPolicy()
  660. client.set_missing_host_key_policy(policy)
  661. client.connect(host, username=username, port=port, **kwargs)
  662. # Open SSH session
  663. channel = client.get_transport().open_session()
  664. # Run commands
  665. apply(channel.exec_command, command)
  666. return ParamikoWrapper(client, channel,
  667. progress_stderr=progress_stderr)
  668. # Can be overridden by users
  669. get_ssh_vendor = SubprocessSSHVendor
  670. class SSHGitClient(TraditionalGitClient):
  671. def __init__(self, host, port=None, username=None, *args, **kwargs):
  672. self.host = host
  673. self.port = port
  674. self.username = username
  675. TraditionalGitClient.__init__(self, *args, **kwargs)
  676. self.alternative_paths = {}
  677. def _get_cmd_path(self, cmd):
  678. return self.alternative_paths.get(cmd, 'git-%s' % cmd)
  679. def _connect(self, cmd, path):
  680. if path.startswith("/~"):
  681. path = path[1:]
  682. con = get_ssh_vendor().run_command(
  683. self.host, ["%s '%s'" % (self._get_cmd_path(cmd), path)],
  684. port=self.port, username=self.username)
  685. return (Protocol(con.read, con.write, report_activity=self._report_activity),
  686. con.can_read)
  687. class HttpGitClient(GitClient):
  688. def __init__(self, base_url, dumb=None, *args, **kwargs):
  689. self.base_url = base_url.rstrip("/") + "/"
  690. self.dumb = dumb
  691. GitClient.__init__(self, *args, **kwargs)
  692. def _get_url(self, path):
  693. return urlparse.urljoin(self.base_url, path).rstrip("/") + "/"
  694. def _http_request(self, url, headers={}, data=None):
  695. req = urllib2.Request(url, headers=headers, data=data)
  696. try:
  697. resp = self._perform(req)
  698. except urllib2.HTTPError as e:
  699. if e.code == 404:
  700. raise NotGitRepository()
  701. if e.code != 200:
  702. raise GitProtocolError("unexpected http response %d" % e.code)
  703. return resp
  704. def _perform(self, req):
  705. """Perform a HTTP request.
  706. This is provided so subclasses can provide their own version.
  707. :param req: urllib2.Request instance
  708. :return: matching response
  709. """
  710. return urllib2.urlopen(req)
  711. def _discover_references(self, service, url):
  712. assert url[-1] == "/"
  713. url = urlparse.urljoin(url, "info/refs")
  714. headers = {}
  715. if self.dumb != False:
  716. url += "?service=%s" % service
  717. headers["Content-Type"] = "application/x-%s-request" % service
  718. resp = self._http_request(url, headers)
  719. self.dumb = (not resp.info().gettype().startswith("application/x-git-"))
  720. proto = Protocol(resp.read, None)
  721. if not self.dumb:
  722. # The first line should mention the service
  723. pkts = list(proto.read_pkt_seq())
  724. if pkts != [('# service=%s\n' % service)]:
  725. raise GitProtocolError(
  726. "unexpected first line %r from smart server" % pkts)
  727. return self._read_refs(proto)
  728. def _smart_request(self, service, url, data):
  729. assert url[-1] == "/"
  730. url = urlparse.urljoin(url, service)
  731. headers = {"Content-Type": "application/x-%s-request" % service}
  732. resp = self._http_request(url, headers, data)
  733. if resp.info().gettype() != ("application/x-%s-result" % service):
  734. raise GitProtocolError("Invalid content-type from server: %s"
  735. % resp.info().gettype())
  736. return resp
  737. def send_pack(self, path, determine_wants, generate_pack_contents,
  738. progress=None):
  739. """Upload a pack to a remote repository.
  740. :param path: Repository path
  741. :param generate_pack_contents: Function that can return a sequence of the
  742. shas of the objects to upload.
  743. :param progress: Optional progress function
  744. :raises SendPackError: if server rejects the pack data
  745. :raises UpdateRefsError: if the server supports report-status
  746. and rejects ref updates
  747. """
  748. url = self._get_url(path)
  749. old_refs, server_capabilities = self._discover_references(
  750. "git-receive-pack", url)
  751. negotiated_capabilities = self._send_capabilities & server_capabilities
  752. if 'report-status' in negotiated_capabilities:
  753. self._report_status_parser = ReportStatusParser()
  754. new_refs = determine_wants(dict(old_refs))
  755. if new_refs is None:
  756. return old_refs
  757. if self.dumb:
  758. raise NotImplementedError(self.fetch_pack)
  759. req_data = StringIO()
  760. req_proto = Protocol(None, req_data.write)
  761. (have, want) = self._handle_receive_pack_head(
  762. req_proto, negotiated_capabilities, old_refs, new_refs)
  763. if not want and old_refs == new_refs:
  764. return new_refs
  765. objects = generate_pack_contents(have, want)
  766. if len(objects) > 0:
  767. entries, sha = write_pack_objects(req_proto.write_file(), objects)
  768. resp = self._smart_request("git-receive-pack", url,
  769. data=req_data.getvalue())
  770. resp_proto = Protocol(resp.read, None)
  771. self._handle_receive_pack_tail(resp_proto, negotiated_capabilities,
  772. progress)
  773. return new_refs
  774. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  775. progress=None):
  776. """Retrieve a pack from a git smart server.
  777. :param determine_wants: Callback that returns list of commits to fetch
  778. :param graph_walker: Object with next() and ack().
  779. :param pack_data: Callback called for each bit of data in the pack
  780. :param progress: Callback for progress reports (strings)
  781. :return: Dictionary with the refs of the remote repository
  782. """
  783. url = self._get_url(path)
  784. refs, server_capabilities = self._discover_references(
  785. "git-upload-pack", url)
  786. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  787. wants = determine_wants(refs)
  788. if wants is not None:
  789. wants = [cid for cid in wants if cid != ZERO_SHA]
  790. if not wants:
  791. return refs
  792. if self.dumb:
  793. raise NotImplementedError(self.send_pack)
  794. req_data = StringIO()
  795. req_proto = Protocol(None, req_data.write)
  796. self._handle_upload_pack_head(req_proto,
  797. negotiated_capabilities, graph_walker, wants,
  798. lambda: False)
  799. resp = self._smart_request("git-upload-pack", url,
  800. data=req_data.getvalue())
  801. resp_proto = Protocol(resp.read, None)
  802. self._handle_upload_pack_tail(resp_proto, negotiated_capabilities,
  803. graph_walker, pack_data, progress)
  804. return refs
  805. def get_transport_and_path(uri, **kwargs):
  806. """Obtain a git client from a URI or path.
  807. :param uri: URI or path
  808. :param thin_packs: Whether or not thin packs should be retrieved
  809. :param report_activity: Optional callback for reporting transport
  810. activity.
  811. :return: Tuple with client instance and relative path.
  812. """
  813. parsed = urlparse.urlparse(uri)
  814. if parsed.scheme == 'git':
  815. return (TCPGitClient(parsed.hostname, port=parsed.port, **kwargs),
  816. parsed.path)
  817. elif parsed.scheme == 'git+ssh':
  818. path = parsed.path
  819. if path.startswith('/'):
  820. path = parsed.path[1:]
  821. return SSHGitClient(parsed.hostname, port=parsed.port,
  822. username=parsed.username, **kwargs), path
  823. elif parsed.scheme in ('http', 'https'):
  824. return HttpGitClient(urlparse.urlunparse(parsed), **kwargs), parsed.path
  825. if parsed.scheme and not parsed.netloc:
  826. # SSH with no user@, zero or one leading slash.
  827. return SSHGitClient(parsed.scheme, **kwargs), parsed.path
  828. elif parsed.scheme:
  829. raise ValueError('Unknown git protocol scheme: %s' % parsed.scheme)
  830. elif '@' in parsed.path and ':' in parsed.path:
  831. # SSH with user@host:foo.
  832. user_host, path = parsed.path.split(':')
  833. user, host = user_host.rsplit('@')
  834. return SSHGitClient(host, username=user, **kwargs), path
  835. # Otherwise, assume it's a local path.
  836. return SubprocessGitClient(**kwargs), uri