client.py 61 KB

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