client.py 66 KB

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