protocol.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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.misc 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. def read_pkt_line(self):
  67. """Reads a pkt-line from the remote git process.
  68. :return: The next string from the stream, without the length prefix, or
  69. None for a flush-pkt ('0000').
  70. """
  71. try:
  72. sizestr = self.read(4)
  73. if not sizestr:
  74. raise HangupException()
  75. size = int(sizestr, 16)
  76. if size == 0:
  77. if self.report_activity:
  78. self.report_activity(4, 'read')
  79. return None
  80. if self.report_activity:
  81. self.report_activity(size, 'read')
  82. return self.read(size-4)
  83. except socket.error, e:
  84. raise GitProtocolError(e)
  85. def read_pkt_seq(self):
  86. """Read a sequence of pkt-lines from the remote git process.
  87. :yield: Each line of data up to but not including the next flush-pkt.
  88. """
  89. pkt = self.read_pkt_line()
  90. while pkt:
  91. yield pkt
  92. pkt = self.read_pkt_line()
  93. def write_pkt_line(self, line):
  94. """Sends a pkt-line to the remote git process.
  95. :param line: A string containing the data to send, without the length
  96. prefix.
  97. """
  98. try:
  99. line = pkt_line(line)
  100. self.write(line)
  101. if self.report_activity:
  102. self.report_activity(len(line), 'write')
  103. except socket.error, e:
  104. raise GitProtocolError(e)
  105. def write_file(self):
  106. """Return a writable file-like object for this protocol."""
  107. class ProtocolFile(object):
  108. def __init__(self, proto):
  109. self._proto = proto
  110. self._offset = 0
  111. def write(self, data):
  112. self._proto.write(data)
  113. self._offset += len(data)
  114. def tell(self):
  115. return self._offset
  116. def close(self):
  117. pass
  118. return ProtocolFile(self)
  119. def write_sideband(self, channel, blob):
  120. """Write multiplexed data to the sideband.
  121. :param channel: An int specifying the channel to write to.
  122. :param blob: A blob of data (as a string) to send on this channel.
  123. """
  124. # a pktline can be a max of 65520. a sideband line can therefore be
  125. # 65520-5 = 65515
  126. # WTF: Why have the len in ASCII, but the channel in binary.
  127. while blob:
  128. self.write_pkt_line("%s%s" % (chr(channel), blob[:65515]))
  129. blob = blob[65515:]
  130. def send_cmd(self, cmd, *args):
  131. """Send a command and some arguments to a git server.
  132. Only used for the TCP git protocol (git://).
  133. :param cmd: The remote service to access.
  134. :param args: List of arguments to send to remove service.
  135. """
  136. self.write_pkt_line("%s %s" % (cmd, "".join(["%s\0" % a for a in args])))
  137. def read_cmd(self):
  138. """Read a command and some arguments from the git client
  139. Only used for the TCP git protocol (git://).
  140. :return: A tuple of (command, [list of arguments]).
  141. """
  142. line = self.read_pkt_line()
  143. splice_at = line.find(" ")
  144. cmd, args = line[:splice_at], line[splice_at+1:]
  145. assert args[-1] == "\x00"
  146. return cmd, args[:-1].split(chr(0))
  147. _RBUFSIZE = 8192 # Default read buffer size.
  148. class ReceivableProtocol(Protocol):
  149. """Variant of Protocol that allows reading up to a size without blocking.
  150. This class has a recv() method that behaves like socket.recv() in addition
  151. to a read() method.
  152. If you want to read n bytes from the wire and block until exactly n bytes
  153. (or EOF) are read, use read(n). If you want to read at most n bytes from the
  154. wire but don't care if you get less, use recv(n). Note that recv(n) will
  155. still block until at least one byte is read.
  156. """
  157. def __init__(self, recv, write, report_activity=None, rbufsize=_RBUFSIZE):
  158. super(ReceivableProtocol, self).__init__(self.read, write,
  159. report_activity)
  160. self._recv = recv
  161. self._rbuf = StringIO()
  162. self._rbufsize = rbufsize
  163. def read(self, size):
  164. # From _fileobj.read in socket.py in the Python 2.6.5 standard library,
  165. # with the following modifications:
  166. # - omit the size <= 0 branch
  167. # - seek back to start rather than 0 in case some buffer has been
  168. # consumed.
  169. # - use SEEK_END instead of the magic number.
  170. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved
  171. # Licensed under the Python Software Foundation License.
  172. # TODO: see if buffer is more efficient than cStringIO.
  173. assert size > 0
  174. # Our use of StringIO rather than lists of string objects returned by
  175. # recv() minimizes memory usage and fragmentation that occurs when
  176. # rbufsize is large compared to the typical return value of recv().
  177. buf = self._rbuf
  178. start = buf.tell()
  179. buf.seek(0, SEEK_END)
  180. # buffer may have been partially consumed by recv()
  181. buf_len = buf.tell() - start
  182. if buf_len >= size:
  183. # Already have size bytes in our buffer? Extract and return.
  184. buf.seek(start)
  185. rv = buf.read(size)
  186. self._rbuf = StringIO()
  187. self._rbuf.write(buf.read())
  188. self._rbuf.seek(0)
  189. return rv
  190. self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
  191. while True:
  192. left = size - buf_len
  193. # recv() will malloc the amount of memory given as its
  194. # parameter even though it often returns much less data
  195. # than that. The returned data string is short lived
  196. # as we copy it into a StringIO and free it. This avoids
  197. # fragmentation issues on many platforms.
  198. data = self._recv(left)
  199. if not data:
  200. break
  201. n = len(data)
  202. if n == size and not buf_len:
  203. # Shortcut. Avoid buffer data copies when:
  204. # - We have no data in our buffer.
  205. # AND
  206. # - Our call to recv returned exactly the
  207. # number of bytes we were asked to read.
  208. return data
  209. if n == left:
  210. buf.write(data)
  211. del data # explicit free
  212. break
  213. assert n <= left, "_recv(%d) returned %d bytes" % (left, n)
  214. buf.write(data)
  215. buf_len += n
  216. del data # explicit free
  217. #assert buf_len == buf.tell()
  218. buf.seek(start)
  219. return buf.read()
  220. def recv(self, size):
  221. assert size > 0
  222. buf = self._rbuf
  223. start = buf.tell()
  224. buf.seek(0, SEEK_END)
  225. buf_len = buf.tell()
  226. buf.seek(start)
  227. left = buf_len - start
  228. if not left:
  229. # only read from the wire if our read buffer is exhausted
  230. data = self._recv(self._rbufsize)
  231. if len(data) == size:
  232. # shortcut: skip the buffer if we read exactly size bytes
  233. return data
  234. buf = StringIO()
  235. buf.write(data)
  236. buf.seek(0)
  237. del data # explicit free
  238. self._rbuf = buf
  239. return buf.read(size)
  240. def extract_capabilities(text):
  241. """Extract a capabilities list from a string, if present.
  242. :param text: String to extract from
  243. :return: Tuple with text with capabilities removed and list of capabilities
  244. """
  245. if not "\0" in text:
  246. return text, []
  247. text, capabilities = text.rstrip().split("\0")
  248. return (text, capabilities.strip().split(" "))
  249. def extract_want_line_capabilities(text):
  250. """Extract a capabilities list from a want line, if present.
  251. Note that want lines have capabilities separated from the rest of the line
  252. by a space instead of a null byte. Thus want lines have the form:
  253. want obj-id cap1 cap2 ...
  254. :param text: Want line to extract from
  255. :return: Tuple with text with capabilities removed and list of capabilities
  256. """
  257. split_text = text.rstrip().split(" ")
  258. if len(split_text) < 3:
  259. return text, []
  260. return (" ".join(split_text[:2]), split_text[2:])
  261. def ack_type(capabilities):
  262. """Extract the ack type from a capabilities list."""
  263. if 'multi_ack_detailed' in capabilities:
  264. return MULTI_ACK_DETAILED
  265. elif 'multi_ack' in capabilities:
  266. return MULTI_ACK
  267. return SINGLE_ACK
  268. class BufferedPktLineWriter(object):
  269. """Writer that wraps its data in pkt-lines and has an independent buffer.
  270. Consecutive calls to write() wrap the data in a pkt-line and then buffers it
  271. until enough lines have been written such that their total length (including
  272. length prefix) reach the buffer size.
  273. """
  274. def __init__(self, write, bufsize=65515):
  275. """Initialize the BufferedPktLineWriter.
  276. :param write: A write callback for the underlying writer.
  277. :param bufsize: The internal buffer size, including length prefixes.
  278. """
  279. self._write = write
  280. self._bufsize = bufsize
  281. self._wbuf = StringIO()
  282. self._buflen = 0
  283. def write(self, data):
  284. """Write data, wrapping it in a pkt-line."""
  285. line = pkt_line(data)
  286. line_len = len(line)
  287. over = self._buflen + line_len - self._bufsize
  288. if over >= 0:
  289. start = line_len - over
  290. self._wbuf.write(line[:start])
  291. self.flush()
  292. else:
  293. start = 0
  294. saved = line[start:]
  295. self._wbuf.write(saved)
  296. self._buflen += len(saved)
  297. def flush(self):
  298. """Flush all data from the buffer."""
  299. data = self._wbuf.getvalue()
  300. if data:
  301. self._write(data)
  302. self._len = 0
  303. self._wbuf = StringIO()