client.py 66 KB

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