client.py 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  1. # client.py -- Implementation of the client side git protocols
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Client side support for the Git protocol.
  21. The Dulwich client supports the following capabilities:
  22. * thin-pack
  23. * multi_ack_detailed
  24. * multi_ack
  25. * side-band-64k
  26. * ofs-delta
  27. * quiet
  28. * report-status
  29. * delete-refs
  30. Known capabilities that are not supported:
  31. * shallow
  32. * no-progress
  33. * include-tag
  34. """
  35. from contextlib import closing
  36. from io import BytesIO, BufferedReader
  37. import select
  38. import socket
  39. import subprocess
  40. import sys
  41. try:
  42. from urllib import quote as urlquote
  43. from urllib import unquote as urlunquote
  44. except ImportError:
  45. from urllib.parse import quote as urlquote
  46. from urllib.parse import unquote as urlunquote
  47. try:
  48. import urlparse
  49. except ImportError:
  50. import urllib.parse as urlparse
  51. import dulwich
  52. from dulwich.errors import (
  53. GitProtocolError,
  54. NotGitRepository,
  55. SendPackError,
  56. UpdateRefsError,
  57. )
  58. from dulwich.protocol import (
  59. HangupException,
  60. _RBUFSIZE,
  61. agent_string,
  62. capability_agent,
  63. extract_capability_names,
  64. CAPABILITY_AGENT,
  65. CAPABILITY_DELETE_REFS,
  66. CAPABILITY_MULTI_ACK,
  67. CAPABILITY_MULTI_ACK_DETAILED,
  68. CAPABILITY_OFS_DELTA,
  69. CAPABILITY_QUIET,
  70. CAPABILITY_REPORT_STATUS,
  71. CAPABILITY_SHALLOW,
  72. CAPABILITY_SYMREF,
  73. CAPABILITY_SIDE_BAND_64K,
  74. CAPABILITY_THIN_PACK,
  75. CAPABILITIES_REF,
  76. KNOWN_RECEIVE_CAPABILITIES,
  77. KNOWN_UPLOAD_CAPABILITIES,
  78. COMMAND_DEEPEN,
  79. COMMAND_SHALLOW,
  80. COMMAND_UNSHALLOW,
  81. COMMAND_DONE,
  82. COMMAND_HAVE,
  83. COMMAND_WANT,
  84. SIDE_BAND_CHANNEL_DATA,
  85. SIDE_BAND_CHANNEL_PROGRESS,
  86. SIDE_BAND_CHANNEL_FATAL,
  87. PktLineParser,
  88. Protocol,
  89. ProtocolFile,
  90. TCP_GIT_PORT,
  91. ZERO_SHA,
  92. extract_capabilities,
  93. parse_capability,
  94. )
  95. from dulwich.pack import (
  96. write_pack_data,
  97. write_pack_objects,
  98. )
  99. from dulwich.refs import (
  100. read_info_refs,
  101. ANNOTATED_TAG_SUFFIX,
  102. )
  103. class InvalidWants(Exception):
  104. """Invalid wants."""
  105. def __init__(self, wants):
  106. Exception.__init__(
  107. self,
  108. "requested wants not in server provided refs: %r" % wants)
  109. def _fileno_can_read(fileno):
  110. """Check if a file descriptor is readable."""
  111. return len(select.select([fileno], [], [], 0)[0]) > 0
  112. def _win32_peek_avail(handle):
  113. """Wrapper around PeekNamedPipe to check how many bytes are available."""
  114. from ctypes import byref, wintypes, windll
  115. c_avail = wintypes.DWORD()
  116. c_message = wintypes.DWORD()
  117. success = windll.kernel32.PeekNamedPipe(
  118. handle, None, 0, None, byref(c_avail),
  119. byref(c_message))
  120. if not success:
  121. raise OSError(wintypes.GetLastError())
  122. return c_avail.value
  123. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  124. UPLOAD_CAPABILITIES = ([CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK,
  125. CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_SHALLOW]
  126. + COMMON_CAPABILITIES)
  127. RECEIVE_CAPABILITIES = [CAPABILITY_REPORT_STATUS] + COMMON_CAPABILITIES
  128. class ReportStatusParser(object):
  129. """Handle status as reported by servers with 'report-status' capability.
  130. """
  131. def __init__(self):
  132. self._done = False
  133. self._pack_status = None
  134. self._ref_status_ok = True
  135. self._ref_statuses = []
  136. def check(self):
  137. """Check if there were any errors and, if so, raise exceptions.
  138. :raise SendPackError: Raised when the server could not unpack
  139. :raise UpdateRefsError: Raised when refs could not be updated
  140. """
  141. if self._pack_status not in (b'unpack ok', None):
  142. raise SendPackError(self._pack_status)
  143. if not self._ref_status_ok:
  144. ref_status = {}
  145. ok = set()
  146. for status in self._ref_statuses:
  147. if b' ' not in status:
  148. # malformed response, move on to the next one
  149. continue
  150. status, ref = status.split(b' ', 1)
  151. if status == b'ng':
  152. if b' ' in ref:
  153. ref, status = ref.split(b' ', 1)
  154. else:
  155. ok.add(ref)
  156. ref_status[ref] = status
  157. # TODO(jelmer): don't assume encoding of refs is ascii.
  158. raise UpdateRefsError(', '.join([
  159. refname.decode('ascii') for refname in ref_status
  160. if refname not in ok]) +
  161. ' failed to update', ref_status=ref_status)
  162. def handle_packet(self, pkt):
  163. """Handle a packet.
  164. :raise GitProtocolError: Raised when packets are received after a
  165. flush packet.
  166. """
  167. if self._done:
  168. raise GitProtocolError("received more data after status report")
  169. if pkt is None:
  170. self._done = True
  171. return
  172. if self._pack_status is None:
  173. self._pack_status = pkt.strip()
  174. else:
  175. ref_status = pkt.strip()
  176. self._ref_statuses.append(ref_status)
  177. if not ref_status.startswith(b'ok '):
  178. self._ref_status_ok = False
  179. def read_pkt_refs(proto):
  180. server_capabilities = None
  181. refs = {}
  182. # Receive refs from server
  183. for pkt in proto.read_pkt_seq():
  184. (sha, ref) = pkt.rstrip(b'\n').split(None, 1)
  185. if sha == b'ERR':
  186. raise GitProtocolError(ref.decode('utf-8', 'replace'))
  187. if server_capabilities is None:
  188. (ref, server_capabilities) = extract_capabilities(ref)
  189. refs[ref] = sha
  190. if len(refs) == 0:
  191. return {}, set([])
  192. if refs == {CAPABILITIES_REF: ZERO_SHA}:
  193. refs = {}
  194. return refs, set(server_capabilities)
  195. class FetchPackResult(object):
  196. """Result of a fetch-pack operation.
  197. :var refs: Dictionary with all remote refs
  198. :var symrefs: Dictionary with remote symrefs
  199. :var agent: User agent string
  200. """
  201. _FORWARDED_ATTRS = [
  202. 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items',
  203. 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem',
  204. 'setdefault', 'update', 'values', 'viewitems', 'viewkeys',
  205. 'viewvalues']
  206. def __init__(self, refs, symrefs, agent, new_shallow=None,
  207. new_unshallow=None):
  208. self.refs = refs
  209. self.symrefs = symrefs
  210. self.agent = agent
  211. self.new_shallow = new_shallow
  212. self.new_unshallow = new_unshallow
  213. def _warn_deprecated(self):
  214. import warnings
  215. warnings.warn(
  216. "Use FetchPackResult.refs instead.",
  217. DeprecationWarning, stacklevel=3)
  218. def __eq__(self, other):
  219. if isinstance(other, dict):
  220. self._warn_deprecated()
  221. return (self.refs == other)
  222. return (self.refs == other.refs and
  223. self.symrefs == other.symrefs and
  224. self.agent == other.agent)
  225. def __contains__(self, name):
  226. self._warn_deprecated()
  227. return name in self.refs
  228. def __getitem__(self, name):
  229. self._warn_deprecated()
  230. return self.refs[name]
  231. def __len__(self):
  232. self._warn_deprecated()
  233. return len(self.refs)
  234. def __iter__(self):
  235. self._warn_deprecated()
  236. return iter(self.refs)
  237. def __getattribute__(self, name):
  238. if name in type(self)._FORWARDED_ATTRS:
  239. self._warn_deprecated()
  240. return getattr(self.refs, name)
  241. return super(FetchPackResult, self).__getattribute__(name)
  242. def __repr__(self):
  243. return "%s(%r, %r, %r)" % (
  244. self.__class__.__name__, self.refs, self.symrefs, self.agent)
  245. def _read_shallow_updates(proto):
  246. new_shallow = set()
  247. new_unshallow = set()
  248. for pkt in proto.read_pkt_seq():
  249. cmd, sha = pkt.split(b' ', 1)
  250. if cmd == COMMAND_SHALLOW:
  251. new_shallow.add(sha.strip())
  252. elif cmd == COMMAND_UNSHALLOW:
  253. new_unshallow.add(sha.strip())
  254. else:
  255. raise GitProtocolError('unknown command %s' % pkt)
  256. return (new_shallow, new_unshallow)
  257. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  258. # support some capabilities. This should work properly with servers
  259. # that don't support multi_ack.
  260. class GitClient(object):
  261. """Git smart server client.
  262. """
  263. def __init__(self, thin_packs=True, report_activity=None, quiet=False):
  264. """Create a new GitClient instance.
  265. :param thin_packs: Whether or not thin packs should be retrieved
  266. :param report_activity: Optional callback for reporting transport
  267. activity.
  268. """
  269. self._report_activity = report_activity
  270. self._report_status_parser = None
  271. self._fetch_capabilities = set(UPLOAD_CAPABILITIES)
  272. self._fetch_capabilities.add(capability_agent())
  273. self._send_capabilities = set(RECEIVE_CAPABILITIES)
  274. self._send_capabilities.add(capability_agent())
  275. if quiet:
  276. self._send_capabilities.add(CAPABILITY_QUIET)
  277. if not thin_packs:
  278. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  279. def get_url(self, path):
  280. """Retrieves full url to given path.
  281. :param path: Repository path (as string)
  282. :return: Url to path (as string)
  283. """
  284. raise NotImplementedError(self.get_url)
  285. @classmethod
  286. def from_parsedurl(cls, parsedurl, **kwargs):
  287. """Create an instance of this client from a urlparse.parsed object.
  288. :param parsedurl: Result of urlparse.urlparse()
  289. :return: A `GitClient` object
  290. """
  291. raise NotImplementedError(cls.from_parsedurl)
  292. def send_pack(self, path, update_refs, generate_pack_data,
  293. progress=None):
  294. """Upload a pack to a remote repository.
  295. :param path: Repository path (as bytestring)
  296. :param update_refs: Function to determine changes to remote refs.
  297. Receive dict with existing remote refs, returns dict with
  298. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  299. :param generate_pack_data: Function that can return a tuple
  300. with number of objects and list of pack data to include
  301. :param progress: Optional progress function
  302. :raises SendPackError: if server rejects the pack data
  303. :raises UpdateRefsError: if the server supports report-status
  304. and rejects ref updates
  305. :return: new_refs dictionary containing the changes that were made
  306. {refname: new_ref}, including deleted refs.
  307. """
  308. raise NotImplementedError(self.send_pack)
  309. def fetch(self, path, target, determine_wants=None, progress=None,
  310. depth=None):
  311. """Fetch into a target repository.
  312. :param path: Path to fetch from (as bytestring)
  313. :param target: Target repository to fetch into
  314. :param determine_wants: Optional function to determine what refs
  315. to fetch. Receives dictionary of name->sha, should return
  316. list of shas to fetch. Defaults to all shas.
  317. :param progress: Optional progress function
  318. :param depth: Depth to fetch at
  319. :return: Dictionary with all remote refs (not just those fetched)
  320. """
  321. if determine_wants is None:
  322. determine_wants = target.object_store.determine_wants_all
  323. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  324. # TODO(jelmer): Avoid reading entire file into memory and
  325. # only processing it after the whole file has been fetched.
  326. f = BytesIO()
  327. def commit():
  328. if f.tell():
  329. f.seek(0)
  330. target.object_store.add_thin_pack(f.read, None)
  331. def abort():
  332. pass
  333. else:
  334. f, commit, abort = target.object_store.add_pack()
  335. try:
  336. result = self.fetch_pack(
  337. path, determine_wants, target.get_graph_walker(), f.write,
  338. progress=progress, depth=depth)
  339. except BaseException:
  340. abort()
  341. raise
  342. else:
  343. commit()
  344. target.update_shallow(result.new_shallow, result.new_unshallow)
  345. return result
  346. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  347. progress=None, depth=None):
  348. """Retrieve a pack from a git smart server.
  349. :param path: Remote path to fetch from
  350. :param determine_wants: Function determine what refs
  351. to fetch. Receives dictionary of name->sha, should return
  352. list of shas to fetch.
  353. :param graph_walker: Object with next() and ack().
  354. :param pack_data: Callback called for each bit of data in the pack
  355. :param progress: Callback for progress reports (strings)
  356. :param depth: Shallow fetch depth
  357. :return: FetchPackResult object
  358. """
  359. raise NotImplementedError(self.fetch_pack)
  360. def get_refs(self, path):
  361. """Retrieve the current refs from a git smart server.
  362. :param path: Path to the repo to fetch from. (as bytestring)
  363. """
  364. raise NotImplementedError(self.get_refs)
  365. def _parse_status_report(self, proto):
  366. unpack = proto.read_pkt_line().strip()
  367. if unpack != b'unpack ok':
  368. st = True
  369. # flush remaining error data
  370. while st is not None:
  371. st = proto.read_pkt_line()
  372. raise SendPackError(unpack)
  373. statuses = []
  374. errs = False
  375. ref_status = proto.read_pkt_line()
  376. while ref_status:
  377. ref_status = ref_status.strip()
  378. statuses.append(ref_status)
  379. if not ref_status.startswith(b'ok '):
  380. errs = True
  381. ref_status = proto.read_pkt_line()
  382. if errs:
  383. ref_status = {}
  384. ok = set()
  385. for status in statuses:
  386. if b' ' not in status:
  387. # malformed response, move on to the next one
  388. continue
  389. status, ref = status.split(b' ', 1)
  390. if status == b'ng':
  391. if b' ' in ref:
  392. ref, status = ref.split(b' ', 1)
  393. else:
  394. ok.add(ref)
  395. ref_status[ref] = status
  396. raise UpdateRefsError(', '.join([
  397. refname for refname in ref_status if refname not in ok]) +
  398. b' failed to update', ref_status=ref_status)
  399. def _read_side_band64k_data(self, proto, channel_callbacks):
  400. """Read per-channel data.
  401. This requires the side-band-64k capability.
  402. :param proto: Protocol object to read from
  403. :param channel_callbacks: Dictionary mapping channels to packet
  404. handlers to use. None for a callback discards channel data.
  405. """
  406. for pkt in proto.read_pkt_seq():
  407. channel = ord(pkt[:1])
  408. pkt = pkt[1:]
  409. try:
  410. cb = channel_callbacks[channel]
  411. except KeyError:
  412. raise AssertionError('Invalid sideband channel %d' % channel)
  413. else:
  414. if cb is not None:
  415. cb(pkt)
  416. def _handle_receive_pack_head(self, proto, capabilities, old_refs,
  417. new_refs):
  418. """Handle the head of a 'git-receive-pack' request.
  419. :param proto: Protocol object to read from
  420. :param capabilities: List of negotiated capabilities
  421. :param old_refs: Old refs, as received from the server
  422. :param new_refs: Refs to change
  423. :return: (have, want) tuple
  424. """
  425. want = []
  426. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  427. sent_capabilities = False
  428. for refname in new_refs:
  429. if not isinstance(refname, bytes):
  430. raise TypeError('refname is not a bytestring: %r' % refname)
  431. old_sha1 = old_refs.get(refname, ZERO_SHA)
  432. if not isinstance(old_sha1, bytes):
  433. raise TypeError('old sha1 for %s is not a bytestring: %r' %
  434. (refname, old_sha1))
  435. new_sha1 = new_refs.get(refname, ZERO_SHA)
  436. if not isinstance(new_sha1, bytes):
  437. raise TypeError('old sha1 for %s is not a bytestring %r' %
  438. (refname, new_sha1))
  439. if old_sha1 != new_sha1:
  440. if sent_capabilities:
  441. proto.write_pkt_line(old_sha1 + b' ' + new_sha1 + b' ' +
  442. refname)
  443. else:
  444. proto.write_pkt_line(
  445. old_sha1 + b' ' + new_sha1 + b' ' + refname + b'\0' +
  446. b' '.join(capabilities))
  447. sent_capabilities = True
  448. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  449. want.append(new_sha1)
  450. proto.write_pkt_line(None)
  451. return (have, want)
  452. def _negotiate_receive_pack_capabilities(self, server_capabilities):
  453. negotiated_capabilities = (
  454. self._send_capabilities & server_capabilities)
  455. unknown_capabilities = ( # noqa: F841
  456. extract_capability_names(server_capabilities) -
  457. KNOWN_RECEIVE_CAPABILITIES)
  458. # TODO(jelmer): warn about unknown capabilities
  459. return negotiated_capabilities
  460. def _handle_receive_pack_tail(self, proto, capabilities, progress=None):
  461. """Handle the tail of a 'git-receive-pack' request.
  462. :param proto: Protocol object to read from
  463. :param capabilities: List of negotiated capabilities
  464. :param progress: Optional progress reporting function
  465. """
  466. if CAPABILITY_SIDE_BAND_64K in capabilities:
  467. if progress is None:
  468. def progress(x):
  469. pass
  470. channel_callbacks = {2: progress}
  471. if CAPABILITY_REPORT_STATUS in capabilities:
  472. channel_callbacks[1] = PktLineParser(
  473. self._report_status_parser.handle_packet).parse
  474. self._read_side_band64k_data(proto, channel_callbacks)
  475. else:
  476. if CAPABILITY_REPORT_STATUS in capabilities:
  477. for pkt in proto.read_pkt_seq():
  478. self._report_status_parser.handle_packet(pkt)
  479. if self._report_status_parser is not None:
  480. self._report_status_parser.check()
  481. def _negotiate_upload_pack_capabilities(self, server_capabilities):
  482. unknown_capabilities = ( # noqa: F841
  483. extract_capability_names(server_capabilities) -
  484. KNOWN_UPLOAD_CAPABILITIES)
  485. # TODO(jelmer): warn about unknown capabilities
  486. symrefs = {}
  487. agent = None
  488. for capability in server_capabilities:
  489. k, v = parse_capability(capability)
  490. if k == CAPABILITY_SYMREF:
  491. (src, dst) = v.split(b':', 1)
  492. symrefs[src] = dst
  493. if k == CAPABILITY_AGENT:
  494. agent = v
  495. negotiated_capabilities = (
  496. self._fetch_capabilities & server_capabilities)
  497. return (negotiated_capabilities, symrefs, agent)
  498. def _handle_upload_pack_head(self, proto, capabilities, graph_walker,
  499. wants, can_read, depth):
  500. """Handle the head of a 'git-upload-pack' request.
  501. :param proto: Protocol object to read from
  502. :param capabilities: List of negotiated capabilities
  503. :param graph_walker: GraphWalker instance to call .ack() on
  504. :param wants: List of commits to fetch
  505. :param can_read: function that returns a boolean that indicates
  506. whether there is extra graph data to read on proto
  507. :param depth: Depth for request
  508. """
  509. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  510. proto.write_pkt_line(COMMAND_WANT + b' ' + wants[0] + b' ' +
  511. b' '.join(capabilities) + b'\n')
  512. for want in wants[1:]:
  513. proto.write_pkt_line(COMMAND_WANT + b' ' + want + b'\n')
  514. if depth not in (0, None) or getattr(graph_walker, 'shallow', None):
  515. if CAPABILITY_SHALLOW not in capabilities:
  516. raise GitProtocolError(
  517. "server does not support shallow capability required for "
  518. "depth")
  519. for sha in graph_walker.shallow:
  520. proto.write_pkt_line(COMMAND_SHALLOW + b' ' + sha + b'\n')
  521. proto.write_pkt_line(COMMAND_DEEPEN + b' ' +
  522. str(depth).encode('ascii') + b'\n')
  523. proto.write_pkt_line(None)
  524. if can_read is not None:
  525. (new_shallow, new_unshallow) = _read_shallow_updates(proto)
  526. else:
  527. new_shallow = new_unshallow = None
  528. else:
  529. new_shallow = new_unshallow = set()
  530. proto.write_pkt_line(None)
  531. have = next(graph_walker)
  532. while have:
  533. proto.write_pkt_line(COMMAND_HAVE + b' ' + have + b'\n')
  534. if can_read is not None and can_read():
  535. pkt = proto.read_pkt_line()
  536. parts = pkt.rstrip(b'\n').split(b' ')
  537. if parts[0] == b'ACK':
  538. graph_walker.ack(parts[1])
  539. if parts[2] in (b'continue', b'common'):
  540. pass
  541. elif parts[2] == b'ready':
  542. break
  543. else:
  544. raise AssertionError(
  545. "%s not in ('continue', 'ready', 'common)" %
  546. parts[2])
  547. have = next(graph_walker)
  548. proto.write_pkt_line(COMMAND_DONE + b'\n')
  549. return (new_shallow, new_unshallow)
  550. def _handle_upload_pack_tail(self, proto, capabilities, graph_walker,
  551. pack_data, progress=None, rbufsize=_RBUFSIZE):
  552. """Handle the tail of a 'git-upload-pack' request.
  553. :param proto: Protocol object to read from
  554. :param capabilities: List of negotiated capabilities
  555. :param graph_walker: GraphWalker instance to call .ack() on
  556. :param pack_data: Function to call with pack data
  557. :param progress: Optional progress reporting function
  558. :param rbufsize: Read buffer size
  559. """
  560. pkt = proto.read_pkt_line()
  561. while pkt:
  562. parts = pkt.rstrip(b'\n').split(b' ')
  563. if parts[0] == b'ACK':
  564. graph_walker.ack(parts[1])
  565. if len(parts) < 3 or parts[2] not in (
  566. b'ready', b'continue', b'common'):
  567. break
  568. pkt = proto.read_pkt_line()
  569. if CAPABILITY_SIDE_BAND_64K in capabilities:
  570. if progress is None:
  571. # Just ignore progress data
  572. def progress(x):
  573. pass
  574. self._read_side_band64k_data(proto, {
  575. SIDE_BAND_CHANNEL_DATA: pack_data,
  576. SIDE_BAND_CHANNEL_PROGRESS: progress}
  577. )
  578. else:
  579. while True:
  580. data = proto.read(rbufsize)
  581. if data == b"":
  582. break
  583. pack_data(data)
  584. def check_wants(wants, refs):
  585. """Check that a set of wants is valid.
  586. :param wants: Set of object SHAs to fetch
  587. :param refs: Refs dictionary to check against
  588. """
  589. missing = set(wants) - {
  590. v for (k, v) in refs.items()
  591. if not k.endswith(ANNOTATED_TAG_SUFFIX)}
  592. if missing:
  593. raise InvalidWants(missing)
  594. def remote_error_from_stderr(stderr):
  595. """Return an appropriate exception based on stderr output. """
  596. if stderr is None:
  597. return HangupException()
  598. for l in stderr.readlines():
  599. if l.startswith(b'ERROR: '):
  600. return GitProtocolError(
  601. l[len(b'ERROR: '):].decode('utf-8', 'replace'))
  602. return GitProtocolError(l.decode('utf-8', 'replace'))
  603. return HangupException()
  604. class TraditionalGitClient(GitClient):
  605. """Traditional Git client."""
  606. DEFAULT_ENCODING = 'utf-8'
  607. def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs):
  608. self._remote_path_encoding = path_encoding
  609. super(TraditionalGitClient, self).__init__(**kwargs)
  610. def _connect(self, cmd, path):
  611. """Create a connection to the server.
  612. This method is abstract - concrete implementations should
  613. implement their own variant which connects to the server and
  614. returns an initialized Protocol object with the service ready
  615. for use and a can_read function which may be used to see if
  616. reads would block.
  617. :param cmd: The git service name to which we should connect.
  618. :param path: The path we should pass to the service. (as bytestirng)
  619. """
  620. raise NotImplementedError()
  621. def send_pack(self, path, update_refs, generate_pack_data,
  622. progress=None):
  623. """Upload a pack to a remote repository.
  624. :param path: Repository path (as bytestring)
  625. :param update_refs: Function to determine changes to remote refs.
  626. Receive dict with existing remote refs, returns dict with
  627. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  628. :param generate_pack_data: Function that can return a tuple with
  629. number of objects and pack data to upload.
  630. :param progress: Optional callback called with progress updates
  631. :raises SendPackError: if server rejects the pack data
  632. :raises UpdateRefsError: if the server supports report-status
  633. and rejects ref updates
  634. :return: new_refs dictionary containing the changes that were made
  635. {refname: new_ref}, including deleted refs.
  636. """
  637. proto, unused_can_read, stderr = self._connect(b'receive-pack', path)
  638. with proto:
  639. try:
  640. old_refs, server_capabilities = read_pkt_refs(proto)
  641. except HangupException:
  642. raise remote_error_from_stderr(stderr)
  643. negotiated_capabilities = \
  644. self._negotiate_receive_pack_capabilities(server_capabilities)
  645. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  646. self._report_status_parser = ReportStatusParser()
  647. report_status_parser = self._report_status_parser
  648. try:
  649. new_refs = orig_new_refs = update_refs(dict(old_refs))
  650. except BaseException:
  651. proto.write_pkt_line(None)
  652. raise
  653. if CAPABILITY_DELETE_REFS not in server_capabilities:
  654. # Server does not support deletions. Fail later.
  655. new_refs = dict(orig_new_refs)
  656. for ref, sha in orig_new_refs.items():
  657. if sha == ZERO_SHA:
  658. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  659. report_status_parser._ref_statuses.append(
  660. b'ng ' + sha +
  661. b' remote does not support deleting refs')
  662. report_status_parser._ref_status_ok = False
  663. del new_refs[ref]
  664. if new_refs is None:
  665. proto.write_pkt_line(None)
  666. return old_refs
  667. if len(new_refs) == 0 and len(orig_new_refs):
  668. # NOOP - Original new refs filtered out by policy
  669. proto.write_pkt_line(None)
  670. if report_status_parser is not None:
  671. report_status_parser.check()
  672. return old_refs
  673. (have, want) = self._handle_receive_pack_head(
  674. proto, negotiated_capabilities, old_refs, new_refs)
  675. if (not want and
  676. set(new_refs.items()).issubset(set(old_refs.items()))):
  677. return new_refs
  678. pack_data_count, pack_data = generate_pack_data(
  679. have, want,
  680. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities))
  681. dowrite = bool(pack_data_count)
  682. dowrite = dowrite or any(old_refs.get(ref) != sha
  683. for (ref, sha) in new_refs.items()
  684. if sha != ZERO_SHA)
  685. if dowrite:
  686. write_pack_data(proto.write_file(), pack_data_count, pack_data)
  687. self._handle_receive_pack_tail(
  688. proto, negotiated_capabilities, progress)
  689. return new_refs
  690. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  691. progress=None, depth=None):
  692. """Retrieve a pack from a git smart server.
  693. :param path: Remote path to fetch from
  694. :param determine_wants: Function determine what refs
  695. to fetch. Receives dictionary of name->sha, should return
  696. list of shas to fetch.
  697. :param graph_walker: Object with next() and ack().
  698. :param pack_data: Callback called for each bit of data in the pack
  699. :param progress: Callback for progress reports (strings)
  700. :param depth: Shallow fetch depth
  701. :return: FetchPackResult object
  702. """
  703. proto, can_read, stderr = self._connect(b'upload-pack', path)
  704. with proto:
  705. try:
  706. refs, server_capabilities = read_pkt_refs(proto)
  707. except HangupException:
  708. raise remote_error_from_stderr(stderr)
  709. negotiated_capabilities, symrefs, agent = (
  710. self._negotiate_upload_pack_capabilities(
  711. server_capabilities))
  712. if refs is None:
  713. proto.write_pkt_line(None)
  714. return FetchPackResult(refs, symrefs, agent)
  715. try:
  716. wants = determine_wants(refs)
  717. except BaseException:
  718. proto.write_pkt_line(None)
  719. raise
  720. if wants is not None:
  721. wants = [cid for cid in wants if cid != ZERO_SHA]
  722. if not wants:
  723. proto.write_pkt_line(None)
  724. return FetchPackResult(refs, symrefs, agent)
  725. check_wants(wants, refs)
  726. (new_shallow, new_unshallow) = self._handle_upload_pack_head(
  727. proto, negotiated_capabilities, graph_walker, wants, can_read,
  728. depth=depth)
  729. self._handle_upload_pack_tail(
  730. proto, negotiated_capabilities, graph_walker, pack_data,
  731. progress)
  732. return FetchPackResult(
  733. refs, symrefs, agent, new_shallow, new_unshallow)
  734. def get_refs(self, path):
  735. """Retrieve the current refs from a git smart server."""
  736. # stock `git ls-remote` uses upload-pack
  737. proto, _, stderr = self._connect(b'upload-pack', path)
  738. with proto:
  739. try:
  740. refs, _ = read_pkt_refs(proto)
  741. except HangupException:
  742. raise remote_error_from_stderr(stderr)
  743. proto.write_pkt_line(None)
  744. return refs
  745. def archive(self, path, committish, write_data, progress=None,
  746. write_error=None, format=None, subdirs=None, prefix=None):
  747. proto, can_read, stderr = self._connect(b'upload-archive', path)
  748. with proto:
  749. if format is not None:
  750. proto.write_pkt_line(b"argument --format=" + format)
  751. proto.write_pkt_line(b"argument " + committish)
  752. if subdirs is not None:
  753. for subdir in subdirs:
  754. proto.write_pkt_line(b"argument " + subdir)
  755. if prefix is not None:
  756. proto.write_pkt_line(b"argument --prefix=" + prefix)
  757. proto.write_pkt_line(None)
  758. try:
  759. pkt = proto.read_pkt_line()
  760. except HangupException:
  761. raise remote_error_from_stderr(stderr)
  762. if pkt == b"NACK\n":
  763. return
  764. elif pkt == b"ACK\n":
  765. pass
  766. elif pkt.startswith(b"ERR "):
  767. raise GitProtocolError(
  768. pkt[4:].rstrip(b"\n").decode('utf-8', 'replace'))
  769. else:
  770. raise AssertionError("invalid response %r" % pkt)
  771. ret = proto.read_pkt_line()
  772. if ret is not None:
  773. raise AssertionError("expected pkt tail")
  774. self._read_side_band64k_data(proto, {
  775. SIDE_BAND_CHANNEL_DATA: write_data,
  776. SIDE_BAND_CHANNEL_PROGRESS: progress,
  777. SIDE_BAND_CHANNEL_FATAL: write_error})
  778. class TCPGitClient(TraditionalGitClient):
  779. """A Git Client that works over TCP directly (i.e. git://)."""
  780. def __init__(self, host, port=None, **kwargs):
  781. if port is None:
  782. port = TCP_GIT_PORT
  783. self._host = host
  784. self._port = port
  785. super(TCPGitClient, self).__init__(**kwargs)
  786. @classmethod
  787. def from_parsedurl(cls, parsedurl, **kwargs):
  788. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  789. def get_url(self, path):
  790. netloc = self._host
  791. if self._port is not None and self._port != TCP_GIT_PORT:
  792. netloc += ":%d" % self._port
  793. return urlparse.urlunsplit(("git", netloc, path, '', ''))
  794. def _connect(self, cmd, path):
  795. if not isinstance(cmd, bytes):
  796. raise TypeError(cmd)
  797. if not isinstance(path, bytes):
  798. path = path.encode(self._remote_path_encoding)
  799. sockaddrs = socket.getaddrinfo(
  800. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  801. s = None
  802. err = socket.error("no address found for %s" % self._host)
  803. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  804. s = socket.socket(family, socktype, proto)
  805. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  806. try:
  807. s.connect(sockaddr)
  808. break
  809. except socket.error as e:
  810. err = e
  811. if s is not None:
  812. s.close()
  813. s = None
  814. if s is None:
  815. raise err
  816. # -1 means system default buffering
  817. rfile = s.makefile('rb', -1)
  818. # 0 means unbuffered
  819. wfile = s.makefile('wb', 0)
  820. def close():
  821. rfile.close()
  822. wfile.close()
  823. s.close()
  824. proto = Protocol(rfile.read, wfile.write, close,
  825. report_activity=self._report_activity)
  826. if path.startswith(b"/~"):
  827. path = path[1:]
  828. # TODO(jelmer): Alternative to ascii?
  829. proto.send_cmd(
  830. b'git-' + cmd, path, b'host=' + self._host.encode('ascii'))
  831. return proto, lambda: _fileno_can_read(s), None
  832. class SubprocessWrapper(object):
  833. """A socket-like object that talks to a subprocess via pipes."""
  834. def __init__(self, proc):
  835. self.proc = proc
  836. if sys.version_info[0] == 2:
  837. self.read = proc.stdout.read
  838. else:
  839. self.read = BufferedReader(proc.stdout).read
  840. self.write = proc.stdin.write
  841. @property
  842. def stderr(self):
  843. return self.proc.stderr
  844. def can_read(self):
  845. if sys.platform == 'win32':
  846. from msvcrt import get_osfhandle
  847. handle = get_osfhandle(self.proc.stdout.fileno())
  848. return _win32_peek_avail(handle) != 0
  849. else:
  850. return _fileno_can_read(self.proc.stdout.fileno())
  851. def close(self):
  852. self.proc.stdin.close()
  853. self.proc.stdout.close()
  854. if self.proc.stderr:
  855. self.proc.stderr.close()
  856. self.proc.wait()
  857. def find_git_command():
  858. """Find command to run for system Git (usually C Git).
  859. """
  860. if sys.platform == 'win32': # support .exe, .bat and .cmd
  861. try: # to avoid overhead
  862. import win32api
  863. except ImportError: # run through cmd.exe with some overhead
  864. return ['cmd', '/c', 'git']
  865. else:
  866. status, git = win32api.FindExecutable('git')
  867. return [git]
  868. else:
  869. return ['git']
  870. class SubprocessGitClient(TraditionalGitClient):
  871. """Git client that talks to a server using a subprocess."""
  872. @classmethod
  873. def from_parsedurl(cls, parsedurl, **kwargs):
  874. return cls(**kwargs)
  875. git_command = None
  876. def _connect(self, service, path):
  877. if not isinstance(service, bytes):
  878. raise TypeError(service)
  879. if isinstance(path, bytes):
  880. path = path.decode(self._remote_path_encoding)
  881. if self.git_command is None:
  882. git_command = find_git_command()
  883. argv = git_command + [service.decode('ascii'), path]
  884. p = subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  885. stdout=subprocess.PIPE,
  886. stderr=subprocess.PIPE)
  887. pw = SubprocessWrapper(p)
  888. return (Protocol(pw.read, pw.write, pw.close,
  889. report_activity=self._report_activity),
  890. pw.can_read, p.stderr)
  891. class LocalGitClient(GitClient):
  892. """Git Client that just uses a local Repo."""
  893. def __init__(self, thin_packs=True, report_activity=None, config=None):
  894. """Create a new LocalGitClient instance.
  895. :param thin_packs: Whether or not thin packs should be retrieved
  896. :param report_activity: Optional callback for reporting transport
  897. activity.
  898. """
  899. self._report_activity = report_activity
  900. # Ignore the thin_packs argument
  901. def get_url(self, path):
  902. return urlparse.urlunsplit(('file', '', path, '', ''))
  903. @classmethod
  904. def from_parsedurl(cls, parsedurl, **kwargs):
  905. return cls(**kwargs)
  906. @classmethod
  907. def _open_repo(cls, path):
  908. from dulwich.repo import Repo
  909. if not isinstance(path, str):
  910. path = path.decode(sys.getfilesystemencoding())
  911. return closing(Repo(path))
  912. def send_pack(self, path, update_refs, generate_pack_data,
  913. progress=None):
  914. """Upload a pack to a remote repository.
  915. :param path: Repository path (as bytestring)
  916. :param update_refs: Function to determine changes to remote refs.
  917. Receive dict with existing remote refs, returns dict with
  918. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  919. :param generate_pack_data: Function that can return a tuple
  920. with number of items and pack data to upload.
  921. :param progress: Optional progress function
  922. :raises SendPackError: if server rejects the pack data
  923. :raises UpdateRefsError: if the server supports report-status
  924. and rejects ref updates
  925. :return: new_refs dictionary containing the changes that were made
  926. {refname: new_ref}, including deleted refs.
  927. """
  928. if not progress:
  929. def progress(x):
  930. pass
  931. with self._open_repo(path) as target:
  932. old_refs = target.get_refs()
  933. new_refs = update_refs(dict(old_refs))
  934. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  935. want = []
  936. for refname, new_sha1 in new_refs.items():
  937. if (new_sha1 not in have and
  938. new_sha1 not in want and
  939. new_sha1 != ZERO_SHA):
  940. want.append(new_sha1)
  941. if (not want and
  942. set(new_refs.items()).issubset(set(old_refs.items()))):
  943. return new_refs
  944. target.object_store.add_pack_data(
  945. *generate_pack_data(have, want, ofs_delta=True))
  946. for refname, new_sha1 in new_refs.items():
  947. old_sha1 = old_refs.get(refname, ZERO_SHA)
  948. if new_sha1 != ZERO_SHA:
  949. if not target.refs.set_if_equals(
  950. refname, old_sha1, new_sha1):
  951. progress('unable to set %s to %s' %
  952. (refname, new_sha1))
  953. else:
  954. if not target.refs.remove_if_equals(refname, old_sha1):
  955. progress('unable to remove %s' % refname)
  956. return new_refs
  957. def fetch(self, path, target, determine_wants=None, progress=None,
  958. depth=None):
  959. """Fetch into a target repository.
  960. :param path: Path to fetch from (as bytestring)
  961. :param target: Target repository to fetch into
  962. :param determine_wants: Optional function determine what refs
  963. to fetch. Receives dictionary of name->sha, should return
  964. list of shas to fetch. Defaults to all shas.
  965. :param progress: Optional progress function
  966. :param depth: Shallow fetch depth
  967. :return: FetchPackResult object
  968. """
  969. with self._open_repo(path) as r:
  970. refs = r.fetch(target, determine_wants=determine_wants,
  971. progress=progress, depth=depth)
  972. return FetchPackResult(refs, r.refs.get_symrefs(),
  973. agent_string())
  974. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  975. progress=None, depth=None):
  976. """Retrieve a pack from a git smart server.
  977. :param path: Remote path to fetch from
  978. :param determine_wants: Function determine what refs
  979. to fetch. Receives dictionary of name->sha, should return
  980. list of shas to fetch.
  981. :param graph_walker: Object with next() and ack().
  982. :param pack_data: Callback called for each bit of data in the pack
  983. :param progress: Callback for progress reports (strings)
  984. :param depth: Shallow fetch depth
  985. :return: FetchPackResult object
  986. """
  987. with self._open_repo(path) as r:
  988. objects_iter = r.fetch_objects(
  989. determine_wants, graph_walker, progress=progress, depth=depth)
  990. symrefs = r.refs.get_symrefs()
  991. agent = agent_string()
  992. # Did the process short-circuit (e.g. in a stateless RPC call)?
  993. # Note that the client still expects a 0-object pack in most cases.
  994. if objects_iter is None:
  995. return FetchPackResult(None, symrefs, agent)
  996. protocol = ProtocolFile(None, pack_data)
  997. write_pack_objects(protocol, objects_iter)
  998. return FetchPackResult(r.get_refs(), symrefs, agent)
  999. def get_refs(self, path):
  1000. """Retrieve the current refs from a git smart server."""
  1001. with self._open_repo(path) as target:
  1002. return target.get_refs()
  1003. # What Git client to use for local access
  1004. default_local_git_client_cls = LocalGitClient
  1005. class SSHVendor(object):
  1006. """A client side SSH implementation."""
  1007. def connect_ssh(self, host, command, username=None, port=None,
  1008. password=None, key_filename=None):
  1009. # This function was deprecated in 0.9.1
  1010. import warnings
  1011. warnings.warn(
  1012. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  1013. DeprecationWarning)
  1014. return self.run_command(host, command, username=username, port=port,
  1015. password=password, key_filename=key_filename)
  1016. def run_command(self, host, command, username=None, port=None,
  1017. password=None, key_filename=None):
  1018. """Connect to an SSH server.
  1019. Run a command remotely and return a file-like object for interaction
  1020. with the remote command.
  1021. :param host: Host name
  1022. :param command: Command to run (as argv array)
  1023. :param username: Optional ame of user to log in as
  1024. :param port: Optional SSH port to use
  1025. :param password: Optional ssh password for login or private key
  1026. :param key_filename: Optional path to private keyfile
  1027. """
  1028. raise NotImplementedError(self.run_command)
  1029. class StrangeHostname(Exception):
  1030. """Refusing to connect to strange SSH hostname."""
  1031. def __init__(self, hostname):
  1032. super(StrangeHostname, self).__init__(hostname)
  1033. class SubprocessSSHVendor(SSHVendor):
  1034. """SSH vendor that shells out to the local 'ssh' command."""
  1035. def run_command(self, host, command, username=None, port=None,
  1036. password=None, key_filename=None):
  1037. if password is not None:
  1038. raise NotImplementedError(
  1039. "Setting password not supported by SubprocessSSHVendor.")
  1040. args = ['ssh', '-x']
  1041. if port:
  1042. args.extend(['-p', str(port)])
  1043. if key_filename:
  1044. args.extend(['-i', str(key_filename)])
  1045. if username:
  1046. host = '%s@%s' % (username, host)
  1047. if host.startswith('-'):
  1048. raise StrangeHostname(hostname=host)
  1049. args.append(host)
  1050. proc = subprocess.Popen(args + [command], bufsize=0,
  1051. stdin=subprocess.PIPE,
  1052. stdout=subprocess.PIPE,
  1053. stderr=subprocess.PIPE)
  1054. return SubprocessWrapper(proc)
  1055. class PLinkSSHVendor(SSHVendor):
  1056. """SSH vendor that shells out to the local 'plink' command."""
  1057. def run_command(self, host, command, username=None, port=None,
  1058. password=None, key_filename=None):
  1059. if sys.platform == 'win32':
  1060. args = ['plink.exe', '-ssh']
  1061. else:
  1062. args = ['plink', '-ssh']
  1063. if password is not None:
  1064. import warnings
  1065. warnings.warn(
  1066. "Invoking PLink with a password exposes the password in the "
  1067. "process list.")
  1068. args.extend(['-pw', str(password)])
  1069. if port:
  1070. args.extend(['-P', str(port)])
  1071. if key_filename:
  1072. args.extend(['-i', str(key_filename)])
  1073. if username:
  1074. host = '%s@%s' % (username, host)
  1075. if host.startswith('-'):
  1076. raise StrangeHostname(hostname=host)
  1077. args.append(host)
  1078. proc = subprocess.Popen(args + [command], bufsize=0,
  1079. stdin=subprocess.PIPE,
  1080. stdout=subprocess.PIPE,
  1081. stderr=subprocess.PIPE)
  1082. return SubprocessWrapper(proc)
  1083. def ParamikoSSHVendor(**kwargs):
  1084. import warnings
  1085. warnings.warn(
  1086. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  1087. DeprecationWarning)
  1088. from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
  1089. return ParamikoSSHVendor(**kwargs)
  1090. # Can be overridden by users
  1091. get_ssh_vendor = SubprocessSSHVendor
  1092. class SSHGitClient(TraditionalGitClient):
  1093. def __init__(self, host, port=None, username=None, vendor=None,
  1094. config=None, password=None, key_filename=None, **kwargs):
  1095. self.host = host
  1096. self.port = port
  1097. self.username = username
  1098. self.password = password
  1099. self.key_filename = key_filename
  1100. super(SSHGitClient, self).__init__(**kwargs)
  1101. self.alternative_paths = {}
  1102. if vendor is not None:
  1103. self.ssh_vendor = vendor
  1104. else:
  1105. self.ssh_vendor = get_ssh_vendor()
  1106. def get_url(self, path):
  1107. netloc = self.host
  1108. if self.port is not None:
  1109. netloc += ":%d" % self.port
  1110. if self.username is not None:
  1111. netloc = urlquote(self.username, '@/:') + "@" + netloc
  1112. return urlparse.urlunsplit(('ssh', netloc, path, '', ''))
  1113. @classmethod
  1114. def from_parsedurl(cls, parsedurl, **kwargs):
  1115. return cls(host=parsedurl.hostname, port=parsedurl.port,
  1116. username=parsedurl.username, **kwargs)
  1117. def _get_cmd_path(self, cmd):
  1118. cmd = self.alternative_paths.get(cmd, b'git-' + cmd)
  1119. assert isinstance(cmd, bytes)
  1120. return cmd
  1121. def _connect(self, cmd, path):
  1122. if not isinstance(cmd, bytes):
  1123. raise TypeError(cmd)
  1124. if isinstance(path, bytes):
  1125. path = path.decode(self._remote_path_encoding)
  1126. if path.startswith("/~"):
  1127. path = path[1:]
  1128. argv = (self._get_cmd_path(cmd).decode(self._remote_path_encoding) +
  1129. " '" + path + "'")
  1130. kwargs = {}
  1131. if self.password is not None:
  1132. kwargs['password'] = self.password
  1133. if self.key_filename is not None:
  1134. kwargs['key_filename'] = self.key_filename
  1135. con = self.ssh_vendor.run_command(
  1136. self.host, argv, port=self.port, username=self.username,
  1137. **kwargs)
  1138. return (Protocol(con.read, con.write, con.close,
  1139. report_activity=self._report_activity),
  1140. con.can_read, getattr(con, 'stderr', None))
  1141. def default_user_agent_string():
  1142. # Start user agent with "git/", because GitHub requires this. :-( See
  1143. # https://github.com/jelmer/dulwich/issues/562 for details.
  1144. return "git/dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  1145. def default_urllib3_manager(config, **override_kwargs):
  1146. """Return `urllib3` connection pool manager.
  1147. Honour detected proxy configurations.
  1148. :param config: `dulwich.config.ConfigDict` instance with Git configuration.
  1149. :param kwargs: Additional arguments for urllib3.ProxyManager
  1150. :return: `urllib3.ProxyManager` instance for proxy configurations,
  1151. `urllib3.PoolManager` otherwise.
  1152. """
  1153. proxy_server = user_agent = None
  1154. ca_certs = ssl_verify = None
  1155. if config is not None:
  1156. try:
  1157. proxy_server = config.get(b"http", b"proxy")
  1158. except KeyError:
  1159. pass
  1160. try:
  1161. user_agent = config.get(b"http", b"useragent")
  1162. except KeyError:
  1163. pass
  1164. # TODO(jelmer): Support per-host settings
  1165. try:
  1166. ssl_verify = config.get_boolean(b"http", b"sslVerify")
  1167. except KeyError:
  1168. ssl_verify = True
  1169. try:
  1170. ca_certs = config.get_boolean(b"http", b"sslCAInfo")
  1171. except KeyError:
  1172. ca_certs = None
  1173. if user_agent is None:
  1174. user_agent = default_user_agent_string()
  1175. headers = {"User-agent": user_agent}
  1176. kwargs = {}
  1177. if ssl_verify is True:
  1178. kwargs['cert_reqs'] = "CERT_REQUIRED"
  1179. elif ssl_verify is False:
  1180. kwargs['cert_reqs'] = 'CERT_NONE'
  1181. else:
  1182. # Default to SSL verification
  1183. kwargs['cert_reqs'] = "CERT_REQUIRED"
  1184. if ca_certs is not None:
  1185. kwargs['ca_certs'] = ca_certs
  1186. kwargs.update(override_kwargs)
  1187. # Try really hard to find a SSL certificate path
  1188. if 'ca_certs' not in kwargs and kwargs.get('cert_reqs') != 'CERT_NONE':
  1189. try:
  1190. import certifi
  1191. except ImportError:
  1192. pass
  1193. else:
  1194. kwargs['ca_certs'] = certifi.where()
  1195. import urllib3
  1196. if proxy_server is not None:
  1197. # `urllib3` requires a `str` object in both Python 2 and 3, while
  1198. # `ConfigDict` coerces entries to `bytes` on Python 3. Compensate.
  1199. if not isinstance(proxy_server, str):
  1200. proxy_server = proxy_server.decode()
  1201. manager = urllib3.ProxyManager(proxy_server, headers=headers,
  1202. **kwargs)
  1203. else:
  1204. manager = urllib3.PoolManager(headers=headers, **kwargs)
  1205. return manager
  1206. class HttpGitClient(GitClient):
  1207. def __init__(self, base_url, dumb=None, pool_manager=None, config=None,
  1208. username=None, password=None, **kwargs):
  1209. self._base_url = base_url.rstrip("/") + "/"
  1210. self._username = username
  1211. self._password = password
  1212. self.dumb = dumb
  1213. if pool_manager is None:
  1214. self.pool_manager = default_urllib3_manager(config)
  1215. else:
  1216. self.pool_manager = pool_manager
  1217. if username is not None:
  1218. # No escaping needed: ":" is not allowed in username:
  1219. # https://tools.ietf.org/html/rfc2617#section-2
  1220. credentials = "%s:%s" % (username, password)
  1221. import urllib3.util
  1222. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  1223. self.pool_manager.headers.update(basic_auth)
  1224. GitClient.__init__(self, **kwargs)
  1225. def get_url(self, path):
  1226. return self._get_url(path).rstrip("/")
  1227. @classmethod
  1228. def from_parsedurl(cls, parsedurl, **kwargs):
  1229. password = parsedurl.password
  1230. if password is not None:
  1231. kwargs['password'] = urlunquote(password)
  1232. username = parsedurl.username
  1233. if username is not None:
  1234. kwargs['username'] = urlunquote(username)
  1235. # TODO(jelmer): This also strips the username
  1236. parsedurl = parsedurl._replace(netloc=parsedurl.hostname)
  1237. return cls(urlparse.urlunparse(parsedurl), **kwargs)
  1238. def __repr__(self):
  1239. return "%s(%r, dumb=%r)" % (
  1240. type(self).__name__, self._base_url, self.dumb)
  1241. def _get_url(self, path):
  1242. if not isinstance(path, str):
  1243. # TODO(jelmer): this is unrelated to the local filesystem;
  1244. # This is not necessarily the right encoding to decode the path
  1245. # with.
  1246. path = path.decode(sys.getfilesystemencoding())
  1247. return urlparse.urljoin(self._base_url, path).rstrip("/") + "/"
  1248. def _http_request(self, url, headers=None, data=None,
  1249. allow_compression=False):
  1250. """Perform HTTP request.
  1251. :param url: Request URL.
  1252. :param headers: Optional custom headers to override defaults.
  1253. :param data: Request data.
  1254. :param allow_compression: Allow GZipped communication.
  1255. :return: Tuple (`response`, `read`), where response is an `urllib3`
  1256. response object with additional `content_type` and
  1257. `redirect_location` properties, and `read` is a consumable read
  1258. method for the response data.
  1259. """
  1260. req_headers = self.pool_manager.headers.copy()
  1261. if headers is not None:
  1262. req_headers.update(headers)
  1263. req_headers["Pragma"] = "no-cache"
  1264. if allow_compression:
  1265. req_headers["Accept-Encoding"] = "gzip"
  1266. else:
  1267. req_headers["Accept-Encoding"] = "identity"
  1268. if data is None:
  1269. resp = self.pool_manager.request("GET", url, headers=req_headers)
  1270. else:
  1271. resp = self.pool_manager.request("POST", url, headers=req_headers,
  1272. body=data)
  1273. if resp.status == 404:
  1274. raise NotGitRepository()
  1275. elif resp.status != 200:
  1276. raise GitProtocolError("unexpected http resp %d for %s" %
  1277. (resp.status, url))
  1278. # TODO: Optimization available by adding `preload_content=False` to the
  1279. # request and just passing the `read` method on instead of going via
  1280. # `BytesIO`, if we can guarantee that the entire response is consumed
  1281. # before issuing the next to still allow for connection reuse from the
  1282. # pool.
  1283. read = BytesIO(resp.data).read
  1284. resp.content_type = resp.getheader("Content-Type")
  1285. resp.redirect_location = resp.get_redirect_location()
  1286. return resp, read
  1287. def _discover_references(self, service, base_url):
  1288. assert base_url[-1] == "/"
  1289. tail = "info/refs"
  1290. headers = {"Accept": "*/*"}
  1291. if self.dumb is not True:
  1292. tail += "?service=%s" % service.decode('ascii')
  1293. url = urlparse.urljoin(base_url, tail)
  1294. resp, read = self._http_request(url, headers, allow_compression=True)
  1295. if resp.redirect_location:
  1296. # Something changed (redirect!), so let's update the base URL
  1297. if not resp.redirect_location.endswith(tail):
  1298. raise GitProtocolError(
  1299. "Redirected from URL %s to URL %s without %s" % (
  1300. url, resp.redirect_location, tail))
  1301. base_url = resp.redirect_location[:-len(tail)]
  1302. try:
  1303. self.dumb = not resp.content_type.startswith("application/x-git-")
  1304. if not self.dumb:
  1305. proto = Protocol(read, None)
  1306. # The first line should mention the service
  1307. try:
  1308. [pkt] = list(proto.read_pkt_seq())
  1309. except ValueError:
  1310. raise GitProtocolError(
  1311. "unexpected number of packets received")
  1312. if pkt.rstrip(b'\n') != (b'# service=' + service):
  1313. raise GitProtocolError(
  1314. "unexpected first line %r from smart server" % pkt)
  1315. return read_pkt_refs(proto) + (base_url, )
  1316. else:
  1317. return read_info_refs(resp), set(), base_url
  1318. finally:
  1319. resp.close()
  1320. def _smart_request(self, service, url, data):
  1321. assert url[-1] == "/"
  1322. url = urlparse.urljoin(url, service)
  1323. result_content_type = "application/x-%s-result" % service
  1324. headers = {
  1325. "Content-Type": "application/x-%s-request" % service,
  1326. "Accept": result_content_type,
  1327. "Content-Length": str(len(data)),
  1328. }
  1329. resp, read = self._http_request(url, headers, data)
  1330. if resp.content_type != result_content_type:
  1331. raise GitProtocolError("Invalid content-type from server: %s"
  1332. % resp.content_type)
  1333. return resp, read
  1334. def send_pack(self, path, update_refs, generate_pack_data,
  1335. progress=None):
  1336. """Upload a pack to a remote repository.
  1337. :param path: Repository path (as bytestring)
  1338. :param update_refs: Function to determine changes to remote refs.
  1339. Receive dict with existing remote refs, returns dict with
  1340. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1341. :param generate_pack_data: Function that can return a tuple
  1342. with number of elements and pack data to upload.
  1343. :param progress: Optional progress function
  1344. :raises SendPackError: if server rejects the pack data
  1345. :raises UpdateRefsError: if the server supports report-status
  1346. and rejects ref updates
  1347. :return: new_refs dictionary containing the changes that were made
  1348. {refname: new_ref}, including deleted refs.
  1349. """
  1350. url = self._get_url(path)
  1351. old_refs, server_capabilities, url = self._discover_references(
  1352. b"git-receive-pack", url)
  1353. negotiated_capabilities = self._negotiate_receive_pack_capabilities(
  1354. server_capabilities)
  1355. negotiated_capabilities.add(capability_agent())
  1356. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1357. self._report_status_parser = ReportStatusParser()
  1358. new_refs = update_refs(dict(old_refs))
  1359. if new_refs is None:
  1360. # Determine wants function is aborting the push.
  1361. return old_refs
  1362. if self.dumb:
  1363. raise NotImplementedError(self.fetch_pack)
  1364. req_data = BytesIO()
  1365. req_proto = Protocol(None, req_data.write)
  1366. (have, want) = self._handle_receive_pack_head(
  1367. req_proto, negotiated_capabilities, old_refs, new_refs)
  1368. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1369. return new_refs
  1370. pack_data_count, pack_data = generate_pack_data(
  1371. have, want,
  1372. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities))
  1373. if pack_data_count:
  1374. write_pack_data(req_proto.write_file(), pack_data_count, pack_data)
  1375. resp, read = self._smart_request("git-receive-pack", url,
  1376. data=req_data.getvalue())
  1377. try:
  1378. resp_proto = Protocol(read, None)
  1379. self._handle_receive_pack_tail(
  1380. resp_proto, negotiated_capabilities, progress)
  1381. return new_refs
  1382. finally:
  1383. resp.close()
  1384. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  1385. progress=None, depth=None):
  1386. """Retrieve a pack from a git smart server.
  1387. :param determine_wants: Callback that returns list of commits to fetch
  1388. :param graph_walker: Object with next() and ack().
  1389. :param pack_data: Callback called for each bit of data in the pack
  1390. :param progress: Callback for progress reports (strings)
  1391. :param depth: Depth for request
  1392. :return: FetchPackResult object
  1393. """
  1394. url = self._get_url(path)
  1395. refs, server_capabilities, url = self._discover_references(
  1396. b"git-upload-pack", url)
  1397. negotiated_capabilities, symrefs, agent = (
  1398. self._negotiate_upload_pack_capabilities(
  1399. server_capabilities))
  1400. wants = determine_wants(refs)
  1401. if wants is not None:
  1402. wants = [cid for cid in wants if cid != ZERO_SHA]
  1403. if not wants:
  1404. return FetchPackResult(refs, symrefs, agent)
  1405. if self.dumb:
  1406. raise NotImplementedError(self.send_pack)
  1407. check_wants(wants, refs)
  1408. req_data = BytesIO()
  1409. req_proto = Protocol(None, req_data.write)
  1410. (new_shallow, new_unshallow) = self._handle_upload_pack_head(
  1411. req_proto, negotiated_capabilities, graph_walker, wants,
  1412. can_read=None, depth=depth)
  1413. resp, read = self._smart_request(
  1414. "git-upload-pack", url, data=req_data.getvalue())
  1415. try:
  1416. resp_proto = Protocol(read, None)
  1417. if new_shallow is None and new_unshallow is None:
  1418. (new_shallow, new_unshallow) = _read_shallow_updates(
  1419. resp_proto)
  1420. self._handle_upload_pack_tail(
  1421. resp_proto, negotiated_capabilities, graph_walker, pack_data,
  1422. progress)
  1423. return FetchPackResult(
  1424. refs, symrefs, agent, new_shallow, new_unshallow)
  1425. finally:
  1426. resp.close()
  1427. def get_refs(self, path):
  1428. """Retrieve the current refs from a git smart server."""
  1429. url = self._get_url(path)
  1430. refs, _, _ = self._discover_references(
  1431. b"git-upload-pack", url)
  1432. return refs
  1433. def get_transport_and_path_from_url(url, config=None, **kwargs):
  1434. """Obtain a git client from a URL.
  1435. :param url: URL to open (a unicode string)
  1436. :param config: Optional config object
  1437. :param thin_packs: Whether or not thin packs should be retrieved
  1438. :param report_activity: Optional callback for reporting transport
  1439. activity.
  1440. :return: Tuple with client instance and relative path.
  1441. """
  1442. parsed = urlparse.urlparse(url)
  1443. if parsed.scheme == 'git':
  1444. return (TCPGitClient.from_parsedurl(parsed, **kwargs),
  1445. parsed.path)
  1446. elif parsed.scheme in ('git+ssh', 'ssh'):
  1447. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  1448. elif parsed.scheme in ('http', 'https'):
  1449. return HttpGitClient.from_parsedurl(
  1450. parsed, config=config, **kwargs), parsed.path
  1451. elif parsed.scheme == 'file':
  1452. return default_local_git_client_cls.from_parsedurl(
  1453. parsed, **kwargs), parsed.path
  1454. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  1455. def parse_rsync_url(location):
  1456. """Parse a rsync-style URL."""
  1457. if ':' in location and '@' not in location:
  1458. # SSH with no user@, zero or one leading slash.
  1459. (host, path) = location.split(':', 1)
  1460. user = None
  1461. elif ':' in location:
  1462. # SSH with user@host:foo.
  1463. user_host, path = location.split(':', 1)
  1464. if '@' in user_host:
  1465. user, host = user_host.rsplit('@', 1)
  1466. else:
  1467. user = None
  1468. host = user_host
  1469. else:
  1470. raise ValueError('not a valid rsync-style URL')
  1471. return (user, host, path)
  1472. def get_transport_and_path(location, **kwargs):
  1473. """Obtain a git client from a URL.
  1474. :param location: URL or path (a string)
  1475. :param config: Optional config object
  1476. :param thin_packs: Whether or not thin packs should be retrieved
  1477. :param report_activity: Optional callback for reporting transport
  1478. activity.
  1479. :return: Tuple with client instance and relative path.
  1480. """
  1481. # First, try to parse it as a URL
  1482. try:
  1483. return get_transport_and_path_from_url(location, **kwargs)
  1484. except ValueError:
  1485. pass
  1486. if (sys.platform == 'win32' and
  1487. location[0].isalpha() and location[1:3] == ':\\'):
  1488. # Windows local path
  1489. return default_local_git_client_cls(**kwargs), location
  1490. try:
  1491. (username, hostname, path) = parse_rsync_url(location)
  1492. except ValueError:
  1493. # Otherwise, assume it's a local path.
  1494. return default_local_git_client_cls(**kwargs), location
  1495. else:
  1496. return SSHGitClient(hostname, username=username, **kwargs), path