protocol.py 13 KB

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