client.py 79 KB

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