2
0

client.py 78 KB

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