client.py 79 KB

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