client.py 62 KB

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