client.py 67 KB

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