client.py 43 KB

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