client.py 61 KB

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