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