client.py 44 KB

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