client.py 66 KB

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