client.py 65 KB

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