client.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. # client.py -- Implementation of the client side git protocols
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@samba.org>
  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 certifi
  55. import urllib3
  56. import urllib3.util
  57. import dulwich
  58. from dulwich.errors import (
  59. GitProtocolError,
  60. NotGitRepository,
  61. SendPackError,
  62. UpdateRefsError,
  63. )
  64. from dulwich.protocol import (
  65. _RBUFSIZE,
  66. agent_string,
  67. capability_agent,
  68. extract_capability_names,
  69. CAPABILITY_AGENT,
  70. CAPABILITY_DELETE_REFS,
  71. CAPABILITY_MULTI_ACK,
  72. CAPABILITY_MULTI_ACK_DETAILED,
  73. CAPABILITY_OFS_DELTA,
  74. CAPABILITY_QUIET,
  75. CAPABILITY_REPORT_STATUS,
  76. CAPABILITY_SYMREF,
  77. CAPABILITY_SIDE_BAND_64K,
  78. CAPABILITY_THIN_PACK,
  79. CAPABILITIES_REF,
  80. KNOWN_RECEIVE_CAPABILITIES,
  81. KNOWN_UPLOAD_CAPABILITIES,
  82. COMMAND_DONE,
  83. COMMAND_HAVE,
  84. COMMAND_WANT,
  85. SIDE_BAND_CHANNEL_DATA,
  86. SIDE_BAND_CHANNEL_PROGRESS,
  87. SIDE_BAND_CHANNEL_FATAL,
  88. PktLineParser,
  89. Protocol,
  90. ProtocolFile,
  91. TCP_GIT_PORT,
  92. ZERO_SHA,
  93. extract_capabilities,
  94. parse_capability,
  95. )
  96. from dulwich.pack import (
  97. write_pack_data,
  98. write_pack_objects,
  99. )
  100. from dulwich.refs import (
  101. read_info_refs,
  102. )
  103. if sys.version_info < (2, 7, 9):
  104. # Before Python 2.7.9 the `ssl` module lacks SNI support and lags behind in
  105. # security updates. Use pyOpenSSL instead.
  106. import urllib3.contrib.pyopenssl
  107. urllib3.contrib.pyopenssl.inject_into_urllib3()
  108. def _fileno_can_read(fileno):
  109. """Check if a file descriptor is readable."""
  110. return len(select.select([fileno], [], [], 0)[0]) > 0
  111. def _win32_peek_avail(handle):
  112. """Wrapper around PeekNamedPipe to check how many bytes are available."""
  113. from ctypes import byref, wintypes, windll
  114. c_avail = wintypes.DWORD()
  115. c_message = wintypes.DWORD()
  116. success = windll.kernel32.PeekNamedPipe(
  117. handle, None, 0, None, byref(c_avail),
  118. byref(c_message))
  119. if not success:
  120. raise OSError(wintypes.GetLastError())
  121. return c_avail.value
  122. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  123. UPLOAD_CAPABILITIES = ([CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK,
  124. CAPABILITY_MULTI_ACK_DETAILED] + COMMON_CAPABILITIES)
  125. RECEIVE_CAPABILITIES = [CAPABILITY_REPORT_STATUS] + COMMON_CAPABILITIES
  126. class ReportStatusParser(object):
  127. """Handle status as reported by servers with 'report-status' capability.
  128. """
  129. def __init__(self):
  130. self._done = False
  131. self._pack_status = None
  132. self._ref_status_ok = True
  133. self._ref_statuses = []
  134. def check(self):
  135. """Check if there were any errors and, if so, raise exceptions.
  136. :raise SendPackError: Raised when the server could not unpack
  137. :raise UpdateRefsError: Raised when refs could not be updated
  138. """
  139. if self._pack_status not in (b'unpack ok', None):
  140. raise SendPackError(self._pack_status)
  141. if not self._ref_status_ok:
  142. ref_status = {}
  143. ok = set()
  144. for status in self._ref_statuses:
  145. if b' ' not in status:
  146. # malformed response, move on to the next one
  147. continue
  148. status, ref = status.split(b' ', 1)
  149. if status == b'ng':
  150. if b' ' in ref:
  151. ref, status = ref.split(b' ', 1)
  152. else:
  153. ok.add(ref)
  154. ref_status[ref] = status
  155. # TODO(jelmer): don't assume encoding of refs is ascii.
  156. raise UpdateRefsError(', '.join([
  157. refname.decode('ascii') for refname in ref_status
  158. if refname not in ok]) +
  159. ' failed to update', ref_status=ref_status)
  160. def handle_packet(self, pkt):
  161. """Handle a packet.
  162. :raise GitProtocolError: Raised when packets are received after a
  163. flush packet.
  164. """
  165. if self._done:
  166. raise GitProtocolError("received more data after status report")
  167. if pkt is None:
  168. self._done = True
  169. return
  170. if self._pack_status is None:
  171. self._pack_status = pkt.strip()
  172. else:
  173. ref_status = pkt.strip()
  174. self._ref_statuses.append(ref_status)
  175. if not ref_status.startswith(b'ok '):
  176. self._ref_status_ok = False
  177. def read_pkt_refs(proto):
  178. server_capabilities = None
  179. refs = {}
  180. # Receive refs from server
  181. for pkt in proto.read_pkt_seq():
  182. (sha, ref) = pkt.rstrip(b'\n').split(None, 1)
  183. if sha == b'ERR':
  184. raise GitProtocolError(ref)
  185. if server_capabilities is None:
  186. (ref, server_capabilities) = extract_capabilities(ref)
  187. refs[ref] = sha
  188. if len(refs) == 0:
  189. return {}, set([])
  190. if refs == {CAPABILITIES_REF: ZERO_SHA}:
  191. refs = {}
  192. return refs, set(server_capabilities)
  193. class FetchPackResult(object):
  194. """Result of a fetch-pack operation.
  195. :var refs: Dictionary with all remote refs
  196. :var symrefs: Dictionary with remote symrefs
  197. :var agent: User agent string
  198. """
  199. _FORWARDED_ATTRS = [
  200. 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items',
  201. 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem',
  202. 'setdefault', 'update', 'values', 'viewitems', 'viewkeys',
  203. 'viewvalues']
  204. def __init__(self, refs, symrefs, agent):
  205. self.refs = refs
  206. self.symrefs = symrefs
  207. self.agent = agent
  208. def _warn_deprecated(self):
  209. import warnings
  210. warnings.warn(
  211. "Use FetchPackResult.refs instead.",
  212. DeprecationWarning, stacklevel=3)
  213. def __eq__(self, other):
  214. if isinstance(other, dict):
  215. self._warn_deprecated()
  216. return (self.refs == other)
  217. return (self.refs == other.refs and
  218. self.symrefs == other.symrefs and
  219. self.agent == other.agent)
  220. def __contains__(self, name):
  221. self._warn_deprecated()
  222. return name in self.refs
  223. def __getitem__(self, name):
  224. self._warn_deprecated()
  225. return self.refs[name]
  226. def __len__(self):
  227. self._warn_deprecated()
  228. return len(self.refs)
  229. def __iter__(self):
  230. self._warn_deprecated()
  231. return iter(self.refs)
  232. def __getattribute__(self, name):
  233. if name in type(self)._FORWARDED_ATTRS:
  234. self._warn_deprecated()
  235. return getattr(self.refs, name)
  236. return super(FetchPackResult, self).__getattribute__(name)
  237. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  238. # support some capabilities. This should work properly with servers
  239. # that don't support multi_ack.
  240. class GitClient(object):
  241. """Git smart server client.
  242. """
  243. def __init__(self, thin_packs=True, report_activity=None, quiet=False):
  244. """Create a new GitClient instance.
  245. :param thin_packs: Whether or not thin packs should be retrieved
  246. :param report_activity: Optional callback for reporting transport
  247. activity.
  248. """
  249. self._report_activity = report_activity
  250. self._report_status_parser = None
  251. self._fetch_capabilities = set(UPLOAD_CAPABILITIES)
  252. self._fetch_capabilities.add(capability_agent())
  253. self._send_capabilities = set(RECEIVE_CAPABILITIES)
  254. self._send_capabilities.add(capability_agent())
  255. if quiet:
  256. self._send_capabilities.add(CAPABILITY_QUIET)
  257. if not thin_packs:
  258. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  259. def get_url(self, path):
  260. """Retrieves full url to given path.
  261. :param path: Repository path (as string)
  262. :return: Url to path (as string)
  263. """
  264. raise NotImplementedError(self.get_url)
  265. @classmethod
  266. def from_parsedurl(cls, parsedurl, **kwargs):
  267. """Create an instance of this client from a urlparse.parsed object.
  268. :param parsedurl: Result of urlparse.urlparse()
  269. :return: A `GitClient` object
  270. """
  271. raise NotImplementedError(cls.from_parsedurl)
  272. def send_pack(self, path, update_refs, generate_pack_data,
  273. progress=None):
  274. """Upload a pack to a remote repository.
  275. :param path: Repository path (as bytestring)
  276. :param update_refs: Function to determine changes to remote refs.
  277. Receive dict with existing remote refs, returns dict with
  278. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  279. :param generate_pack_data: Function that can return a tuple
  280. with number of objects and list of pack data to include
  281. :param progress: Optional progress function
  282. :raises SendPackError: if server rejects the pack data
  283. :raises UpdateRefsError: if the server supports report-status
  284. and rejects ref updates
  285. :return: new_refs dictionary containing the changes that were made
  286. {refname: new_ref}, including deleted refs.
  287. """
  288. raise NotImplementedError(self.send_pack)
  289. def fetch(self, path, target, determine_wants=None, progress=None):
  290. """Fetch into a target repository.
  291. :param path: Path to fetch from (as bytestring)
  292. :param target: Target repository to fetch into
  293. :param determine_wants: Optional function to determine what refs
  294. to fetch. Receives dictionary of name->sha, should return
  295. list of shas to fetch. Defaults to all shas.
  296. :param progress: Optional progress function
  297. :return: Dictionary with all remote refs (not just those fetched)
  298. """
  299. if determine_wants is None:
  300. determine_wants = target.object_store.determine_wants_all
  301. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  302. # TODO(jelmer): Avoid reading entire file into memory and
  303. # only processing it after the whole file has been fetched.
  304. f = BytesIO()
  305. def commit():
  306. if f.tell():
  307. f.seek(0)
  308. target.object_store.add_thin_pack(f.read, None)
  309. def abort():
  310. pass
  311. else:
  312. f, commit, abort = target.object_store.add_pack()
  313. try:
  314. result = self.fetch_pack(
  315. path, determine_wants, target.get_graph_walker(), f.write,
  316. progress)
  317. except BaseException:
  318. abort()
  319. raise
  320. else:
  321. commit()
  322. return result
  323. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  324. progress=None):
  325. """Retrieve a pack from a git smart server.
  326. :param path: Remote path to fetch from
  327. :param determine_wants: Function determine what refs
  328. to fetch. Receives dictionary of name->sha, should return
  329. list of shas to fetch.
  330. :param graph_walker: Object with next() and ack().
  331. :param pack_data: Callback called for each bit of data in the pack
  332. :param progress: Callback for progress reports (strings)
  333. :return: FetchPackResult object
  334. """
  335. raise NotImplementedError(self.fetch_pack)
  336. def get_refs(self, path):
  337. """Retrieve the current refs from a git smart server.
  338. :param path: Path to the repo to fetch from. (as bytestring)
  339. """
  340. raise NotImplementedError(self.get_refs)
  341. def _parse_status_report(self, proto):
  342. unpack = proto.read_pkt_line().strip()
  343. if unpack != b'unpack ok':
  344. st = True
  345. # flush remaining error data
  346. while st is not None:
  347. st = proto.read_pkt_line()
  348. raise SendPackError(unpack)
  349. statuses = []
  350. errs = False
  351. ref_status = proto.read_pkt_line()
  352. while ref_status:
  353. ref_status = ref_status.strip()
  354. statuses.append(ref_status)
  355. if not ref_status.startswith(b'ok '):
  356. errs = True
  357. ref_status = proto.read_pkt_line()
  358. if errs:
  359. ref_status = {}
  360. ok = set()
  361. for status in statuses:
  362. if b' ' not in status:
  363. # malformed response, move on to the next one
  364. continue
  365. status, ref = status.split(b' ', 1)
  366. if status == b'ng':
  367. if b' ' in ref:
  368. ref, status = ref.split(b' ', 1)
  369. else:
  370. ok.add(ref)
  371. ref_status[ref] = status
  372. raise UpdateRefsError(', '.join([
  373. refname for refname in ref_status if refname not in ok]) +
  374. b' failed to update', ref_status=ref_status)
  375. def _read_side_band64k_data(self, proto, channel_callbacks):
  376. """Read per-channel data.
  377. This requires the side-band-64k capability.
  378. :param proto: Protocol object to read from
  379. :param channel_callbacks: Dictionary mapping channels to packet
  380. handlers to use. None for a callback discards channel data.
  381. """
  382. for pkt in proto.read_pkt_seq():
  383. channel = ord(pkt[:1])
  384. pkt = pkt[1:]
  385. try:
  386. cb = channel_callbacks[channel]
  387. except KeyError:
  388. raise AssertionError('Invalid sideband channel %d' % channel)
  389. else:
  390. if cb is not None:
  391. cb(pkt)
  392. def _handle_receive_pack_head(self, proto, capabilities, old_refs,
  393. new_refs):
  394. """Handle the head of a 'git-receive-pack' request.
  395. :param proto: Protocol object to read from
  396. :param capabilities: List of negotiated capabilities
  397. :param old_refs: Old refs, as received from the server
  398. :param new_refs: Refs to change
  399. :return: (have, want) tuple
  400. """
  401. want = []
  402. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  403. sent_capabilities = False
  404. for refname in new_refs:
  405. if not isinstance(refname, bytes):
  406. raise TypeError('refname is not a bytestring: %r' % refname)
  407. old_sha1 = old_refs.get(refname, ZERO_SHA)
  408. if not isinstance(old_sha1, bytes):
  409. raise TypeError('old sha1 for %s is not a bytestring: %r' %
  410. (refname, old_sha1))
  411. new_sha1 = new_refs.get(refname, ZERO_SHA)
  412. if not isinstance(new_sha1, bytes):
  413. raise TypeError('old sha1 for %s is not a bytestring %r' %
  414. (refname, new_sha1))
  415. if old_sha1 != new_sha1:
  416. if sent_capabilities:
  417. proto.write_pkt_line(old_sha1 + b' ' + new_sha1 + b' ' +
  418. refname)
  419. else:
  420. proto.write_pkt_line(
  421. old_sha1 + b' ' + new_sha1 + b' ' + refname + b'\0' +
  422. b' '.join(capabilities))
  423. sent_capabilities = True
  424. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  425. want.append(new_sha1)
  426. proto.write_pkt_line(None)
  427. return (have, want)
  428. def _negotiate_receive_pack_capabilities(self, server_capabilities):
  429. negotiated_capabilities = (
  430. self._send_capabilities & server_capabilities)
  431. unknown_capabilities = ( # noqa: F841
  432. extract_capability_names(server_capabilities) -
  433. KNOWN_RECEIVE_CAPABILITIES)
  434. # TODO(jelmer): warn about unknown capabilities
  435. return negotiated_capabilities
  436. def _handle_receive_pack_tail(self, proto, capabilities, progress=None):
  437. """Handle the tail of a 'git-receive-pack' request.
  438. :param proto: Protocol object to read from
  439. :param capabilities: List of negotiated capabilities
  440. :param progress: Optional progress reporting function
  441. """
  442. if CAPABILITY_SIDE_BAND_64K in capabilities:
  443. if progress is None:
  444. def progress(x):
  445. pass
  446. channel_callbacks = {2: progress}
  447. if CAPABILITY_REPORT_STATUS in capabilities:
  448. channel_callbacks[1] = PktLineParser(
  449. self._report_status_parser.handle_packet).parse
  450. self._read_side_band64k_data(proto, channel_callbacks)
  451. else:
  452. if CAPABILITY_REPORT_STATUS in capabilities:
  453. for pkt in proto.read_pkt_seq():
  454. self._report_status_parser.handle_packet(pkt)
  455. if self._report_status_parser is not None:
  456. self._report_status_parser.check()
  457. def _negotiate_upload_pack_capabilities(self, server_capabilities):
  458. unknown_capabilities = ( # noqa: F841
  459. extract_capability_names(server_capabilities) -
  460. KNOWN_UPLOAD_CAPABILITIES)
  461. # TODO(jelmer): warn about unknown capabilities
  462. symrefs = {}
  463. agent = None
  464. for capability in server_capabilities:
  465. k, v = parse_capability(capability)
  466. if k == CAPABILITY_SYMREF:
  467. (src, dst) = v.split(b':', 1)
  468. symrefs[src] = dst
  469. if k == CAPABILITY_AGENT:
  470. agent = v
  471. negotiated_capabilities = (
  472. self._fetch_capabilities & server_capabilities)
  473. return (negotiated_capabilities, symrefs, agent)
  474. def _handle_upload_pack_head(self, proto, capabilities, graph_walker,
  475. wants, can_read):
  476. """Handle the head of a 'git-upload-pack' request.
  477. :param proto: Protocol object to read from
  478. :param capabilities: List of negotiated capabilities
  479. :param graph_walker: GraphWalker instance to call .ack() on
  480. :param wants: List of commits to fetch
  481. :param can_read: function that returns a boolean that indicates
  482. whether there is extra graph data to read on proto
  483. """
  484. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  485. proto.write_pkt_line(COMMAND_WANT + b' ' + wants[0] + b' ' +
  486. b' '.join(capabilities) + b'\n')
  487. for want in wants[1:]:
  488. proto.write_pkt_line(COMMAND_WANT + b' ' + want + b'\n')
  489. proto.write_pkt_line(None)
  490. have = next(graph_walker)
  491. while have:
  492. proto.write_pkt_line(COMMAND_HAVE + b' ' + have + b'\n')
  493. if can_read():
  494. pkt = proto.read_pkt_line()
  495. parts = pkt.rstrip(b'\n').split(b' ')
  496. if parts[0] == b'ACK':
  497. graph_walker.ack(parts[1])
  498. if parts[2] in (b'continue', b'common'):
  499. pass
  500. elif parts[2] == b'ready':
  501. break
  502. else:
  503. raise AssertionError(
  504. "%s not in ('continue', 'ready', 'common)" %
  505. parts[2])
  506. have = next(graph_walker)
  507. proto.write_pkt_line(COMMAND_DONE + b'\n')
  508. def _handle_upload_pack_tail(self, proto, capabilities, graph_walker,
  509. pack_data, progress=None, rbufsize=_RBUFSIZE):
  510. """Handle the tail of a 'git-upload-pack' request.
  511. :param proto: Protocol object to read from
  512. :param capabilities: List of negotiated capabilities
  513. :param graph_walker: GraphWalker instance to call .ack() on
  514. :param pack_data: Function to call with pack data
  515. :param progress: Optional progress reporting function
  516. :param rbufsize: Read buffer size
  517. """
  518. pkt = proto.read_pkt_line()
  519. while pkt:
  520. parts = pkt.rstrip(b'\n').split(b' ')
  521. if parts[0] == b'ACK':
  522. graph_walker.ack(parts[1])
  523. if len(parts) < 3 or parts[2] not in (
  524. b'ready', b'continue', b'common'):
  525. break
  526. pkt = proto.read_pkt_line()
  527. if CAPABILITY_SIDE_BAND_64K in capabilities:
  528. if progress is None:
  529. # Just ignore progress data
  530. def progress(x):
  531. pass
  532. self._read_side_band64k_data(proto, {
  533. SIDE_BAND_CHANNEL_DATA: pack_data,
  534. SIDE_BAND_CHANNEL_PROGRESS: progress}
  535. )
  536. else:
  537. while True:
  538. data = proto.read(rbufsize)
  539. if data == b"":
  540. break
  541. pack_data(data)
  542. class TraditionalGitClient(GitClient):
  543. """Traditional Git client."""
  544. DEFAULT_ENCODING = 'utf-8'
  545. def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs):
  546. self._remote_path_encoding = path_encoding
  547. super(TraditionalGitClient, self).__init__(**kwargs)
  548. def _connect(self, cmd, path):
  549. """Create a connection to the server.
  550. This method is abstract - concrete implementations should
  551. implement their own variant which connects to the server and
  552. returns an initialized Protocol object with the service ready
  553. for use and a can_read function which may be used to see if
  554. reads would block.
  555. :param cmd: The git service name to which we should connect.
  556. :param path: The path we should pass to the service. (as bytestirng)
  557. """
  558. raise NotImplementedError()
  559. def send_pack(self, path, update_refs, generate_pack_data,
  560. progress=None):
  561. """Upload a pack to a remote repository.
  562. :param path: Repository path (as bytestring)
  563. :param update_refs: Function to determine changes to remote refs.
  564. Receive dict with existing remote refs, returns dict with
  565. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  566. :param generate_pack_data: Function that can return a tuple with
  567. number of objects and pack data to upload.
  568. :param progress: Optional callback called with progress updates
  569. :raises SendPackError: if server rejects the pack data
  570. :raises UpdateRefsError: if the server supports report-status
  571. and rejects ref updates
  572. :return: new_refs dictionary containing the changes that were made
  573. {refname: new_ref}, including deleted refs.
  574. """
  575. proto, unused_can_read = self._connect(b'receive-pack', path)
  576. with proto:
  577. old_refs, server_capabilities = read_pkt_refs(proto)
  578. negotiated_capabilities = \
  579. self._negotiate_receive_pack_capabilities(server_capabilities)
  580. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  581. self._report_status_parser = ReportStatusParser()
  582. report_status_parser = self._report_status_parser
  583. try:
  584. new_refs = orig_new_refs = update_refs(dict(old_refs))
  585. except BaseException:
  586. proto.write_pkt_line(None)
  587. raise
  588. if CAPABILITY_DELETE_REFS not in server_capabilities:
  589. # Server does not support deletions. Fail later.
  590. new_refs = dict(orig_new_refs)
  591. for ref, sha in orig_new_refs.items():
  592. if sha == ZERO_SHA:
  593. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  594. report_status_parser._ref_statuses.append(
  595. b'ng ' + sha +
  596. b' remote does not support deleting refs')
  597. report_status_parser._ref_status_ok = False
  598. del new_refs[ref]
  599. if new_refs is None:
  600. proto.write_pkt_line(None)
  601. return old_refs
  602. if len(new_refs) == 0 and len(orig_new_refs):
  603. # NOOP - Original new refs filtered out by policy
  604. proto.write_pkt_line(None)
  605. if report_status_parser is not None:
  606. report_status_parser.check()
  607. return old_refs
  608. (have, want) = self._handle_receive_pack_head(
  609. proto, negotiated_capabilities, old_refs, new_refs)
  610. if (not want and
  611. set(new_refs.items()).issubset(set(old_refs.items()))):
  612. return new_refs
  613. pack_data_count, pack_data = generate_pack_data(
  614. have, want,
  615. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities))
  616. dowrite = bool(pack_data_count)
  617. dowrite = dowrite or any(old_refs.get(ref) != sha
  618. for (ref, sha) in new_refs.items()
  619. if sha != ZERO_SHA)
  620. if dowrite:
  621. write_pack_data(proto.write_file(), pack_data_count, pack_data)
  622. self._handle_receive_pack_tail(
  623. proto, negotiated_capabilities, progress)
  624. return new_refs
  625. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  626. progress=None):
  627. """Retrieve a pack from a git smart server.
  628. :param path: Remote path to fetch from
  629. :param determine_wants: Function determine what refs
  630. to fetch. Receives dictionary of name->sha, should return
  631. list of shas to fetch.
  632. :param graph_walker: Object with next() and ack().
  633. :param pack_data: Callback called for each bit of data in the pack
  634. :param progress: Callback for progress reports (strings)
  635. :return: FetchPackResult object
  636. """
  637. proto, can_read = self._connect(b'upload-pack', path)
  638. with proto:
  639. refs, server_capabilities = read_pkt_refs(proto)
  640. negotiated_capabilities, symrefs, agent = (
  641. self._negotiate_upload_pack_capabilities(
  642. server_capabilities))
  643. if refs is None:
  644. proto.write_pkt_line(None)
  645. return FetchPackResult(refs, symrefs, agent)
  646. try:
  647. wants = determine_wants(refs)
  648. except BaseException:
  649. proto.write_pkt_line(None)
  650. raise
  651. if wants is not None:
  652. wants = [cid for cid in wants if cid != ZERO_SHA]
  653. if not wants:
  654. proto.write_pkt_line(None)
  655. return FetchPackResult(refs, symrefs, agent)
  656. self._handle_upload_pack_head(
  657. proto, negotiated_capabilities, graph_walker, wants, can_read)
  658. self._handle_upload_pack_tail(
  659. proto, negotiated_capabilities, graph_walker, pack_data,
  660. progress)
  661. return FetchPackResult(refs, symrefs, agent)
  662. def get_refs(self, path):
  663. """Retrieve the current refs from a git smart server."""
  664. # stock `git ls-remote` uses upload-pack
  665. proto, _ = self._connect(b'upload-pack', path)
  666. with proto:
  667. refs, _ = read_pkt_refs(proto)
  668. proto.write_pkt_line(None)
  669. return refs
  670. def archive(self, path, committish, write_data, progress=None,
  671. write_error=None):
  672. proto, can_read = self._connect(b'upload-archive', path)
  673. with proto:
  674. proto.write_pkt_line(b"argument " + committish)
  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:
  951. raise NotImplementedError(
  952. "You can't set password or passphrase for ssh key "
  953. "with SubprocessSSHVendor, use ParamikoSSHVendor instead"
  954. )
  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 PuttySSHVendor(SSHVendor):
  970. """SSH vendor that shells out to the local 'putty' command."""
  971. def run_command(self, host, command, username=None, port=None,
  972. password=None, key_filename=None):
  973. if password and key_filename:
  974. raise NotImplementedError(
  975. "You can't set passphrase for ssh key "
  976. "with PuttySSHVendor, use ParamikoSSHVendor instead"
  977. )
  978. if sys.platform == 'win32':
  979. args = ['putty.exe', '-ssh']
  980. else:
  981. args = ['putty', '-ssh']
  982. if password:
  983. import warnings
  984. warnings.warn(
  985. "Invoking Putty with a password exposes the password in the "
  986. "process list.")
  987. args.extend(['-pw', str(password)])
  988. if port:
  989. args.extend(['-P', str(port)])
  990. if key_filename:
  991. args.extend(['-i', str(key_filename)])
  992. if username:
  993. host = '%s@%s' % (username, host)
  994. if host.startswith('-'):
  995. raise StrangeHostname(hostname=host)
  996. args.append(host)
  997. proc = subprocess.Popen(args + [command], bufsize=0,
  998. stdin=subprocess.PIPE,
  999. stdout=subprocess.PIPE)
  1000. return SubprocessWrapper(proc)
  1001. def ParamikoSSHVendor(**kwargs):
  1002. import warnings
  1003. warnings.warn(
  1004. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  1005. DeprecationWarning)
  1006. from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
  1007. return ParamikoSSHVendor(**kwargs)
  1008. # Can be overridden by users
  1009. get_ssh_vendor = SubprocessSSHVendor
  1010. class SSHGitClient(TraditionalGitClient):
  1011. def __init__(self, host, port=None, username=None, vendor=None,
  1012. config=None, password=None, key_filename=None, **kwargs):
  1013. self.host = host
  1014. self.port = port
  1015. self.username = username
  1016. self.password = password
  1017. self.key_filename = key_filename
  1018. super(SSHGitClient, self).__init__(**kwargs)
  1019. self.alternative_paths = {}
  1020. if vendor is not None:
  1021. self.ssh_vendor = vendor
  1022. else:
  1023. self.ssh_vendor = get_ssh_vendor()
  1024. def get_url(self, path):
  1025. netloc = self.host
  1026. if self.port is not None:
  1027. netloc += ":%d" % self.port
  1028. if self.username is not None:
  1029. netloc = urlquote(self.username, '@/:') + "@" + netloc
  1030. return urlparse.urlunsplit(('ssh', netloc, path, '', ''))
  1031. @classmethod
  1032. def from_parsedurl(cls, parsedurl, **kwargs):
  1033. return cls(host=parsedurl.hostname, port=parsedurl.port,
  1034. username=parsedurl.username, **kwargs)
  1035. def _get_cmd_path(self, cmd):
  1036. cmd = self.alternative_paths.get(cmd, b'git-' + cmd)
  1037. assert isinstance(cmd, bytes)
  1038. return cmd
  1039. def _connect(self, cmd, path):
  1040. if not isinstance(cmd, bytes):
  1041. raise TypeError(cmd)
  1042. if isinstance(path, bytes):
  1043. path = path.decode(self._remote_path_encoding)
  1044. if path.startswith("/~"):
  1045. path = path[1:]
  1046. argv = (self._get_cmd_path(cmd).decode(self._remote_path_encoding) +
  1047. " '" + path + "'")
  1048. con = self.ssh_vendor.run_command(
  1049. self.host, argv, port=self.port, username=self.username,
  1050. password=self.password, key_filename=self.key_filename)
  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, verify_ssl=True):
  1059. """Return `urllib3` connection pool manager.
  1060. Honour detected proxy configurations.
  1061. :param config: `dulwich.config.ConfigDict` instance with Git configuration.
  1062. :param verify_ssl: Whether SSL verification is enabled.
  1063. :return: `urllib3.ProxyManager` instance for proxy configurations,
  1064. `urllib3.PoolManager` otherwise.
  1065. """
  1066. proxy_server = user_agent = None
  1067. if config is not None:
  1068. try:
  1069. proxy_server = config.get(b"http", b"proxy")
  1070. except KeyError:
  1071. pass
  1072. try:
  1073. user_agent = config.get(b"http", b"useragent")
  1074. except KeyError:
  1075. pass
  1076. ssl_kwargs = {}
  1077. if verify_ssl:
  1078. ssl_kwargs.update(cert_reqs="CERT_REQUIRED", ca_certs=certifi.where())
  1079. if user_agent is None:
  1080. user_agent = default_user_agent_string()
  1081. headers = {"User-agent": user_agent}
  1082. if proxy_server is not None:
  1083. # `urllib3` requires a `str` object in both Python 2 and 3, while
  1084. # `ConfigDict` coerces entries to `bytes` on Python 3. Compensate.
  1085. if not isinstance(proxy_server, str):
  1086. proxy_server = proxy_server.decode()
  1087. manager = urllib3.ProxyManager(proxy_server, headers=headers,
  1088. **ssl_kwargs)
  1089. else:
  1090. manager = urllib3.PoolManager(headers=headers, **ssl_kwargs)
  1091. return manager
  1092. class HttpGitClient(GitClient):
  1093. def __init__(self, base_url, dumb=None, pool_manager=None, config=None,
  1094. username=None, password=None, **kwargs):
  1095. self._base_url = base_url.rstrip("/") + "/"
  1096. self._username = username
  1097. self._password = password
  1098. self.dumb = dumb
  1099. self.headers = {}
  1100. if pool_manager is None:
  1101. self.pool_manager = default_urllib3_manager(config)
  1102. else:
  1103. self.pool_manager = pool_manager
  1104. if username is not None:
  1105. # No escaping needed: ":" is not allowed in username:
  1106. # https://tools.ietf.org/html/rfc2617#section-2
  1107. credentials = "%s:%s" % (username, password)
  1108. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  1109. self.pool_manager.headers.update(basic_auth)
  1110. GitClient.__init__(self, **kwargs)
  1111. def get_url(self, path):
  1112. return self._get_url(path).rstrip("/")
  1113. @classmethod
  1114. def from_parsedurl(cls, parsedurl, **kwargs):
  1115. auth, host = urllib2.splituser(parsedurl.netloc)
  1116. password = parsedurl.password
  1117. if password is not None:
  1118. password = urlunquote(password)
  1119. username = parsedurl.username
  1120. if username is not None:
  1121. username = urlunquote(username)
  1122. # TODO(jelmer): This also strips the username
  1123. parsedurl = parsedurl._replace(netloc=host)
  1124. return cls(urlparse.urlunparse(parsedurl),
  1125. password=password, username=username, **kwargs)
  1126. def __repr__(self):
  1127. return "%s(%r, dumb=%r)" % (
  1128. type(self).__name__, self._base_url, self.dumb)
  1129. def _get_url(self, path):
  1130. if not isinstance(path, str):
  1131. # TODO(jelmer): this is unrelated to the local filesystem;
  1132. # This is not necessarily the right encoding to decode the path
  1133. # with.
  1134. path = path.decode(sys.getfilesystemencoding())
  1135. return urlparse.urljoin(self._base_url, path).rstrip("/") + "/"
  1136. def _http_request(self, url, headers=None, data=None,
  1137. allow_compression=False):
  1138. """Perform HTTP request.
  1139. :param url: Request URL.
  1140. :param headers: Optional custom headers to override defaults.
  1141. :param data: Request data.
  1142. :param allow_compression: Allow GZipped communication.
  1143. :return: Tuple (`response`, `read`), where response is an `urllib3`
  1144. response object with additional `content_type` and
  1145. `redirect_location` properties, and `read` is a consumable read
  1146. method for the response data.
  1147. """
  1148. req_headers = self.pool_manager.headers.copy()
  1149. if headers is not None:
  1150. req_headers.update(headers)
  1151. req_headers["Pragma"] = "no-cache"
  1152. if allow_compression:
  1153. req_headers["Accept-Encoding"] = "gzip"
  1154. else:
  1155. req_headers["Accept-Encoding"] = "identity"
  1156. if data is None:
  1157. resp = self.pool_manager.request("GET", url, headers=req_headers)
  1158. else:
  1159. resp = self.pool_manager.request("POST", url, headers=req_headers,
  1160. body=data)
  1161. if resp.status == 404:
  1162. raise NotGitRepository()
  1163. elif resp.status != 200:
  1164. raise GitProtocolError("unexpected http resp %d for %s" %
  1165. (resp.status, url))
  1166. # TODO: Optimization available by adding `preload_content=False` to the
  1167. # request and just passing the `read` method on instead of going via
  1168. # `BytesIO`, if we can guarantee that the entire response is consumed
  1169. # before issuing the next to still allow for connection reuse from the
  1170. # pool.
  1171. if resp.getheader("Content-Encoding") == "gzip":
  1172. read = gzip.GzipFile(fileobj=BytesIO(resp.data)).read
  1173. else:
  1174. read = BytesIO(resp.data).read
  1175. resp.content_type = resp.getheader("Content-Type")
  1176. resp.redirect_location = resp.get_redirect_location()
  1177. return resp, read
  1178. def _discover_references(self, service, base_url):
  1179. assert base_url[-1] == "/"
  1180. tail = "info/refs"
  1181. headers = {"Accept": "*/*"}
  1182. if self.dumb is not False:
  1183. tail += "?service=%s" % service.decode('ascii')
  1184. url = urlparse.urljoin(base_url, tail)
  1185. resp, read = self._http_request(url, headers, allow_compression=True)
  1186. if resp.redirect_location:
  1187. # Something changed (redirect!), so let's update the base URL
  1188. if not resp.redirect_location.endswith(tail):
  1189. raise GitProtocolError(
  1190. "Redirected from URL %s to URL %s without %s" % (
  1191. url, resp.redirect_location, tail))
  1192. base_url = resp.redirect_location[:-len(tail)]
  1193. try:
  1194. self.dumb = not resp.content_type.startswith("application/x-git-")
  1195. if not self.dumb:
  1196. proto = Protocol(read, None)
  1197. # The first line should mention the service
  1198. try:
  1199. [pkt] = list(proto.read_pkt_seq())
  1200. except ValueError:
  1201. raise GitProtocolError(
  1202. "unexpected number of packets received")
  1203. if pkt.rstrip(b'\n') != (b'# service=' + service):
  1204. raise GitProtocolError(
  1205. "unexpected first line %r from smart server" % pkt)
  1206. return read_pkt_refs(proto) + (base_url, )
  1207. else:
  1208. return read_info_refs(resp), set(), base_url
  1209. finally:
  1210. resp.close()
  1211. def _smart_request(self, service, url, data):
  1212. assert url[-1] == "/"
  1213. url = urlparse.urljoin(url, service)
  1214. result_content_type = "application/x-%s-result" % service
  1215. headers = {
  1216. "Content-Type": "application/x-%s-request" % service,
  1217. "Accept": result_content_type,
  1218. "Content-Length": str(len(data)),
  1219. }
  1220. resp, read = self._http_request(url, headers, data)
  1221. if resp.content_type != result_content_type:
  1222. raise GitProtocolError("Invalid content-type from server: %s"
  1223. % resp.content_type)
  1224. return resp, read
  1225. def send_pack(self, path, update_refs, generate_pack_data,
  1226. progress=None):
  1227. """Upload a pack to a remote repository.
  1228. :param path: Repository path (as bytestring)
  1229. :param update_refs: Function to determine changes to remote refs.
  1230. Receive dict with existing remote refs, returns dict with
  1231. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1232. :param generate_pack_data: Function that can return a tuple
  1233. with number of elements and pack data to upload.
  1234. :param progress: Optional progress function
  1235. :raises SendPackError: if server rejects the pack data
  1236. :raises UpdateRefsError: if the server supports report-status
  1237. and rejects ref updates
  1238. :return: new_refs dictionary containing the changes that were made
  1239. {refname: new_ref}, including deleted refs.
  1240. """
  1241. url = self._get_url(path)
  1242. old_refs, server_capabilities, url = self._discover_references(
  1243. b"git-receive-pack", url)
  1244. negotiated_capabilities = self._negotiate_receive_pack_capabilities(
  1245. server_capabilities)
  1246. negotiated_capabilities.add(capability_agent())
  1247. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1248. self._report_status_parser = ReportStatusParser()
  1249. new_refs = update_refs(dict(old_refs))
  1250. if new_refs is None:
  1251. # Determine wants function is aborting the push.
  1252. return old_refs
  1253. if self.dumb:
  1254. raise NotImplementedError(self.fetch_pack)
  1255. req_data = BytesIO()
  1256. req_proto = Protocol(None, req_data.write)
  1257. (have, want) = self._handle_receive_pack_head(
  1258. req_proto, negotiated_capabilities, old_refs, new_refs)
  1259. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1260. return new_refs
  1261. pack_data_count, pack_data = generate_pack_data(
  1262. have, want,
  1263. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities))
  1264. if pack_data_count:
  1265. write_pack_data(req_proto.write_file(), pack_data_count, pack_data)
  1266. resp, read = self._smart_request("git-receive-pack", url,
  1267. data=req_data.getvalue())
  1268. try:
  1269. resp_proto = Protocol(read, None)
  1270. self._handle_receive_pack_tail(
  1271. resp_proto, negotiated_capabilities, progress)
  1272. return new_refs
  1273. finally:
  1274. resp.close()
  1275. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  1276. progress=None):
  1277. """Retrieve a pack from a git smart server.
  1278. :param determine_wants: Callback that returns list of commits to fetch
  1279. :param graph_walker: Object with next() and ack().
  1280. :param pack_data: Callback called for each bit of data in the pack
  1281. :param progress: Callback for progress reports (strings)
  1282. :return: FetchPackResult object
  1283. """
  1284. url = self._get_url(path)
  1285. refs, server_capabilities, url = self._discover_references(
  1286. b"git-upload-pack", url)
  1287. negotiated_capabilities, symrefs, agent = (
  1288. self._negotiate_upload_pack_capabilities(
  1289. server_capabilities))
  1290. wants = determine_wants(refs)
  1291. if wants is not None:
  1292. wants = [cid for cid in wants if cid != ZERO_SHA]
  1293. if not wants:
  1294. return FetchPackResult(refs, symrefs, agent)
  1295. if self.dumb:
  1296. raise NotImplementedError(self.send_pack)
  1297. req_data = BytesIO()
  1298. req_proto = Protocol(None, req_data.write)
  1299. self._handle_upload_pack_head(
  1300. req_proto, negotiated_capabilities, graph_walker, wants,
  1301. lambda: False)
  1302. resp, read = self._smart_request(
  1303. "git-upload-pack", url, data=req_data.getvalue())
  1304. try:
  1305. resp_proto = Protocol(read, None)
  1306. self._handle_upload_pack_tail(
  1307. resp_proto, negotiated_capabilities, graph_walker, pack_data,
  1308. progress)
  1309. return FetchPackResult(refs, symrefs, agent)
  1310. finally:
  1311. resp.close()
  1312. def get_refs(self, path):
  1313. """Retrieve the current refs from a git smart server."""
  1314. url = self._get_url(path)
  1315. refs, _, _ = self._discover_references(
  1316. b"git-upload-pack", url)
  1317. return refs
  1318. def get_transport_and_path_from_url(url, config=None, **kwargs):
  1319. """Obtain a git client from a URL.
  1320. :param url: URL to open (a unicode string)
  1321. :param config: Optional config object
  1322. :param thin_packs: Whether or not thin packs should be retrieved
  1323. :param report_activity: Optional callback for reporting transport
  1324. activity.
  1325. :return: Tuple with client instance and relative path.
  1326. """
  1327. parsed = urlparse.urlparse(url)
  1328. if parsed.scheme == 'git':
  1329. return (TCPGitClient.from_parsedurl(parsed, **kwargs),
  1330. parsed.path)
  1331. elif parsed.scheme in ('git+ssh', 'ssh'):
  1332. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  1333. elif parsed.scheme in ('http', 'https'):
  1334. return HttpGitClient.from_parsedurl(
  1335. parsed, config=config, **kwargs), parsed.path
  1336. elif parsed.scheme == 'file':
  1337. return default_local_git_client_cls.from_parsedurl(
  1338. parsed, **kwargs), parsed.path
  1339. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  1340. def get_transport_and_path(location, **kwargs):
  1341. """Obtain a git client from a URL.
  1342. :param location: URL or path (a string)
  1343. :param config: Optional config object
  1344. :param thin_packs: Whether or not thin packs should be retrieved
  1345. :param report_activity: Optional callback for reporting transport
  1346. activity.
  1347. :return: Tuple with client instance and relative path.
  1348. """
  1349. # First, try to parse it as a URL
  1350. try:
  1351. return get_transport_and_path_from_url(location, **kwargs)
  1352. except ValueError:
  1353. pass
  1354. if (sys.platform == 'win32' and
  1355. location[0].isalpha() and location[1:3] == ':\\'):
  1356. # Windows local path
  1357. return default_local_git_client_cls(**kwargs), location
  1358. if ':' in location and '@' not in location:
  1359. # SSH with no user@, zero or one leading slash.
  1360. (hostname, path) = location.split(':', 1)
  1361. return SSHGitClient(hostname, **kwargs), path
  1362. elif ':' in location:
  1363. # SSH with user@host:foo.
  1364. user_host, path = location.split(':', 1)
  1365. if '@' in user_host:
  1366. user, host = user_host.rsplit('@', 1)
  1367. else:
  1368. user = None
  1369. host = user_host
  1370. return SSHGitClient(host, username=user, **kwargs), path
  1371. # Otherwise, assume it's a local path.
  1372. return default_local_git_client_cls(**kwargs), location