protocol.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. # protocol.py -- Shared parts of the git protocols
  2. # Copyright (C) 2008 John Carr <john.carr@unrouted.co.uk>
  3. # Copyright (C) 2008-2012 Jelmer Vernooij <jelmer@samba.org>
  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; version 2
  8. # or (at your option) any 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. """Generic functions for talking the git smart server protocol."""
  20. from io import BytesIO
  21. from os import (
  22. SEEK_END,
  23. )
  24. import socket
  25. from dulwich.errors import (
  26. HangupException,
  27. GitProtocolError,
  28. )
  29. TCP_GIT_PORT = 9418
  30. ZERO_SHA = b"0" * 40
  31. SINGLE_ACK = 0
  32. MULTI_ACK = 1
  33. MULTI_ACK_DETAILED = 2
  34. # pack data
  35. SIDE_BAND_CHANNEL_DATA = 1
  36. # progress messages
  37. SIDE_BAND_CHANNEL_PROGRESS = 2
  38. # fatal error message just before stream aborts
  39. SIDE_BAND_CHANNEL_FATAL = 3
  40. CAPABILITY_DELETE_REFS = b'delete-refs'
  41. CAPABILITY_INCLUDE_TAG = b'include-tag'
  42. CAPABILITY_MULTI_ACK = b'multi_ack'
  43. CAPABILITY_MULTI_ACK_DETAILED = b'multi_ack_detailed'
  44. CAPABILITY_NO_DONE = b'no-done'
  45. CAPABILITY_NO_PROGRESS = b'no-progress'
  46. CAPABILITY_OFS_DELTA = b'ofs-delta'
  47. CAPABILITY_QUIET = b'quiet'
  48. CAPABILITY_REPORT_STATUS = b'report-status'
  49. CAPABILITY_SHALLOW = b'shallow'
  50. CAPABILITY_SIDE_BAND_64K = b'side-band-64k'
  51. CAPABILITY_THIN_PACK = b'thin-pack'
  52. COMMAND_DEEPEN = b'deepen'
  53. COMMAND_SHALLOW = b'shallow'
  54. COMMAND_UNSHALLOW = b'unshallow'
  55. COMMAND_DONE = b'done'
  56. COMMAND_WANT = b'want'
  57. COMMAND_HAVE = b'have'
  58. class ProtocolFile(object):
  59. """A dummy file for network ops that expect file-like objects."""
  60. def __init__(self, read, write):
  61. self.read = read
  62. self.write = write
  63. def tell(self):
  64. pass
  65. def close(self):
  66. pass
  67. def pkt_line(data):
  68. """Wrap data in a pkt-line.
  69. :param data: The data to wrap, as a str or None.
  70. :return: The data prefixed with its length in pkt-line format; if data was
  71. None, returns the flush-pkt ('0000').
  72. """
  73. if data is None:
  74. return b'0000'
  75. return ('%04x' % (len(data) + 4)).encode('ascii') + data
  76. class Protocol(object):
  77. """Class for interacting with a remote git process over the wire.
  78. Parts of the git wire protocol use 'pkt-lines' to communicate. A pkt-line
  79. consists of the length of the line as a 4-byte hex string, followed by the
  80. payload data. The length includes the 4-byte header. The special line '0000'
  81. indicates the end of a section of input and is called a 'flush-pkt'.
  82. For details on the pkt-line format, see the cgit distribution:
  83. Documentation/technical/protocol-common.txt
  84. """
  85. def __init__(self, read, write, close=None, report_activity=None):
  86. self.read = read
  87. self.write = write
  88. self._close = close
  89. self.report_activity = report_activity
  90. self._readahead = None
  91. def close(self):
  92. if self._close:
  93. self._close()
  94. def __enter__(self):
  95. return self
  96. def __exit__(self, exc_type, exc_val, exc_tb):
  97. self.close()
  98. def read_pkt_line(self):
  99. """Reads a pkt-line from the remote git process.
  100. This method may read from the readahead buffer; see unread_pkt_line.
  101. :return: The next string from the stream, without the length prefix, or
  102. None for a flush-pkt ('0000').
  103. """
  104. if self._readahead is None:
  105. read = self.read
  106. else:
  107. read = self._readahead.read
  108. self._readahead = None
  109. try:
  110. sizestr = read(4)
  111. if not sizestr:
  112. raise HangupException()
  113. size = int(sizestr, 16)
  114. if size == 0:
  115. if self.report_activity:
  116. self.report_activity(4, 'read')
  117. return None
  118. if self.report_activity:
  119. self.report_activity(size, 'read')
  120. pkt_contents = read(size-4)
  121. except socket.error as e:
  122. raise GitProtocolError(e)
  123. else:
  124. if len(pkt_contents) + 4 != size:
  125. raise GitProtocolError(
  126. 'Length of pkt read %04x does not match length prefix %04x' % (len(pkt_contents) + 4, size))
  127. return pkt_contents
  128. def eof(self):
  129. """Test whether the protocol stream has reached EOF.
  130. Note that this refers to the actual stream EOF and not just a flush-pkt.
  131. :return: True if the stream is at EOF, False otherwise.
  132. """
  133. try:
  134. next_line = self.read_pkt_line()
  135. except HangupException:
  136. return True
  137. self.unread_pkt_line(next_line)
  138. return False
  139. def unread_pkt_line(self, data):
  140. """Unread a single line of data into the readahead buffer.
  141. This method can be used to unread a single pkt-line into a fixed
  142. readahead buffer.
  143. :param data: The data to unread, without the length prefix.
  144. :raise ValueError: If more than one pkt-line is unread.
  145. """
  146. if self._readahead is not None:
  147. raise ValueError('Attempted to unread multiple pkt-lines.')
  148. self._readahead = BytesIO(pkt_line(data))
  149. def read_pkt_seq(self):
  150. """Read a sequence of pkt-lines from the remote git process.
  151. :return: Yields each line of data up to but not including the next flush-pkt.
  152. """
  153. pkt = self.read_pkt_line()
  154. while pkt:
  155. yield pkt
  156. pkt = self.read_pkt_line()
  157. def write_pkt_line(self, line):
  158. """Sends a pkt-line to the remote git process.
  159. :param line: A string containing the data to send, without the length
  160. prefix.
  161. """
  162. try:
  163. line = pkt_line(line)
  164. self.write(line)
  165. if self.report_activity:
  166. self.report_activity(len(line), 'write')
  167. except socket.error as e:
  168. raise GitProtocolError(e)
  169. def write_file(self):
  170. """Return a writable file-like object for this protocol."""
  171. class ProtocolFile(object):
  172. def __init__(self, proto):
  173. self._proto = proto
  174. self._offset = 0
  175. def write(self, data):
  176. self._proto.write(data)
  177. self._offset += len(data)
  178. def tell(self):
  179. return self._offset
  180. def close(self):
  181. pass
  182. return ProtocolFile(self)
  183. def write_sideband(self, channel, blob):
  184. """Write multiplexed data to the sideband.
  185. :param channel: An int specifying the channel to write to.
  186. :param blob: A blob of data (as a string) to send on this channel.
  187. """
  188. # a pktline can be a max of 65520. a sideband line can therefore be
  189. # 65520-5 = 65515
  190. # WTF: Why have the len in ASCII, but the channel in binary.
  191. while blob:
  192. self.write_pkt_line(bytes(bytearray([channel])) + blob[:65515])
  193. blob = blob[65515:]
  194. def send_cmd(self, cmd, *args):
  195. """Send a command and some arguments to a git server.
  196. Only used for the TCP git protocol (git://).
  197. :param cmd: The remote service to access.
  198. :param args: List of arguments to send to remove service.
  199. """
  200. self.write_pkt_line(cmd + b" " + b"".join([(a + b"\0") for a in args]))
  201. def read_cmd(self):
  202. """Read a command and some arguments from the git client
  203. Only used for the TCP git protocol (git://).
  204. :return: A tuple of (command, [list of arguments]).
  205. """
  206. line = self.read_pkt_line()
  207. splice_at = line.find(b" ")
  208. cmd, args = line[:splice_at], line[splice_at+1:]
  209. assert args[-1:] == b"\x00"
  210. return cmd, args[:-1].split(b"\0")
  211. _RBUFSIZE = 8192 # Default read buffer size.
  212. class ReceivableProtocol(Protocol):
  213. """Variant of Protocol that allows reading up to a size without blocking.
  214. This class has a recv() method that behaves like socket.recv() in addition
  215. to a read() method.
  216. If you want to read n bytes from the wire and block until exactly n bytes
  217. (or EOF) are read, use read(n). If you want to read at most n bytes from the
  218. wire but don't care if you get less, use recv(n). Note that recv(n) will
  219. still block until at least one byte is read.
  220. """
  221. def __init__(self, recv, write, report_activity=None, rbufsize=_RBUFSIZE):
  222. super(ReceivableProtocol, self).__init__(self.read, write,
  223. report_activity)
  224. self._recv = recv
  225. self._rbuf = BytesIO()
  226. self._rbufsize = rbufsize
  227. def read(self, size):
  228. # From _fileobj.read in socket.py in the Python 2.6.5 standard library,
  229. # with the following modifications:
  230. # - omit the size <= 0 branch
  231. # - seek back to start rather than 0 in case some buffer has been
  232. # consumed.
  233. # - use SEEK_END instead of the magic number.
  234. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved
  235. # Licensed under the Python Software Foundation License.
  236. # TODO: see if buffer is more efficient than cBytesIO.
  237. assert size > 0
  238. # Our use of BytesIO rather than lists of string objects returned by
  239. # recv() minimizes memory usage and fragmentation that occurs when
  240. # rbufsize is large compared to the typical return value of recv().
  241. buf = self._rbuf
  242. start = buf.tell()
  243. buf.seek(0, SEEK_END)
  244. # buffer may have been partially consumed by recv()
  245. buf_len = buf.tell() - start
  246. if buf_len >= size:
  247. # Already have size bytes in our buffer? Extract and return.
  248. buf.seek(start)
  249. rv = buf.read(size)
  250. self._rbuf = BytesIO()
  251. self._rbuf.write(buf.read())
  252. self._rbuf.seek(0)
  253. return rv
  254. self._rbuf = BytesIO() # reset _rbuf. we consume it via buf.
  255. while True:
  256. left = size - buf_len
  257. # recv() will malloc the amount of memory given as its
  258. # parameter even though it often returns much less data
  259. # than that. The returned data string is short lived
  260. # as we copy it into a BytesIO and free it. This avoids
  261. # fragmentation issues on many platforms.
  262. data = self._recv(left)
  263. if not data:
  264. break
  265. n = len(data)
  266. if n == size and not buf_len:
  267. # Shortcut. Avoid buffer data copies when:
  268. # - We have no data in our buffer.
  269. # AND
  270. # - Our call to recv returned exactly the
  271. # number of bytes we were asked to read.
  272. return data
  273. if n == left:
  274. buf.write(data)
  275. del data # explicit free
  276. break
  277. assert n <= left, "_recv(%d) returned %d bytes" % (left, n)
  278. buf.write(data)
  279. buf_len += n
  280. del data # explicit free
  281. #assert buf_len == buf.tell()
  282. buf.seek(start)
  283. return buf.read()
  284. def recv(self, size):
  285. assert size > 0
  286. buf = self._rbuf
  287. start = buf.tell()
  288. buf.seek(0, SEEK_END)
  289. buf_len = buf.tell()
  290. buf.seek(start)
  291. left = buf_len - start
  292. if not left:
  293. # only read from the wire if our read buffer is exhausted
  294. data = self._recv(self._rbufsize)
  295. if len(data) == size:
  296. # shortcut: skip the buffer if we read exactly size bytes
  297. return data
  298. buf = BytesIO()
  299. buf.write(data)
  300. buf.seek(0)
  301. del data # explicit free
  302. self._rbuf = buf
  303. return buf.read(size)
  304. def extract_capabilities(text):
  305. """Extract a capabilities list from a string, if present.
  306. :param text: String to extract from
  307. :return: Tuple with text with capabilities removed and list of capabilities
  308. """
  309. if not b"\0" in text:
  310. return text, []
  311. text, capabilities = text.rstrip().split(b"\0")
  312. return (text, capabilities.strip().split(b" "))
  313. def extract_want_line_capabilities(text):
  314. """Extract a capabilities list from a want line, if present.
  315. Note that want lines have capabilities separated from the rest of the line
  316. by a space instead of a null byte. Thus want lines have the form:
  317. want obj-id cap1 cap2 ...
  318. :param text: Want line to extract from
  319. :return: Tuple with text with capabilities removed and list of capabilities
  320. """
  321. split_text = text.rstrip().split(b" ")
  322. if len(split_text) < 3:
  323. return text, []
  324. return (b" ".join(split_text[:2]), split_text[2:])
  325. def ack_type(capabilities):
  326. """Extract the ack type from a capabilities list."""
  327. if b'multi_ack_detailed' in capabilities:
  328. return MULTI_ACK_DETAILED
  329. elif b'multi_ack' in capabilities:
  330. return MULTI_ACK
  331. return SINGLE_ACK
  332. class BufferedPktLineWriter(object):
  333. """Writer that wraps its data in pkt-lines and has an independent buffer.
  334. Consecutive calls to write() wrap the data in a pkt-line and then buffers it
  335. until enough lines have been written such that their total length (including
  336. length prefix) reach the buffer size.
  337. """
  338. def __init__(self, write, bufsize=65515):
  339. """Initialize the BufferedPktLineWriter.
  340. :param write: A write callback for the underlying writer.
  341. :param bufsize: The internal buffer size, including length prefixes.
  342. """
  343. self._write = write
  344. self._bufsize = bufsize
  345. self._wbuf = BytesIO()
  346. self._buflen = 0
  347. def write(self, data):
  348. """Write data, wrapping it in a pkt-line."""
  349. line = pkt_line(data)
  350. line_len = len(line)
  351. over = self._buflen + line_len - self._bufsize
  352. if over >= 0:
  353. start = line_len - over
  354. self._wbuf.write(line[:start])
  355. self.flush()
  356. else:
  357. start = 0
  358. saved = line[start:]
  359. self._wbuf.write(saved)
  360. self._buflen += len(saved)
  361. def flush(self):
  362. """Flush all data from the buffer."""
  363. data = self._wbuf.getvalue()
  364. if data:
  365. self._write(data)
  366. self._len = 0
  367. self._wbuf = BytesIO()
  368. class PktLineParser(object):
  369. """Packet line parser that hands completed packets off to a callback.
  370. """
  371. def __init__(self, handle_pkt):
  372. self.handle_pkt = handle_pkt
  373. self._readahead = BytesIO()
  374. def parse(self, data):
  375. """Parse a fragment of data and call back for any completed packets.
  376. """
  377. self._readahead.write(data)
  378. buf = self._readahead.getvalue()
  379. if len(buf) < 4:
  380. return
  381. while len(buf) >= 4:
  382. size = int(buf[:4], 16)
  383. if size == 0:
  384. self.handle_pkt(None)
  385. buf = buf[4:]
  386. elif size <= len(buf):
  387. self.handle_pkt(buf[4:size])
  388. buf = buf[size:]
  389. else:
  390. break
  391. self._readahead = BytesIO()
  392. self._readahead.write(buf)
  393. def get_tail(self):
  394. """Read back any unused data."""
  395. return self._readahead.getvalue()