client.py 71 KB

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