client.py 78 KB

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