client.py 45 KB

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