client.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647
  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):
  667. proto, can_read = self._connect(b'upload-archive', path)
  668. with proto:
  669. proto.write_pkt_line(b"argument " + committish)
  670. proto.write_pkt_line(None)
  671. pkt = proto.read_pkt_line()
  672. if pkt == b"NACK\n":
  673. return
  674. elif pkt == b"ACK\n":
  675. pass
  676. elif pkt.startswith(b"ERR "):
  677. raise GitProtocolError(pkt[4:].rstrip(b"\n"))
  678. else:
  679. raise AssertionError("invalid response %r" % pkt)
  680. ret = proto.read_pkt_line()
  681. if ret is not None:
  682. raise AssertionError("expected pkt tail")
  683. self._read_side_band64k_data(proto, {
  684. SIDE_BAND_CHANNEL_DATA: write_data,
  685. SIDE_BAND_CHANNEL_PROGRESS: progress,
  686. SIDE_BAND_CHANNEL_FATAL: write_error})
  687. class TCPGitClient(TraditionalGitClient):
  688. """A Git Client that works over TCP directly (i.e. git://)."""
  689. def __init__(self, host, port=None, **kwargs):
  690. if port is None:
  691. port = TCP_GIT_PORT
  692. self._host = host
  693. self._port = port
  694. super(TCPGitClient, self).__init__(**kwargs)
  695. @classmethod
  696. def from_parsedurl(cls, parsedurl, **kwargs):
  697. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  698. def get_url(self, path):
  699. netloc = self._host
  700. if self._port is not None and self._port != TCP_GIT_PORT:
  701. netloc += ":%d" % self._port
  702. return urlparse.urlunsplit(("git", netloc, path, '', ''))
  703. def _connect(self, cmd, path):
  704. if not isinstance(cmd, bytes):
  705. raise TypeError(cmd)
  706. if not isinstance(path, bytes):
  707. path = path.encode(self._remote_path_encoding)
  708. sockaddrs = socket.getaddrinfo(
  709. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  710. s = None
  711. err = socket.error("no address found for %s" % self._host)
  712. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  713. s = socket.socket(family, socktype, proto)
  714. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  715. try:
  716. s.connect(sockaddr)
  717. break
  718. except socket.error as err:
  719. if s is not None:
  720. s.close()
  721. s = None
  722. if s is None:
  723. raise err
  724. # -1 means system default buffering
  725. rfile = s.makefile('rb', -1)
  726. # 0 means unbuffered
  727. wfile = s.makefile('wb', 0)
  728. def close():
  729. rfile.close()
  730. wfile.close()
  731. s.close()
  732. proto = Protocol(rfile.read, wfile.write, close,
  733. report_activity=self._report_activity)
  734. if path.startswith(b"/~"):
  735. path = path[1:]
  736. # TODO(jelmer): Alternative to ascii?
  737. proto.send_cmd(
  738. b'git-' + cmd, path, b'host=' + self._host.encode('ascii'))
  739. return proto, lambda: _fileno_can_read(s)
  740. class SubprocessWrapper(object):
  741. """A socket-like object that talks to a subprocess via pipes."""
  742. def __init__(self, proc):
  743. self.proc = proc
  744. if sys.version_info[0] == 2:
  745. self.read = proc.stdout.read
  746. else:
  747. self.read = BufferedReader(proc.stdout).read
  748. self.write = proc.stdin.write
  749. def can_read(self):
  750. if sys.platform == 'win32':
  751. from msvcrt import get_osfhandle
  752. handle = get_osfhandle(self.proc.stdout.fileno())
  753. return _win32_peek_avail(handle) != 0
  754. else:
  755. return _fileno_can_read(self.proc.stdout.fileno())
  756. def close(self):
  757. self.proc.stdin.close()
  758. self.proc.stdout.close()
  759. if self.proc.stderr:
  760. self.proc.stderr.close()
  761. self.proc.wait()
  762. def find_git_command():
  763. """Find command to run for system Git (usually C Git).
  764. """
  765. if sys.platform == 'win32': # support .exe, .bat and .cmd
  766. try: # to avoid overhead
  767. import win32api
  768. except ImportError: # run through cmd.exe with some overhead
  769. return ['cmd', '/c', 'git']
  770. else:
  771. status, git = win32api.FindExecutable('git')
  772. return [git]
  773. else:
  774. return ['git']
  775. class SubprocessGitClient(TraditionalGitClient):
  776. """Git client that talks to a server using a subprocess."""
  777. def __init__(self, **kwargs):
  778. self._connection = None
  779. self._stderr = None
  780. self._stderr = kwargs.get('stderr')
  781. if 'stderr' in kwargs:
  782. del kwargs['stderr']
  783. super(SubprocessGitClient, self).__init__(**kwargs)
  784. @classmethod
  785. def from_parsedurl(cls, parsedurl, **kwargs):
  786. return cls(**kwargs)
  787. git_command = None
  788. def _connect(self, service, path):
  789. if not isinstance(service, bytes):
  790. raise TypeError(service)
  791. if isinstance(path, bytes):
  792. path = path.decode(self._remote_path_encoding)
  793. if self.git_command is None:
  794. git_command = find_git_command()
  795. argv = git_command + [service.decode('ascii'), path]
  796. p = SubprocessWrapper(
  797. subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  798. stdout=subprocess.PIPE,
  799. stderr=self._stderr))
  800. return Protocol(p.read, p.write, p.close,
  801. report_activity=self._report_activity), p.can_read
  802. class LocalGitClient(GitClient):
  803. """Git Client that just uses a local Repo."""
  804. def __init__(self, thin_packs=True, report_activity=None, config=None):
  805. """Create a new LocalGitClient instance.
  806. :param thin_packs: Whether or not thin packs should be retrieved
  807. :param report_activity: Optional callback for reporting transport
  808. activity.
  809. """
  810. self._report_activity = report_activity
  811. # Ignore the thin_packs argument
  812. def get_url(self, path):
  813. return urlparse.urlunsplit(('file', '', path, '', ''))
  814. @classmethod
  815. def from_parsedurl(cls, parsedurl, **kwargs):
  816. return cls(**kwargs)
  817. @classmethod
  818. def _open_repo(cls, path):
  819. from dulwich.repo import Repo
  820. if not isinstance(path, str):
  821. path = path.decode(sys.getfilesystemencoding())
  822. return closing(Repo(path))
  823. def send_pack(self, path, update_refs, generate_pack_data,
  824. progress=None):
  825. """Upload a pack to a remote repository.
  826. :param path: Repository path (as bytestring)
  827. :param update_refs: Function to determine changes to remote refs.
  828. Receive dict with existing remote refs, returns dict with
  829. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  830. :param generate_pack_data: Function that can return a tuple
  831. with number of items and pack data to upload.
  832. :param progress: Optional progress function
  833. :raises SendPackError: if server rejects the pack data
  834. :raises UpdateRefsError: if the server supports report-status
  835. and rejects ref updates
  836. :return: new_refs dictionary containing the changes that were made
  837. {refname: new_ref}, including deleted refs.
  838. """
  839. if not progress:
  840. def progress(x):
  841. pass
  842. with self._open_repo(path) as target:
  843. old_refs = target.get_refs()
  844. new_refs = update_refs(dict(old_refs))
  845. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  846. want = []
  847. for refname, new_sha1 in new_refs.items():
  848. if (new_sha1 not in have and
  849. new_sha1 not in want and
  850. new_sha1 != ZERO_SHA):
  851. want.append(new_sha1)
  852. if (not want and
  853. set(new_refs.items()).issubset(set(old_refs.items()))):
  854. return new_refs
  855. target.object_store.add_pack_data(
  856. *generate_pack_data(have, want, ofs_delta=True))
  857. for refname, new_sha1 in new_refs.items():
  858. old_sha1 = old_refs.get(refname, ZERO_SHA)
  859. if new_sha1 != ZERO_SHA:
  860. if not target.refs.set_if_equals(
  861. refname, old_sha1, new_sha1):
  862. progress('unable to set %s to %s' %
  863. (refname, new_sha1))
  864. else:
  865. if not target.refs.remove_if_equals(refname, old_sha1):
  866. progress('unable to remove %s' % refname)
  867. return new_refs
  868. def fetch(self, path, target, determine_wants=None, progress=None):
  869. """Fetch into a target repository.
  870. :param path: Path to fetch from (as bytestring)
  871. :param target: Target repository to fetch into
  872. :param determine_wants: Optional function determine what refs
  873. to fetch. Receives dictionary of name->sha, should return
  874. list of shas to fetch. Defaults to all shas.
  875. :param progress: Optional progress function
  876. :return: FetchPackResult object
  877. """
  878. with self._open_repo(path) as r:
  879. refs = r.fetch(target, determine_wants=determine_wants,
  880. progress=progress)
  881. return FetchPackResult(refs, r.refs.get_symrefs(),
  882. agent_string())
  883. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  884. progress=None):
  885. """Retrieve a pack from a git smart server.
  886. :param path: Remote path to fetch from
  887. :param determine_wants: Function determine what refs
  888. to fetch. Receives dictionary of name->sha, should return
  889. list of shas to fetch.
  890. :param graph_walker: Object with next() and ack().
  891. :param pack_data: Callback called for each bit of data in the pack
  892. :param progress: Callback for progress reports (strings)
  893. :return: FetchPackResult object
  894. """
  895. with self._open_repo(path) as r:
  896. objects_iter = r.fetch_objects(
  897. determine_wants, graph_walker, progress)
  898. symrefs = r.refs.get_symrefs()
  899. agent = agent_string()
  900. # Did the process short-circuit (e.g. in a stateless RPC call)?
  901. # Note that the client still expects a 0-object pack in most cases.
  902. if objects_iter is None:
  903. return FetchPackResult(None, symrefs, agent)
  904. protocol = ProtocolFile(None, pack_data)
  905. write_pack_objects(protocol, objects_iter)
  906. return FetchPackResult(r.get_refs(), symrefs, agent)
  907. def get_refs(self, path):
  908. """Retrieve the current refs from a git smart server."""
  909. with self._open_repo(path) as target:
  910. return target.get_refs()
  911. # What Git client to use for local access
  912. default_local_git_client_cls = LocalGitClient
  913. class SSHVendor(object):
  914. """A client side SSH implementation."""
  915. def connect_ssh(self, host, command, username=None, port=None,
  916. password=None, key_filename=None):
  917. # This function was deprecated in 0.9.1
  918. import warnings
  919. warnings.warn(
  920. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  921. DeprecationWarning)
  922. return self.run_command(host, command, username=username, port=port,
  923. password=password, key_filename=key_filename)
  924. def run_command(self, host, command, username=None, port=None,
  925. password=None, key_filename=None):
  926. """Connect to an SSH server.
  927. Run a command remotely and return a file-like object for interaction
  928. with the remote command.
  929. :param host: Host name
  930. :param command: Command to run (as argv array)
  931. :param username: Optional ame of user to log in as
  932. :param port: Optional SSH port to use
  933. :param password: Optional ssh password for login or private key
  934. :param key_filename: Optional path to private keyfile
  935. """
  936. raise NotImplementedError(self.run_command)
  937. class StrangeHostname(Exception):
  938. """Refusing to connect to strange SSH hostname."""
  939. def __init__(self, hostname):
  940. super(StrangeHostname, self).__init__(hostname)
  941. class SubprocessSSHVendor(SSHVendor):
  942. """SSH vendor that shells out to the local 'ssh' command."""
  943. def run_command(self, host, command, username=None, port=None,
  944. password=None, key_filename=None):
  945. if password is not None:
  946. raise NotImplementedError(
  947. "Setting password not supported by SubprocessSSHVendor.")
  948. args = ['ssh', '-x']
  949. if port:
  950. args.extend(['-p', str(port)])
  951. if key_filename:
  952. args.extend(['-i', str(key_filename)])
  953. if username:
  954. host = '%s@%s' % (username, host)
  955. if host.startswith('-'):
  956. raise StrangeHostname(hostname=host)
  957. args.append(host)
  958. proc = subprocess.Popen(args + [command], bufsize=0,
  959. stdin=subprocess.PIPE,
  960. stdout=subprocess.PIPE)
  961. return SubprocessWrapper(proc)
  962. class PLinkSSHVendor(SSHVendor):
  963. """SSH vendor that shells out to the local 'plink' command."""
  964. def run_command(self, host, command, username=None, port=None,
  965. password=None, key_filename=None):
  966. if sys.platform == 'win32':
  967. args = ['plink.exe', '-ssh']
  968. else:
  969. args = ['plink', '-ssh']
  970. if password is not None:
  971. import warnings
  972. warnings.warn(
  973. "Invoking PLink with a password exposes the password in the "
  974. "process list.")
  975. args.extend(['-pw', str(password)])
  976. if port:
  977. args.extend(['-P', str(port)])
  978. if key_filename:
  979. args.extend(['-i', str(key_filename)])
  980. if username:
  981. host = '%s@%s' % (username, host)
  982. if host.startswith('-'):
  983. raise StrangeHostname(hostname=host)
  984. args.append(host)
  985. proc = subprocess.Popen(args + [command], bufsize=0,
  986. stdin=subprocess.PIPE,
  987. stdout=subprocess.PIPE)
  988. return SubprocessWrapper(proc)
  989. def ParamikoSSHVendor(**kwargs):
  990. import warnings
  991. warnings.warn(
  992. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  993. DeprecationWarning)
  994. from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
  995. return ParamikoSSHVendor(**kwargs)
  996. # Can be overridden by users
  997. get_ssh_vendor = SubprocessSSHVendor
  998. class SSHGitClient(TraditionalGitClient):
  999. def __init__(self, host, port=None, username=None, vendor=None,
  1000. config=None, password=None, key_filename=None, **kwargs):
  1001. self.host = host
  1002. self.port = port
  1003. self.username = username
  1004. self.password = password
  1005. self.key_filename = key_filename
  1006. super(SSHGitClient, self).__init__(**kwargs)
  1007. self.alternative_paths = {}
  1008. if vendor is not None:
  1009. self.ssh_vendor = vendor
  1010. else:
  1011. self.ssh_vendor = get_ssh_vendor()
  1012. def get_url(self, path):
  1013. netloc = self.host
  1014. if self.port is not None:
  1015. netloc += ":%d" % self.port
  1016. if self.username is not None:
  1017. netloc = urlquote(self.username, '@/:') + "@" + netloc
  1018. return urlparse.urlunsplit(('ssh', netloc, path, '', ''))
  1019. @classmethod
  1020. def from_parsedurl(cls, parsedurl, **kwargs):
  1021. return cls(host=parsedurl.hostname, port=parsedurl.port,
  1022. username=parsedurl.username, **kwargs)
  1023. def _get_cmd_path(self, cmd):
  1024. cmd = self.alternative_paths.get(cmd, b'git-' + cmd)
  1025. assert isinstance(cmd, bytes)
  1026. return cmd
  1027. def _connect(self, cmd, path):
  1028. if not isinstance(cmd, bytes):
  1029. raise TypeError(cmd)
  1030. if isinstance(path, bytes):
  1031. path = path.decode(self._remote_path_encoding)
  1032. if path.startswith("/~"):
  1033. path = path[1:]
  1034. argv = (self._get_cmd_path(cmd).decode(self._remote_path_encoding) +
  1035. " '" + path + "'")
  1036. kwargs = {}
  1037. if self.password is not None:
  1038. kwargs['password'] = self.password
  1039. if self.key_filename is not None:
  1040. kwargs['key_filename'] = self.key_filename
  1041. con = self.ssh_vendor.run_command(
  1042. self.host, argv, port=self.port, username=self.username,
  1043. **kwargs)
  1044. return (Protocol(con.read, con.write, con.close,
  1045. report_activity=self._report_activity),
  1046. con.can_read)
  1047. def default_user_agent_string():
  1048. # Start user agent with "git/", because GitHub requires this. :-( See
  1049. # https://github.com/jelmer/dulwich/issues/562 for details.
  1050. return "git/dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  1051. def default_urllib3_manager(config, **override_kwargs):
  1052. """Return `urllib3` connection pool manager.
  1053. Honour detected proxy configurations.
  1054. :param config: `dulwich.config.ConfigDict` instance with Git configuration.
  1055. :param kwargs: Additional arguments for urllib3.ProxyManager
  1056. :return: `urllib3.ProxyManager` instance for proxy configurations,
  1057. `urllib3.PoolManager` otherwise.
  1058. """
  1059. proxy_server = user_agent = None
  1060. ca_certs = ssl_verify = None
  1061. if config is not None:
  1062. try:
  1063. proxy_server = config.get(b"http", b"proxy")
  1064. except KeyError:
  1065. pass
  1066. try:
  1067. user_agent = config.get(b"http", b"useragent")
  1068. except KeyError:
  1069. pass
  1070. # TODO(jelmer): Support per-host settings
  1071. try:
  1072. ssl_verify = config.get_boolean(b"http", b"sslVerify")
  1073. except KeyError:
  1074. ssl_verify = True
  1075. try:
  1076. ca_certs = config.get_boolean(b"http", b"sslCAInfo")
  1077. except KeyError:
  1078. ca_certs = None
  1079. if user_agent is None:
  1080. user_agent = default_user_agent_string()
  1081. headers = {"User-agent": user_agent}
  1082. kwargs = {}
  1083. if ssl_verify is True:
  1084. kwargs['cert_reqs'] = "CERT_REQUIRED"
  1085. elif ssl_verify is False:
  1086. kwargs['cert_reqs'] = 'CERT_NONE'
  1087. else:
  1088. # Default to SSL verification
  1089. kwargs['cert_reqs'] = "CERT_REQUIRED"
  1090. if ca_certs is not None:
  1091. kwargs['ca_certs'] = ca_certs
  1092. kwargs.update(override_kwargs)
  1093. # Try really hard to find a SSL certificate path
  1094. if 'ca_certs' not in kwargs and kwargs.get('cert_reqs') != 'CERT_NONE':
  1095. try:
  1096. import certifi
  1097. except ImportError:
  1098. pass
  1099. else:
  1100. kwargs['ca_certs'] = certifi.where()
  1101. import urllib3
  1102. if proxy_server is not None:
  1103. # `urllib3` requires a `str` object in both Python 2 and 3, while
  1104. # `ConfigDict` coerces entries to `bytes` on Python 3. Compensate.
  1105. if not isinstance(proxy_server, str):
  1106. proxy_server = proxy_server.decode()
  1107. manager = urllib3.ProxyManager(proxy_server, headers=headers,
  1108. **kwargs)
  1109. else:
  1110. manager = urllib3.PoolManager(headers=headers, **kwargs)
  1111. return manager
  1112. class HttpGitClient(GitClient):
  1113. def __init__(self, base_url, dumb=None, pool_manager=None, config=None,
  1114. username=None, password=None, **kwargs):
  1115. self._base_url = base_url.rstrip("/") + "/"
  1116. self._username = username
  1117. self._password = password
  1118. self.dumb = dumb
  1119. self.headers = {}
  1120. if pool_manager is None:
  1121. self.pool_manager = default_urllib3_manager(config)
  1122. else:
  1123. self.pool_manager = pool_manager
  1124. if username is not None:
  1125. # No escaping needed: ":" is not allowed in username:
  1126. # https://tools.ietf.org/html/rfc2617#section-2
  1127. credentials = "%s:%s" % (username, password)
  1128. import urllib3.util
  1129. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  1130. self.pool_manager.headers.update(basic_auth)
  1131. GitClient.__init__(self, **kwargs)
  1132. def get_url(self, path):
  1133. return self._get_url(path).rstrip("/")
  1134. @classmethod
  1135. def from_parsedurl(cls, parsedurl, **kwargs):
  1136. auth, host = urllib2.splituser(parsedurl.netloc)
  1137. password = parsedurl.password
  1138. if password is not None:
  1139. password = urlunquote(password)
  1140. username = parsedurl.username
  1141. if username is not None:
  1142. username = urlunquote(username)
  1143. # TODO(jelmer): This also strips the username
  1144. parsedurl = parsedurl._replace(netloc=host)
  1145. return cls(urlparse.urlunparse(parsedurl),
  1146. password=password, username=username, **kwargs)
  1147. def __repr__(self):
  1148. return "%s(%r, dumb=%r)" % (
  1149. type(self).__name__, self._base_url, self.dumb)
  1150. def _get_url(self, path):
  1151. if not isinstance(path, str):
  1152. # TODO(jelmer): this is unrelated to the local filesystem;
  1153. # This is not necessarily the right encoding to decode the path
  1154. # with.
  1155. path = path.decode(sys.getfilesystemencoding())
  1156. return urlparse.urljoin(self._base_url, path).rstrip("/") + "/"
  1157. def _http_request(self, url, headers=None, data=None,
  1158. allow_compression=False):
  1159. """Perform HTTP request.
  1160. :param url: Request URL.
  1161. :param headers: Optional custom headers to override defaults.
  1162. :param data: Request data.
  1163. :param allow_compression: Allow GZipped communication.
  1164. :return: Tuple (`response`, `read`), where response is an `urllib3`
  1165. response object with additional `content_type` and
  1166. `redirect_location` properties, and `read` is a consumable read
  1167. method for the response data.
  1168. """
  1169. req_headers = self.pool_manager.headers.copy()
  1170. if headers is not None:
  1171. req_headers.update(headers)
  1172. req_headers["Pragma"] = "no-cache"
  1173. if allow_compression:
  1174. req_headers["Accept-Encoding"] = "gzip"
  1175. else:
  1176. req_headers["Accept-Encoding"] = "identity"
  1177. if data is None:
  1178. resp = self.pool_manager.request("GET", url, headers=req_headers)
  1179. else:
  1180. resp = self.pool_manager.request("POST", url, headers=req_headers,
  1181. body=data)
  1182. if resp.status == 404:
  1183. raise NotGitRepository()
  1184. elif resp.status != 200:
  1185. raise GitProtocolError("unexpected http resp %d for %s" %
  1186. (resp.status, url))
  1187. # TODO: Optimization available by adding `preload_content=False` to the
  1188. # request and just passing the `read` method on instead of going via
  1189. # `BytesIO`, if we can guarantee that the entire response is consumed
  1190. # before issuing the next to still allow for connection reuse from the
  1191. # pool.
  1192. if resp.getheader("Content-Encoding") == "gzip":
  1193. read = gzip.GzipFile(fileobj=BytesIO(resp.data)).read
  1194. else:
  1195. read = BytesIO(resp.data).read
  1196. resp.content_type = resp.getheader("Content-Type")
  1197. resp.redirect_location = resp.get_redirect_location()
  1198. return resp, read
  1199. def _discover_references(self, service, base_url):
  1200. assert base_url[-1] == "/"
  1201. tail = "info/refs"
  1202. headers = {"Accept": "*/*"}
  1203. if self.dumb is not True:
  1204. tail += "?service=%s" % service.decode('ascii')
  1205. url = urlparse.urljoin(base_url, tail)
  1206. resp, read = self._http_request(url, headers, allow_compression=True)
  1207. if resp.redirect_location:
  1208. # Something changed (redirect!), so let's update the base URL
  1209. if not resp.redirect_location.endswith(tail):
  1210. raise GitProtocolError(
  1211. "Redirected from URL %s to URL %s without %s" % (
  1212. url, resp.redirect_location, tail))
  1213. base_url = resp.redirect_location[:-len(tail)]
  1214. try:
  1215. self.dumb = not resp.content_type.startswith("application/x-git-")
  1216. if not self.dumb:
  1217. proto = Protocol(read, None)
  1218. # The first line should mention the service
  1219. try:
  1220. [pkt] = list(proto.read_pkt_seq())
  1221. except ValueError:
  1222. raise GitProtocolError(
  1223. "unexpected number of packets received")
  1224. if pkt.rstrip(b'\n') != (b'# service=' + service):
  1225. raise GitProtocolError(
  1226. "unexpected first line %r from smart server" % pkt)
  1227. return read_pkt_refs(proto) + (base_url, )
  1228. else:
  1229. return read_info_refs(resp), set(), base_url
  1230. finally:
  1231. resp.close()
  1232. def _smart_request(self, service, url, data):
  1233. assert url[-1] == "/"
  1234. url = urlparse.urljoin(url, service)
  1235. result_content_type = "application/x-%s-result" % service
  1236. headers = {
  1237. "Content-Type": "application/x-%s-request" % service,
  1238. "Accept": result_content_type,
  1239. "Content-Length": str(len(data)),
  1240. }
  1241. resp, read = self._http_request(url, headers, data)
  1242. if resp.content_type != result_content_type:
  1243. raise GitProtocolError("Invalid content-type from server: %s"
  1244. % resp.content_type)
  1245. return resp, read
  1246. def send_pack(self, path, update_refs, generate_pack_data,
  1247. progress=None):
  1248. """Upload a pack to a remote repository.
  1249. :param path: Repository path (as bytestring)
  1250. :param update_refs: Function to determine changes to remote refs.
  1251. Receive dict with existing remote refs, returns dict with
  1252. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1253. :param generate_pack_data: Function that can return a tuple
  1254. with number of elements and pack data to upload.
  1255. :param progress: Optional progress function
  1256. :raises SendPackError: if server rejects the pack data
  1257. :raises UpdateRefsError: if the server supports report-status
  1258. and rejects ref updates
  1259. :return: new_refs dictionary containing the changes that were made
  1260. {refname: new_ref}, including deleted refs.
  1261. """
  1262. url = self._get_url(path)
  1263. old_refs, server_capabilities, url = self._discover_references(
  1264. b"git-receive-pack", url)
  1265. negotiated_capabilities = self._negotiate_receive_pack_capabilities(
  1266. server_capabilities)
  1267. negotiated_capabilities.add(capability_agent())
  1268. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1269. self._report_status_parser = ReportStatusParser()
  1270. new_refs = update_refs(dict(old_refs))
  1271. if new_refs is None:
  1272. # Determine wants function is aborting the push.
  1273. return old_refs
  1274. if self.dumb:
  1275. raise NotImplementedError(self.fetch_pack)
  1276. req_data = BytesIO()
  1277. req_proto = Protocol(None, req_data.write)
  1278. (have, want) = self._handle_receive_pack_head(
  1279. req_proto, negotiated_capabilities, old_refs, new_refs)
  1280. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1281. return new_refs
  1282. pack_data_count, pack_data = generate_pack_data(
  1283. have, want,
  1284. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities))
  1285. if pack_data_count:
  1286. write_pack_data(req_proto.write_file(), pack_data_count, pack_data)
  1287. resp, read = self._smart_request("git-receive-pack", url,
  1288. data=req_data.getvalue())
  1289. try:
  1290. resp_proto = Protocol(read, None)
  1291. self._handle_receive_pack_tail(
  1292. resp_proto, negotiated_capabilities, progress)
  1293. return new_refs
  1294. finally:
  1295. resp.close()
  1296. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  1297. progress=None):
  1298. """Retrieve a pack from a git smart server.
  1299. :param determine_wants: Callback that returns list of commits to fetch
  1300. :param graph_walker: Object with next() and ack().
  1301. :param pack_data: Callback called for each bit of data in the pack
  1302. :param progress: Callback for progress reports (strings)
  1303. :return: FetchPackResult object
  1304. """
  1305. url = self._get_url(path)
  1306. refs, server_capabilities, url = self._discover_references(
  1307. b"git-upload-pack", url)
  1308. negotiated_capabilities, symrefs, agent = (
  1309. self._negotiate_upload_pack_capabilities(
  1310. server_capabilities))
  1311. wants = determine_wants(refs)
  1312. if wants is not None:
  1313. wants = [cid for cid in wants if cid != ZERO_SHA]
  1314. if not wants:
  1315. return FetchPackResult(refs, symrefs, agent)
  1316. if self.dumb:
  1317. raise NotImplementedError(self.send_pack)
  1318. req_data = BytesIO()
  1319. req_proto = Protocol(None, req_data.write)
  1320. self._handle_upload_pack_head(
  1321. req_proto, negotiated_capabilities, graph_walker, wants,
  1322. lambda: False)
  1323. resp, read = self._smart_request(
  1324. "git-upload-pack", url, data=req_data.getvalue())
  1325. try:
  1326. resp_proto = Protocol(read, None)
  1327. self._handle_upload_pack_tail(
  1328. resp_proto, negotiated_capabilities, graph_walker, pack_data,
  1329. progress)
  1330. return FetchPackResult(refs, symrefs, agent)
  1331. finally:
  1332. resp.close()
  1333. def get_refs(self, path):
  1334. """Retrieve the current refs from a git smart server."""
  1335. url = self._get_url(path)
  1336. refs, _, _ = self._discover_references(
  1337. b"git-upload-pack", url)
  1338. return refs
  1339. def get_transport_and_path_from_url(url, config=None, **kwargs):
  1340. """Obtain a git client from a URL.
  1341. :param url: URL to open (a unicode string)
  1342. :param config: Optional config object
  1343. :param thin_packs: Whether or not thin packs should be retrieved
  1344. :param report_activity: Optional callback for reporting transport
  1345. activity.
  1346. :return: Tuple with client instance and relative path.
  1347. """
  1348. parsed = urlparse.urlparse(url)
  1349. if parsed.scheme == 'git':
  1350. return (TCPGitClient.from_parsedurl(parsed, **kwargs),
  1351. parsed.path)
  1352. elif parsed.scheme in ('git+ssh', 'ssh'):
  1353. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  1354. elif parsed.scheme in ('http', 'https'):
  1355. return HttpGitClient.from_parsedurl(
  1356. parsed, config=config, **kwargs), parsed.path
  1357. elif parsed.scheme == 'file':
  1358. return default_local_git_client_cls.from_parsedurl(
  1359. parsed, **kwargs), parsed.path
  1360. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  1361. def parse_rsync_url(location):
  1362. """Parse a rsync-style URL."""
  1363. if ':' in location and '@' not in location:
  1364. # SSH with no user@, zero or one leading slash.
  1365. (host, path) = location.split(':', 1)
  1366. user = None
  1367. elif ':' in location:
  1368. # SSH with user@host:foo.
  1369. user_host, path = location.split(':', 1)
  1370. if '@' in user_host:
  1371. user, host = user_host.rsplit('@', 1)
  1372. else:
  1373. user = None
  1374. host = user_host
  1375. else:
  1376. raise ValueError('not a valid rsync-style URL')
  1377. return (user, host, path)
  1378. def get_transport_and_path(location, **kwargs):
  1379. """Obtain a git client from a URL.
  1380. :param location: URL or path (a string)
  1381. :param config: Optional config object
  1382. :param thin_packs: Whether or not thin packs should be retrieved
  1383. :param report_activity: Optional callback for reporting transport
  1384. activity.
  1385. :return: Tuple with client instance and relative path.
  1386. """
  1387. # First, try to parse it as a URL
  1388. try:
  1389. return get_transport_and_path_from_url(location, **kwargs)
  1390. except ValueError:
  1391. pass
  1392. if (sys.platform == 'win32' and
  1393. location[0].isalpha() and location[1:3] == ':\\'):
  1394. # Windows local path
  1395. return default_local_git_client_cls(**kwargs), location
  1396. try:
  1397. (username, hostname, path) = parse_rsync_url(location)
  1398. except ValueError:
  1399. # Otherwise, assume it's a local path.
  1400. return default_local_git_client_cls(**kwargs), location
  1401. else:
  1402. return SSHGitClient(hostname, username=username, **kwargs), path