client.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
  1. # client.py -- Implementation of the client side git protocols
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Client side support for the Git protocol.
  21. The Dulwich client supports the following capabilities:
  22. * thin-pack
  23. * multi_ack_detailed
  24. * multi_ack
  25. * side-band-64k
  26. * ofs-delta
  27. * quiet
  28. * report-status
  29. * delete-refs
  30. Known capabilities that are not supported:
  31. * shallow
  32. * no-progress
  33. * include-tag
  34. """
  35. from contextlib import closing
  36. from io import BytesIO, BufferedReader
  37. import gzip
  38. import select
  39. import socket
  40. import subprocess
  41. import sys
  42. try:
  43. from urllib import quote as urlquote
  44. from urllib import unquote as urlunquote
  45. except ImportError:
  46. from urllib.parse import quote as urlquote
  47. from urllib.parse import unquote as urlunquote
  48. try:
  49. import urlparse
  50. except ImportError:
  51. import urllib.parse as urlparse
  52. import dulwich
  53. from dulwich.errors import (
  54. GitProtocolError,
  55. NotGitRepository,
  56. SendPackError,
  57. UpdateRefsError,
  58. )
  59. from dulwich.protocol import (
  60. _RBUFSIZE,
  61. agent_string,
  62. capability_agent,
  63. extract_capability_names,
  64. CAPABILITY_AGENT,
  65. CAPABILITY_DELETE_REFS,
  66. CAPABILITY_MULTI_ACK,
  67. CAPABILITY_MULTI_ACK_DETAILED,
  68. CAPABILITY_OFS_DELTA,
  69. CAPABILITY_QUIET,
  70. CAPABILITY_REPORT_STATUS,
  71. CAPABILITY_SYMREF,
  72. CAPABILITY_SIDE_BAND_64K,
  73. CAPABILITY_THIN_PACK,
  74. CAPABILITIES_REF,
  75. KNOWN_RECEIVE_CAPABILITIES,
  76. KNOWN_UPLOAD_CAPABILITIES,
  77. COMMAND_DONE,
  78. COMMAND_HAVE,
  79. COMMAND_WANT,
  80. SIDE_BAND_CHANNEL_DATA,
  81. SIDE_BAND_CHANNEL_PROGRESS,
  82. SIDE_BAND_CHANNEL_FATAL,
  83. PktLineParser,
  84. Protocol,
  85. ProtocolFile,
  86. TCP_GIT_PORT,
  87. ZERO_SHA,
  88. extract_capabilities,
  89. parse_capability,
  90. )
  91. from dulwich.pack import (
  92. write_pack_data,
  93. write_pack_objects,
  94. )
  95. from dulwich.refs import (
  96. read_info_refs,
  97. ANNOTATED_TAG_SUFFIX,
  98. )
  99. class InvalidWants(Exception):
  100. """Invalid wants."""
  101. def __init__(self, wants):
  102. Exception.__init__(
  103. self,
  104. "requested wants not in server provided refs: %r" % wants)
  105. def _fileno_can_read(fileno):
  106. """Check if a file descriptor is readable."""
  107. return len(select.select([fileno], [], [], 0)[0]) > 0
  108. def _win32_peek_avail(handle):
  109. """Wrapper around PeekNamedPipe to check how many bytes are available."""
  110. from ctypes import byref, wintypes, windll
  111. c_avail = wintypes.DWORD()
  112. c_message = wintypes.DWORD()
  113. success = windll.kernel32.PeekNamedPipe(
  114. handle, None, 0, None, byref(c_avail),
  115. byref(c_message))
  116. if not success:
  117. raise OSError(wintypes.GetLastError())
  118. return c_avail.value
  119. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  120. UPLOAD_CAPABILITIES = ([CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK,
  121. CAPABILITY_MULTI_ACK_DETAILED] + COMMON_CAPABILITIES)
  122. RECEIVE_CAPABILITIES = [CAPABILITY_REPORT_STATUS] + COMMON_CAPABILITIES
  123. class ReportStatusParser(object):
  124. """Handle status as reported by servers with 'report-status' capability.
  125. """
  126. def __init__(self):
  127. self._done = False
  128. self._pack_status = None
  129. self._ref_status_ok = True
  130. self._ref_statuses = []
  131. def check(self):
  132. """Check if there were any errors and, if so, raise exceptions.
  133. :raise SendPackError: Raised when the server could not unpack
  134. :raise UpdateRefsError: Raised when refs could not be updated
  135. """
  136. if self._pack_status not in (b'unpack ok', None):
  137. raise SendPackError(self._pack_status)
  138. if not self._ref_status_ok:
  139. ref_status = {}
  140. ok = set()
  141. for status in self._ref_statuses:
  142. if b' ' not in status:
  143. # malformed response, move on to the next one
  144. continue
  145. status, ref = status.split(b' ', 1)
  146. if status == b'ng':
  147. if b' ' in ref:
  148. ref, status = ref.split(b' ', 1)
  149. else:
  150. ok.add(ref)
  151. ref_status[ref] = status
  152. # TODO(jelmer): don't assume encoding of refs is ascii.
  153. raise UpdateRefsError(', '.join([
  154. refname.decode('ascii') for refname in ref_status
  155. if refname not in ok]) +
  156. ' failed to update', ref_status=ref_status)
  157. def handle_packet(self, pkt):
  158. """Handle a packet.
  159. :raise GitProtocolError: Raised when packets are received after a
  160. flush packet.
  161. """
  162. if self._done:
  163. raise GitProtocolError("received more data after status report")
  164. if pkt is None:
  165. self._done = True
  166. return
  167. if self._pack_status is None:
  168. self._pack_status = pkt.strip()
  169. else:
  170. ref_status = pkt.strip()
  171. self._ref_statuses.append(ref_status)
  172. if not ref_status.startswith(b'ok '):
  173. self._ref_status_ok = False
  174. def read_pkt_refs(proto):
  175. server_capabilities = None
  176. refs = {}
  177. # Receive refs from server
  178. for pkt in proto.read_pkt_seq():
  179. (sha, ref) = pkt.rstrip(b'\n').split(None, 1)
  180. if sha == b'ERR':
  181. raise GitProtocolError(ref)
  182. if server_capabilities is None:
  183. (ref, server_capabilities) = extract_capabilities(ref)
  184. refs[ref] = sha
  185. if len(refs) == 0:
  186. return {}, set([])
  187. if refs == {CAPABILITIES_REF: ZERO_SHA}:
  188. refs = {}
  189. return refs, set(server_capabilities)
  190. class FetchPackResult(object):
  191. """Result of a fetch-pack operation.
  192. :var refs: Dictionary with all remote refs
  193. :var symrefs: Dictionary with remote symrefs
  194. :var agent: User agent string
  195. """
  196. _FORWARDED_ATTRS = [
  197. 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items',
  198. 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem',
  199. 'setdefault', 'update', 'values', 'viewitems', 'viewkeys',
  200. 'viewvalues']
  201. def __init__(self, refs, symrefs, agent):
  202. self.refs = refs
  203. self.symrefs = symrefs
  204. self.agent = agent
  205. def _warn_deprecated(self):
  206. import warnings
  207. warnings.warn(
  208. "Use FetchPackResult.refs instead.",
  209. DeprecationWarning, stacklevel=3)
  210. def __eq__(self, other):
  211. if isinstance(other, dict):
  212. self._warn_deprecated()
  213. return (self.refs == other)
  214. return (self.refs == other.refs and
  215. self.symrefs == other.symrefs and
  216. self.agent == other.agent)
  217. def __contains__(self, name):
  218. self._warn_deprecated()
  219. return name in self.refs
  220. def __getitem__(self, name):
  221. self._warn_deprecated()
  222. return self.refs[name]
  223. def __len__(self):
  224. self._warn_deprecated()
  225. return len(self.refs)
  226. def __iter__(self):
  227. self._warn_deprecated()
  228. return iter(self.refs)
  229. def __getattribute__(self, name):
  230. if name in type(self)._FORWARDED_ATTRS:
  231. self._warn_deprecated()
  232. return getattr(self.refs, name)
  233. return super(FetchPackResult, self).__getattribute__(name)
  234. def __repr__(self):
  235. return "%s(%r, %r, %r)" % (
  236. self.__class__.__name__, self.refs, self.symrefs, self.agent)
  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. def check_wants(wants, refs):
  543. """Check that a set of wants is valid.
  544. :param wants: Set of object SHAs to fetch
  545. :param refs: Refs dictionary to check against
  546. """
  547. missing = set(wants) - {
  548. v for (k, v) in refs.items()
  549. if not k.endswith(ANNOTATED_TAG_SUFFIX)}
  550. if missing:
  551. raise InvalidWants(missing)
  552. class TraditionalGitClient(GitClient):
  553. """Traditional Git client."""
  554. DEFAULT_ENCODING = 'utf-8'
  555. def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs):
  556. self._remote_path_encoding = path_encoding
  557. super(TraditionalGitClient, self).__init__(**kwargs)
  558. def _connect(self, cmd, path):
  559. """Create a connection to the server.
  560. This method is abstract - concrete implementations should
  561. implement their own variant which connects to the server and
  562. returns an initialized Protocol object with the service ready
  563. for use and a can_read function which may be used to see if
  564. reads would block.
  565. :param cmd: The git service name to which we should connect.
  566. :param path: The path we should pass to the service. (as bytestirng)
  567. """
  568. raise NotImplementedError()
  569. def send_pack(self, path, update_refs, generate_pack_data,
  570. progress=None):
  571. """Upload a pack to a remote repository.
  572. :param path: Repository path (as bytestring)
  573. :param update_refs: Function to determine changes to remote refs.
  574. Receive dict with existing remote refs, returns dict with
  575. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  576. :param generate_pack_data: Function that can return a tuple with
  577. number of objects and pack data to upload.
  578. :param progress: Optional callback called with progress updates
  579. :raises SendPackError: if server rejects the pack data
  580. :raises UpdateRefsError: if the server supports report-status
  581. and rejects ref updates
  582. :return: new_refs dictionary containing the changes that were made
  583. {refname: new_ref}, including deleted refs.
  584. """
  585. proto, unused_can_read = self._connect(b'receive-pack', path)
  586. with proto:
  587. old_refs, server_capabilities = read_pkt_refs(proto)
  588. negotiated_capabilities = \
  589. self._negotiate_receive_pack_capabilities(server_capabilities)
  590. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  591. self._report_status_parser = ReportStatusParser()
  592. report_status_parser = self._report_status_parser
  593. try:
  594. new_refs = orig_new_refs = update_refs(dict(old_refs))
  595. except BaseException:
  596. proto.write_pkt_line(None)
  597. raise
  598. if CAPABILITY_DELETE_REFS not in server_capabilities:
  599. # Server does not support deletions. Fail later.
  600. new_refs = dict(orig_new_refs)
  601. for ref, sha in orig_new_refs.items():
  602. if sha == ZERO_SHA:
  603. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  604. report_status_parser._ref_statuses.append(
  605. b'ng ' + sha +
  606. b' remote does not support deleting refs')
  607. report_status_parser._ref_status_ok = False
  608. del new_refs[ref]
  609. if new_refs is None:
  610. proto.write_pkt_line(None)
  611. return old_refs
  612. if len(new_refs) == 0 and len(orig_new_refs):
  613. # NOOP - Original new refs filtered out by policy
  614. proto.write_pkt_line(None)
  615. if report_status_parser is not None:
  616. report_status_parser.check()
  617. return old_refs
  618. (have, want) = self._handle_receive_pack_head(
  619. proto, negotiated_capabilities, old_refs, new_refs)
  620. if (not want and
  621. set(new_refs.items()).issubset(set(old_refs.items()))):
  622. return new_refs
  623. pack_data_count, pack_data = generate_pack_data(
  624. have, want,
  625. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities))
  626. dowrite = bool(pack_data_count)
  627. dowrite = dowrite or any(old_refs.get(ref) != sha
  628. for (ref, sha) in new_refs.items()
  629. if sha != ZERO_SHA)
  630. if dowrite:
  631. write_pack_data(proto.write_file(), pack_data_count, pack_data)
  632. self._handle_receive_pack_tail(
  633. proto, negotiated_capabilities, progress)
  634. return new_refs
  635. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  636. progress=None):
  637. """Retrieve a pack from a git smart server.
  638. :param path: Remote path to fetch from
  639. :param determine_wants: Function determine what refs
  640. to fetch. Receives dictionary of name->sha, should return
  641. list of shas to fetch.
  642. :param graph_walker: Object with next() and ack().
  643. :param pack_data: Callback called for each bit of data in the pack
  644. :param progress: Callback for progress reports (strings)
  645. :return: FetchPackResult object
  646. """
  647. proto, can_read = self._connect(b'upload-pack', path)
  648. with proto:
  649. refs, server_capabilities = read_pkt_refs(proto)
  650. negotiated_capabilities, symrefs, agent = (
  651. self._negotiate_upload_pack_capabilities(
  652. server_capabilities))
  653. if refs is None:
  654. proto.write_pkt_line(None)
  655. return FetchPackResult(refs, symrefs, agent)
  656. try:
  657. wants = determine_wants(refs)
  658. except BaseException:
  659. proto.write_pkt_line(None)
  660. raise
  661. if wants is not None:
  662. wants = [cid for cid in wants if cid != ZERO_SHA]
  663. if not wants:
  664. proto.write_pkt_line(None)
  665. return FetchPackResult(refs, symrefs, agent)
  666. check_wants(wants, refs)
  667. self._handle_upload_pack_head(
  668. proto, negotiated_capabilities, graph_walker, wants, can_read)
  669. self._handle_upload_pack_tail(
  670. proto, negotiated_capabilities, graph_walker, pack_data,
  671. progress)
  672. return FetchPackResult(refs, symrefs, agent)
  673. def get_refs(self, path):
  674. """Retrieve the current refs from a git smart server."""
  675. # stock `git ls-remote` uses upload-pack
  676. proto, _ = self._connect(b'upload-pack', path)
  677. with proto:
  678. refs, _ = read_pkt_refs(proto)
  679. proto.write_pkt_line(None)
  680. return refs
  681. def archive(self, path, committish, write_data, progress=None,
  682. write_error=None, format=None, subdirs=None, prefix=None):
  683. proto, can_read = self._connect(b'upload-archive', path)
  684. with proto:
  685. if format is not None:
  686. proto.write_pkt_line(b"argument --format=" + format)
  687. proto.write_pkt_line(b"argument " + committish)
  688. if subdirs is not None:
  689. for subdir in subdirs:
  690. proto.write_pkt_line(b"argument " + subdir)
  691. if prefix is not None:
  692. proto.write_pkt_line(b"argument --prefix=" + prefix)
  693. proto.write_pkt_line(None)
  694. pkt = proto.read_pkt_line()
  695. if pkt == b"NACK\n":
  696. return
  697. elif pkt == b"ACK\n":
  698. pass
  699. elif pkt.startswith(b"ERR "):
  700. raise GitProtocolError(pkt[4:].rstrip(b"\n"))
  701. else:
  702. raise AssertionError("invalid response %r" % pkt)
  703. ret = proto.read_pkt_line()
  704. if ret is not None:
  705. raise AssertionError("expected pkt tail")
  706. self._read_side_band64k_data(proto, {
  707. SIDE_BAND_CHANNEL_DATA: write_data,
  708. SIDE_BAND_CHANNEL_PROGRESS: progress,
  709. SIDE_BAND_CHANNEL_FATAL: write_error})
  710. class TCPGitClient(TraditionalGitClient):
  711. """A Git Client that works over TCP directly (i.e. git://)."""
  712. def __init__(self, host, port=None, **kwargs):
  713. if port is None:
  714. port = TCP_GIT_PORT
  715. self._host = host
  716. self._port = port
  717. super(TCPGitClient, self).__init__(**kwargs)
  718. @classmethod
  719. def from_parsedurl(cls, parsedurl, **kwargs):
  720. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  721. def get_url(self, path):
  722. netloc = self._host
  723. if self._port is not None and self._port != TCP_GIT_PORT:
  724. netloc += ":%d" % self._port
  725. return urlparse.urlunsplit(("git", netloc, path, '', ''))
  726. def _connect(self, cmd, path):
  727. if not isinstance(cmd, bytes):
  728. raise TypeError(cmd)
  729. if not isinstance(path, bytes):
  730. path = path.encode(self._remote_path_encoding)
  731. sockaddrs = socket.getaddrinfo(
  732. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  733. s = None
  734. err = socket.error("no address found for %s" % self._host)
  735. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  736. s = socket.socket(family, socktype, proto)
  737. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  738. try:
  739. s.connect(sockaddr)
  740. break
  741. except socket.error as err:
  742. if s is not None:
  743. s.close()
  744. s = None
  745. if s is None:
  746. raise err
  747. # -1 means system default buffering
  748. rfile = s.makefile('rb', -1)
  749. # 0 means unbuffered
  750. wfile = s.makefile('wb', 0)
  751. def close():
  752. rfile.close()
  753. wfile.close()
  754. s.close()
  755. proto = Protocol(rfile.read, wfile.write, close,
  756. report_activity=self._report_activity)
  757. if path.startswith(b"/~"):
  758. path = path[1:]
  759. # TODO(jelmer): Alternative to ascii?
  760. proto.send_cmd(
  761. b'git-' + cmd, path, b'host=' + self._host.encode('ascii'))
  762. return proto, lambda: _fileno_can_read(s)
  763. class SubprocessWrapper(object):
  764. """A socket-like object that talks to a subprocess via pipes."""
  765. def __init__(self, proc):
  766. self.proc = proc
  767. if sys.version_info[0] == 2:
  768. self.read = proc.stdout.read
  769. else:
  770. self.read = BufferedReader(proc.stdout).read
  771. self.write = proc.stdin.write
  772. def can_read(self):
  773. if sys.platform == 'win32':
  774. from msvcrt import get_osfhandle
  775. handle = get_osfhandle(self.proc.stdout.fileno())
  776. return _win32_peek_avail(handle) != 0
  777. else:
  778. return _fileno_can_read(self.proc.stdout.fileno())
  779. def close(self):
  780. self.proc.stdin.close()
  781. self.proc.stdout.close()
  782. if self.proc.stderr:
  783. self.proc.stderr.close()
  784. self.proc.wait()
  785. def find_git_command():
  786. """Find command to run for system Git (usually C Git).
  787. """
  788. if sys.platform == 'win32': # support .exe, .bat and .cmd
  789. try: # to avoid overhead
  790. import win32api
  791. except ImportError: # run through cmd.exe with some overhead
  792. return ['cmd', '/c', 'git']
  793. else:
  794. status, git = win32api.FindExecutable('git')
  795. return [git]
  796. else:
  797. return ['git']
  798. class SubprocessGitClient(TraditionalGitClient):
  799. """Git client that talks to a server using a subprocess."""
  800. def __init__(self, **kwargs):
  801. self._connection = None
  802. self._stderr = None
  803. self._stderr = kwargs.get('stderr')
  804. if 'stderr' in kwargs:
  805. del kwargs['stderr']
  806. super(SubprocessGitClient, self).__init__(**kwargs)
  807. @classmethod
  808. def from_parsedurl(cls, parsedurl, **kwargs):
  809. return cls(**kwargs)
  810. git_command = None
  811. def _connect(self, service, path):
  812. if not isinstance(service, bytes):
  813. raise TypeError(service)
  814. if isinstance(path, bytes):
  815. path = path.decode(self._remote_path_encoding)
  816. if self.git_command is None:
  817. git_command = find_git_command()
  818. argv = git_command + [service.decode('ascii'), path]
  819. p = SubprocessWrapper(
  820. subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  821. stdout=subprocess.PIPE,
  822. stderr=self._stderr))
  823. return Protocol(p.read, p.write, p.close,
  824. report_activity=self._report_activity), p.can_read
  825. class LocalGitClient(GitClient):
  826. """Git Client that just uses a local Repo."""
  827. def __init__(self, thin_packs=True, report_activity=None, config=None):
  828. """Create a new LocalGitClient instance.
  829. :param thin_packs: Whether or not thin packs should be retrieved
  830. :param report_activity: Optional callback for reporting transport
  831. activity.
  832. """
  833. self._report_activity = report_activity
  834. # Ignore the thin_packs argument
  835. def get_url(self, path):
  836. return urlparse.urlunsplit(('file', '', path, '', ''))
  837. @classmethod
  838. def from_parsedurl(cls, parsedurl, **kwargs):
  839. return cls(**kwargs)
  840. @classmethod
  841. def _open_repo(cls, path):
  842. from dulwich.repo import Repo
  843. if not isinstance(path, str):
  844. path = path.decode(sys.getfilesystemencoding())
  845. return closing(Repo(path))
  846. def send_pack(self, path, update_refs, generate_pack_data,
  847. progress=None):
  848. """Upload a pack to a remote repository.
  849. :param path: Repository path (as bytestring)
  850. :param update_refs: Function to determine changes to remote refs.
  851. Receive dict with existing remote refs, returns dict with
  852. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  853. :param generate_pack_data: Function that can return a tuple
  854. with number of items and pack data to upload.
  855. :param progress: Optional progress function
  856. :raises SendPackError: if server rejects the pack data
  857. :raises UpdateRefsError: if the server supports report-status
  858. and rejects ref updates
  859. :return: new_refs dictionary containing the changes that were made
  860. {refname: new_ref}, including deleted refs.
  861. """
  862. if not progress:
  863. def progress(x):
  864. pass
  865. with self._open_repo(path) as target:
  866. old_refs = target.get_refs()
  867. new_refs = update_refs(dict(old_refs))
  868. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  869. want = []
  870. for refname, new_sha1 in new_refs.items():
  871. if (new_sha1 not in have and
  872. new_sha1 not in want and
  873. new_sha1 != ZERO_SHA):
  874. want.append(new_sha1)
  875. if (not want and
  876. set(new_refs.items()).issubset(set(old_refs.items()))):
  877. return new_refs
  878. target.object_store.add_pack_data(
  879. *generate_pack_data(have, want, ofs_delta=True))
  880. for refname, new_sha1 in new_refs.items():
  881. old_sha1 = old_refs.get(refname, ZERO_SHA)
  882. if new_sha1 != ZERO_SHA:
  883. if not target.refs.set_if_equals(
  884. refname, old_sha1, new_sha1):
  885. progress('unable to set %s to %s' %
  886. (refname, new_sha1))
  887. else:
  888. if not target.refs.remove_if_equals(refname, old_sha1):
  889. progress('unable to remove %s' % refname)
  890. return new_refs
  891. def fetch(self, path, target, determine_wants=None, progress=None):
  892. """Fetch into a target repository.
  893. :param path: Path to fetch from (as bytestring)
  894. :param target: Target repository to fetch into
  895. :param determine_wants: Optional function determine what refs
  896. to fetch. Receives dictionary of name->sha, should return
  897. list of shas to fetch. Defaults to all shas.
  898. :param progress: Optional progress function
  899. :return: FetchPackResult object
  900. """
  901. with self._open_repo(path) as r:
  902. refs = r.fetch(target, determine_wants=determine_wants,
  903. progress=progress)
  904. return FetchPackResult(refs, r.refs.get_symrefs(),
  905. agent_string())
  906. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  907. progress=None):
  908. """Retrieve a pack from a git smart server.
  909. :param path: Remote path to fetch from
  910. :param determine_wants: Function determine what refs
  911. to fetch. Receives dictionary of name->sha, should return
  912. list of shas to fetch.
  913. :param graph_walker: Object with next() and ack().
  914. :param pack_data: Callback called for each bit of data in the pack
  915. :param progress: Callback for progress reports (strings)
  916. :return: FetchPackResult object
  917. """
  918. with self._open_repo(path) as r:
  919. objects_iter = r.fetch_objects(
  920. determine_wants, graph_walker, progress)
  921. symrefs = r.refs.get_symrefs()
  922. agent = agent_string()
  923. # Did the process short-circuit (e.g. in a stateless RPC call)?
  924. # Note that the client still expects a 0-object pack in most cases.
  925. if objects_iter is None:
  926. return FetchPackResult(None, symrefs, agent)
  927. protocol = ProtocolFile(None, pack_data)
  928. write_pack_objects(protocol, objects_iter)
  929. return FetchPackResult(r.get_refs(), symrefs, agent)
  930. def get_refs(self, path):
  931. """Retrieve the current refs from a git smart server."""
  932. with self._open_repo(path) as target:
  933. return target.get_refs()
  934. # What Git client to use for local access
  935. default_local_git_client_cls = LocalGitClient
  936. class SSHVendor(object):
  937. """A client side SSH implementation."""
  938. def connect_ssh(self, host, command, username=None, port=None,
  939. password=None, key_filename=None):
  940. # This function was deprecated in 0.9.1
  941. import warnings
  942. warnings.warn(
  943. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  944. DeprecationWarning)
  945. return self.run_command(host, command, username=username, port=port,
  946. password=password, key_filename=key_filename)
  947. def run_command(self, host, command, username=None, port=None,
  948. password=None, key_filename=None):
  949. """Connect to an SSH server.
  950. Run a command remotely and return a file-like object for interaction
  951. with the remote command.
  952. :param host: Host name
  953. :param command: Command to run (as argv array)
  954. :param username: Optional ame of user to log in as
  955. :param port: Optional SSH port to use
  956. :param password: Optional ssh password for login or private key
  957. :param key_filename: Optional path to private keyfile
  958. """
  959. raise NotImplementedError(self.run_command)
  960. class StrangeHostname(Exception):
  961. """Refusing to connect to strange SSH hostname."""
  962. def __init__(self, hostname):
  963. super(StrangeHostname, self).__init__(hostname)
  964. class SubprocessSSHVendor(SSHVendor):
  965. """SSH vendor that shells out to the local 'ssh' command."""
  966. def run_command(self, host, command, username=None, port=None,
  967. password=None, key_filename=None):
  968. if password is not None:
  969. raise NotImplementedError(
  970. "Setting password not supported by SubprocessSSHVendor.")
  971. args = ['ssh', '-x']
  972. if port:
  973. args.extend(['-p', str(port)])
  974. if key_filename:
  975. args.extend(['-i', str(key_filename)])
  976. if username:
  977. host = '%s@%s' % (username, host)
  978. if host.startswith('-'):
  979. raise StrangeHostname(hostname=host)
  980. args.append(host)
  981. proc = subprocess.Popen(args + [command], bufsize=0,
  982. stdin=subprocess.PIPE,
  983. stdout=subprocess.PIPE)
  984. return SubprocessWrapper(proc)
  985. class PLinkSSHVendor(SSHVendor):
  986. """SSH vendor that shells out to the local 'plink' command."""
  987. def run_command(self, host, command, username=None, port=None,
  988. password=None, key_filename=None):
  989. if sys.platform == 'win32':
  990. args = ['plink.exe', '-ssh']
  991. else:
  992. args = ['plink', '-ssh']
  993. if password is not None:
  994. import warnings
  995. warnings.warn(
  996. "Invoking PLink with a password exposes the password in the "
  997. "process list.")
  998. args.extend(['-pw', str(password)])
  999. if port:
  1000. args.extend(['-P', str(port)])
  1001. if key_filename:
  1002. args.extend(['-i', str(key_filename)])
  1003. if username:
  1004. host = '%s@%s' % (username, host)
  1005. if host.startswith('-'):
  1006. raise StrangeHostname(hostname=host)
  1007. args.append(host)
  1008. proc = subprocess.Popen(args + [command], bufsize=0,
  1009. stdin=subprocess.PIPE,
  1010. stdout=subprocess.PIPE)
  1011. return SubprocessWrapper(proc)
  1012. def ParamikoSSHVendor(**kwargs):
  1013. import warnings
  1014. warnings.warn(
  1015. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  1016. DeprecationWarning)
  1017. from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
  1018. return ParamikoSSHVendor(**kwargs)
  1019. # Can be overridden by users
  1020. get_ssh_vendor = SubprocessSSHVendor
  1021. class SSHGitClient(TraditionalGitClient):
  1022. def __init__(self, host, port=None, username=None, vendor=None,
  1023. config=None, password=None, key_filename=None, **kwargs):
  1024. self.host = host
  1025. self.port = port
  1026. self.username = username
  1027. self.password = password
  1028. self.key_filename = key_filename
  1029. super(SSHGitClient, self).__init__(**kwargs)
  1030. self.alternative_paths = {}
  1031. if vendor is not None:
  1032. self.ssh_vendor = vendor
  1033. else:
  1034. self.ssh_vendor = get_ssh_vendor()
  1035. def get_url(self, path):
  1036. netloc = self.host
  1037. if self.port is not None:
  1038. netloc += ":%d" % self.port
  1039. if self.username is not None:
  1040. netloc = urlquote(self.username, '@/:') + "@" + netloc
  1041. return urlparse.urlunsplit(('ssh', netloc, path, '', ''))
  1042. @classmethod
  1043. def from_parsedurl(cls, parsedurl, **kwargs):
  1044. return cls(host=parsedurl.hostname, port=parsedurl.port,
  1045. username=parsedurl.username, **kwargs)
  1046. def _get_cmd_path(self, cmd):
  1047. cmd = self.alternative_paths.get(cmd, b'git-' + cmd)
  1048. assert isinstance(cmd, bytes)
  1049. return cmd
  1050. def _connect(self, cmd, path):
  1051. if not isinstance(cmd, bytes):
  1052. raise TypeError(cmd)
  1053. if isinstance(path, bytes):
  1054. path = path.decode(self._remote_path_encoding)
  1055. if path.startswith("/~"):
  1056. path = path[1:]
  1057. argv = (self._get_cmd_path(cmd).decode(self._remote_path_encoding) +
  1058. " '" + path + "'")
  1059. kwargs = {}
  1060. if self.password is not None:
  1061. kwargs['password'] = self.password
  1062. if self.key_filename is not None:
  1063. kwargs['key_filename'] = self.key_filename
  1064. con = self.ssh_vendor.run_command(
  1065. self.host, argv, port=self.port, username=self.username,
  1066. **kwargs)
  1067. return (Protocol(con.read, con.write, con.close,
  1068. report_activity=self._report_activity),
  1069. con.can_read)
  1070. def default_user_agent_string():
  1071. # Start user agent with "git/", because GitHub requires this. :-( See
  1072. # https://github.com/jelmer/dulwich/issues/562 for details.
  1073. return "git/dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  1074. def default_urllib3_manager(config, **override_kwargs):
  1075. """Return `urllib3` connection pool manager.
  1076. Honour detected proxy configurations.
  1077. :param config: `dulwich.config.ConfigDict` instance with Git configuration.
  1078. :param kwargs: Additional arguments for urllib3.ProxyManager
  1079. :return: `urllib3.ProxyManager` instance for proxy configurations,
  1080. `urllib3.PoolManager` otherwise.
  1081. """
  1082. proxy_server = user_agent = None
  1083. ca_certs = ssl_verify = None
  1084. if config is not None:
  1085. try:
  1086. proxy_server = config.get(b"http", b"proxy")
  1087. except KeyError:
  1088. pass
  1089. try:
  1090. user_agent = config.get(b"http", b"useragent")
  1091. except KeyError:
  1092. pass
  1093. # TODO(jelmer): Support per-host settings
  1094. try:
  1095. ssl_verify = config.get_boolean(b"http", b"sslVerify")
  1096. except KeyError:
  1097. ssl_verify = True
  1098. try:
  1099. ca_certs = config.get_boolean(b"http", b"sslCAInfo")
  1100. except KeyError:
  1101. ca_certs = None
  1102. if user_agent is None:
  1103. user_agent = default_user_agent_string()
  1104. headers = {"User-agent": user_agent}
  1105. kwargs = {}
  1106. if ssl_verify is True:
  1107. kwargs['cert_reqs'] = "CERT_REQUIRED"
  1108. elif ssl_verify is False:
  1109. kwargs['cert_reqs'] = 'CERT_NONE'
  1110. else:
  1111. # Default to SSL verification
  1112. kwargs['cert_reqs'] = "CERT_REQUIRED"
  1113. if ca_certs is not None:
  1114. kwargs['ca_certs'] = ca_certs
  1115. kwargs.update(override_kwargs)
  1116. # Try really hard to find a SSL certificate path
  1117. if 'ca_certs' not in kwargs and kwargs.get('cert_reqs') != 'CERT_NONE':
  1118. try:
  1119. import certifi
  1120. except ImportError:
  1121. pass
  1122. else:
  1123. kwargs['ca_certs'] = certifi.where()
  1124. import urllib3
  1125. if proxy_server is not None:
  1126. # `urllib3` requires a `str` object in both Python 2 and 3, while
  1127. # `ConfigDict` coerces entries to `bytes` on Python 3. Compensate.
  1128. if not isinstance(proxy_server, str):
  1129. proxy_server = proxy_server.decode()
  1130. manager = urllib3.ProxyManager(proxy_server, headers=headers,
  1131. **kwargs)
  1132. else:
  1133. manager = urllib3.PoolManager(headers=headers, **kwargs)
  1134. return manager
  1135. class HttpGitClient(GitClient):
  1136. def __init__(self, base_url, dumb=None, pool_manager=None, config=None,
  1137. username=None, password=None, **kwargs):
  1138. self._base_url = base_url.rstrip("/") + "/"
  1139. self._username = username
  1140. self._password = password
  1141. self.dumb = dumb
  1142. if pool_manager is None:
  1143. self.pool_manager = default_urllib3_manager(config)
  1144. else:
  1145. self.pool_manager = pool_manager
  1146. if username is not None:
  1147. # No escaping needed: ":" is not allowed in username:
  1148. # https://tools.ietf.org/html/rfc2617#section-2
  1149. credentials = "%s:%s" % (username, password)
  1150. import urllib3.util
  1151. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  1152. self.pool_manager.headers.update(basic_auth)
  1153. GitClient.__init__(self, **kwargs)
  1154. def get_url(self, path):
  1155. return self._get_url(path).rstrip("/")
  1156. @classmethod
  1157. def from_parsedurl(cls, parsedurl, **kwargs):
  1158. password = parsedurl.password
  1159. if password is not None:
  1160. kwargs['password'] = urlunquote(password)
  1161. username = parsedurl.username
  1162. if username is not None:
  1163. kwargs['username'] = urlunquote(username)
  1164. # TODO(jelmer): This also strips the username
  1165. parsedurl = parsedurl._replace(netloc=parsedurl.hostname)
  1166. return cls(urlparse.urlunparse(parsedurl), **kwargs)
  1167. def __repr__(self):
  1168. return "%s(%r, dumb=%r)" % (
  1169. type(self).__name__, self._base_url, self.dumb)
  1170. def _get_url(self, path):
  1171. if not isinstance(path, str):
  1172. # TODO(jelmer): this is unrelated to the local filesystem;
  1173. # This is not necessarily the right encoding to decode the path
  1174. # with.
  1175. path = path.decode(sys.getfilesystemencoding())
  1176. return urlparse.urljoin(self._base_url, path).rstrip("/") + "/"
  1177. def _http_request(self, url, headers=None, data=None,
  1178. allow_compression=False):
  1179. """Perform HTTP request.
  1180. :param url: Request URL.
  1181. :param headers: Optional custom headers to override defaults.
  1182. :param data: Request data.
  1183. :param allow_compression: Allow GZipped communication.
  1184. :return: Tuple (`response`, `read`), where response is an `urllib3`
  1185. response object with additional `content_type` and
  1186. `redirect_location` properties, and `read` is a consumable read
  1187. method for the response data.
  1188. """
  1189. req_headers = self.pool_manager.headers.copy()
  1190. if headers is not None:
  1191. req_headers.update(headers)
  1192. req_headers["Pragma"] = "no-cache"
  1193. if allow_compression:
  1194. req_headers["Accept-Encoding"] = "gzip"
  1195. else:
  1196. req_headers["Accept-Encoding"] = "identity"
  1197. if data is None:
  1198. resp = self.pool_manager.request("GET", url, headers=req_headers)
  1199. else:
  1200. resp = self.pool_manager.request("POST", url, headers=req_headers,
  1201. body=data)
  1202. if resp.status == 404:
  1203. raise NotGitRepository()
  1204. elif resp.status != 200:
  1205. raise GitProtocolError("unexpected http resp %d for %s" %
  1206. (resp.status, url))
  1207. # TODO: Optimization available by adding `preload_content=False` to the
  1208. # request and just passing the `read` method on instead of going via
  1209. # `BytesIO`, if we can guarantee that the entire response is consumed
  1210. # before issuing the next to still allow for connection reuse from the
  1211. # pool.
  1212. read = BytesIO(resp.data).read
  1213. resp.content_type = resp.getheader("Content-Type")
  1214. resp.redirect_location = resp.get_redirect_location()
  1215. return resp, read
  1216. def _discover_references(self, service, base_url):
  1217. assert base_url[-1] == "/"
  1218. tail = "info/refs"
  1219. headers = {"Accept": "*/*"}
  1220. if self.dumb is not True:
  1221. tail += "?service=%s" % service.decode('ascii')
  1222. url = urlparse.urljoin(base_url, tail)
  1223. resp, read = self._http_request(url, headers, allow_compression=True)
  1224. if resp.redirect_location:
  1225. # Something changed (redirect!), so let's update the base URL
  1226. if not resp.redirect_location.endswith(tail):
  1227. raise GitProtocolError(
  1228. "Redirected from URL %s to URL %s without %s" % (
  1229. url, resp.redirect_location, tail))
  1230. base_url = resp.redirect_location[:-len(tail)]
  1231. try:
  1232. self.dumb = not resp.content_type.startswith("application/x-git-")
  1233. if not self.dumb:
  1234. proto = Protocol(read, None)
  1235. # The first line should mention the service
  1236. try:
  1237. [pkt] = list(proto.read_pkt_seq())
  1238. except ValueError:
  1239. raise GitProtocolError(
  1240. "unexpected number of packets received")
  1241. if pkt.rstrip(b'\n') != (b'# service=' + service):
  1242. raise GitProtocolError(
  1243. "unexpected first line %r from smart server" % pkt)
  1244. return read_pkt_refs(proto) + (base_url, )
  1245. else:
  1246. return read_info_refs(resp), set(), base_url
  1247. finally:
  1248. resp.close()
  1249. def _smart_request(self, service, url, data):
  1250. assert url[-1] == "/"
  1251. url = urlparse.urljoin(url, service)
  1252. result_content_type = "application/x-%s-result" % service
  1253. headers = {
  1254. "Content-Type": "application/x-%s-request" % service,
  1255. "Accept": result_content_type,
  1256. "Content-Length": str(len(data)),
  1257. }
  1258. resp, read = self._http_request(url, headers, data)
  1259. if resp.content_type != result_content_type:
  1260. raise GitProtocolError("Invalid content-type from server: %s"
  1261. % resp.content_type)
  1262. return resp, read
  1263. def send_pack(self, path, update_refs, generate_pack_data,
  1264. progress=None):
  1265. """Upload a pack to a remote repository.
  1266. :param path: Repository path (as bytestring)
  1267. :param update_refs: Function to determine changes to remote refs.
  1268. Receive dict with existing remote refs, returns dict with
  1269. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1270. :param generate_pack_data: Function that can return a tuple
  1271. with number of elements and pack data to upload.
  1272. :param progress: Optional progress function
  1273. :raises SendPackError: if server rejects the pack data
  1274. :raises UpdateRefsError: if the server supports report-status
  1275. and rejects ref updates
  1276. :return: new_refs dictionary containing the changes that were made
  1277. {refname: new_ref}, including deleted refs.
  1278. """
  1279. url = self._get_url(path)
  1280. old_refs, server_capabilities, url = self._discover_references(
  1281. b"git-receive-pack", url)
  1282. negotiated_capabilities = self._negotiate_receive_pack_capabilities(
  1283. server_capabilities)
  1284. negotiated_capabilities.add(capability_agent())
  1285. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1286. self._report_status_parser = ReportStatusParser()
  1287. new_refs = update_refs(dict(old_refs))
  1288. if new_refs is None:
  1289. # Determine wants function is aborting the push.
  1290. return old_refs
  1291. if self.dumb:
  1292. raise NotImplementedError(self.fetch_pack)
  1293. req_data = BytesIO()
  1294. req_proto = Protocol(None, req_data.write)
  1295. (have, want) = self._handle_receive_pack_head(
  1296. req_proto, negotiated_capabilities, old_refs, new_refs)
  1297. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1298. return new_refs
  1299. pack_data_count, pack_data = generate_pack_data(
  1300. have, want,
  1301. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities))
  1302. if pack_data_count:
  1303. write_pack_data(req_proto.write_file(), pack_data_count, pack_data)
  1304. resp, read = self._smart_request("git-receive-pack", url,
  1305. data=req_data.getvalue())
  1306. try:
  1307. resp_proto = Protocol(read, None)
  1308. self._handle_receive_pack_tail(
  1309. resp_proto, negotiated_capabilities, progress)
  1310. return new_refs
  1311. finally:
  1312. resp.close()
  1313. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  1314. progress=None):
  1315. """Retrieve a pack from a git smart server.
  1316. :param determine_wants: Callback that returns list of commits to fetch
  1317. :param graph_walker: Object with next() and ack().
  1318. :param pack_data: Callback called for each bit of data in the pack
  1319. :param progress: Callback for progress reports (strings)
  1320. :return: FetchPackResult object
  1321. """
  1322. url = self._get_url(path)
  1323. refs, server_capabilities, url = self._discover_references(
  1324. b"git-upload-pack", url)
  1325. negotiated_capabilities, symrefs, agent = (
  1326. self._negotiate_upload_pack_capabilities(
  1327. server_capabilities))
  1328. wants = determine_wants(refs)
  1329. if wants is not None:
  1330. wants = [cid for cid in wants if cid != ZERO_SHA]
  1331. if not wants:
  1332. return FetchPackResult(refs, symrefs, agent)
  1333. if self.dumb:
  1334. raise NotImplementedError(self.send_pack)
  1335. check_wants(wants, refs)
  1336. req_data = BytesIO()
  1337. req_proto = Protocol(None, req_data.write)
  1338. self._handle_upload_pack_head(
  1339. req_proto, negotiated_capabilities, graph_walker, wants,
  1340. lambda: False)
  1341. resp, read = self._smart_request(
  1342. "git-upload-pack", url, data=req_data.getvalue())
  1343. try:
  1344. resp_proto = Protocol(read, None)
  1345. self._handle_upload_pack_tail(
  1346. resp_proto, negotiated_capabilities, graph_walker, pack_data,
  1347. progress)
  1348. return FetchPackResult(refs, symrefs, agent)
  1349. finally:
  1350. resp.close()
  1351. def get_refs(self, path):
  1352. """Retrieve the current refs from a git smart server."""
  1353. url = self._get_url(path)
  1354. refs, _, _ = self._discover_references(
  1355. b"git-upload-pack", url)
  1356. return refs
  1357. def get_transport_and_path_from_url(url, config=None, **kwargs):
  1358. """Obtain a git client from a URL.
  1359. :param url: URL to open (a unicode string)
  1360. :param config: Optional config object
  1361. :param thin_packs: Whether or not thin packs should be retrieved
  1362. :param report_activity: Optional callback for reporting transport
  1363. activity.
  1364. :return: Tuple with client instance and relative path.
  1365. """
  1366. parsed = urlparse.urlparse(url)
  1367. if parsed.scheme == 'git':
  1368. return (TCPGitClient.from_parsedurl(parsed, **kwargs),
  1369. parsed.path)
  1370. elif parsed.scheme in ('git+ssh', 'ssh'):
  1371. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  1372. elif parsed.scheme in ('http', 'https'):
  1373. return HttpGitClient.from_parsedurl(
  1374. parsed, config=config, **kwargs), parsed.path
  1375. elif parsed.scheme == 'file':
  1376. return default_local_git_client_cls.from_parsedurl(
  1377. parsed, **kwargs), parsed.path
  1378. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  1379. def parse_rsync_url(location):
  1380. """Parse a rsync-style URL."""
  1381. if ':' in location and '@' not in location:
  1382. # SSH with no user@, zero or one leading slash.
  1383. (host, path) = location.split(':', 1)
  1384. user = None
  1385. elif ':' in location:
  1386. # SSH with user@host:foo.
  1387. user_host, path = location.split(':', 1)
  1388. if '@' in user_host:
  1389. user, host = user_host.rsplit('@', 1)
  1390. else:
  1391. user = None
  1392. host = user_host
  1393. else:
  1394. raise ValueError('not a valid rsync-style URL')
  1395. return (user, host, path)
  1396. def get_transport_and_path(location, **kwargs):
  1397. """Obtain a git client from a URL.
  1398. :param location: URL or path (a string)
  1399. :param config: Optional config object
  1400. :param thin_packs: Whether or not thin packs should be retrieved
  1401. :param report_activity: Optional callback for reporting transport
  1402. activity.
  1403. :return: Tuple with client instance and relative path.
  1404. """
  1405. # First, try to parse it as a URL
  1406. try:
  1407. return get_transport_and_path_from_url(location, **kwargs)
  1408. except ValueError:
  1409. pass
  1410. if (sys.platform == 'win32' and
  1411. location[0].isalpha() and location[1:3] == ':\\'):
  1412. # Windows local path
  1413. return default_local_git_client_cls(**kwargs), location
  1414. try:
  1415. (username, hostname, path) = parse_rsync_url(location)
  1416. except ValueError:
  1417. # Otherwise, assume it's a local path.
  1418. return default_local_git_client_cls(**kwargs), location
  1419. else:
  1420. return SSHGitClient(hostname, username=username, **kwargs), path