client.py 62 KB

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