client.py 78 KB

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