client.py 78 KB

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