client.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. # client.py -- Implementation of the client side git protocols
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # or (at your option) a later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Client side support for the Git protocol.
  19. The Dulwich client supports the following capabilities:
  20. * thin-pack
  21. * multi_ack_detailed
  22. * multi_ack
  23. * side-band-64k
  24. * ofs-delta
  25. * quiet
  26. * report-status
  27. * delete-refs
  28. Known capabilities that are not supported:
  29. * shallow
  30. * no-progress
  31. * include-tag
  32. """
  33. __docformat__ = 'restructuredText'
  34. from contextlib import closing
  35. from io import BytesIO, BufferedReader
  36. import dulwich
  37. import select
  38. import socket
  39. import subprocess
  40. import sys
  41. try:
  42. import urllib2
  43. import urlparse
  44. except ImportError:
  45. import urllib.request as urllib2
  46. import urllib.parse as urlparse
  47. from dulwich.errors import (
  48. GitProtocolError,
  49. NotGitRepository,
  50. SendPackError,
  51. UpdateRefsError,
  52. )
  53. from dulwich.protocol import (
  54. _RBUFSIZE,
  55. capability_agent,
  56. CAPABILITY_DELETE_REFS,
  57. CAPABILITY_MULTI_ACK,
  58. CAPABILITY_MULTI_ACK_DETAILED,
  59. CAPABILITY_OFS_DELTA,
  60. CAPABILITY_QUIET,
  61. CAPABILITY_REPORT_STATUS,
  62. CAPABILITY_SIDE_BAND_64K,
  63. CAPABILITY_THIN_PACK,
  64. COMMAND_DONE,
  65. COMMAND_HAVE,
  66. COMMAND_WANT,
  67. SIDE_BAND_CHANNEL_DATA,
  68. SIDE_BAND_CHANNEL_PROGRESS,
  69. SIDE_BAND_CHANNEL_FATAL,
  70. PktLineParser,
  71. Protocol,
  72. ProtocolFile,
  73. TCP_GIT_PORT,
  74. ZERO_SHA,
  75. extract_capabilities,
  76. )
  77. from dulwich.pack import (
  78. write_pack_objects,
  79. )
  80. from dulwich.refs import (
  81. read_info_refs,
  82. )
  83. def _fileno_can_read(fileno):
  84. """Check if a file descriptor is readable."""
  85. return len(select.select([fileno], [], [], 0)[0]) > 0
  86. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  87. FETCH_CAPABILITIES = ([CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK,
  88. CAPABILITY_MULTI_ACK_DETAILED] +
  89. COMMON_CAPABILITIES)
  90. SEND_CAPABILITIES = [CAPABILITY_REPORT_STATUS] + COMMON_CAPABILITIES
  91. class ReportStatusParser(object):
  92. """Handle status as reported by servers with 'report-status' capability.
  93. """
  94. def __init__(self):
  95. self._done = False
  96. self._pack_status = None
  97. self._ref_status_ok = True
  98. self._ref_statuses = []
  99. def check(self):
  100. """Check if there were any errors and, if so, raise exceptions.
  101. :raise SendPackError: Raised when the server could not unpack
  102. :raise UpdateRefsError: Raised when refs could not be updated
  103. """
  104. if self._pack_status not in (b'unpack ok', None):
  105. raise SendPackError(self._pack_status)
  106. if not self._ref_status_ok:
  107. ref_status = {}
  108. ok = set()
  109. for status in self._ref_statuses:
  110. if b' ' not in status:
  111. # malformed response, move on to the next one
  112. continue
  113. status, ref = status.split(b' ', 1)
  114. if status == b'ng':
  115. if b' ' in ref:
  116. ref, status = ref.split(b' ', 1)
  117. else:
  118. ok.add(ref)
  119. ref_status[ref] = status
  120. # TODO(jelmer): don't assume encoding of refs is ascii.
  121. raise UpdateRefsError(', '.join([
  122. ref.decode('ascii') for ref in ref_status if ref not in ok]) +
  123. ' failed to update', ref_status=ref_status)
  124. def handle_packet(self, pkt):
  125. """Handle a packet.
  126. :raise GitProtocolError: Raised when packets are received after a
  127. flush packet.
  128. """
  129. if self._done:
  130. raise GitProtocolError("received more data after status report")
  131. if pkt is None:
  132. self._done = True
  133. return
  134. if self._pack_status is None:
  135. self._pack_status = pkt.strip()
  136. else:
  137. ref_status = pkt.strip()
  138. self._ref_statuses.append(ref_status)
  139. if not ref_status.startswith(b'ok '):
  140. self._ref_status_ok = False
  141. def read_pkt_refs(proto):
  142. server_capabilities = None
  143. refs = {}
  144. # Receive refs from server
  145. for pkt in proto.read_pkt_seq():
  146. (sha, ref) = pkt.rstrip(b'\n').split(None, 1)
  147. if sha == b'ERR':
  148. raise GitProtocolError(ref)
  149. if server_capabilities is None:
  150. (ref, server_capabilities) = extract_capabilities(ref)
  151. refs[ref] = sha
  152. if len(refs) == 0:
  153. return None, set([])
  154. return refs, set(server_capabilities)
  155. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  156. # support some capabilities. This should work properly with servers
  157. # that don't support multi_ack.
  158. class GitClient(object):
  159. """Git smart server client.
  160. """
  161. def __init__(self, thin_packs=True, report_activity=None, quiet=False):
  162. """Create a new GitClient instance.
  163. :param thin_packs: Whether or not thin packs should be retrieved
  164. :param report_activity: Optional callback for reporting transport
  165. activity.
  166. """
  167. self._report_activity = report_activity
  168. self._report_status_parser = None
  169. self._fetch_capabilities = set(FETCH_CAPABILITIES)
  170. self._fetch_capabilities.add(capability_agent())
  171. self._send_capabilities = set(SEND_CAPABILITIES)
  172. self._send_capabilities.add(capability_agent())
  173. if quiet:
  174. self._send_capabilities.add(CAPABILITY_QUIET)
  175. if not thin_packs:
  176. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  177. def send_pack(self, path, determine_wants, generate_pack_contents,
  178. progress=None, write_pack=write_pack_objects):
  179. """Upload a pack to a remote repository.
  180. :param path: Repository path (as bytestring)
  181. :param generate_pack_contents: Function that can return a sequence of
  182. the shas of the objects to upload.
  183. :param progress: Optional progress function
  184. :param write_pack: Function called with (file, iterable of objects) to
  185. write the objects returned by generate_pack_contents to the server.
  186. :raises SendPackError: if server rejects the pack data
  187. :raises UpdateRefsError: if the server supports report-status
  188. and rejects ref updates
  189. """
  190. raise NotImplementedError(self.send_pack)
  191. def fetch(self, path, target, determine_wants=None, progress=None):
  192. """Fetch into a target repository.
  193. :param path: Path to fetch from (as bytestring)
  194. :param target: Target repository to fetch into
  195. :param determine_wants: Optional function to determine what refs
  196. to fetch
  197. :param progress: Optional progress function
  198. :return: Dictionary with all remote refs (not just those fetched)
  199. """
  200. if determine_wants is None:
  201. determine_wants = target.object_store.determine_wants_all
  202. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  203. # TODO(jelmer): Avoid reading entire file into memory and
  204. # only processing it after the whole file has been fetched.
  205. f = BytesIO()
  206. def commit():
  207. if f.tell():
  208. f.seek(0)
  209. target.object_store.add_thin_pack(f.read, None)
  210. def abort():
  211. pass
  212. else:
  213. f, commit, abort = target.object_store.add_pack()
  214. try:
  215. result = self.fetch_pack(
  216. path, determine_wants, target.get_graph_walker(), f.write,
  217. progress)
  218. except:
  219. abort()
  220. raise
  221. else:
  222. commit()
  223. return result
  224. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  225. progress=None):
  226. """Retrieve a pack from a git smart server.
  227. :param determine_wants: Callback that returns list of commits to fetch
  228. :param graph_walker: Object with next() and ack().
  229. :param pack_data: Callback called for each bit of data in the pack
  230. :param progress: Callback for progress reports (strings)
  231. :return: Dictionary with all remote refs (not just those fetched)
  232. """
  233. raise NotImplementedError(self.fetch_pack)
  234. def get_refs(self, path):
  235. """Retrieve the current refs from a git smart server.
  236. :param path: Path to the repo to fetch from. (as bytestring)
  237. """
  238. raise NotImplementedError(self.get_refs)
  239. def _parse_status_report(self, proto):
  240. unpack = proto.read_pkt_line().strip()
  241. if unpack != b'unpack ok':
  242. st = True
  243. # flush remaining error data
  244. while st is not None:
  245. st = proto.read_pkt_line()
  246. raise SendPackError(unpack)
  247. statuses = []
  248. errs = False
  249. ref_status = proto.read_pkt_line()
  250. while ref_status:
  251. ref_status = ref_status.strip()
  252. statuses.append(ref_status)
  253. if not ref_status.startswith(b'ok '):
  254. errs = True
  255. ref_status = proto.read_pkt_line()
  256. if errs:
  257. ref_status = {}
  258. ok = set()
  259. for status in statuses:
  260. if b' ' not in status:
  261. # malformed response, move on to the next one
  262. continue
  263. status, ref = status.split(b' ', 1)
  264. if status == b'ng':
  265. if b' ' in ref:
  266. ref, status = ref.split(b' ', 1)
  267. else:
  268. ok.add(ref)
  269. ref_status[ref] = status
  270. raise UpdateRefsError(', '.join([ref for ref in ref_status
  271. if ref not in ok]) +
  272. b' failed to update',
  273. ref_status=ref_status)
  274. def _read_side_band64k_data(self, proto, channel_callbacks):
  275. """Read per-channel data.
  276. This requires the side-band-64k capability.
  277. :param proto: Protocol object to read from
  278. :param channel_callbacks: Dictionary mapping channels to packet
  279. handlers to use. None for a callback discards channel data.
  280. """
  281. for pkt in proto.read_pkt_seq():
  282. channel = ord(pkt[:1])
  283. pkt = pkt[1:]
  284. try:
  285. cb = channel_callbacks[channel]
  286. except KeyError:
  287. raise AssertionError('Invalid sideband channel %d' % channel)
  288. else:
  289. if cb is not None:
  290. cb(pkt)
  291. def _handle_receive_pack_head(self, proto, capabilities, old_refs,
  292. new_refs):
  293. """Handle the head of a 'git-receive-pack' request.
  294. :param proto: Protocol object to read from
  295. :param capabilities: List of negotiated capabilities
  296. :param old_refs: Old refs, as received from the server
  297. :param new_refs: New refs
  298. :return: (have, want) tuple
  299. """
  300. want = []
  301. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  302. sent_capabilities = False
  303. all_refs = set(new_refs.keys()).union(set(old_refs.keys()))
  304. for refname in all_refs:
  305. old_sha1 = old_refs.get(refname, ZERO_SHA)
  306. new_sha1 = new_refs.get(refname, ZERO_SHA)
  307. if old_sha1 != new_sha1:
  308. if sent_capabilities:
  309. proto.write_pkt_line(old_sha1 + b' ' + new_sha1 + b' ' + refname)
  310. else:
  311. proto.write_pkt_line(
  312. old_sha1 + b' ' + new_sha1 + b' ' + refname + b'\0' +
  313. b' '.join(capabilities))
  314. sent_capabilities = True
  315. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  316. want.append(new_sha1)
  317. proto.write_pkt_line(None)
  318. return (have, want)
  319. def _handle_receive_pack_tail(self, proto, capabilities, progress=None):
  320. """Handle the tail of a 'git-receive-pack' request.
  321. :param proto: Protocol object to read from
  322. :param capabilities: List of negotiated capabilities
  323. :param progress: Optional progress reporting function
  324. """
  325. if b"side-band-64k" in capabilities:
  326. if progress is None:
  327. progress = lambda x: None
  328. channel_callbacks = {2: progress}
  329. if CAPABILITY_REPORT_STATUS in capabilities:
  330. channel_callbacks[1] = PktLineParser(
  331. self._report_status_parser.handle_packet).parse
  332. self._read_side_band64k_data(proto, channel_callbacks)
  333. else:
  334. if CAPABILITY_REPORT_STATUS in capabilities:
  335. for pkt in proto.read_pkt_seq():
  336. self._report_status_parser.handle_packet(pkt)
  337. if self._report_status_parser is not None:
  338. self._report_status_parser.check()
  339. def _handle_upload_pack_head(self, proto, capabilities, graph_walker,
  340. wants, can_read):
  341. """Handle the head of a 'git-upload-pack' request.
  342. :param proto: Protocol object to read from
  343. :param capabilities: List of negotiated capabilities
  344. :param graph_walker: GraphWalker instance to call .ack() on
  345. :param wants: List of commits to fetch
  346. :param can_read: function that returns a boolean that indicates
  347. whether there is extra graph data to read on proto
  348. """
  349. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  350. proto.write_pkt_line(COMMAND_WANT + b' ' + wants[0] + b' ' + b' '.join(capabilities) + b'\n')
  351. for want in wants[1:]:
  352. proto.write_pkt_line(COMMAND_WANT + b' ' + want + b'\n')
  353. proto.write_pkt_line(None)
  354. have = next(graph_walker)
  355. while have:
  356. proto.write_pkt_line(COMMAND_HAVE + b' ' + have + b'\n')
  357. if can_read():
  358. pkt = proto.read_pkt_line()
  359. parts = pkt.rstrip(b'\n').split(b' ')
  360. if parts[0] == b'ACK':
  361. graph_walker.ack(parts[1])
  362. if parts[2] in (b'continue', b'common'):
  363. pass
  364. elif parts[2] == b'ready':
  365. break
  366. else:
  367. raise AssertionError(
  368. "%s not in ('continue', 'ready', 'common)" %
  369. parts[2])
  370. have = next(graph_walker)
  371. proto.write_pkt_line(COMMAND_DONE + b'\n')
  372. def _handle_upload_pack_tail(self, proto, capabilities, graph_walker,
  373. pack_data, progress=None, rbufsize=_RBUFSIZE):
  374. """Handle the tail of a 'git-upload-pack' request.
  375. :param proto: Protocol object to read from
  376. :param capabilities: List of negotiated capabilities
  377. :param graph_walker: GraphWalker instance to call .ack() on
  378. :param pack_data: Function to call with pack data
  379. :param progress: Optional progress reporting function
  380. :param rbufsize: Read buffer size
  381. """
  382. pkt = proto.read_pkt_line()
  383. while pkt:
  384. parts = pkt.rstrip(b'\n').split(b' ')
  385. if parts[0] == b'ACK':
  386. graph_walker.ack(parts[1])
  387. if len(parts) < 3 or parts[2] not in (
  388. b'ready', b'continue', b'common'):
  389. break
  390. pkt = proto.read_pkt_line()
  391. if CAPABILITY_SIDE_BAND_64K in capabilities:
  392. if progress is None:
  393. # Just ignore progress data
  394. progress = lambda x: None
  395. self._read_side_band64k_data(proto, {
  396. SIDE_BAND_CHANNEL_DATA: pack_data,
  397. SIDE_BAND_CHANNEL_PROGRESS: progress}
  398. )
  399. else:
  400. while True:
  401. data = proto.read(rbufsize)
  402. if data == b"":
  403. break
  404. pack_data(data)
  405. class TraditionalGitClient(GitClient):
  406. """Traditional Git client."""
  407. def _connect(self, cmd, path):
  408. """Create a connection to the server.
  409. This method is abstract - concrete implementations should
  410. implement their own variant which connects to the server and
  411. returns an initialized Protocol object with the service ready
  412. for use and a can_read function which may be used to see if
  413. reads would block.
  414. :param cmd: The git service name to which we should connect.
  415. :param path: The path we should pass to the service. (as bytestirng)
  416. """
  417. raise NotImplementedError()
  418. def send_pack(self, path, determine_wants, generate_pack_contents,
  419. progress=None, write_pack=write_pack_objects):
  420. """Upload a pack to a remote repository.
  421. :param path: Repository path (as bytestring)
  422. :param generate_pack_contents: Function that can return a sequence of
  423. the shas of the objects to upload.
  424. :param progress: Optional callback called with progress updates
  425. :param write_pack: Function called with (file, iterable of objects) to
  426. write the objects returned by generate_pack_contents to the server.
  427. :raises SendPackError: if server rejects the pack data
  428. :raises UpdateRefsError: if the server supports report-status
  429. and rejects ref updates
  430. """
  431. proto, unused_can_read = self._connect(b'receive-pack', path)
  432. with proto:
  433. old_refs, server_capabilities = read_pkt_refs(proto)
  434. negotiated_capabilities = self._send_capabilities & server_capabilities
  435. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  436. self._report_status_parser = ReportStatusParser()
  437. report_status_parser = self._report_status_parser
  438. try:
  439. new_refs = orig_new_refs = determine_wants(dict(old_refs))
  440. except:
  441. proto.write_pkt_line(None)
  442. raise
  443. if not CAPABILITY_DELETE_REFS in server_capabilities:
  444. # Server does not support deletions. Fail later.
  445. new_refs = dict(orig_new_refs)
  446. for ref, sha in orig_new_refs.items():
  447. if sha == ZERO_SHA:
  448. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  449. report_status_parser._ref_statuses.append(
  450. b'ng ' + sha + b' remote does not support deleting refs')
  451. report_status_parser._ref_status_ok = False
  452. del new_refs[ref]
  453. if new_refs is None:
  454. proto.write_pkt_line(None)
  455. return old_refs
  456. if len(new_refs) == 0 and len(orig_new_refs):
  457. # NOOP - Original new refs filtered out by policy
  458. proto.write_pkt_line(None)
  459. if report_status_parser is not None:
  460. report_status_parser.check()
  461. return old_refs
  462. (have, want) = self._handle_receive_pack_head(
  463. proto, negotiated_capabilities, old_refs, new_refs)
  464. if not want and old_refs == new_refs:
  465. return new_refs
  466. objects = generate_pack_contents(have, want)
  467. dowrite = len(objects) > 0
  468. dowrite = dowrite or any(old_refs.get(ref) != sha
  469. for (ref, sha) in new_refs.items()
  470. if sha != ZERO_SHA)
  471. if dowrite:
  472. write_pack(proto.write_file(), objects)
  473. self._handle_receive_pack_tail(
  474. proto, negotiated_capabilities, progress)
  475. return new_refs
  476. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  477. progress=None):
  478. """Retrieve a pack from a git smart server.
  479. :param determine_wants: Callback that returns list of commits to fetch
  480. :param graph_walker: Object with next() and ack().
  481. :param pack_data: Callback called for each bit of data in the pack
  482. :param progress: Callback for progress reports (strings)
  483. :return: Dictionary with all remote refs (not just those fetched)
  484. """
  485. proto, can_read = self._connect(b'upload-pack', path)
  486. with proto:
  487. refs, server_capabilities = read_pkt_refs(proto)
  488. negotiated_capabilities = (
  489. self._fetch_capabilities & server_capabilities)
  490. if refs is None:
  491. proto.write_pkt_line(None)
  492. return refs
  493. try:
  494. wants = determine_wants(refs)
  495. except:
  496. proto.write_pkt_line(None)
  497. raise
  498. if wants is not None:
  499. wants = [cid for cid in wants if cid != ZERO_SHA]
  500. if not wants:
  501. proto.write_pkt_line(None)
  502. return refs
  503. self._handle_upload_pack_head(
  504. proto, negotiated_capabilities, graph_walker, wants, can_read)
  505. self._handle_upload_pack_tail(
  506. proto, negotiated_capabilities, graph_walker, pack_data, progress)
  507. return refs
  508. def get_refs(self, path):
  509. """Retrieve the current refs from a git smart server."""
  510. # stock `git ls-remote` uses upload-pack
  511. proto, _ = self._connect(b'upload-pack', path)
  512. with proto:
  513. refs, _ = read_pkt_refs(proto)
  514. return refs
  515. def archive(self, path, committish, write_data, progress=None,
  516. write_error=None):
  517. proto, can_read = self._connect(b'upload-archive', path)
  518. with proto:
  519. proto.write_pkt_line(b"argument " + committish)
  520. proto.write_pkt_line(None)
  521. pkt = proto.read_pkt_line()
  522. if pkt == b"NACK\n":
  523. return
  524. elif pkt == b"ACK\n":
  525. pass
  526. elif pkt.startswith(b"ERR "):
  527. raise GitProtocolError(pkt[4:].rstrip(b"\n"))
  528. else:
  529. raise AssertionError("invalid response %r" % pkt)
  530. ret = proto.read_pkt_line()
  531. if ret is not None:
  532. raise AssertionError("expected pkt tail")
  533. self._read_side_band64k_data(proto, {
  534. SIDE_BAND_CHANNEL_DATA: write_data,
  535. SIDE_BAND_CHANNEL_PROGRESS: progress,
  536. SIDE_BAND_CHANNEL_FATAL: write_error})
  537. class TCPGitClient(TraditionalGitClient):
  538. """A Git Client that works over TCP directly (i.e. git://)."""
  539. def __init__(self, host, port=None, **kwargs):
  540. if port is None:
  541. port = TCP_GIT_PORT
  542. self._host = host
  543. self._port = port
  544. TraditionalGitClient.__init__(self, **kwargs)
  545. def _connect(self, cmd, path):
  546. if type(cmd) is not bytes:
  547. raise TypeError(path)
  548. if type(path) is not bytes:
  549. raise TypeError(path)
  550. sockaddrs = socket.getaddrinfo(
  551. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  552. s = None
  553. err = socket.error("no address found for %s" % self._host)
  554. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  555. s = socket.socket(family, socktype, proto)
  556. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  557. try:
  558. s.connect(sockaddr)
  559. break
  560. except socket.error as err:
  561. if s is not None:
  562. s.close()
  563. s = None
  564. if s is None:
  565. raise err
  566. # -1 means system default buffering
  567. rfile = s.makefile('rb', -1)
  568. # 0 means unbuffered
  569. wfile = s.makefile('wb', 0)
  570. def close():
  571. rfile.close()
  572. wfile.close()
  573. s.close()
  574. proto = Protocol(rfile.read, wfile.write, close,
  575. report_activity=self._report_activity)
  576. if path.startswith(b"/~"):
  577. path = path[1:]
  578. # TODO(jelmer): Alternative to ascii?
  579. proto.send_cmd(b'git-' + cmd, path, b'host=' + self._host.encode('ascii'))
  580. return proto, lambda: _fileno_can_read(s)
  581. class SubprocessWrapper(object):
  582. """A socket-like object that talks to a subprocess via pipes."""
  583. def __init__(self, proc):
  584. self.proc = proc
  585. if sys.version_info[0] == 2:
  586. self.read = proc.stdout.read
  587. else:
  588. self.read = BufferedReader(proc.stdout).read
  589. self.write = proc.stdin.write
  590. def can_read(self):
  591. if sys.platform == 'win32':
  592. from msvcrt import get_osfhandle
  593. from win32pipe import PeekNamedPipe
  594. handle = get_osfhandle(self.proc.stdout.fileno())
  595. data, total_bytes_avail, msg_bytes_left = PeekNamedPipe(handle, 0)
  596. return total_bytes_avail != 0
  597. else:
  598. return _fileno_can_read(self.proc.stdout.fileno())
  599. def close(self):
  600. self.proc.stdin.close()
  601. self.proc.stdout.close()
  602. if self.proc.stderr:
  603. self.proc.stderr.close()
  604. self.proc.wait()
  605. def find_git_command():
  606. """Find command to run for system Git (usually C Git).
  607. """
  608. if sys.platform == 'win32': # support .exe, .bat and .cmd
  609. try: # to avoid overhead
  610. import win32api
  611. except ImportError: # run through cmd.exe with some overhead
  612. return ['cmd', '/c', 'git']
  613. else:
  614. status, git = win32api.FindExecutable('git')
  615. return [git]
  616. else:
  617. return ['git']
  618. class SubprocessGitClient(TraditionalGitClient):
  619. """Git client that talks to a server using a subprocess."""
  620. def __init__(self, **kwargs):
  621. self._connection = None
  622. self._stderr = None
  623. self._stderr = kwargs.get('stderr')
  624. if 'stderr' in kwargs:
  625. del kwargs['stderr']
  626. TraditionalGitClient.__init__(self, **kwargs)
  627. git_command = None
  628. def _connect(self, service, path):
  629. if type(service) is not bytes:
  630. raise TypeError(path)
  631. if type(path) is not bytes:
  632. raise TypeError(path)
  633. if self.git_command is None:
  634. git_command = find_git_command()
  635. argv = git_command + [service.decode('ascii'), path]
  636. p = SubprocessWrapper(
  637. subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  638. stdout=subprocess.PIPE,
  639. stderr=self._stderr))
  640. return Protocol(p.read, p.write, p.close,
  641. report_activity=self._report_activity), p.can_read
  642. class LocalGitClient(GitClient):
  643. """Git Client that just uses a local Repo."""
  644. def __init__(self, thin_packs=True, report_activity=None):
  645. """Create a new LocalGitClient instance.
  646. :param thin_packs: Whether or not thin packs should be retrieved
  647. :param report_activity: Optional callback for reporting transport
  648. activity.
  649. """
  650. self._report_activity = report_activity
  651. # Ignore the thin_packs argument
  652. def send_pack(self, path, determine_wants, generate_pack_contents,
  653. progress=None, write_pack=write_pack_objects):
  654. """Upload a pack to a remote repository.
  655. :param path: Repository path (as bytestring)
  656. :param generate_pack_contents: Function that can return a sequence of
  657. the shas of the objects to upload.
  658. :param progress: Optional progress function
  659. :param write_pack: Function called with (file, iterable of objects) to
  660. write the objects returned by generate_pack_contents to the server.
  661. :raises SendPackError: if server rejects the pack data
  662. :raises UpdateRefsError: if the server supports report-status
  663. and rejects ref updates
  664. """
  665. from dulwich.repo import Repo
  666. with closing(Repo(path)) as target:
  667. old_refs = target.get_refs()
  668. new_refs = determine_wants(dict(old_refs))
  669. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  670. want = []
  671. all_refs = set(new_refs.keys()).union(set(old_refs.keys()))
  672. for refname in all_refs:
  673. old_sha1 = old_refs.get(refname, ZERO_SHA)
  674. new_sha1 = new_refs.get(refname, ZERO_SHA)
  675. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  676. want.append(new_sha1)
  677. if not want and old_refs == new_refs:
  678. return new_refs
  679. target.object_store.add_objects(generate_pack_contents(have, want))
  680. for name, sha in new_refs.items():
  681. target.refs[name] = sha
  682. return new_refs
  683. def fetch(self, path, target, determine_wants=None, progress=None):
  684. """Fetch into a target repository.
  685. :param path: Path to fetch from (as bytestring)
  686. :param target: Target repository to fetch into
  687. :param determine_wants: Optional function to determine what refs
  688. to fetch
  689. :param progress: Optional progress function
  690. :return: Dictionary with all remote refs (not just those fetched)
  691. """
  692. from dulwich.repo import Repo
  693. with closing(Repo(path)) as r:
  694. return r.fetch(target, determine_wants=determine_wants,
  695. progress=progress)
  696. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  697. progress=None):
  698. """Retrieve a pack from a git smart server.
  699. :param determine_wants: Callback that returns list of commits to fetch
  700. :param graph_walker: Object with next() and ack().
  701. :param pack_data: Callback called for each bit of data in the pack
  702. :param progress: Callback for progress reports (strings)
  703. :return: Dictionary with all remote refs (not just those fetched)
  704. """
  705. from dulwich.repo import Repo
  706. with closing(Repo(path)) as r:
  707. objects_iter = r.fetch_objects(determine_wants, graph_walker, progress)
  708. # Did the process short-circuit (e.g. in a stateless RPC call)? Note
  709. # that the client still expects a 0-object pack in most cases.
  710. if objects_iter is None:
  711. return
  712. write_pack_objects(ProtocolFile(None, pack_data), objects_iter)
  713. def get_refs(self, path):
  714. """Retrieve the current refs from a git smart server."""
  715. from dulwich.repo import Repo
  716. with closing(Repo(path)) as target:
  717. return target.get_refs()
  718. # What Git client to use for local access
  719. default_local_git_client_cls = LocalGitClient
  720. class SSHVendor(object):
  721. """A client side SSH implementation."""
  722. def connect_ssh(self, host, command, username=None, port=None):
  723. import warnings
  724. warnings.warn(
  725. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  726. DeprecationWarning)
  727. return self.run_command(host, command, username=username, port=port)
  728. def run_command(self, host, command, username=None, port=None):
  729. """Connect to an SSH server.
  730. Run a command remotely and return a file-like object for interaction
  731. with the remote command.
  732. :param host: Host name
  733. :param command: Command to run (as argv array)
  734. :param username: Optional ame of user to log in as
  735. :param port: Optional SSH port to use
  736. """
  737. raise NotImplementedError(self.run_command)
  738. class SubprocessSSHVendor(SSHVendor):
  739. """SSH vendor that shells out to the local 'ssh' command."""
  740. def run_command(self, host, command, username=None, port=None):
  741. if not isinstance(command, bytes):
  742. raise TypeError(command)
  743. #FIXME: This has no way to deal with passwords..
  744. args = ['ssh', '-x']
  745. if port is not None:
  746. args.extend(['-p', str(port)])
  747. if username is not None:
  748. host = '%s@%s' % (username, host)
  749. args.append(host)
  750. proc = subprocess.Popen(args + [command],
  751. stdin=subprocess.PIPE,
  752. stdout=subprocess.PIPE)
  753. return SubprocessWrapper(proc)
  754. def ParamikoSSHVendor(**kwargs):
  755. import warnings
  756. warnings.warn(
  757. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  758. DeprecationWarning)
  759. from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
  760. return ParamikoSSHVendor(**kwargs)
  761. # Can be overridden by users
  762. get_ssh_vendor = SubprocessSSHVendor
  763. class SSHGitClient(TraditionalGitClient):
  764. def __init__(self, host, port=None, username=None, vendor=None, **kwargs):
  765. self.host = host
  766. self.port = port
  767. self.username = username
  768. TraditionalGitClient.__init__(self, **kwargs)
  769. self.alternative_paths = {}
  770. if vendor is not None:
  771. self.ssh_vendor = vendor
  772. else:
  773. self.ssh_vendor = get_ssh_vendor()
  774. def _get_cmd_path(self, cmd):
  775. cmd = self.alternative_paths.get(cmd, b'git-' + cmd)
  776. assert isinstance(cmd, bytes)
  777. return cmd
  778. def _connect(self, cmd, path):
  779. if type(cmd) is not bytes:
  780. raise TypeError(path)
  781. if type(path) is not bytes:
  782. raise TypeError(path)
  783. if path.startswith(b"/~"):
  784. path = path[1:]
  785. argv = self._get_cmd_path(cmd) + b" '" + path + b"'"
  786. con = self.ssh_vendor.run_command(
  787. self.host, argv, port=self.port, username=self.username)
  788. return (Protocol(con.read, con.write, con.close,
  789. report_activity=self._report_activity),
  790. con.can_read)
  791. def default_user_agent_string():
  792. return "dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  793. def default_urllib2_opener(config):
  794. if config is not None:
  795. proxy_server = config.get("http", "proxy")
  796. else:
  797. proxy_server = None
  798. handlers = []
  799. if proxy_server is not None:
  800. handlers.append(urllib2.ProxyHandler({"http": proxy_server}))
  801. opener = urllib2.build_opener(*handlers)
  802. if config is not None:
  803. user_agent = config.get("http", "useragent")
  804. else:
  805. user_agent = None
  806. if user_agent is None:
  807. user_agent = default_user_agent_string()
  808. opener.addheaders = [('User-agent', user_agent)]
  809. return opener
  810. class HttpGitClient(GitClient):
  811. def __init__(self, base_url, dumb=None, opener=None, config=None, **kwargs):
  812. self.base_url = base_url.rstrip("/") + "/"
  813. self.dumb = dumb
  814. if opener is None:
  815. self.opener = default_urllib2_opener(config)
  816. else:
  817. self.opener = opener
  818. GitClient.__init__(self, **kwargs)
  819. def __repr__(self):
  820. return "%s(%r, dumb=%r)" % (type(self).__name__, self.base_url, self.dumb)
  821. def _get_url(self, path):
  822. return urlparse.urljoin(self.base_url, path).rstrip("/") + "/"
  823. def _http_request(self, url, headers={}, data=None):
  824. req = urllib2.Request(url, headers=headers, data=data)
  825. try:
  826. resp = self.opener.open(req)
  827. except urllib2.HTTPError as e:
  828. if e.code == 404:
  829. raise NotGitRepository()
  830. if e.code != 200:
  831. raise GitProtocolError("unexpected http response %d" % e.code)
  832. return resp
  833. def _discover_references(self, service, url):
  834. assert url[-1] == "/"
  835. url = urlparse.urljoin(url, "info/refs")
  836. headers = {}
  837. if self.dumb is not False:
  838. url += "?service=%s" % service
  839. headers["Content-Type"] = "application/x-%s-request" % service
  840. resp = self._http_request(url, headers)
  841. try:
  842. self.dumb = (not resp.info().gettype().startswith("application/x-git-"))
  843. if not self.dumb:
  844. proto = Protocol(resp.read, None)
  845. # The first line should mention the service
  846. pkts = list(proto.read_pkt_seq())
  847. if pkts != [('# service=%s\n' % service)]:
  848. raise GitProtocolError(
  849. "unexpected first line %r from smart server" % pkts)
  850. return read_pkt_refs(proto)
  851. else:
  852. return read_info_refs(resp), set()
  853. finally:
  854. resp.close()
  855. def _smart_request(self, service, url, data):
  856. assert url[-1] == "/"
  857. url = urlparse.urljoin(url, service)
  858. headers = {"Content-Type": "application/x-%s-request" % service}
  859. resp = self._http_request(url, headers, data)
  860. if resp.info().gettype() != ("application/x-%s-result" % service):
  861. raise GitProtocolError("Invalid content-type from server: %s"
  862. % resp.info().gettype())
  863. return resp
  864. def send_pack(self, path, determine_wants, generate_pack_contents,
  865. progress=None, write_pack=write_pack_objects):
  866. """Upload a pack to a remote repository.
  867. :param path: Repository path (as bytestring)
  868. :param generate_pack_contents: Function that can return a sequence of
  869. the shas of the objects to upload.
  870. :param progress: Optional progress function
  871. :param write_pack: Function called with (file, iterable of objects) to
  872. write the objects returned by generate_pack_contents to the server.
  873. :raises SendPackError: if server rejects the pack data
  874. :raises UpdateRefsError: if the server supports report-status
  875. and rejects ref updates
  876. """
  877. url = self._get_url(path)
  878. old_refs, server_capabilities = self._discover_references(
  879. b"git-receive-pack", url)
  880. negotiated_capabilities = self._send_capabilities & server_capabilities
  881. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  882. self._report_status_parser = ReportStatusParser()
  883. new_refs = determine_wants(dict(old_refs))
  884. if new_refs is None:
  885. return old_refs
  886. if self.dumb:
  887. raise NotImplementedError(self.fetch_pack)
  888. req_data = BytesIO()
  889. req_proto = Protocol(None, req_data.write)
  890. (have, want) = self._handle_receive_pack_head(
  891. req_proto, negotiated_capabilities, old_refs, new_refs)
  892. if not want and old_refs == new_refs:
  893. return new_refs
  894. objects = generate_pack_contents(have, want)
  895. if len(objects) > 0:
  896. write_pack(req_proto.write_file(), objects)
  897. resp = self._smart_request(b"git-receive-pack", url,
  898. data=req_data.getvalue())
  899. try:
  900. resp_proto = Protocol(resp.read, None)
  901. self._handle_receive_pack_tail(resp_proto, negotiated_capabilities,
  902. progress)
  903. return new_refs
  904. finally:
  905. resp.close()
  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 determine_wants: Callback that returns list of commits to fetch
  910. :param graph_walker: Object with next() and ack().
  911. :param pack_data: Callback called for each bit of data in the pack
  912. :param progress: Callback for progress reports (strings)
  913. :return: Dictionary with all remote refs (not just those fetched)
  914. """
  915. url = self._get_url(path)
  916. refs, server_capabilities = self._discover_references(
  917. b"git-upload-pack", url)
  918. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  919. wants = determine_wants(refs)
  920. if wants is not None:
  921. wants = [cid for cid in wants if cid != ZERO_SHA]
  922. if not wants:
  923. return refs
  924. if self.dumb:
  925. raise NotImplementedError(self.send_pack)
  926. req_data = BytesIO()
  927. req_proto = Protocol(None, req_data.write)
  928. self._handle_upload_pack_head(
  929. req_proto, negotiated_capabilities, graph_walker, wants,
  930. lambda: False)
  931. resp = self._smart_request(
  932. b"git-upload-pack", url, data=req_data.getvalue())
  933. try:
  934. resp_proto = Protocol(resp.read, None)
  935. self._handle_upload_pack_tail(resp_proto, negotiated_capabilities,
  936. graph_walker, pack_data, progress)
  937. return refs
  938. finally:
  939. resp.close()
  940. def get_refs(self, path):
  941. """Retrieve the current refs from a git smart server."""
  942. url = self._get_url(path)
  943. refs, _ = self._discover_references(
  944. b"git-upload-pack", url)
  945. return refs
  946. def get_transport_and_path_from_url(url, config=None, **kwargs):
  947. """Obtain a git client from a URL.
  948. :param url: URL to open (a unicode string)
  949. :param config: Optional config object
  950. :param thin_packs: Whether or not thin packs should be retrieved
  951. :param report_activity: Optional callback for reporting transport
  952. activity.
  953. :return: Tuple with client instance and relative path.
  954. """
  955. parsed = urlparse.urlparse(url)
  956. if parsed.scheme == 'git':
  957. return (TCPGitClient(parsed.hostname, port=parsed.port, **kwargs),
  958. parsed.path)
  959. elif parsed.scheme in ('git+ssh', 'ssh'):
  960. path = parsed.path
  961. if path.startswith('/'):
  962. path = parsed.path[1:]
  963. return SSHGitClient(parsed.hostname, port=parsed.port,
  964. username=parsed.username, **kwargs), path
  965. elif parsed.scheme in ('http', 'https'):
  966. return HttpGitClient(urlparse.urlunparse(parsed), config=config,
  967. **kwargs), parsed.path
  968. elif parsed.scheme == 'file':
  969. return default_local_git_client_cls(**kwargs), parsed.path
  970. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  971. def get_transport_and_path(location, **kwargs):
  972. """Obtain a git client from a URL.
  973. :param location: URL or path (a string)
  974. :param config: Optional config object
  975. :param thin_packs: Whether or not thin packs should be retrieved
  976. :param report_activity: Optional callback for reporting transport
  977. activity.
  978. :return: Tuple with client instance and relative path.
  979. """
  980. # First, try to parse it as a URL
  981. try:
  982. return get_transport_and_path_from_url(location, **kwargs)
  983. except ValueError:
  984. pass
  985. if (sys.platform == 'win32' and
  986. location[0].isalpha() and location[1:3] == ':\\'):
  987. # Windows local path
  988. return default_local_git_client_cls(**kwargs), location
  989. if ':' in location and not '@' in location:
  990. # SSH with no user@, zero or one leading slash.
  991. (hostname, path) = location.split(':')
  992. return SSHGitClient(hostname, **kwargs), path
  993. elif '@' in location and ':' in location:
  994. # SSH with user@host:foo.
  995. user_host, path = location.split(':')
  996. user, host = user_host.rsplit('@')
  997. return SSHGitClient(host, username=user, **kwargs), path
  998. # Otherwise, assume it's a local path.
  999. return default_local_git_client_cls(**kwargs), location