client.py 98 KB

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