client.py 78 KB

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