client.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489
  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. import logging
  36. import os
  37. import select
  38. import socket
  39. import subprocess
  40. import sys
  41. from contextlib import closing
  42. from io import BufferedReader, BytesIO
  43. from typing import (
  44. IO,
  45. TYPE_CHECKING,
  46. Callable,
  47. ClassVar,
  48. Dict,
  49. Iterable,
  50. Iterator,
  51. List,
  52. Optional,
  53. Set,
  54. Tuple,
  55. Union,
  56. )
  57. from urllib.parse import quote as urlquote
  58. from urllib.parse import unquote as urlunquote
  59. from urllib.parse import urljoin, urlparse, urlunparse, urlunsplit
  60. if TYPE_CHECKING:
  61. import urllib3
  62. import dulwich
  63. from .config import Config, apply_instead_of, get_xdg_config_home_path
  64. from .errors import GitProtocolError, NotGitRepository, SendPackError
  65. from .pack import (
  66. PACK_SPOOL_FILE_MAX_SIZE,
  67. PackChunkGenerator,
  68. UnpackedObject,
  69. write_pack_from_container,
  70. )
  71. from .protocol import (
  72. _RBUFSIZE,
  73. CAPABILITIES_REF,
  74. CAPABILITY_AGENT,
  75. CAPABILITY_DELETE_REFS,
  76. CAPABILITY_INCLUDE_TAG,
  77. CAPABILITY_MULTI_ACK,
  78. CAPABILITY_MULTI_ACK_DETAILED,
  79. CAPABILITY_OFS_DELTA,
  80. CAPABILITY_QUIET,
  81. CAPABILITY_REPORT_STATUS,
  82. CAPABILITY_SHALLOW,
  83. CAPABILITY_SIDE_BAND_64K,
  84. CAPABILITY_SYMREF,
  85. CAPABILITY_THIN_PACK,
  86. COMMAND_DEEPEN,
  87. COMMAND_DONE,
  88. COMMAND_HAVE,
  89. COMMAND_SHALLOW,
  90. COMMAND_UNSHALLOW,
  91. COMMAND_WANT,
  92. KNOWN_RECEIVE_CAPABILITIES,
  93. KNOWN_UPLOAD_CAPABILITIES,
  94. SIDE_BAND_CHANNEL_DATA,
  95. SIDE_BAND_CHANNEL_FATAL,
  96. SIDE_BAND_CHANNEL_PROGRESS,
  97. TCP_GIT_PORT,
  98. ZERO_SHA,
  99. HangupException,
  100. PktLineParser,
  101. Protocol,
  102. agent_string,
  103. capability_agent,
  104. extract_capabilities,
  105. extract_capability_names,
  106. parse_capability,
  107. pkt_line,
  108. )
  109. from .refs import PEELED_TAG_SUFFIX, _import_remote_refs, read_info_refs
  110. from .repo import Repo
  111. # url2pathname is lazily imported
  112. url2pathname = None
  113. logger = logging.getLogger(__name__)
  114. class InvalidWants(Exception):
  115. """Invalid wants."""
  116. def __init__(self, wants) -> None:
  117. Exception.__init__(
  118. self, f"requested wants not in server provided refs: {wants!r}"
  119. )
  120. class HTTPUnauthorized(Exception):
  121. """Raised when authentication fails."""
  122. def __init__(self, www_authenticate, url) -> None:
  123. Exception.__init__(self, "No valid credentials provided")
  124. self.www_authenticate = www_authenticate
  125. self.url = url
  126. class HTTPProxyUnauthorized(Exception):
  127. """Raised when proxy authentication fails."""
  128. def __init__(self, proxy_authenticate, url) -> None:
  129. Exception.__init__(self, "No valid proxy credentials provided")
  130. self.proxy_authenticate = proxy_authenticate
  131. self.url = url
  132. def _fileno_can_read(fileno):
  133. """Check if a file descriptor is readable."""
  134. return len(select.select([fileno], [], [], 0)[0]) > 0
  135. def _win32_peek_avail(handle):
  136. """Wrapper around PeekNamedPipe to check how many bytes are available."""
  137. from ctypes import byref, windll, wintypes
  138. c_avail = wintypes.DWORD()
  139. c_message = wintypes.DWORD()
  140. success = windll.kernel32.PeekNamedPipe(
  141. handle, None, 0, None, byref(c_avail), byref(c_message)
  142. )
  143. if not success:
  144. raise OSError(wintypes.GetLastError())
  145. return c_avail.value
  146. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  147. UPLOAD_CAPABILITIES = [
  148. CAPABILITY_THIN_PACK,
  149. CAPABILITY_MULTI_ACK,
  150. CAPABILITY_MULTI_ACK_DETAILED,
  151. CAPABILITY_SHALLOW,
  152. *COMMON_CAPABILITIES,
  153. ]
  154. RECEIVE_CAPABILITIES = [
  155. CAPABILITY_REPORT_STATUS,
  156. CAPABILITY_DELETE_REFS,
  157. *COMMON_CAPABILITIES,
  158. ]
  159. class ReportStatusParser:
  160. """Handle status as reported by servers with 'report-status' capability."""
  161. def __init__(self) -> None:
  162. self._done = False
  163. self._pack_status = None
  164. self._ref_statuses: List[bytes] = []
  165. def check(self):
  166. """Check if there were any errors and, if so, raise exceptions.
  167. Raises:
  168. SendPackError: Raised when the server could not unpack
  169. Returns:
  170. iterator over refs
  171. """
  172. if self._pack_status not in (b"unpack ok", None):
  173. raise SendPackError(self._pack_status)
  174. for status in self._ref_statuses:
  175. try:
  176. status, rest = status.split(b" ", 1)
  177. except ValueError:
  178. # malformed response, move on to the next one
  179. continue
  180. if status == b"ng":
  181. ref, error = rest.split(b" ", 1)
  182. yield ref, error.decode("utf-8")
  183. elif status == b"ok":
  184. yield rest, None
  185. else:
  186. raise GitProtocolError(f"invalid ref status {status!r}")
  187. def handle_packet(self, pkt):
  188. """Handle a packet.
  189. Raises:
  190. GitProtocolError: Raised when packets are received after a flush
  191. packet.
  192. """
  193. if self._done:
  194. raise GitProtocolError("received more data after status report")
  195. if pkt is None:
  196. self._done = True
  197. return
  198. if self._pack_status is None:
  199. self._pack_status = pkt.strip()
  200. else:
  201. ref_status = pkt.strip()
  202. self._ref_statuses.append(ref_status)
  203. def read_pkt_refs(pkt_seq):
  204. server_capabilities = None
  205. refs = {}
  206. # Receive refs from server
  207. for pkt in pkt_seq:
  208. (sha, ref) = pkt.rstrip(b"\n").split(None, 1)
  209. if sha == b"ERR":
  210. raise GitProtocolError(ref.decode("utf-8", "replace"))
  211. if server_capabilities is None:
  212. (ref, server_capabilities) = extract_capabilities(ref)
  213. refs[ref] = sha
  214. if len(refs) == 0:
  215. return {}, set()
  216. if refs == {CAPABILITIES_REF: ZERO_SHA}:
  217. refs = {}
  218. return refs, set(server_capabilities)
  219. class FetchPackResult:
  220. """Result of a fetch-pack operation.
  221. Attributes:
  222. refs: Dictionary with all remote refs
  223. symrefs: Dictionary with remote symrefs
  224. agent: User agent string
  225. """
  226. _FORWARDED_ATTRS: ClassVar[Set[str]] = {
  227. "clear",
  228. "copy",
  229. "fromkeys",
  230. "get",
  231. "items",
  232. "keys",
  233. "pop",
  234. "popitem",
  235. "setdefault",
  236. "update",
  237. "values",
  238. "viewitems",
  239. "viewkeys",
  240. "viewvalues",
  241. }
  242. def __init__(
  243. self, refs, symrefs, agent, new_shallow=None, new_unshallow=None
  244. ) -> None:
  245. self.refs = refs
  246. self.symrefs = symrefs
  247. self.agent = agent
  248. self.new_shallow = new_shallow
  249. self.new_unshallow = new_unshallow
  250. def _warn_deprecated(self):
  251. import warnings
  252. warnings.warn(
  253. "Use FetchPackResult.refs instead.",
  254. DeprecationWarning,
  255. stacklevel=3,
  256. )
  257. def __eq__(self, other):
  258. if isinstance(other, dict):
  259. self._warn_deprecated()
  260. return self.refs == other
  261. return (
  262. self.refs == other.refs
  263. and self.symrefs == other.symrefs
  264. and self.agent == other.agent
  265. )
  266. def __contains__(self, name) -> bool:
  267. self._warn_deprecated()
  268. return name in self.refs
  269. def __getitem__(self, name):
  270. self._warn_deprecated()
  271. return self.refs[name]
  272. def __len__(self) -> int:
  273. self._warn_deprecated()
  274. return len(self.refs)
  275. def __iter__(self):
  276. self._warn_deprecated()
  277. return iter(self.refs)
  278. def __getattribute__(self, name):
  279. if name in type(self)._FORWARDED_ATTRS:
  280. self._warn_deprecated()
  281. return getattr(self.refs, name)
  282. return super().__getattribute__(name)
  283. def __repr__(self) -> str:
  284. return f"{self.__class__.__name__}({self.refs!r}, {self.symrefs!r}, {self.agent!r})"
  285. class SendPackResult:
  286. """Result of a upload-pack operation.
  287. Attributes:
  288. refs: Dictionary with all remote refs
  289. agent: User agent string
  290. ref_status: Optional dictionary mapping ref name to error message (if it
  291. failed to update), or None if it was updated successfully
  292. """
  293. _FORWARDED_ATTRS: ClassVar[Set[str]] = {
  294. "clear",
  295. "copy",
  296. "fromkeys",
  297. "get",
  298. "items",
  299. "keys",
  300. "pop",
  301. "popitem",
  302. "setdefault",
  303. "update",
  304. "values",
  305. "viewitems",
  306. "viewkeys",
  307. "viewvalues",
  308. }
  309. def __init__(self, refs, agent=None, ref_status=None) -> None:
  310. self.refs = refs
  311. self.agent = agent
  312. self.ref_status = ref_status
  313. def _warn_deprecated(self):
  314. import warnings
  315. warnings.warn(
  316. "Use SendPackResult.refs instead.",
  317. DeprecationWarning,
  318. stacklevel=3,
  319. )
  320. def __eq__(self, other):
  321. if isinstance(other, dict):
  322. self._warn_deprecated()
  323. return self.refs == other
  324. return self.refs == other.refs and self.agent == other.agent
  325. def __contains__(self, name) -> bool:
  326. self._warn_deprecated()
  327. return name in self.refs
  328. def __getitem__(self, name):
  329. self._warn_deprecated()
  330. return self.refs[name]
  331. def __len__(self) -> int:
  332. self._warn_deprecated()
  333. return len(self.refs)
  334. def __iter__(self):
  335. self._warn_deprecated()
  336. return iter(self.refs)
  337. def __getattribute__(self, name):
  338. if name in type(self)._FORWARDED_ATTRS:
  339. self._warn_deprecated()
  340. return getattr(self.refs, name)
  341. return super().__getattribute__(name)
  342. def __repr__(self) -> str:
  343. return f"{self.__class__.__name__}({self.refs!r}, {self.agent!r})"
  344. def _read_shallow_updates(pkt_seq):
  345. new_shallow = set()
  346. new_unshallow = set()
  347. for pkt in pkt_seq:
  348. try:
  349. cmd, sha = pkt.split(b" ", 1)
  350. except ValueError:
  351. raise GitProtocolError(f"unknown command {pkt}")
  352. if cmd == COMMAND_SHALLOW:
  353. new_shallow.add(sha.strip())
  354. elif cmd == COMMAND_UNSHALLOW:
  355. new_unshallow.add(sha.strip())
  356. else:
  357. raise GitProtocolError(f"unknown command {pkt}")
  358. return (new_shallow, new_unshallow)
  359. class _v1ReceivePackHeader:
  360. def __init__(self, capabilities, old_refs, new_refs) -> None:
  361. self.want: List[bytes] = []
  362. self.have: List[bytes] = []
  363. self._it = self._handle_receive_pack_head(capabilities, old_refs, new_refs)
  364. self.sent_capabilities = False
  365. def __iter__(self):
  366. return self._it
  367. def _handle_receive_pack_head(self, capabilities, old_refs, new_refs):
  368. """Handle the head of a 'git-receive-pack' request.
  369. Args:
  370. capabilities: List of negotiated capabilities
  371. old_refs: Old refs, as received from the server
  372. new_refs: Refs to change
  373. Returns:
  374. (have, want) tuple
  375. """
  376. self.have = [x for x in old_refs.values() if not x == ZERO_SHA]
  377. for refname in new_refs:
  378. if not isinstance(refname, bytes):
  379. raise TypeError(f"refname is not a bytestring: {refname!r}")
  380. old_sha1 = old_refs.get(refname, ZERO_SHA)
  381. if not isinstance(old_sha1, bytes):
  382. raise TypeError(
  383. f"old sha1 for {refname!r} is not a bytestring: {old_sha1!r}"
  384. )
  385. new_sha1 = new_refs.get(refname, ZERO_SHA)
  386. if not isinstance(new_sha1, bytes):
  387. raise TypeError(
  388. f"old sha1 for {refname!r} is not a bytestring {new_sha1!r}"
  389. )
  390. if old_sha1 != new_sha1:
  391. logger.debug(
  392. "Sending updated ref %r: %r -> %r", refname, old_sha1, new_sha1
  393. )
  394. if self.sent_capabilities:
  395. yield old_sha1 + b" " + new_sha1 + b" " + refname
  396. else:
  397. yield (
  398. old_sha1
  399. + b" "
  400. + new_sha1
  401. + b" "
  402. + refname
  403. + b"\0"
  404. + b" ".join(sorted(capabilities))
  405. )
  406. self.sent_capabilities = True
  407. if new_sha1 not in self.have and new_sha1 != ZERO_SHA:
  408. self.want.append(new_sha1)
  409. yield None
  410. def _read_side_band64k_data(pkt_seq: Iterable[bytes]) -> Iterator[Tuple[int, bytes]]:
  411. """Read per-channel data.
  412. This requires the side-band-64k capability.
  413. Args:
  414. pkt_seq: Sequence of packets to read
  415. """
  416. for pkt in pkt_seq:
  417. channel = ord(pkt[:1])
  418. yield channel, pkt[1:]
  419. def _handle_upload_pack_head(proto, capabilities, graph_walker, wants, can_read, depth):
  420. """Handle the head of a 'git-upload-pack' request.
  421. Args:
  422. proto: Protocol object to read from
  423. capabilities: List of negotiated capabilities
  424. graph_walker: GraphWalker instance to call .ack() on
  425. wants: List of commits to fetch
  426. can_read: function that returns a boolean that indicates
  427. whether there is extra graph data to read on proto
  428. depth: Depth for request
  429. """
  430. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  431. proto.write_pkt_line(
  432. COMMAND_WANT + b" " + wants[0] + b" " + b" ".join(sorted(capabilities)) + b"\n"
  433. )
  434. for want in wants[1:]:
  435. proto.write_pkt_line(COMMAND_WANT + b" " + want + b"\n")
  436. if depth not in (0, None) or getattr(graph_walker, "shallow", None):
  437. if CAPABILITY_SHALLOW not in capabilities:
  438. raise GitProtocolError(
  439. "server does not support shallow capability required for " "depth"
  440. )
  441. for sha in graph_walker.shallow:
  442. proto.write_pkt_line(COMMAND_SHALLOW + b" " + sha + b"\n")
  443. if depth is not None:
  444. proto.write_pkt_line(
  445. COMMAND_DEEPEN + b" " + str(depth).encode("ascii") + b"\n"
  446. )
  447. proto.write_pkt_line(None)
  448. if depth not in (0, None):
  449. if can_read is not None:
  450. (new_shallow, new_unshallow) = _read_shallow_updates(proto.read_pkt_seq())
  451. else:
  452. new_shallow = new_unshallow = None
  453. else:
  454. new_shallow = new_unshallow = set()
  455. have = next(graph_walker)
  456. while have:
  457. proto.write_pkt_line(COMMAND_HAVE + b" " + have + b"\n")
  458. if can_read is not None and can_read():
  459. pkt = proto.read_pkt_line()
  460. parts = pkt.rstrip(b"\n").split(b" ")
  461. if parts[0] == b"ACK":
  462. graph_walker.ack(parts[1])
  463. if parts[2] in (b"continue", b"common"):
  464. pass
  465. elif parts[2] == b"ready":
  466. break
  467. else:
  468. raise AssertionError(
  469. f"{parts[2]} not in ('continue', 'ready', 'common)"
  470. )
  471. have = next(graph_walker)
  472. proto.write_pkt_line(COMMAND_DONE + b"\n")
  473. return (new_shallow, new_unshallow)
  474. def _handle_upload_pack_tail(
  475. proto,
  476. capabilities: Set[bytes],
  477. graph_walker,
  478. pack_data: Callable[[bytes], None],
  479. progress: Optional[Callable[[bytes], None]] = None,
  480. rbufsize=_RBUFSIZE,
  481. ):
  482. """Handle the tail of a 'git-upload-pack' request.
  483. Args:
  484. proto: Protocol object to read from
  485. capabilities: List of negotiated capabilities
  486. graph_walker: GraphWalker instance to call .ack() on
  487. pack_data: Function to call with pack data
  488. progress: Optional progress reporting function
  489. rbufsize: Read buffer size
  490. """
  491. pkt = proto.read_pkt_line()
  492. while pkt:
  493. parts = pkt.rstrip(b"\n").split(b" ")
  494. if parts[0] == b"ACK":
  495. graph_walker.ack(parts[1])
  496. if parts[0] == b"NAK":
  497. graph_walker.nak()
  498. if len(parts) < 3 or parts[2] not in (
  499. b"ready",
  500. b"continue",
  501. b"common",
  502. ):
  503. break
  504. pkt = proto.read_pkt_line()
  505. if CAPABILITY_SIDE_BAND_64K in capabilities:
  506. if progress is None:
  507. # Just ignore progress data
  508. def progress(x):
  509. pass
  510. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  511. if chan == SIDE_BAND_CHANNEL_DATA:
  512. pack_data(data)
  513. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  514. progress(data)
  515. else:
  516. raise AssertionError("Invalid sideband channel %d" % chan)
  517. else:
  518. while True:
  519. data = proto.read(rbufsize)
  520. if data == b"":
  521. break
  522. pack_data(data)
  523. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  524. # support some capabilities. This should work properly with servers
  525. # that don't support multi_ack.
  526. class GitClient:
  527. """Git smart server client."""
  528. def __init__(
  529. self,
  530. thin_packs=True,
  531. report_activity=None,
  532. quiet=False,
  533. include_tags=False,
  534. ) -> None:
  535. """Create a new GitClient instance.
  536. Args:
  537. thin_packs: Whether or not thin packs should be retrieved
  538. report_activity: Optional callback for reporting transport
  539. activity.
  540. include_tags: send annotated tags when sending the objects they point
  541. to
  542. """
  543. self._report_activity = report_activity
  544. self._report_status_parser: Optional[ReportStatusParser] = None
  545. self._fetch_capabilities = set(UPLOAD_CAPABILITIES)
  546. self._fetch_capabilities.add(capability_agent())
  547. self._send_capabilities = set(RECEIVE_CAPABILITIES)
  548. self._send_capabilities.add(capability_agent())
  549. if quiet:
  550. self._send_capabilities.add(CAPABILITY_QUIET)
  551. if not thin_packs:
  552. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  553. if include_tags:
  554. self._fetch_capabilities.add(CAPABILITY_INCLUDE_TAG)
  555. def get_url(self, path):
  556. """Retrieves full url to given path.
  557. Args:
  558. path: Repository path (as string)
  559. Returns:
  560. Url to path (as string)
  561. """
  562. raise NotImplementedError(self.get_url)
  563. @classmethod
  564. def from_parsedurl(cls, parsedurl, **kwargs):
  565. """Create an instance of this client from a urlparse.parsed object.
  566. Args:
  567. parsedurl: Result of urlparse()
  568. Returns:
  569. A `GitClient` object
  570. """
  571. raise NotImplementedError(cls.from_parsedurl)
  572. def send_pack(
  573. self,
  574. path,
  575. update_refs,
  576. generate_pack_data: Callable[
  577. [Set[bytes], Set[bytes], bool], Tuple[int, Iterator[UnpackedObject]]
  578. ],
  579. progress=None,
  580. ):
  581. """Upload a pack to a remote repository.
  582. Args:
  583. path: Repository path (as bytestring)
  584. update_refs: Function to determine changes to remote refs. Receive
  585. dict with existing remote refs, returns dict with
  586. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  587. generate_pack_data: Function that can return a tuple
  588. with number of objects and list of pack data to include
  589. progress: Optional progress function
  590. Returns:
  591. SendPackResult object
  592. Raises:
  593. SendPackError: if server rejects the pack data
  594. """
  595. raise NotImplementedError(self.send_pack)
  596. def clone(
  597. self,
  598. path,
  599. target_path,
  600. mkdir: bool = True,
  601. bare: bool = False,
  602. origin: Optional[str] = "origin",
  603. checkout=None,
  604. branch=None,
  605. progress=None,
  606. depth=None,
  607. ) -> Repo:
  608. """Clone a repository."""
  609. from .refs import _set_default_branch, _set_head, _set_origin_head
  610. if mkdir:
  611. os.mkdir(target_path)
  612. try:
  613. target = None
  614. if not bare:
  615. target = Repo.init(target_path)
  616. if checkout is None:
  617. checkout = True
  618. else:
  619. if checkout:
  620. raise ValueError("checkout and bare are incompatible")
  621. target = Repo.init_bare(target_path)
  622. # TODO(jelmer): abstract method for get_location?
  623. if isinstance(self, (LocalGitClient, SubprocessGitClient)):
  624. encoded_path = path.encode("utf-8")
  625. else:
  626. encoded_path = self.get_url(path).encode("utf-8")
  627. assert target is not None
  628. if origin is not None:
  629. target_config = target.get_config()
  630. target_config.set(
  631. (b"remote", origin.encode("utf-8")), b"url", encoded_path
  632. )
  633. target_config.set(
  634. (b"remote", origin.encode("utf-8")),
  635. b"fetch",
  636. b"+refs/heads/*:refs/remotes/" + origin.encode("utf-8") + b"/*",
  637. )
  638. target_config.write_to_path()
  639. ref_message = b"clone: from " + encoded_path
  640. result = self.fetch(path, target, progress=progress, depth=depth)
  641. if origin is not None:
  642. _import_remote_refs(
  643. target.refs, origin, result.refs, message=ref_message
  644. )
  645. origin_head = result.symrefs.get(b"HEAD")
  646. origin_sha = result.refs.get(b"HEAD")
  647. if origin is None or (origin_sha and not origin_head):
  648. # set detached HEAD
  649. target.refs[b"HEAD"] = origin_sha
  650. head = origin_sha
  651. else:
  652. _set_origin_head(target.refs, origin.encode("utf-8"), origin_head)
  653. head_ref = _set_default_branch(
  654. target.refs,
  655. origin.encode("utf-8"),
  656. origin_head,
  657. branch,
  658. ref_message,
  659. )
  660. # Update target head
  661. if head_ref:
  662. head = _set_head(target.refs, head_ref, ref_message)
  663. else:
  664. head = None
  665. if checkout and head is not None:
  666. target.reset_index()
  667. except BaseException:
  668. if target is not None:
  669. target.close()
  670. if mkdir:
  671. import shutil
  672. shutil.rmtree(target_path)
  673. raise
  674. return target
  675. def fetch(
  676. self,
  677. path: str,
  678. target: Repo,
  679. determine_wants: Optional[
  680. Callable[[Dict[bytes, bytes], Optional[int]], List[bytes]]
  681. ] = None,
  682. progress: Optional[Callable[[bytes], None]] = None,
  683. depth: Optional[int] = None,
  684. ) -> FetchPackResult:
  685. """Fetch into a target repository.
  686. Args:
  687. path: Path to fetch from (as bytestring)
  688. target: Target repository to fetch into
  689. determine_wants: Optional function to determine what refs to fetch.
  690. Receives dictionary of name->sha, should return
  691. list of shas to fetch. Defaults to all shas.
  692. progress: Optional progress function
  693. depth: Depth to fetch at
  694. Returns:
  695. Dictionary with all remote refs (not just those fetched)
  696. """
  697. if determine_wants is None:
  698. determine_wants = target.object_store.determine_wants_all
  699. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  700. from tempfile import SpooledTemporaryFile
  701. f: IO[bytes] = SpooledTemporaryFile(
  702. max_size=PACK_SPOOL_FILE_MAX_SIZE,
  703. prefix="incoming-",
  704. dir=getattr(target.object_store, "path", None),
  705. )
  706. def commit():
  707. if f.tell():
  708. f.seek(0)
  709. target.object_store.add_thin_pack(f.read, None, progress=progress)
  710. f.close()
  711. def abort():
  712. f.close()
  713. else:
  714. f, commit, abort = target.object_store.add_pack()
  715. try:
  716. result = self.fetch_pack(
  717. path,
  718. determine_wants,
  719. target.get_graph_walker(),
  720. f.write,
  721. progress=progress,
  722. depth=depth,
  723. )
  724. except BaseException:
  725. abort()
  726. raise
  727. else:
  728. commit()
  729. target.update_shallow(result.new_shallow, result.new_unshallow)
  730. return result
  731. def fetch_pack(
  732. self,
  733. path: str,
  734. determine_wants,
  735. graph_walker,
  736. pack_data,
  737. *,
  738. progress: Optional[Callable[[bytes], None]] = None,
  739. depth: Optional[int] = None,
  740. ):
  741. """Retrieve a pack from a git smart server.
  742. Args:
  743. path: Remote path to fetch from
  744. determine_wants: Function determine what refs
  745. to fetch. Receives dictionary of name->sha, should return
  746. list of shas to fetch.
  747. graph_walker: Object with next() and ack().
  748. pack_data: Callback called for each bit of data in the pack
  749. progress: Callback for progress reports (strings)
  750. depth: Shallow fetch depth
  751. Returns:
  752. FetchPackResult object
  753. """
  754. raise NotImplementedError(self.fetch_pack)
  755. def get_refs(self, path):
  756. """Retrieve the current refs from a git smart server.
  757. Args:
  758. path: Path to the repo to fetch from. (as bytestring)
  759. """
  760. raise NotImplementedError(self.get_refs)
  761. @staticmethod
  762. def _should_send_pack(new_refs):
  763. # The packfile MUST NOT be sent if the only command used is delete.
  764. return any(sha != ZERO_SHA for sha in new_refs.values())
  765. def _negotiate_receive_pack_capabilities(self, server_capabilities):
  766. negotiated_capabilities = self._send_capabilities & server_capabilities
  767. agent = None
  768. for capability in server_capabilities:
  769. k, v = parse_capability(capability)
  770. if k == CAPABILITY_AGENT:
  771. agent = v
  772. (extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES)
  773. # TODO(jelmer): warn about unknown capabilities
  774. return negotiated_capabilities, agent
  775. def _handle_receive_pack_tail(
  776. self,
  777. proto: Protocol,
  778. capabilities: Set[bytes],
  779. progress: Optional[Callable[[bytes], None]] = None,
  780. ) -> Optional[Dict[bytes, Optional[str]]]:
  781. """Handle the tail of a 'git-receive-pack' request.
  782. Args:
  783. proto: Protocol object to read from
  784. capabilities: List of negotiated capabilities
  785. progress: Optional progress reporting function
  786. Returns:
  787. dict mapping ref name to:
  788. error message if the ref failed to update
  789. None if it was updated successfully
  790. """
  791. if CAPABILITY_SIDE_BAND_64K in capabilities:
  792. if progress is None:
  793. def progress(x):
  794. pass
  795. if CAPABILITY_REPORT_STATUS in capabilities:
  796. assert self._report_status_parser is not None
  797. pktline_parser = PktLineParser(self._report_status_parser.handle_packet)
  798. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  799. if chan == SIDE_BAND_CHANNEL_DATA:
  800. if CAPABILITY_REPORT_STATUS in capabilities:
  801. pktline_parser.parse(data)
  802. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  803. progress(data)
  804. else:
  805. raise AssertionError("Invalid sideband channel %d" % chan)
  806. else:
  807. if CAPABILITY_REPORT_STATUS in capabilities:
  808. assert self._report_status_parser
  809. for pkt in proto.read_pkt_seq():
  810. self._report_status_parser.handle_packet(pkt)
  811. if self._report_status_parser is not None:
  812. return dict(self._report_status_parser.check())
  813. return None
  814. def _negotiate_upload_pack_capabilities(self, server_capabilities):
  815. (extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES)
  816. # TODO(jelmer): warn about unknown capabilities
  817. symrefs = {}
  818. agent = None
  819. for capability in server_capabilities:
  820. k, v = parse_capability(capability)
  821. if k == CAPABILITY_SYMREF:
  822. (src, dst) = v.split(b":", 1)
  823. symrefs[src] = dst
  824. if k == CAPABILITY_AGENT:
  825. agent = v
  826. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  827. return (negotiated_capabilities, symrefs, agent)
  828. def archive(
  829. self,
  830. path,
  831. committish,
  832. write_data,
  833. progress=None,
  834. write_error=None,
  835. format=None,
  836. subdirs=None,
  837. prefix=None,
  838. ):
  839. """Retrieve an archive of the specified tree."""
  840. raise NotImplementedError(self.archive)
  841. def check_wants(wants, refs):
  842. """Check that a set of wants is valid.
  843. Args:
  844. wants: Set of object SHAs to fetch
  845. refs: Refs dictionary to check against
  846. """
  847. missing = set(wants) - {
  848. v for (k, v) in refs.items() if not k.endswith(PEELED_TAG_SUFFIX)
  849. }
  850. if missing:
  851. raise InvalidWants(missing)
  852. def _remote_error_from_stderr(stderr):
  853. if stderr is None:
  854. return HangupException()
  855. lines = [line.rstrip(b"\n") for line in stderr.readlines()]
  856. for line in lines:
  857. if line.startswith(b"ERROR: "):
  858. return GitProtocolError(line[len(b"ERROR: ") :].decode("utf-8", "replace"))
  859. return HangupException(lines)
  860. class TraditionalGitClient(GitClient):
  861. """Traditional Git client."""
  862. DEFAULT_ENCODING = "utf-8"
  863. def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs) -> None:
  864. self._remote_path_encoding = path_encoding
  865. super().__init__(**kwargs)
  866. async def _connect(self, cmd, path):
  867. """Create a connection to the server.
  868. This method is abstract - concrete implementations should
  869. implement their own variant which connects to the server and
  870. returns an initialized Protocol object with the service ready
  871. for use and a can_read function which may be used to see if
  872. reads would block.
  873. Args:
  874. cmd: The git service name to which we should connect.
  875. path: The path we should pass to the service. (as bytestirng)
  876. """
  877. raise NotImplementedError
  878. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  879. """Upload a pack to a remote repository.
  880. Args:
  881. path: Repository path (as bytestring)
  882. update_refs: Function to determine changes to remote refs.
  883. Receive dict with existing remote refs, returns dict with
  884. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  885. generate_pack_data: Function that can return a tuple with
  886. number of objects and pack data to upload.
  887. progress: Optional callback called with progress updates
  888. Returns:
  889. SendPackResult
  890. Raises:
  891. SendPackError: if server rejects the pack data
  892. """
  893. proto, unused_can_read, stderr = self._connect(b"receive-pack", path)
  894. with proto:
  895. try:
  896. old_refs, server_capabilities = read_pkt_refs(proto.read_pkt_seq())
  897. except HangupException as exc:
  898. raise _remote_error_from_stderr(stderr) from exc
  899. (
  900. negotiated_capabilities,
  901. agent,
  902. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  903. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  904. self._report_status_parser = ReportStatusParser()
  905. report_status_parser = self._report_status_parser
  906. try:
  907. new_refs = orig_new_refs = update_refs(dict(old_refs))
  908. except BaseException:
  909. proto.write_pkt_line(None)
  910. raise
  911. if set(new_refs.items()).issubset(set(old_refs.items())):
  912. proto.write_pkt_line(None)
  913. return SendPackResult(new_refs, agent=agent, ref_status={})
  914. if CAPABILITY_DELETE_REFS not in server_capabilities:
  915. # Server does not support deletions. Fail later.
  916. new_refs = dict(orig_new_refs)
  917. for ref, sha in orig_new_refs.items():
  918. if sha == ZERO_SHA:
  919. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  920. report_status_parser._ref_statuses.append(
  921. b"ng " + ref + b" remote does not support deleting refs"
  922. )
  923. report_status_parser._ref_status_ok = False
  924. del new_refs[ref]
  925. if new_refs is None:
  926. proto.write_pkt_line(None)
  927. return SendPackResult(old_refs, agent=agent, ref_status={})
  928. if len(new_refs) == 0 and orig_new_refs:
  929. # NOOP - Original new refs filtered out by policy
  930. proto.write_pkt_line(None)
  931. if report_status_parser is not None:
  932. ref_status = dict(report_status_parser.check())
  933. else:
  934. ref_status = None
  935. return SendPackResult(old_refs, agent=agent, ref_status=ref_status)
  936. header_handler = _v1ReceivePackHeader(
  937. negotiated_capabilities, old_refs, new_refs
  938. )
  939. for pkt in header_handler:
  940. proto.write_pkt_line(pkt)
  941. pack_data_count, pack_data = generate_pack_data(
  942. header_handler.have,
  943. header_handler.want,
  944. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  945. progress=progress,
  946. )
  947. if self._should_send_pack(new_refs):
  948. for chunk in PackChunkGenerator(
  949. pack_data_count, pack_data, progress=progress
  950. ):
  951. proto.write(chunk)
  952. ref_status = self._handle_receive_pack_tail(
  953. proto, negotiated_capabilities, progress
  954. )
  955. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  956. def fetch_pack(
  957. self,
  958. path,
  959. determine_wants,
  960. graph_walker,
  961. pack_data,
  962. progress=None,
  963. depth=None,
  964. ):
  965. """Retrieve a pack from a git smart server.
  966. Args:
  967. path: Remote path to fetch from
  968. determine_wants: Function determine what refs
  969. to fetch. Receives dictionary of name->sha, should return
  970. list of shas to fetch.
  971. graph_walker: Object with next() and ack().
  972. pack_data: Callback called for each bit of data in the pack
  973. progress: Callback for progress reports (strings)
  974. depth: Shallow fetch depth
  975. Returns:
  976. FetchPackResult object
  977. """
  978. proto, can_read, stderr = self._connect(b"upload-pack", path)
  979. with proto:
  980. try:
  981. refs, server_capabilities = read_pkt_refs(proto.read_pkt_seq())
  982. except HangupException as exc:
  983. raise _remote_error_from_stderr(stderr) from exc
  984. (
  985. negotiated_capabilities,
  986. symrefs,
  987. agent,
  988. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  989. if refs is None:
  990. proto.write_pkt_line(None)
  991. return FetchPackResult(refs, symrefs, agent)
  992. try:
  993. if depth is not None:
  994. wants = determine_wants(refs, depth=depth)
  995. else:
  996. wants = determine_wants(refs)
  997. except BaseException:
  998. proto.write_pkt_line(None)
  999. raise
  1000. if wants is not None:
  1001. wants = [cid for cid in wants if cid != ZERO_SHA]
  1002. if not wants:
  1003. proto.write_pkt_line(None)
  1004. return FetchPackResult(refs, symrefs, agent)
  1005. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  1006. proto,
  1007. negotiated_capabilities,
  1008. graph_walker,
  1009. wants,
  1010. can_read,
  1011. depth=depth,
  1012. )
  1013. _handle_upload_pack_tail(
  1014. proto,
  1015. negotiated_capabilities,
  1016. graph_walker,
  1017. pack_data,
  1018. progress,
  1019. )
  1020. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  1021. def get_refs(self, path):
  1022. """Retrieve the current refs from a git smart server."""
  1023. # stock `git ls-remote` uses upload-pack
  1024. proto, _, stderr = self._connect(b"upload-pack", path)
  1025. with proto:
  1026. try:
  1027. refs, _ = read_pkt_refs(proto.read_pkt_seq())
  1028. except HangupException as exc:
  1029. raise _remote_error_from_stderr(stderr) from exc
  1030. proto.write_pkt_line(None)
  1031. return refs
  1032. def archive(
  1033. self,
  1034. path,
  1035. committish,
  1036. write_data,
  1037. progress=None,
  1038. write_error=None,
  1039. format=None,
  1040. subdirs=None,
  1041. prefix=None,
  1042. ):
  1043. proto, can_read, stderr = self._connect(b"upload-archive", path)
  1044. with proto:
  1045. if format is not None:
  1046. proto.write_pkt_line(b"argument --format=" + format)
  1047. proto.write_pkt_line(b"argument " + committish)
  1048. if subdirs is not None:
  1049. for subdir in subdirs:
  1050. proto.write_pkt_line(b"argument " + subdir)
  1051. if prefix is not None:
  1052. proto.write_pkt_line(b"argument --prefix=" + prefix)
  1053. proto.write_pkt_line(None)
  1054. try:
  1055. pkt = proto.read_pkt_line()
  1056. except HangupException as exc:
  1057. raise _remote_error_from_stderr(stderr) from exc
  1058. if pkt == b"NACK\n" or pkt == b"NACK":
  1059. return
  1060. elif pkt == b"ACK\n" or pkt == b"ACK":
  1061. pass
  1062. elif pkt.startswith(b"ERR "):
  1063. raise GitProtocolError(pkt[4:].rstrip(b"\n").decode("utf-8", "replace"))
  1064. else:
  1065. raise AssertionError(f"invalid response {pkt!r}")
  1066. ret = proto.read_pkt_line()
  1067. if ret is not None:
  1068. raise AssertionError("expected pkt tail")
  1069. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  1070. if chan == SIDE_BAND_CHANNEL_DATA:
  1071. write_data(data)
  1072. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  1073. progress(data)
  1074. elif chan == SIDE_BAND_CHANNEL_FATAL:
  1075. write_error(data)
  1076. else:
  1077. raise AssertionError("Invalid sideband channel %d" % chan)
  1078. class TCPGitClient(TraditionalGitClient):
  1079. """A Git Client that works over TCP directly (i.e. git://)."""
  1080. def __init__(self, host, port=None, **kwargs) -> None:
  1081. if port is None:
  1082. port = TCP_GIT_PORT
  1083. self._host = host
  1084. self._port = port
  1085. super().__init__(**kwargs)
  1086. @classmethod
  1087. def from_parsedurl(cls, parsedurl, **kwargs):
  1088. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  1089. def get_url(self, path):
  1090. netloc = self._host
  1091. if self._port is not None and self._port != TCP_GIT_PORT:
  1092. netloc += ":%d" % self._port
  1093. return urlunsplit(("git", netloc, path, "", ""))
  1094. def _connect(self, cmd, path):
  1095. if not isinstance(cmd, bytes):
  1096. raise TypeError(cmd)
  1097. if not isinstance(path, bytes):
  1098. path = path.encode(self._remote_path_encoding)
  1099. sockaddrs = socket.getaddrinfo(
  1100. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM
  1101. )
  1102. s = None
  1103. err = OSError(f"no address found for {self._host}")
  1104. for family, socktype, proto, canonname, sockaddr in sockaddrs:
  1105. s = socket.socket(family, socktype, proto)
  1106. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  1107. try:
  1108. s.connect(sockaddr)
  1109. break
  1110. except OSError as e:
  1111. err = e
  1112. if s is not None:
  1113. s.close()
  1114. s = None
  1115. if s is None:
  1116. raise err
  1117. # -1 means system default buffering
  1118. rfile = s.makefile("rb", -1)
  1119. # 0 means unbuffered
  1120. wfile = s.makefile("wb", 0)
  1121. def close():
  1122. rfile.close()
  1123. wfile.close()
  1124. s.close()
  1125. proto = Protocol(
  1126. rfile.read,
  1127. wfile.write,
  1128. close,
  1129. report_activity=self._report_activity,
  1130. )
  1131. if path.startswith(b"/~"):
  1132. path = path[1:]
  1133. # TODO(jelmer): Alternative to ascii?
  1134. proto.send_cmd(b"git-" + cmd, path, b"host=" + self._host.encode("ascii"))
  1135. return proto, lambda: _fileno_can_read(s), None
  1136. class SubprocessWrapper:
  1137. """A socket-like object that talks to a subprocess via pipes."""
  1138. def __init__(self, proc) -> None:
  1139. self.proc = proc
  1140. self.read = BufferedReader(proc.stdout).read
  1141. self.write = proc.stdin.write
  1142. @property
  1143. def stderr(self):
  1144. return self.proc.stderr
  1145. def can_read(self):
  1146. if sys.platform == "win32":
  1147. from msvcrt import get_osfhandle
  1148. handle = get_osfhandle(self.proc.stdout.fileno())
  1149. return _win32_peek_avail(handle) != 0
  1150. else:
  1151. return _fileno_can_read(self.proc.stdout.fileno())
  1152. def close(self):
  1153. self.proc.stdin.close()
  1154. self.proc.stdout.close()
  1155. if self.proc.stderr:
  1156. self.proc.stderr.close()
  1157. self.proc.wait()
  1158. def find_git_command() -> List[str]:
  1159. """Find command to run for system Git (usually C Git)."""
  1160. if sys.platform == "win32": # support .exe, .bat and .cmd
  1161. try: # to avoid overhead
  1162. import pywintypes
  1163. import win32api
  1164. except ImportError: # run through cmd.exe with some overhead
  1165. return ["cmd", "/c", "git"]
  1166. else:
  1167. try:
  1168. status, git = win32api.FindExecutable("git")
  1169. return [git]
  1170. except pywintypes.error:
  1171. return ["cmd", "/c", "git"]
  1172. else:
  1173. return ["git"]
  1174. class SubprocessGitClient(TraditionalGitClient):
  1175. """Git client that talks to a server using a subprocess."""
  1176. @classmethod
  1177. def from_parsedurl(cls, parsedurl, **kwargs):
  1178. return cls(**kwargs)
  1179. git_command = None
  1180. def _connect(self, service, path):
  1181. if not isinstance(service, bytes):
  1182. raise TypeError(service)
  1183. if isinstance(path, bytes):
  1184. path = path.decode(self._remote_path_encoding)
  1185. if self.git_command is None:
  1186. git_command = find_git_command()
  1187. argv = [*git_command, service.decode("ascii"), path]
  1188. p = subprocess.Popen(
  1189. argv,
  1190. bufsize=0,
  1191. stdin=subprocess.PIPE,
  1192. stdout=subprocess.PIPE,
  1193. stderr=subprocess.PIPE,
  1194. )
  1195. pw = SubprocessWrapper(p)
  1196. return (
  1197. Protocol(
  1198. pw.read,
  1199. pw.write,
  1200. pw.close,
  1201. report_activity=self._report_activity,
  1202. ),
  1203. pw.can_read,
  1204. p.stderr,
  1205. )
  1206. class LocalGitClient(GitClient):
  1207. """Git Client that just uses a local on-disk repository."""
  1208. def __init__(
  1209. self, thin_packs=True, report_activity=None, config: Optional[Config] = None
  1210. ) -> None:
  1211. """Create a new LocalGitClient instance.
  1212. Args:
  1213. thin_packs: Whether or not thin packs should be retrieved
  1214. report_activity: Optional callback for reporting transport
  1215. activity.
  1216. """
  1217. self._report_activity = report_activity
  1218. # Ignore the thin_packs argument
  1219. def get_url(self, path):
  1220. return urlunsplit(("file", "", path, "", ""))
  1221. @classmethod
  1222. def from_parsedurl(cls, parsedurl, **kwargs):
  1223. return cls(**kwargs)
  1224. @classmethod
  1225. def _open_repo(cls, path):
  1226. if not isinstance(path, str):
  1227. path = os.fsdecode(path)
  1228. return closing(Repo(path))
  1229. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1230. """Upload a pack to a local on-disk repository.
  1231. Args:
  1232. path: Repository path (as bytestring)
  1233. update_refs: Function to determine changes to remote refs.
  1234. Receive dict with existing remote refs, returns dict with
  1235. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1236. with number of items and pack data to upload.
  1237. progress: Optional progress function
  1238. Returns:
  1239. SendPackResult
  1240. Raises:
  1241. SendPackError: if server rejects the pack data
  1242. """
  1243. if not progress:
  1244. def progress(x):
  1245. pass
  1246. with self._open_repo(path) as target:
  1247. old_refs = target.get_refs()
  1248. new_refs = update_refs(dict(old_refs))
  1249. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  1250. want = []
  1251. for refname, new_sha1 in new_refs.items():
  1252. if (
  1253. new_sha1 not in have
  1254. and new_sha1 not in want
  1255. and new_sha1 != ZERO_SHA
  1256. ):
  1257. want.append(new_sha1)
  1258. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1259. return SendPackResult(new_refs, ref_status={})
  1260. target.object_store.add_pack_data(
  1261. *generate_pack_data(have, want, ofs_delta=True)
  1262. )
  1263. ref_status = {}
  1264. for refname, new_sha1 in new_refs.items():
  1265. old_sha1 = old_refs.get(refname, ZERO_SHA)
  1266. if new_sha1 != ZERO_SHA:
  1267. if not target.refs.set_if_equals(refname, old_sha1, new_sha1):
  1268. msg = f"unable to set {refname} to {new_sha1}"
  1269. progress(msg)
  1270. ref_status[refname] = msg
  1271. else:
  1272. if not target.refs.remove_if_equals(refname, old_sha1):
  1273. progress(f"unable to remove {refname}")
  1274. ref_status[refname] = "unable to remove"
  1275. return SendPackResult(new_refs, ref_status=ref_status)
  1276. def fetch(self, path, target, determine_wants=None, progress=None, depth=None):
  1277. """Fetch into a target repository.
  1278. Args:
  1279. path: Path to fetch from (as bytestring)
  1280. target: Target repository to fetch into
  1281. determine_wants: Optional function determine what refs
  1282. to fetch. Receives dictionary of name->sha, should return
  1283. list of shas to fetch. Defaults to all shas.
  1284. progress: Optional progress function
  1285. depth: Shallow fetch depth
  1286. Returns:
  1287. FetchPackResult object
  1288. """
  1289. with self._open_repo(path) as r:
  1290. refs = r.fetch(
  1291. target,
  1292. determine_wants=determine_wants,
  1293. progress=progress,
  1294. depth=depth,
  1295. )
  1296. return FetchPackResult(refs, r.refs.get_symrefs(), agent_string())
  1297. def fetch_pack(
  1298. self,
  1299. path,
  1300. determine_wants,
  1301. graph_walker,
  1302. pack_data,
  1303. progress=None,
  1304. depth=None,
  1305. ) -> FetchPackResult:
  1306. """Retrieve a pack from a local on-disk repository.
  1307. Args:
  1308. path: Remote path to fetch from
  1309. determine_wants: Function determine what refs
  1310. to fetch. Receives dictionary of name->sha, should return
  1311. list of shas to fetch.
  1312. graph_walker: Object with next() and ack().
  1313. pack_data: Callback called for each bit of data in the pack
  1314. progress: Callback for progress reports (strings)
  1315. depth: Shallow fetch depth
  1316. Returns:
  1317. FetchPackResult object
  1318. """
  1319. with self._open_repo(path) as r:
  1320. missing_objects = r.find_missing_objects(
  1321. determine_wants, graph_walker, progress=progress, depth=depth
  1322. )
  1323. other_haves = missing_objects.get_remote_has()
  1324. object_ids = list(missing_objects)
  1325. symrefs = r.refs.get_symrefs()
  1326. agent = agent_string()
  1327. # Did the process short-circuit (e.g. in a stateless RPC call)?
  1328. # Note that the client still expects a 0-object pack in most cases.
  1329. if object_ids is None:
  1330. return FetchPackResult(None, symrefs, agent)
  1331. write_pack_from_container(
  1332. pack_data, r.object_store, object_ids, other_haves=other_haves
  1333. )
  1334. return FetchPackResult(r.get_refs(), symrefs, agent)
  1335. def get_refs(self, path):
  1336. """Retrieve the current refs from a local on-disk repository."""
  1337. with self._open_repo(path) as target:
  1338. return target.get_refs()
  1339. # What Git client to use for local access
  1340. default_local_git_client_cls = LocalGitClient
  1341. class SSHVendor:
  1342. """A client side SSH implementation."""
  1343. def run_command(
  1344. self,
  1345. host,
  1346. command,
  1347. username=None,
  1348. port=None,
  1349. password=None,
  1350. key_filename=None,
  1351. ssh_command=None,
  1352. ):
  1353. """Connect to an SSH server.
  1354. Run a command remotely and return a file-like object for interaction
  1355. with the remote command.
  1356. Args:
  1357. host: Host name
  1358. command: Command to run (as argv array)
  1359. username: Optional ame of user to log in as
  1360. port: Optional SSH port to use
  1361. password: Optional ssh password for login or private key
  1362. key_filename: Optional path to private keyfile
  1363. ssh_command: Optional SSH command
  1364. """
  1365. raise NotImplementedError(self.run_command)
  1366. class StrangeHostname(Exception):
  1367. """Refusing to connect to strange SSH hostname."""
  1368. def __init__(self, hostname) -> None:
  1369. super().__init__(hostname)
  1370. class SubprocessSSHVendor(SSHVendor):
  1371. """SSH vendor that shells out to the local 'ssh' command."""
  1372. def run_command(
  1373. self,
  1374. host,
  1375. command,
  1376. username=None,
  1377. port=None,
  1378. password=None,
  1379. key_filename=None,
  1380. ssh_command=None,
  1381. ):
  1382. if password is not None:
  1383. raise NotImplementedError(
  1384. "Setting password not supported by SubprocessSSHVendor."
  1385. )
  1386. if ssh_command:
  1387. import shlex
  1388. args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-x"]
  1389. else:
  1390. args = ["ssh", "-x"]
  1391. if port:
  1392. args.extend(["-p", str(port)])
  1393. if key_filename:
  1394. args.extend(["-i", str(key_filename)])
  1395. if username:
  1396. host = f"{username}@{host}"
  1397. if host.startswith("-"):
  1398. raise StrangeHostname(hostname=host)
  1399. args.append(host)
  1400. proc = subprocess.Popen(
  1401. [*args, command],
  1402. bufsize=0,
  1403. stdin=subprocess.PIPE,
  1404. stdout=subprocess.PIPE,
  1405. stderr=subprocess.PIPE,
  1406. )
  1407. return SubprocessWrapper(proc)
  1408. class PLinkSSHVendor(SSHVendor):
  1409. """SSH vendor that shells out to the local 'plink' command."""
  1410. def run_command(
  1411. self,
  1412. host,
  1413. command,
  1414. username=None,
  1415. port=None,
  1416. password=None,
  1417. key_filename=None,
  1418. ssh_command=None,
  1419. ):
  1420. if ssh_command:
  1421. import shlex
  1422. args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-ssh"]
  1423. elif sys.platform == "win32":
  1424. args = ["plink.exe", "-ssh"]
  1425. else:
  1426. args = ["plink", "-ssh"]
  1427. if password is not None:
  1428. import warnings
  1429. warnings.warn(
  1430. "Invoking PLink with a password exposes the password in the "
  1431. "process list."
  1432. )
  1433. args.extend(["-pw", str(password)])
  1434. if port:
  1435. args.extend(["-P", str(port)])
  1436. if key_filename:
  1437. args.extend(["-i", str(key_filename)])
  1438. if username:
  1439. host = f"{username}@{host}"
  1440. if host.startswith("-"):
  1441. raise StrangeHostname(hostname=host)
  1442. args.append(host)
  1443. proc = subprocess.Popen(
  1444. [*args, command],
  1445. bufsize=0,
  1446. stdin=subprocess.PIPE,
  1447. stdout=subprocess.PIPE,
  1448. stderr=subprocess.PIPE,
  1449. )
  1450. return SubprocessWrapper(proc)
  1451. def ParamikoSSHVendor(**kwargs):
  1452. import warnings
  1453. warnings.warn(
  1454. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  1455. DeprecationWarning,
  1456. )
  1457. from .contrib.paramiko_vendor import ParamikoSSHVendor
  1458. return ParamikoSSHVendor(**kwargs)
  1459. # Can be overridden by users
  1460. get_ssh_vendor = SubprocessSSHVendor
  1461. class SSHGitClient(TraditionalGitClient):
  1462. def __init__(
  1463. self,
  1464. host,
  1465. port=None,
  1466. username=None,
  1467. vendor=None,
  1468. config=None,
  1469. password=None,
  1470. key_filename=None,
  1471. ssh_command=None,
  1472. **kwargs,
  1473. ) -> None:
  1474. self.host = host
  1475. self.port = port
  1476. self.username = username
  1477. self.password = password
  1478. self.key_filename = key_filename
  1479. self.ssh_command = ssh_command or os.environ.get(
  1480. "GIT_SSH_COMMAND", os.environ.get("GIT_SSH")
  1481. )
  1482. super().__init__(**kwargs)
  1483. self.alternative_paths: Dict[bytes, bytes] = {}
  1484. if vendor is not None:
  1485. self.ssh_vendor = vendor
  1486. else:
  1487. self.ssh_vendor = get_ssh_vendor()
  1488. def get_url(self, path):
  1489. netloc = self.host
  1490. if self.port is not None:
  1491. netloc += ":%d" % self.port
  1492. if self.username is not None:
  1493. netloc = urlquote(self.username, "@/:") + "@" + netloc
  1494. return urlunsplit(("ssh", netloc, path, "", ""))
  1495. @classmethod
  1496. def from_parsedurl(cls, parsedurl, **kwargs):
  1497. return cls(
  1498. host=parsedurl.hostname,
  1499. port=parsedurl.port,
  1500. username=parsedurl.username,
  1501. **kwargs,
  1502. )
  1503. def _get_cmd_path(self, cmd):
  1504. cmd = self.alternative_paths.get(cmd, b"git-" + cmd)
  1505. assert isinstance(cmd, bytes)
  1506. return cmd
  1507. def _connect(self, cmd, path):
  1508. if not isinstance(cmd, bytes):
  1509. raise TypeError(cmd)
  1510. if isinstance(path, bytes):
  1511. path = path.decode(self._remote_path_encoding)
  1512. if path.startswith("/~"):
  1513. path = path[1:]
  1514. argv = (
  1515. self._get_cmd_path(cmd).decode(self._remote_path_encoding)
  1516. + " '"
  1517. + path
  1518. + "'"
  1519. )
  1520. kwargs = {}
  1521. if self.password is not None:
  1522. kwargs["password"] = self.password
  1523. if self.key_filename is not None:
  1524. kwargs["key_filename"] = self.key_filename
  1525. # GIT_SSH_COMMAND takes precedence over GIT_SSH
  1526. if self.ssh_command is not None:
  1527. kwargs["ssh_command"] = self.ssh_command
  1528. con = self.ssh_vendor.run_command(
  1529. self.host, argv, port=self.port, username=self.username, **kwargs
  1530. )
  1531. return (
  1532. Protocol(
  1533. con.read,
  1534. con.write,
  1535. con.close,
  1536. report_activity=self._report_activity,
  1537. ),
  1538. con.can_read,
  1539. getattr(con, "stderr", None),
  1540. )
  1541. def default_user_agent_string():
  1542. # Start user agent with "git/", because GitHub requires this. :-( See
  1543. # https://github.com/jelmer/dulwich/issues/562 for details.
  1544. return "git/dulwich/{}".format(".".join([str(x) for x in dulwich.__version__]))
  1545. def default_urllib3_manager(
  1546. config,
  1547. pool_manager_cls=None,
  1548. proxy_manager_cls=None,
  1549. base_url=None,
  1550. **override_kwargs,
  1551. ) -> Union["urllib3.ProxyManager", "urllib3.PoolManager"]:
  1552. """Return urllib3 connection pool manager.
  1553. Honour detected proxy configurations.
  1554. Args:
  1555. config: `dulwich.config.ConfigDict` instance with Git configuration.
  1556. override_kwargs: Additional arguments for `urllib3.ProxyManager`
  1557. Returns:
  1558. Either pool_manager_cls (defaults to `urllib3.ProxyManager`) instance for
  1559. proxy configurations, proxy_manager_cls
  1560. (defaults to `urllib3.PoolManager`) instance otherwise
  1561. """
  1562. proxy_server = user_agent = None
  1563. ca_certs = ssl_verify = None
  1564. if proxy_server is None:
  1565. for proxyname in ("https_proxy", "http_proxy", "all_proxy"):
  1566. proxy_server = os.environ.get(proxyname)
  1567. if proxy_server:
  1568. break
  1569. if proxy_server:
  1570. if check_for_proxy_bypass(base_url):
  1571. proxy_server = None
  1572. if config is not None:
  1573. if proxy_server is None:
  1574. try:
  1575. proxy_server = config.get(b"http", b"proxy")
  1576. except KeyError:
  1577. pass
  1578. try:
  1579. user_agent = config.get(b"http", b"useragent")
  1580. except KeyError:
  1581. pass
  1582. # TODO(jelmer): Support per-host settings
  1583. try:
  1584. ssl_verify = config.get_boolean(b"http", b"sslVerify")
  1585. except KeyError:
  1586. ssl_verify = True
  1587. try:
  1588. ca_certs = config.get(b"http", b"sslCAInfo")
  1589. except KeyError:
  1590. ca_certs = None
  1591. if user_agent is None:
  1592. user_agent = default_user_agent_string()
  1593. headers = {"User-agent": user_agent}
  1594. kwargs = {
  1595. "ca_certs": ca_certs,
  1596. }
  1597. if ssl_verify is True:
  1598. kwargs["cert_reqs"] = "CERT_REQUIRED"
  1599. elif ssl_verify is False:
  1600. kwargs["cert_reqs"] = "CERT_NONE"
  1601. else:
  1602. # Default to SSL verification
  1603. kwargs["cert_reqs"] = "CERT_REQUIRED"
  1604. kwargs.update(override_kwargs)
  1605. import urllib3
  1606. if proxy_server is not None:
  1607. if proxy_manager_cls is None:
  1608. proxy_manager_cls = urllib3.ProxyManager
  1609. if not isinstance(proxy_server, str):
  1610. proxy_server = proxy_server.decode()
  1611. proxy_server_url = urlparse(proxy_server)
  1612. if proxy_server_url.username is not None:
  1613. proxy_headers = urllib3.make_headers(
  1614. proxy_basic_auth=f"{proxy_server_url.username}:{proxy_server_url.password or ''}" # type: ignore
  1615. )
  1616. else:
  1617. proxy_headers = {}
  1618. manager = proxy_manager_cls(
  1619. proxy_server, proxy_headers=proxy_headers, headers=headers, **kwargs
  1620. )
  1621. else:
  1622. if pool_manager_cls is None:
  1623. pool_manager_cls = urllib3.PoolManager
  1624. manager = pool_manager_cls(headers=headers, **kwargs)
  1625. return manager
  1626. def check_for_proxy_bypass(base_url):
  1627. # Check if a proxy bypass is defined with the no_proxy environment variable
  1628. if base_url: # only check if base_url is provided
  1629. no_proxy_str = os.environ.get("no_proxy")
  1630. if no_proxy_str:
  1631. # implementation based on curl behavior: https://curl.se/libcurl/c/CURLOPT_NOPROXY.html
  1632. # get hostname of provided parsed url
  1633. parsed_url = urlparse(base_url)
  1634. hostname = parsed_url.hostname
  1635. if hostname:
  1636. import ipaddress
  1637. # check if hostname is an ip address
  1638. try:
  1639. hostname_ip = ipaddress.ip_address(hostname)
  1640. except ValueError:
  1641. hostname_ip = None
  1642. no_proxy_values = no_proxy_str.split(",")
  1643. for no_proxy_value in no_proxy_values:
  1644. no_proxy_value = no_proxy_value.strip()
  1645. if no_proxy_value:
  1646. no_proxy_value = no_proxy_value.lower()
  1647. no_proxy_value = no_proxy_value.lstrip(
  1648. "."
  1649. ) # ignore leading dots
  1650. if hostname_ip:
  1651. # check if no_proxy_value is a ip network
  1652. try:
  1653. no_proxy_value_network = ipaddress.ip_network(
  1654. no_proxy_value, strict=False
  1655. )
  1656. except ValueError:
  1657. no_proxy_value_network = None
  1658. if no_proxy_value_network:
  1659. # if hostname is a ip address and no_proxy_value is a ip network -> check if ip address is part of network
  1660. if hostname_ip in no_proxy_value_network:
  1661. return True
  1662. if no_proxy_value == "*":
  1663. # '*' is special case for always bypass proxy
  1664. return True
  1665. if hostname == no_proxy_value:
  1666. return True
  1667. no_proxy_value = (
  1668. "." + no_proxy_value
  1669. ) # add a dot to only match complete domains
  1670. if hostname.endswith(no_proxy_value):
  1671. return True
  1672. return False
  1673. class AbstractHttpGitClient(GitClient):
  1674. """Abstract base class for HTTP Git Clients.
  1675. This is agonistic of the actual HTTP implementation.
  1676. Subclasses should provide an implementation of the
  1677. _http_request method.
  1678. """
  1679. def __init__(self, base_url, dumb=False, **kwargs) -> None:
  1680. self._base_url = base_url.rstrip("/") + "/"
  1681. self.dumb = dumb
  1682. GitClient.__init__(self, **kwargs)
  1683. def _http_request(self, url, headers=None, data=None):
  1684. """Perform HTTP request.
  1685. Args:
  1686. url: Request URL.
  1687. headers: Optional custom headers to override defaults.
  1688. data: Request data.
  1689. Returns:
  1690. Tuple (response, read), where response is an urllib3
  1691. response object with additional content_type and
  1692. redirect_location properties, and read is a consumable read
  1693. method for the response data.
  1694. Raises:
  1695. GitProtocolError
  1696. """
  1697. raise NotImplementedError(self._http_request)
  1698. def _discover_references(self, service, base_url):
  1699. assert base_url[-1] == "/"
  1700. tail = "info/refs"
  1701. headers = {"Accept": "*/*"}
  1702. if self.dumb is not True:
  1703. tail += "?service={}".format(service.decode("ascii"))
  1704. url = urljoin(base_url, tail)
  1705. resp, read = self._http_request(url, headers)
  1706. if resp.redirect_location:
  1707. # Something changed (redirect!), so let's update the base URL
  1708. if not resp.redirect_location.endswith(tail):
  1709. raise GitProtocolError(
  1710. f"Redirected from URL {url} to URL {resp.redirect_location} without {tail}"
  1711. )
  1712. base_url = urljoin(url, resp.redirect_location[: -len(tail)])
  1713. try:
  1714. self.dumb = resp.content_type is None or not resp.content_type.startswith(
  1715. "application/x-git-"
  1716. )
  1717. if not self.dumb:
  1718. proto = Protocol(read, None)
  1719. # The first line should mention the service
  1720. try:
  1721. [pkt] = list(proto.read_pkt_seq())
  1722. except ValueError as exc:
  1723. raise GitProtocolError(
  1724. "unexpected number of packets received"
  1725. ) from exc
  1726. if pkt.rstrip(b"\n") != (b"# service=" + service):
  1727. raise GitProtocolError(
  1728. f"unexpected first line {pkt!r} from smart server"
  1729. )
  1730. return (*read_pkt_refs(proto.read_pkt_seq()), base_url)
  1731. else:
  1732. return read_info_refs(resp), set(), base_url
  1733. finally:
  1734. resp.close()
  1735. def _smart_request(self, service, url, data):
  1736. """Send a 'smart' HTTP request.
  1737. This is a simple wrapper around _http_request that sets
  1738. a couple of extra headers.
  1739. """
  1740. assert url[-1] == "/"
  1741. url = urljoin(url, service)
  1742. result_content_type = f"application/x-{service}-result"
  1743. headers = {
  1744. "Content-Type": f"application/x-{service}-request",
  1745. "Accept": result_content_type,
  1746. }
  1747. if isinstance(data, bytes):
  1748. headers["Content-Length"] = str(len(data))
  1749. resp, read = self._http_request(url, headers, data)
  1750. if resp.content_type.split(";")[0] != result_content_type:
  1751. raise GitProtocolError(
  1752. f"Invalid content-type from server: {resp.content_type}"
  1753. )
  1754. return resp, read
  1755. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1756. """Upload a pack to a remote repository.
  1757. Args:
  1758. path: Repository path (as bytestring)
  1759. update_refs: Function to determine changes to remote refs.
  1760. Receives dict with existing remote refs, returns dict with
  1761. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1762. generate_pack_data: Function that can return a tuple
  1763. with number of elements and pack data to upload.
  1764. progress: Optional progress function
  1765. Returns:
  1766. SendPackResult
  1767. Raises:
  1768. SendPackError: if server rejects the pack data
  1769. """
  1770. url = self._get_url(path)
  1771. old_refs, server_capabilities, url = self._discover_references(
  1772. b"git-receive-pack", url
  1773. )
  1774. (
  1775. negotiated_capabilities,
  1776. agent,
  1777. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  1778. negotiated_capabilities.add(capability_agent())
  1779. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1780. self._report_status_parser = ReportStatusParser()
  1781. new_refs = update_refs(dict(old_refs))
  1782. if new_refs is None:
  1783. # Determine wants function is aborting the push.
  1784. return SendPackResult(old_refs, agent=agent, ref_status={})
  1785. if set(new_refs.items()).issubset(set(old_refs.items())):
  1786. return SendPackResult(new_refs, agent=agent, ref_status={})
  1787. if self.dumb:
  1788. raise NotImplementedError(self.fetch_pack)
  1789. def body_generator():
  1790. header_handler = _v1ReceivePackHeader(
  1791. negotiated_capabilities, old_refs, new_refs
  1792. )
  1793. for pkt in header_handler:
  1794. yield pkt_line(pkt)
  1795. pack_data_count, pack_data = generate_pack_data(
  1796. header_handler.have,
  1797. header_handler.want,
  1798. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  1799. )
  1800. if self._should_send_pack(new_refs):
  1801. yield from PackChunkGenerator(pack_data_count, pack_data)
  1802. resp, read = self._smart_request("git-receive-pack", url, data=body_generator())
  1803. try:
  1804. resp_proto = Protocol(read, None)
  1805. ref_status = self._handle_receive_pack_tail(
  1806. resp_proto, negotiated_capabilities, progress
  1807. )
  1808. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  1809. finally:
  1810. resp.close()
  1811. def fetch_pack(
  1812. self,
  1813. path,
  1814. determine_wants,
  1815. graph_walker,
  1816. pack_data,
  1817. progress=None,
  1818. depth=None,
  1819. ):
  1820. """Retrieve a pack from a git smart server.
  1821. Args:
  1822. path: Path to fetch from
  1823. determine_wants: Callback that returns list of commits to fetch
  1824. graph_walker: Object with next() and ack().
  1825. pack_data: Callback called for each bit of data in the pack
  1826. progress: Callback for progress reports (strings)
  1827. depth: Depth for request
  1828. Returns:
  1829. FetchPackResult object
  1830. """
  1831. url = self._get_url(path)
  1832. refs, server_capabilities, url = self._discover_references(
  1833. b"git-upload-pack", url
  1834. )
  1835. (
  1836. negotiated_capabilities,
  1837. symrefs,
  1838. agent,
  1839. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1840. if depth is not None:
  1841. wants = determine_wants(refs, depth=depth)
  1842. else:
  1843. wants = determine_wants(refs)
  1844. if wants is not None:
  1845. wants = [cid for cid in wants if cid != ZERO_SHA]
  1846. if not wants:
  1847. return FetchPackResult(refs, symrefs, agent)
  1848. if self.dumb:
  1849. raise NotImplementedError(self.fetch_pack)
  1850. req_data = BytesIO()
  1851. req_proto = Protocol(None, req_data.write)
  1852. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  1853. req_proto,
  1854. negotiated_capabilities,
  1855. graph_walker,
  1856. wants,
  1857. can_read=None,
  1858. depth=depth,
  1859. )
  1860. resp, read = self._smart_request(
  1861. "git-upload-pack", url, data=req_data.getvalue()
  1862. )
  1863. try:
  1864. resp_proto = Protocol(read, None)
  1865. if new_shallow is None and new_unshallow is None:
  1866. (new_shallow, new_unshallow) = _read_shallow_updates(
  1867. resp_proto.read_pkt_seq()
  1868. )
  1869. _handle_upload_pack_tail(
  1870. resp_proto,
  1871. negotiated_capabilities,
  1872. graph_walker,
  1873. pack_data,
  1874. progress,
  1875. )
  1876. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  1877. finally:
  1878. resp.close()
  1879. def get_refs(self, path):
  1880. """Retrieve the current refs from a git smart server."""
  1881. url = self._get_url(path)
  1882. refs, _, _ = self._discover_references(b"git-upload-pack", url)
  1883. return refs
  1884. def get_url(self, path):
  1885. return self._get_url(path).rstrip("/")
  1886. def _get_url(self, path):
  1887. return urljoin(self._base_url, path).rstrip("/") + "/"
  1888. @classmethod
  1889. def from_parsedurl(cls, parsedurl, **kwargs):
  1890. password = parsedurl.password
  1891. if password is not None:
  1892. kwargs["password"] = urlunquote(password)
  1893. username = parsedurl.username
  1894. if username is not None:
  1895. kwargs["username"] = urlunquote(username)
  1896. return cls(urlunparse(parsedurl), **kwargs)
  1897. def __repr__(self) -> str:
  1898. return f"{type(self).__name__}({self._base_url!r}, dumb={self.dumb!r})"
  1899. def _wrap_urllib3_exceptions(func):
  1900. from urllib3.exceptions import ProtocolError
  1901. def wrapper(*args, **kwargs):
  1902. try:
  1903. return func(*args, **kwargs)
  1904. except ProtocolError as error:
  1905. raise GitProtocolError(str(error)) from error
  1906. return wrapper
  1907. class Urllib3HttpGitClient(AbstractHttpGitClient):
  1908. def __init__(
  1909. self,
  1910. base_url,
  1911. dumb=None,
  1912. pool_manager=None,
  1913. config=None,
  1914. username=None,
  1915. password=None,
  1916. **kwargs,
  1917. ) -> None:
  1918. self._username = username
  1919. self._password = password
  1920. if pool_manager is None:
  1921. self.pool_manager = default_urllib3_manager(config, base_url=base_url)
  1922. else:
  1923. self.pool_manager = pool_manager
  1924. if username is not None:
  1925. # No escaping needed: ":" is not allowed in username:
  1926. # https://tools.ietf.org/html/rfc2617#section-2
  1927. credentials = f"{username}:{password or ''}"
  1928. import urllib3.util
  1929. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  1930. self.pool_manager.headers.update(basic_auth) # type: ignore
  1931. self.config = config
  1932. super().__init__(base_url=base_url, dumb=dumb, **kwargs)
  1933. def _get_url(self, path):
  1934. if not isinstance(path, str):
  1935. # urllib3.util.url._encode_invalid_chars() converts the path back
  1936. # to bytes using the utf-8 codec.
  1937. path = path.decode("utf-8")
  1938. return urljoin(self._base_url, path).rstrip("/") + "/"
  1939. def _http_request(self, url, headers=None, data=None):
  1940. import urllib3.exceptions
  1941. req_headers = self.pool_manager.headers.copy()
  1942. if headers is not None:
  1943. req_headers.update(headers)
  1944. req_headers["Pragma"] = "no-cache"
  1945. try:
  1946. if data is None:
  1947. resp = self.pool_manager.request(
  1948. "GET", url, headers=req_headers, preload_content=False
  1949. )
  1950. else:
  1951. resp = self.pool_manager.request(
  1952. "POST", url, headers=req_headers, body=data, preload_content=False
  1953. )
  1954. except urllib3.exceptions.HTTPError as e:
  1955. raise GitProtocolError(str(e)) from e
  1956. if resp.status == 404:
  1957. raise NotGitRepository
  1958. if resp.status == 401:
  1959. raise HTTPUnauthorized(resp.headers.get("WWW-Authenticate"), url)
  1960. if resp.status == 407:
  1961. raise HTTPProxyUnauthorized(resp.headers.get("Proxy-Authenticate"), url)
  1962. if resp.status != 200:
  1963. raise GitProtocolError(
  1964. "unexpected http resp %d for %s" % (resp.status, url)
  1965. )
  1966. resp.content_type = resp.headers.get("Content-Type")
  1967. # Check if geturl() is available (urllib3 version >= 1.23)
  1968. try:
  1969. resp_url = resp.geturl()
  1970. except AttributeError:
  1971. # get_redirect_location() is available for urllib3 >= 1.1
  1972. resp.redirect_location = resp.get_redirect_location()
  1973. else:
  1974. resp.redirect_location = resp_url if resp_url != url else ""
  1975. return resp, _wrap_urllib3_exceptions(resp.read)
  1976. HttpGitClient = Urllib3HttpGitClient
  1977. def _win32_url_to_path(parsed) -> str:
  1978. """Convert a file: URL to a path.
  1979. https://datatracker.ietf.org/doc/html/rfc8089
  1980. """
  1981. assert sys.platform == "win32" or os.name == "nt"
  1982. assert parsed.scheme == "file"
  1983. _, netloc, path, _, _, _ = parsed
  1984. if netloc == "localhost" or not netloc:
  1985. netloc = ""
  1986. elif (
  1987. netloc
  1988. and len(netloc) >= 2
  1989. and netloc[0].isalpha()
  1990. and netloc[1:2] in (":", ":/")
  1991. ):
  1992. # file://C:/foo.bar/baz or file://C://foo.bar//baz
  1993. netloc = netloc[:2]
  1994. else:
  1995. raise NotImplementedError("Non-local file URLs are not supported")
  1996. global url2pathname
  1997. if url2pathname is None:
  1998. from urllib.request import url2pathname # type: ignore
  1999. return url2pathname(netloc + path) # type: ignore
  2000. def get_transport_and_path_from_url(
  2001. url: str, config: Optional[Config] = None, operation: Optional[str] = None, **kwargs
  2002. ) -> Tuple[GitClient, str]:
  2003. """Obtain a git client from a URL.
  2004. Args:
  2005. url: URL to open (a unicode string)
  2006. config: Optional config object
  2007. operation: Kind of operation that'll be performed; "pull" or "push"
  2008. thin_packs: Whether or not thin packs should be retrieved
  2009. report_activity: Optional callback for reporting transport
  2010. activity.
  2011. Returns:
  2012. Tuple with client instance and relative path.
  2013. """
  2014. if config is not None:
  2015. url = apply_instead_of(config, url, push=(operation == "push"))
  2016. return _get_transport_and_path_from_url(
  2017. url, config=config, operation=operation, **kwargs
  2018. )
  2019. def _get_transport_and_path_from_url(url, config, operation, **kwargs):
  2020. parsed = urlparse(url)
  2021. if parsed.scheme == "git":
  2022. return (TCPGitClient.from_parsedurl(parsed, **kwargs), parsed.path)
  2023. elif parsed.scheme in ("git+ssh", "ssh"):
  2024. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  2025. elif parsed.scheme in ("http", "https"):
  2026. return (
  2027. HttpGitClient.from_parsedurl(parsed, config=config, **kwargs),
  2028. parsed.path,
  2029. )
  2030. elif parsed.scheme == "file":
  2031. if sys.platform == "win32" or os.name == "nt":
  2032. return default_local_git_client_cls(**kwargs), _win32_url_to_path(parsed)
  2033. return (
  2034. default_local_git_client_cls.from_parsedurl(parsed, **kwargs),
  2035. parsed.path,
  2036. )
  2037. raise ValueError(f"unknown scheme '{parsed.scheme}'")
  2038. def parse_rsync_url(location: str) -> Tuple[Optional[str], str, str]:
  2039. """Parse a rsync-style URL."""
  2040. if ":" in location and "@" not in location:
  2041. # SSH with no user@, zero or one leading slash.
  2042. (host, path) = location.split(":", 1)
  2043. user = None
  2044. elif ":" in location:
  2045. # SSH with user@host:foo.
  2046. user_host, path = location.split(":", 1)
  2047. if "@" in user_host:
  2048. user, host = user_host.rsplit("@", 1)
  2049. else:
  2050. user = None
  2051. host = user_host
  2052. else:
  2053. raise ValueError("not a valid rsync-style URL")
  2054. return (user, host, path)
  2055. def get_transport_and_path(
  2056. location: str,
  2057. config: Optional[Config] = None,
  2058. operation: Optional[str] = None,
  2059. **kwargs,
  2060. ) -> Tuple[GitClient, str]:
  2061. """Obtain a git client from a URL.
  2062. Args:
  2063. location: URL or path (a string)
  2064. config: Optional config object
  2065. operation: Kind of operation that'll be performed; "pull" or "push"
  2066. thin_packs: Whether or not thin packs should be retrieved
  2067. report_activity: Optional callback for reporting transport
  2068. activity.
  2069. Returns:
  2070. Tuple with client instance and relative path.
  2071. """
  2072. if config is not None:
  2073. location = apply_instead_of(config, location, push=(operation == "push"))
  2074. # First, try to parse it as a URL
  2075. try:
  2076. return _get_transport_and_path_from_url(
  2077. location, config=config, operation=operation, **kwargs
  2078. )
  2079. except ValueError:
  2080. pass
  2081. if sys.platform == "win32" and location[0].isalpha() and location[1:3] == ":\\":
  2082. # Windows local path
  2083. return default_local_git_client_cls(**kwargs), location
  2084. try:
  2085. (username, hostname, path) = parse_rsync_url(location)
  2086. except ValueError:
  2087. # Otherwise, assume it's a local path.
  2088. return default_local_git_client_cls(**kwargs), location
  2089. else:
  2090. return SSHGitClient(hostname, username=username, **kwargs), path
  2091. DEFAULT_GIT_CREDENTIALS_PATHS = [
  2092. os.path.expanduser("~/.git-credentials"),
  2093. get_xdg_config_home_path("git", "credentials"),
  2094. ]
  2095. def get_credentials_from_store(
  2096. scheme, hostname, username=None, fnames=DEFAULT_GIT_CREDENTIALS_PATHS
  2097. ):
  2098. for fname in fnames:
  2099. try:
  2100. with open(fname, "rb") as f:
  2101. for line in f:
  2102. parsed_line = urlparse(line.strip())
  2103. if (
  2104. parsed_line.scheme == scheme
  2105. and parsed_line.hostname == hostname
  2106. and (username is None or parsed_line.username == username)
  2107. ):
  2108. return parsed_line.username, parsed_line.password
  2109. except FileNotFoundError:
  2110. # If the file doesn't exist, try the next one.
  2111. continue