client.py 68 KB

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