client.py 99 KB

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