client.py 74 KB

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