protocol.py 15 KB

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