client.py 67 KB

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