client.py 78 KB

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