client.py 42 KB

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