client.py 78 KB

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