client.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. # client.py -- Implementation of the server side git protocols
  2. # Copyright (C) 2008-2013 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 io import BytesIO
  35. import dulwich
  36. import select
  37. import socket
  38. import subprocess
  39. import sys
  40. try:
  41. import urllib2
  42. import urlparse
  43. except ImportError:
  44. import urllib.request as urllib2
  45. import urllib.parse as urlparse
  46. from dulwich.errors import (
  47. GitProtocolError,
  48. NotGitRepository,
  49. SendPackError,
  50. UpdateRefsError,
  51. )
  52. from dulwich.protocol import (
  53. _RBUFSIZE,
  54. CAPABILITY_DELETE_REFS,
  55. CAPABILITY_MULTI_ACK,
  56. CAPABILITY_MULTI_ACK_DETAILED,
  57. CAPABILITY_OFS_DELTA,
  58. CAPABILITY_REPORT_STATUS,
  59. CAPABILITY_SIDE_BAND_64K,
  60. CAPABILITY_THIN_PACK,
  61. PktLineParser,
  62. Protocol,
  63. ProtocolFile,
  64. TCP_GIT_PORT,
  65. ZERO_SHA,
  66. extract_capabilities,
  67. )
  68. from dulwich.pack import (
  69. write_pack_objects,
  70. )
  71. from dulwich.refs import (
  72. read_info_refs,
  73. )
  74. def _fileno_can_read(fileno):
  75. """Check if a file descriptor is readable."""
  76. return len(select.select([fileno], [], [], 0)[0]) > 0
  77. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  78. FETCH_CAPABILITIES = ([CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK,
  79. CAPABILITY_MULTI_ACK_DETAILED] +
  80. COMMON_CAPABILITIES)
  81. SEND_CAPABILITIES = [CAPABILITY_REPORT_STATUS] + COMMON_CAPABILITIES
  82. class ReportStatusParser(object):
  83. """Handle status as reported by servers with 'report-status' capability.
  84. """
  85. def __init__(self):
  86. self._done = False
  87. self._pack_status = None
  88. self._ref_status_ok = True
  89. self._ref_statuses = []
  90. def check(self):
  91. """Check if there were any errors and, if so, raise exceptions.
  92. :raise SendPackError: Raised when the server could not unpack
  93. :raise UpdateRefsError: Raised when refs could not be updated
  94. """
  95. if self._pack_status not in (b'unpack ok', None):
  96. raise SendPackError(self._pack_status)
  97. if not self._ref_status_ok:
  98. ref_status = {}
  99. ok = set()
  100. for status in self._ref_statuses:
  101. if b' ' not in status:
  102. # malformed response, move on to the next one
  103. continue
  104. status, ref = status.split(b' ', 1)
  105. if status == b'ng':
  106. if b' ' in ref:
  107. ref, status = ref.split(b' ', 1)
  108. else:
  109. ok.add(ref)
  110. ref_status[ref] = status
  111. raise UpdateRefsError(b', '.join([ref for ref in ref_status
  112. if ref not in ok]) +
  113. b' failed to update',
  114. ref_status=ref_status)
  115. def handle_packet(self, pkt):
  116. """Handle a packet.
  117. :raise GitProtocolError: Raised when packets are received after a
  118. flush packet.
  119. """
  120. if self._done:
  121. raise GitProtocolError("received more data after status report")
  122. if pkt is None:
  123. self._done = True
  124. return
  125. if self._pack_status is None:
  126. self._pack_status = pkt.strip()
  127. else:
  128. ref_status = pkt.strip()
  129. self._ref_statuses.append(ref_status)
  130. if not ref_status.startswith(b'ok '):
  131. self._ref_status_ok = False
  132. def read_pkt_refs(proto):
  133. server_capabilities = None
  134. refs = {}
  135. # Receive refs from server
  136. for pkt in proto.read_pkt_seq():
  137. (sha, ref) = pkt.rstrip(b'\n').split(None, 1)
  138. if sha == b'ERR':
  139. raise GitProtocolError(ref)
  140. if server_capabilities is None:
  141. (ref, server_capabilities) = extract_capabilities(ref)
  142. refs[ref] = sha
  143. if len(refs) == 0:
  144. return None, set([])
  145. return refs, set(server_capabilities)
  146. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  147. # support some capabilities. This should work properly with servers
  148. # that don't support multi_ack.
  149. class GitClient(object):
  150. """Git smart server client.
  151. """
  152. def __init__(self, thin_packs=True, report_activity=None):
  153. """Create a new GitClient instance.
  154. :param thin_packs: Whether or not thin packs should be retrieved
  155. :param report_activity: Optional callback for reporting transport
  156. activity.
  157. """
  158. self._report_activity = report_activity
  159. self._report_status_parser = None
  160. self._fetch_capabilities = set(FETCH_CAPABILITIES)
  161. self._send_capabilities = set(SEND_CAPABILITIES)
  162. if not thin_packs:
  163. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  164. def send_pack(self, path, determine_wants, generate_pack_contents,
  165. progress=None, write_pack=write_pack_objects):
  166. """Upload a pack to a remote repository.
  167. :param path: Repository path
  168. :param generate_pack_contents: Function that can return a sequence of
  169. the shas of the objects to upload.
  170. :param progress: Optional progress function
  171. :param write_pack: Function called with (file, iterable of objects) to
  172. write the objects returned by generate_pack_contents to the server.
  173. :raises SendPackError: if server rejects the pack data
  174. :raises UpdateRefsError: if the server supports report-status
  175. and rejects ref updates
  176. """
  177. raise NotImplementedError(self.send_pack)
  178. def fetch(self, path, target, determine_wants=None, progress=None):
  179. """Fetch into a target repository.
  180. :param path: Path to fetch from
  181. :param target: Target repository to fetch into
  182. :param determine_wants: Optional function to determine what refs
  183. to fetch
  184. :param progress: Optional progress function
  185. :return: remote refs as dictionary
  186. """
  187. if determine_wants is None:
  188. determine_wants = target.object_store.determine_wants_all
  189. f, commit, abort = target.object_store.add_pack()
  190. try:
  191. result = self.fetch_pack(
  192. path, determine_wants, target.get_graph_walker(), f.write,
  193. progress)
  194. except:
  195. abort()
  196. raise
  197. else:
  198. commit()
  199. return result
  200. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  201. progress=None):
  202. """Retrieve a pack from a git smart server.
  203. :param determine_wants: Callback that returns list of commits to fetch
  204. :param graph_walker: Object with next() and ack().
  205. :param pack_data: Callback called for each bit of data in the pack
  206. :param progress: Callback for progress reports (strings)
  207. """
  208. raise NotImplementedError(self.fetch_pack)
  209. def _parse_status_report(self, proto):
  210. unpack = proto.read_pkt_line().strip()
  211. if unpack != b'unpack ok':
  212. st = True
  213. # flush remaining error data
  214. while st is not None:
  215. st = proto.read_pkt_line()
  216. raise SendPackError(unpack)
  217. statuses = []
  218. errs = False
  219. ref_status = proto.read_pkt_line()
  220. while ref_status:
  221. ref_status = ref_status.strip()
  222. statuses.append(ref_status)
  223. if not ref_status.startswith(b'ok '):
  224. errs = True
  225. ref_status = proto.read_pkt_line()
  226. if errs:
  227. ref_status = {}
  228. ok = set()
  229. for status in statuses:
  230. if b' ' not in status:
  231. # malformed response, move on to the next one
  232. continue
  233. status, ref = status.split(b' ', 1)
  234. if status == b'ng':
  235. if b' ' in ref:
  236. ref, status = ref.split(b' ', 1)
  237. else:
  238. ok.add(ref)
  239. ref_status[ref] = status
  240. raise UpdateRefsError(b', '.join([ref for ref in ref_status
  241. if ref not in ok]) +
  242. b' failed to update',
  243. ref_status=ref_status)
  244. def _read_side_band64k_data(self, proto, channel_callbacks):
  245. """Read per-channel data.
  246. This requires the side-band-64k capability.
  247. :param proto: Protocol object to read from
  248. :param channel_callbacks: Dictionary mapping channels to packet
  249. handlers to use. None for a callback discards channel data.
  250. """
  251. for pkt in proto.read_pkt_seq():
  252. channel = ord(pkt[:1])
  253. pkt = pkt[1:]
  254. try:
  255. cb = channel_callbacks[channel]
  256. except KeyError:
  257. raise AssertionError('Invalid sideband channel %d' % channel)
  258. else:
  259. if cb is not None:
  260. cb(pkt)
  261. def _handle_receive_pack_head(self, proto, capabilities, old_refs,
  262. new_refs):
  263. """Handle the head of a 'git-receive-pack' request.
  264. :param proto: Protocol object to read from
  265. :param capabilities: List of negotiated capabilities
  266. :param old_refs: Old refs, as received from the server
  267. :param new_refs: New refs
  268. :return: (have, want) tuple
  269. """
  270. want = []
  271. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  272. sent_capabilities = False
  273. all_refs = set(new_refs.keys()).union(set(old_refs.keys()))
  274. for refname in all_refs:
  275. old_sha1 = old_refs.get(refname, ZERO_SHA)
  276. new_sha1 = new_refs.get(refname, ZERO_SHA)
  277. if old_sha1 != new_sha1:
  278. if sent_capabilities:
  279. proto.write_pkt_line(old_sha1 + b' ' + new_sha1 + b' ' + refname)
  280. else:
  281. proto.write_pkt_line(
  282. old_sha1 + b' ' + new_sha1 + b' ' + refname + b'\0' +
  283. b' '.join(capabilities))
  284. sent_capabilities = True
  285. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  286. want.append(new_sha1)
  287. proto.write_pkt_line(None)
  288. return (have, want)
  289. def _handle_receive_pack_tail(self, proto, capabilities, progress=None):
  290. """Handle the tail of a 'git-receive-pack' request.
  291. :param proto: Protocol object to read from
  292. :param capabilities: List of negotiated capabilities
  293. :param progress: Optional progress reporting function
  294. """
  295. if b"side-band-64k" in capabilities:
  296. if progress is None:
  297. progress = lambda x: None
  298. channel_callbacks = {2: progress}
  299. if CAPABILITY_REPORT_STATUS in capabilities:
  300. channel_callbacks[1] = PktLineParser(
  301. self._report_status_parser.handle_packet).parse
  302. self._read_side_band64k_data(proto, channel_callbacks)
  303. else:
  304. if CAPABILITY_REPORT_STATUS in capabilities:
  305. for pkt in proto.read_pkt_seq():
  306. self._report_status_parser.handle_packet(pkt)
  307. if self._report_status_parser is not None:
  308. self._report_status_parser.check()
  309. def _handle_upload_pack_head(self, proto, capabilities, graph_walker,
  310. wants, can_read):
  311. """Handle the head of a 'git-upload-pack' request.
  312. :param proto: Protocol object to read from
  313. :param capabilities: List of negotiated capabilities
  314. :param graph_walker: GraphWalker instance to call .ack() on
  315. :param wants: List of commits to fetch
  316. :param can_read: function that returns a boolean that indicates
  317. whether there is extra graph data to read on proto
  318. """
  319. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  320. proto.write_pkt_line(b'want ' + wants[0] + b' ' + b' '.join(capabilities) + b'\n')
  321. for want in wants[1:]:
  322. proto.write_pkt_line(b'want ' + want + b'\n')
  323. proto.write_pkt_line(None)
  324. have = next(graph_walker)
  325. while have:
  326. proto.write_pkt_line(b'have ' + have + b'\n')
  327. if can_read():
  328. pkt = proto.read_pkt_line()
  329. parts = pkt.rstrip(b'\n').split(b' ')
  330. if parts[0] == b'ACK':
  331. graph_walker.ack(parts[1])
  332. if parts[2] in (b'continue', b'common'):
  333. pass
  334. elif parts[2] == b'ready':
  335. break
  336. else:
  337. raise AssertionError(
  338. "%s not in ('continue', 'ready', 'common)" %
  339. parts[2])
  340. have = next(graph_walker)
  341. proto.write_pkt_line(b'done\n')
  342. def _handle_upload_pack_tail(self, proto, capabilities, graph_walker,
  343. pack_data, progress=None, rbufsize=_RBUFSIZE):
  344. """Handle the tail of a 'git-upload-pack' request.
  345. :param proto: Protocol object to read from
  346. :param capabilities: List of negotiated capabilities
  347. :param graph_walker: GraphWalker instance to call .ack() on
  348. :param pack_data: Function to call with pack data
  349. :param progress: Optional progress reporting function
  350. :param rbufsize: Read buffer size
  351. """
  352. pkt = proto.read_pkt_line()
  353. while pkt:
  354. parts = pkt.rstrip(b'\n').split(b' ')
  355. if parts[0] == b'ACK':
  356. graph_walker.ack(parts[1])
  357. if len(parts) < 3 or parts[2] not in (
  358. b'ready', b'continue', b'common'):
  359. break
  360. pkt = proto.read_pkt_line()
  361. if CAPABILITY_SIDE_BAND_64K in capabilities:
  362. if progress is None:
  363. # Just ignore progress data
  364. progress = lambda x: None
  365. self._read_side_band64k_data(proto, {1: pack_data, 2: progress})
  366. else:
  367. while True:
  368. data = proto.read(rbufsize)
  369. if data == b"":
  370. break
  371. pack_data(data)
  372. class TraditionalGitClient(GitClient):
  373. """Traditional Git client."""
  374. def _connect(self, cmd, path):
  375. """Create a connection to the server.
  376. This method is abstract - concrete implementations should
  377. implement their own variant which connects to the server and
  378. returns an initialized Protocol object with the service ready
  379. for use and a can_read function which may be used to see if
  380. reads would block.
  381. :param cmd: The git service name to which we should connect.
  382. :param path: The path we should pass to the service.
  383. """
  384. raise NotImplementedError()
  385. def send_pack(self, path, determine_wants, generate_pack_contents,
  386. progress=None, write_pack=write_pack_objects):
  387. """Upload a pack to a remote repository.
  388. :param path: Repository path
  389. :param generate_pack_contents: Function that can return a sequence of
  390. the shas of the objects to upload.
  391. :param progress: Optional callback called with progress updates
  392. :param write_pack: Function called with (file, iterable of objects) to
  393. write the objects returned by generate_pack_contents to the server.
  394. :raises SendPackError: if server rejects the pack data
  395. :raises UpdateRefsError: if the server supports report-status
  396. and rejects ref updates
  397. """
  398. proto, unused_can_read = self._connect(b'receive-pack', path)
  399. with proto:
  400. old_refs, server_capabilities = read_pkt_refs(proto)
  401. negotiated_capabilities = self._send_capabilities & server_capabilities
  402. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  403. self._report_status_parser = ReportStatusParser()
  404. report_status_parser = self._report_status_parser
  405. try:
  406. new_refs = orig_new_refs = determine_wants(dict(old_refs))
  407. except:
  408. proto.write_pkt_line(None)
  409. raise
  410. if not CAPABILITY_DELETE_REFS in server_capabilities:
  411. # Server does not support deletions. Fail later.
  412. new_refs = dict(orig_new_refs)
  413. for ref, sha in orig_new_refs.items():
  414. if sha == ZERO_SHA:
  415. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  416. report_status_parser._ref_statuses.append(
  417. b'ng ' + sha + b' remote does not support deleting refs')
  418. report_status_parser._ref_status_ok = False
  419. del new_refs[ref]
  420. if new_refs is None:
  421. proto.write_pkt_line(None)
  422. return old_refs
  423. if len(new_refs) == 0 and len(orig_new_refs):
  424. # NOOP - Original new refs filtered out by policy
  425. proto.write_pkt_line(None)
  426. if report_status_parser is not None:
  427. report_status_parser.check()
  428. return old_refs
  429. (have, want) = self._handle_receive_pack_head(
  430. proto, negotiated_capabilities, old_refs, new_refs)
  431. if not want and old_refs == new_refs:
  432. return new_refs
  433. objects = generate_pack_contents(have, want)
  434. dowrite = len(objects) > 0
  435. dowrite = dowrite or any(old_refs.get(ref) != sha
  436. for (ref, sha) in new_refs.items()
  437. if sha != ZERO_SHA)
  438. if dowrite:
  439. write_pack(proto.write_file(), objects)
  440. self._handle_receive_pack_tail(
  441. proto, negotiated_capabilities, progress)
  442. return new_refs
  443. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  444. progress=None):
  445. """Retrieve a pack from a git smart server.
  446. :param determine_wants: Callback that returns list of commits to fetch
  447. :param graph_walker: Object with next() and ack().
  448. :param pack_data: Callback called for each bit of data in the pack
  449. :param progress: Callback for progress reports (strings)
  450. """
  451. proto, can_read = self._connect(b'upload-pack', path)
  452. with proto:
  453. refs, server_capabilities = read_pkt_refs(proto)
  454. negotiated_capabilities = (
  455. self._fetch_capabilities & server_capabilities)
  456. if refs is None:
  457. proto.write_pkt_line(None)
  458. return refs
  459. try:
  460. wants = determine_wants(refs)
  461. except:
  462. proto.write_pkt_line(None)
  463. raise
  464. if wants is not None:
  465. wants = [cid for cid in wants if cid != ZERO_SHA]
  466. if not wants:
  467. proto.write_pkt_line(None)
  468. return refs
  469. self._handle_upload_pack_head(
  470. proto, negotiated_capabilities, graph_walker, wants, can_read)
  471. self._handle_upload_pack_tail(
  472. proto, negotiated_capabilities, graph_walker, pack_data, progress)
  473. return refs
  474. def archive(self, path, committish, write_data, progress=None,
  475. write_error=None):
  476. proto, can_read = self._connect(b'upload-archive', path)
  477. with proto:
  478. proto.write_pkt_line(b"argument " + committish)
  479. proto.write_pkt_line(None)
  480. pkt = proto.read_pkt_line()
  481. if pkt == b"NACK\n":
  482. return
  483. elif pkt == b"ACK\n":
  484. pass
  485. elif pkt.startswith(b"ERR "):
  486. raise GitProtocolError(pkt[4:].rstrip(b"\n"))
  487. else:
  488. raise AssertionError("invalid response %r" % pkt)
  489. ret = proto.read_pkt_line()
  490. if ret is not None:
  491. raise AssertionError("expected pkt tail")
  492. self._read_side_band64k_data(proto, {
  493. 1: write_data, 2: progress, 3: write_error})
  494. class TCPGitClient(TraditionalGitClient):
  495. """A Git Client that works over TCP directly (i.e. git://)."""
  496. def __init__(self, host, port=None, *args, **kwargs):
  497. if port is None:
  498. port = TCP_GIT_PORT
  499. self._host = host
  500. self._port = port
  501. TraditionalGitClient.__init__(self, *args, **kwargs)
  502. def _connect(self, cmd, path):
  503. sockaddrs = socket.getaddrinfo(
  504. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  505. s = None
  506. err = socket.error("no address found for %s" % self._host)
  507. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  508. s = socket.socket(family, socktype, proto)
  509. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  510. try:
  511. s.connect(sockaddr)
  512. break
  513. except socket.error as err:
  514. if s is not None:
  515. s.close()
  516. s = None
  517. if s is None:
  518. raise err
  519. # -1 means system default buffering
  520. rfile = s.makefile('rb', -1)
  521. # 0 means unbuffered
  522. wfile = s.makefile('wb', 0)
  523. def close():
  524. rfile.close()
  525. wfile.close()
  526. s.close()
  527. proto = Protocol(rfile.read, wfile.write, close,
  528. report_activity=self._report_activity)
  529. if path.startswith(b"/~"):
  530. path = path[1:]
  531. proto.send_cmd(b'git-' + cmd, path, b'host=' + self._host)
  532. return proto, lambda: _fileno_can_read(s)
  533. class SubprocessWrapper(object):
  534. """A socket-like object that talks to a subprocess via pipes."""
  535. def __init__(self, proc):
  536. self.proc = proc
  537. self.read = proc.stdout.read
  538. self.write = proc.stdin.write
  539. def can_read(self):
  540. if subprocess.mswindows:
  541. from msvcrt import get_osfhandle
  542. from win32pipe import PeekNamedPipe
  543. handle = get_osfhandle(self.proc.stdout.fileno())
  544. data, total_bytes_avail, msg_bytes_left = PeekNamedPipe(handle, 0)
  545. return total_bytes_avail != 0
  546. else:
  547. return _fileno_can_read(self.proc.stdout.fileno())
  548. def close(self):
  549. self.proc.stdin.close()
  550. self.proc.stdout.close()
  551. if self.proc.stderr:
  552. self.proc.stderr.close()
  553. self.proc.wait()
  554. class SubprocessGitClient(TraditionalGitClient):
  555. """Git client that talks to a server using a subprocess."""
  556. def __init__(self, *args, **kwargs):
  557. self._connection = None
  558. self._stderr = None
  559. self._stderr = kwargs.get('stderr')
  560. if 'stderr' in kwargs:
  561. del kwargs['stderr']
  562. TraditionalGitClient.__init__(self, *args, **kwargs)
  563. def _connect(self, service, path):
  564. import subprocess
  565. argv = ['git', service, path]
  566. p = SubprocessWrapper(
  567. subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  568. stdout=subprocess.PIPE,
  569. stderr=self._stderr))
  570. return Protocol(p.read, p.write, p.close,
  571. report_activity=self._report_activity), p.can_read
  572. class LocalGitClient(GitClient):
  573. """Git Client that just uses a local Repo."""
  574. def __init__(self, thin_packs=True, report_activity=None):
  575. """Create a new LocalGitClient instance.
  576. :param path: Path to the local repository
  577. :param thin_packs: Whether or not thin packs should be retrieved
  578. :param report_activity: Optional callback for reporting transport
  579. activity.
  580. """
  581. self._report_activity = report_activity
  582. # Ignore the thin_packs argument
  583. def send_pack(self, path, determine_wants, generate_pack_contents,
  584. progress=None, write_pack=write_pack_objects):
  585. """Upload a pack to a remote repository.
  586. :param path: Repository path
  587. :param generate_pack_contents: Function that can return a sequence of
  588. the shas of the objects to upload.
  589. :param progress: Optional progress function
  590. :param write_pack: Function called with (file, iterable of objects) to
  591. write the objects returned by generate_pack_contents to the server.
  592. :raises SendPackError: if server rejects the pack data
  593. :raises UpdateRefsError: if the server supports report-status
  594. and rejects ref updates
  595. """
  596. from dulwich.repo import Repo
  597. target = Repo(path)
  598. old_refs = target.get_refs()
  599. new_refs = determine_wants(old_refs)
  600. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  601. want = []
  602. all_refs = set(new_refs.keys()).union(set(old_refs.keys()))
  603. for refname in all_refs:
  604. old_sha1 = old_refs.get(refname, ZERO_SHA)
  605. new_sha1 = new_refs.get(refname, ZERO_SHA)
  606. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  607. want.append(new_sha1)
  608. if not want and old_refs == new_refs:
  609. return new_refs
  610. target.object_store.add_objects(generate_pack_contents(have, want))
  611. for name, sha in new_refs.items():
  612. target.refs[name] = sha
  613. return new_refs
  614. def fetch(self, path, target, determine_wants=None, progress=None):
  615. """Fetch into a target repository.
  616. :param path: Path to fetch from
  617. :param target: Target repository to fetch into
  618. :param determine_wants: Optional function to determine what refs
  619. to fetch
  620. :param progress: Optional progress function
  621. :return: remote refs as dictionary
  622. """
  623. from dulwich.repo import Repo
  624. r = Repo(path)
  625. return r.fetch(target, determine_wants=determine_wants,
  626. progress=progress)
  627. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  628. progress=None):
  629. """Retrieve a pack from a git smart server.
  630. :param determine_wants: Callback that returns list of commits to fetch
  631. :param graph_walker: Object with next() and ack().
  632. :param pack_data: Callback called for each bit of data in the pack
  633. :param progress: Callback for progress reports (strings)
  634. """
  635. from dulwich.repo import Repo
  636. r = Repo(path)
  637. objects_iter = r.fetch_objects(determine_wants, graph_walker, progress)
  638. # Did the process short-circuit (e.g. in a stateless RPC call)? Note
  639. # that the client still expects a 0-object pack in most cases.
  640. if objects_iter is None:
  641. return
  642. write_pack_objects(ProtocolFile(None, pack_data), objects_iter)
  643. # What Git client to use for local access
  644. default_local_git_client_cls = SubprocessGitClient
  645. class SSHVendor(object):
  646. """A client side SSH implementation."""
  647. def connect_ssh(self, host, command, username=None, port=None):
  648. import warnings
  649. warnings.warn(
  650. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  651. DeprecationWarning)
  652. return self.run_command(host, command, username=username, port=port)
  653. def run_command(self, host, command, username=None, port=None):
  654. """Connect to an SSH server.
  655. Run a command remotely and return a file-like object for interaction
  656. with the remote command.
  657. :param host: Host name
  658. :param command: Command to run
  659. :param username: Optional ame of user to log in as
  660. :param port: Optional SSH port to use
  661. """
  662. raise NotImplementedError(self.run_command)
  663. class SubprocessSSHVendor(SSHVendor):
  664. """SSH vendor that shells out to the local 'ssh' command."""
  665. def run_command(self, host, command, username=None, port=None):
  666. import subprocess
  667. #FIXME: This has no way to deal with passwords..
  668. args = ['ssh', '-x']
  669. if port is not None:
  670. args.extend(['-p', str(port)])
  671. if username is not None:
  672. host = '%s@%s' % (username, host)
  673. args.append(host)
  674. proc = subprocess.Popen(args + command,
  675. stdin=subprocess.PIPE,
  676. stdout=subprocess.PIPE)
  677. return SubprocessWrapper(proc)
  678. try:
  679. import paramiko
  680. except ImportError:
  681. pass
  682. else:
  683. import threading
  684. class ParamikoWrapper(object):
  685. STDERR_READ_N = 2048 # 2k
  686. def __init__(self, client, channel, progress_stderr=None):
  687. self.client = client
  688. self.channel = channel
  689. self.progress_stderr = progress_stderr
  690. self.should_monitor = bool(progress_stderr) or True
  691. self.monitor_thread = None
  692. self.stderr = ''
  693. # Channel must block
  694. self.channel.setblocking(True)
  695. # Start
  696. if self.should_monitor:
  697. self.monitor_thread = threading.Thread(
  698. target=self.monitor_stderr)
  699. self.monitor_thread.start()
  700. def monitor_stderr(self):
  701. while self.should_monitor:
  702. # Block and read
  703. data = self.read_stderr(self.STDERR_READ_N)
  704. # Socket closed
  705. if not data:
  706. self.should_monitor = False
  707. break
  708. # Emit data
  709. if self.progress_stderr:
  710. self.progress_stderr(data)
  711. # Append to buffer
  712. self.stderr += data
  713. def stop_monitoring(self):
  714. # Stop StdErr thread
  715. if self.should_monitor:
  716. self.should_monitor = False
  717. self.monitor_thread.join()
  718. # Get left over data
  719. data = self.channel.in_stderr_buffer.empty()
  720. self.stderr += data
  721. def can_read(self):
  722. return self.channel.recv_ready()
  723. def write(self, data):
  724. return self.channel.sendall(data)
  725. def read_stderr(self, n):
  726. return self.channel.recv_stderr(n)
  727. def read(self, n=None):
  728. data = self.channel.recv(n)
  729. data_len = len(data)
  730. # Closed socket
  731. if not data:
  732. return
  733. # Read more if needed
  734. if n and data_len < n:
  735. diff_len = n - data_len
  736. return data + self.read(diff_len)
  737. return data
  738. def close(self):
  739. self.channel.close()
  740. self.stop_monitoring()
  741. class ParamikoSSHVendor(object):
  742. def __init__(self):
  743. self.ssh_kwargs = {}
  744. def run_command(self, host, command, username=None, port=None,
  745. progress_stderr=None):
  746. # Paramiko needs an explicit port. None is not valid
  747. if port is None:
  748. port = 22
  749. client = paramiko.SSHClient()
  750. policy = paramiko.client.MissingHostKeyPolicy()
  751. client.set_missing_host_key_policy(policy)
  752. client.connect(host, username=username, port=port,
  753. **self.ssh_kwargs)
  754. # Open SSH session
  755. channel = client.get_transport().open_session()
  756. # Run commands
  757. channel.exec_command(*command)
  758. return ParamikoWrapper(
  759. client, channel, progress_stderr=progress_stderr)
  760. # Can be overridden by users
  761. get_ssh_vendor = SubprocessSSHVendor
  762. class SSHGitClient(TraditionalGitClient):
  763. def __init__(self, host, port=None, username=None, *args, **kwargs):
  764. self.host = host
  765. self.port = port
  766. self.username = username
  767. TraditionalGitClient.__init__(self, *args, **kwargs)
  768. self.alternative_paths = {}
  769. def _get_cmd_path(self, cmd):
  770. return self.alternative_paths.get(cmd, b'git-' + cmd)
  771. def _connect(self, cmd, path):
  772. if path.startswith(b"/~"):
  773. path = path[1:]
  774. con = get_ssh_vendor().run_command(
  775. self.host, [self._get_cmd_path(cmd) + b" '" + path + b"'"],
  776. port=self.port, username=self.username)
  777. return (Protocol(con.read, con.write, con.close,
  778. report_activity=self._report_activity),
  779. con.can_read)
  780. def default_user_agent_string():
  781. return "dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  782. def default_urllib2_opener(config):
  783. if config is not None:
  784. proxy_server = config.get("http", "proxy")
  785. else:
  786. proxy_server = None
  787. handlers = []
  788. if proxy_server is not None:
  789. handlers.append(urllib2.ProxyHandler({"http": proxy_server}))
  790. opener = urllib2.build_opener(*handlers)
  791. if config is not None:
  792. user_agent = config.get("http", "useragent")
  793. else:
  794. user_agent = None
  795. if user_agent is None:
  796. user_agent = default_user_agent_string()
  797. opener.addheaders = [('User-agent', user_agent)]
  798. return opener
  799. class HttpGitClient(GitClient):
  800. def __init__(self, base_url, dumb=None, opener=None, config=None, *args,
  801. **kwargs):
  802. self.base_url = base_url.rstrip("/") + "/"
  803. self.dumb = dumb
  804. if opener is None:
  805. self.opener = default_urllib2_opener(config)
  806. else:
  807. self.opener = opener
  808. GitClient.__init__(self, *args, **kwargs)
  809. def _get_url(self, path):
  810. return urlparse.urljoin(self.base_url, path).rstrip("/") + "/"
  811. def _http_request(self, url, headers={}, data=None):
  812. req = urllib2.Request(url, headers=headers, data=data)
  813. try:
  814. resp = self.opener.open(req)
  815. except urllib2.HTTPError as e:
  816. if e.code == 404:
  817. raise NotGitRepository()
  818. if e.code != 200:
  819. raise GitProtocolError("unexpected http response %d" % e.code)
  820. return resp
  821. def _discover_references(self, service, url):
  822. assert url[-1] == "/"
  823. url = urlparse.urljoin(url, "info/refs")
  824. headers = {}
  825. if self.dumb is not False:
  826. url += "?service=%s" % service
  827. headers["Content-Type"] = "application/x-%s-request" % service
  828. resp = self._http_request(url, headers)
  829. try:
  830. self.dumb = (not resp.info().gettype().startswith("application/x-git-"))
  831. if not self.dumb:
  832. proto = Protocol(resp.read, None)
  833. # The first line should mention the service
  834. pkts = list(proto.read_pkt_seq())
  835. if pkts != [('# service=%s\n' % service)]:
  836. raise GitProtocolError(
  837. "unexpected first line %r from smart server" % pkts)
  838. return read_pkt_refs(proto)
  839. else:
  840. return read_info_refs(resp), set()
  841. finally:
  842. resp.close()
  843. def _smart_request(self, service, url, data):
  844. assert url[-1] == "/"
  845. url = urlparse.urljoin(url, service)
  846. headers = {"Content-Type": "application/x-%s-request" % service}
  847. resp = self._http_request(url, headers, data)
  848. if resp.info().gettype() != ("application/x-%s-result" % service):
  849. raise GitProtocolError("Invalid content-type from server: %s"
  850. % resp.info().gettype())
  851. return resp
  852. def send_pack(self, path, determine_wants, generate_pack_contents,
  853. progress=None, write_pack=write_pack_objects):
  854. """Upload a pack to a remote repository.
  855. :param path: Repository path
  856. :param generate_pack_contents: Function that can return a sequence of
  857. the shas of the objects to upload.
  858. :param progress: Optional progress function
  859. :param write_pack: Function called with (file, iterable of objects) to
  860. write the objects returned by generate_pack_contents to the server.
  861. :raises SendPackError: if server rejects the pack data
  862. :raises UpdateRefsError: if the server supports report-status
  863. and rejects ref updates
  864. """
  865. url = self._get_url(path)
  866. old_refs, server_capabilities = self._discover_references(
  867. b"git-receive-pack", url)
  868. negotiated_capabilities = self._send_capabilities & server_capabilities
  869. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  870. self._report_status_parser = ReportStatusParser()
  871. new_refs = determine_wants(dict(old_refs))
  872. if new_refs is None:
  873. return old_refs
  874. if self.dumb:
  875. raise NotImplementedError(self.fetch_pack)
  876. req_data = BytesIO()
  877. req_proto = Protocol(None, req_data.write)
  878. (have, want) = self._handle_receive_pack_head(
  879. req_proto, negotiated_capabilities, old_refs, new_refs)
  880. if not want and old_refs == new_refs:
  881. return new_refs
  882. objects = generate_pack_contents(have, want)
  883. if len(objects) > 0:
  884. write_pack(req_proto.write_file(), objects)
  885. resp = self._smart_request(b"git-receive-pack", url,
  886. data=req_data.getvalue())
  887. try:
  888. resp_proto = Protocol(resp.read, None)
  889. self._handle_receive_pack_tail(resp_proto, negotiated_capabilities,
  890. progress)
  891. return new_refs
  892. finally:
  893. resp.close()
  894. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  895. progress=None):
  896. """Retrieve a pack from a git smart server.
  897. :param determine_wants: Callback that returns list of commits to fetch
  898. :param graph_walker: Object with next() and ack().
  899. :param pack_data: Callback called for each bit of data in the pack
  900. :param progress: Callback for progress reports (strings)
  901. :return: Dictionary with the refs of the remote repository
  902. """
  903. url = self._get_url(path)
  904. refs, server_capabilities = self._discover_references(
  905. b"git-upload-pack", url)
  906. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  907. wants = determine_wants(refs)
  908. if wants is not None:
  909. wants = [cid for cid in wants if cid != ZERO_SHA]
  910. if not wants:
  911. return refs
  912. if self.dumb:
  913. raise NotImplementedError(self.send_pack)
  914. req_data = BytesIO()
  915. req_proto = Protocol(None, req_data.write)
  916. self._handle_upload_pack_head(
  917. req_proto, negotiated_capabilities, graph_walker, wants,
  918. lambda: False)
  919. resp = self._smart_request(
  920. b"git-upload-pack", url, data=req_data.getvalue())
  921. try:
  922. resp_proto = Protocol(resp.read, None)
  923. self._handle_upload_pack_tail(resp_proto, negotiated_capabilities,
  924. graph_walker, pack_data, progress)
  925. return refs
  926. finally:
  927. resp.close()
  928. def get_transport_and_path_from_url(url, config=None, **kwargs):
  929. """Obtain a git client from a URL.
  930. :param url: URL to open
  931. :param config: Optional config object
  932. :param thin_packs: Whether or not thin packs should be retrieved
  933. :param report_activity: Optional callback for reporting transport
  934. activity.
  935. :return: Tuple with client instance and relative path.
  936. """
  937. parsed = urlparse.urlparse(url)
  938. if parsed.scheme == 'git':
  939. return (TCPGitClient(parsed.hostname, port=parsed.port, **kwargs),
  940. parsed.path)
  941. elif parsed.scheme == 'git+ssh':
  942. path = parsed.path
  943. if path.startswith('/'):
  944. path = parsed.path[1:]
  945. return SSHGitClient(parsed.hostname, port=parsed.port,
  946. username=parsed.username, **kwargs), path
  947. elif parsed.scheme in ('http', 'https'):
  948. return HttpGitClient(urlparse.urlunparse(parsed), config=config,
  949. **kwargs), parsed.path
  950. elif parsed.scheme == 'file':
  951. return default_local_git_client_cls(**kwargs), parsed.path
  952. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  953. def get_transport_and_path(location, **kwargs):
  954. """Obtain a git client from a URL.
  955. :param location: URL or path
  956. :param config: Optional config object
  957. :param thin_packs: Whether or not thin packs should be retrieved
  958. :param report_activity: Optional callback for reporting transport
  959. activity.
  960. :return: Tuple with client instance and relative path.
  961. """
  962. # First, try to parse it as a URL
  963. try:
  964. return get_transport_and_path_from_url(location, **kwargs)
  965. except ValueError:
  966. pass
  967. if (sys.platform == 'win32' and
  968. location[0].isalpha() and location[1:3] == ':\\'):
  969. # Windows local path
  970. return default_local_git_client_cls(**kwargs), location
  971. if ':' in location and not '@' in location:
  972. # SSH with no user@, zero or one leading slash.
  973. (hostname, path) = location.split(':')
  974. return SSHGitClient(hostname, **kwargs), path
  975. elif '@' in location and ':' in location:
  976. # SSH with user@host:foo.
  977. user_host, path = location.split(':')
  978. user, host = user_host.rsplit('@')
  979. return SSHGitClient(host, username=user, **kwargs), path
  980. # Otherwise, assume it's a local path.
  981. return default_local_git_client_cls(**kwargs), location