client.py 39 KB

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