protocol.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. """
  37. Some network ops are like file ops. The file ops expect to operate on
  38. file objects, so provide them with a dummy file.
  39. """
  40. def __init__(self, read, write):
  41. self.read = read
  42. self.write = write
  43. def tell(self):
  44. pass
  45. def close(self):
  46. pass
  47. def pkt_line(data):
  48. """Wrap data in a pkt-line.
  49. :param data: The data to wrap, as a str or None.
  50. :return: The data prefixed with its length in pkt-line format; if data was
  51. None, returns the flush-pkt ('0000')
  52. """
  53. if data is None:
  54. return '0000'
  55. return '%04x%s' % (len(data) + 4, data)
  56. class Protocol(object):
  57. def __init__(self, read, write, report_activity=None):
  58. self.read = read
  59. self.write = write
  60. self.report_activity = report_activity
  61. def read_pkt_line(self):
  62. """
  63. Reads a 'pkt line' from the remote git process
  64. :return: The next string from the stream
  65. """
  66. try:
  67. sizestr = self.read(4)
  68. if not sizestr:
  69. raise HangupException()
  70. size = int(sizestr, 16)
  71. if size == 0:
  72. if self.report_activity:
  73. self.report_activity(4, 'read')
  74. return None
  75. if self.report_activity:
  76. self.report_activity(size, 'read')
  77. return self.read(size-4)
  78. except socket.error, e:
  79. raise GitProtocolError(e)
  80. def read_pkt_seq(self):
  81. pkt = self.read_pkt_line()
  82. while pkt:
  83. yield pkt
  84. pkt = self.read_pkt_line()
  85. def write_pkt_line(self, line):
  86. """
  87. Sends a 'pkt line' to the remote git process
  88. :param line: A string containing the data to send
  89. """
  90. try:
  91. line = pkt_line(line)
  92. self.write(line)
  93. if self.report_activity:
  94. self.report_activity(len(line), 'write')
  95. except socket.error, e:
  96. raise GitProtocolError(e)
  97. def write_file(self):
  98. class ProtocolFile(object):
  99. def __init__(self, proto):
  100. self._proto = proto
  101. self._offset = 0
  102. def write(self, data):
  103. self._proto.write(data)
  104. self._offset += len(data)
  105. def tell(self):
  106. return self._offset
  107. def close(self):
  108. pass
  109. return ProtocolFile(self)
  110. def write_sideband(self, channel, blob):
  111. """
  112. Write data to the sideband (a git multiplexing method)
  113. :param channel: int specifying which channel to write to
  114. :param blob: a blob of data (as a string) to send on this channel
  115. """
  116. # a pktline can be a max of 65520. a sideband line can therefore be
  117. # 65520-5 = 65515
  118. # WTF: Why have the len in ASCII, but the channel in binary.
  119. while blob:
  120. self.write_pkt_line("%s%s" % (chr(channel), blob[:65515]))
  121. blob = blob[65515:]
  122. def send_cmd(self, cmd, *args):
  123. """
  124. Send a command and some arguments to a git server
  125. Only used for git://
  126. :param cmd: The remote service to access
  127. :param args: List of arguments to send to remove service
  128. """
  129. self.write_pkt_line("%s %s" % (cmd, "".join(["%s\0" % a for a in args])))
  130. def read_cmd(self):
  131. """
  132. Read a command and some arguments from the git client
  133. Only used for git://
  134. :return: A tuple of (command, [list of arguments])
  135. """
  136. line = self.read_pkt_line()
  137. splice_at = line.find(" ")
  138. cmd, args = line[:splice_at], line[splice_at+1:]
  139. assert args[-1] == "\x00"
  140. return cmd, args[:-1].split(chr(0))
  141. _RBUFSIZE = 8192 # Default read buffer size.
  142. class ReceivableProtocol(Protocol):
  143. """Variant of Protocol that allows reading up to a size without blocking.
  144. This class has a recv() method that behaves like socket.recv() in addition
  145. to a read() method.
  146. If you want to read n bytes from the wire and block until exactly n bytes
  147. (or EOF) are read, use read(n). If you want to read at most n bytes from the
  148. wire but don't care if you get less, use recv(n). Note that recv(n) will
  149. still block until at least one byte is read.
  150. """
  151. def __init__(self, recv, write, report_activity=None, rbufsize=_RBUFSIZE):
  152. super(ReceivableProtocol, self).__init__(self.read, write,
  153. report_activity)
  154. self._recv = recv
  155. self._rbuf = StringIO()
  156. self._rbufsize = rbufsize
  157. def read(self, size):
  158. # From _fileobj.read in socket.py in the Python 2.6.5 standard library,
  159. # with the following modifications:
  160. # - omit the size <= 0 branch
  161. # - seek back to start rather than 0 in case some buffer has been
  162. # consumed.
  163. # - use SEEK_END instead of the magic number.
  164. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved
  165. # Licensed under the Python Software Foundation License.
  166. # TODO: see if buffer is more efficient than cStringIO.
  167. assert size > 0
  168. # Our use of StringIO rather than lists of string objects returned by
  169. # recv() minimizes memory usage and fragmentation that occurs when
  170. # rbufsize is large compared to the typical return value of recv().
  171. buf = self._rbuf
  172. start = buf.tell()
  173. buf.seek(0, SEEK_END)
  174. # buffer may have been partially consumed by recv()
  175. buf_len = buf.tell() - start
  176. if buf_len >= size:
  177. # Already have size bytes in our buffer? Extract and return.
  178. buf.seek(start)
  179. rv = buf.read(size)
  180. self._rbuf = StringIO()
  181. self._rbuf.write(buf.read())
  182. self._rbuf.seek(0)
  183. return rv
  184. self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
  185. while True:
  186. left = size - buf_len
  187. # recv() will malloc the amount of memory given as its
  188. # parameter even though it often returns much less data
  189. # than that. The returned data string is short lived
  190. # as we copy it into a StringIO and free it. This avoids
  191. # fragmentation issues on many platforms.
  192. data = self._recv(left)
  193. if not data:
  194. break
  195. n = len(data)
  196. if n == size and not buf_len:
  197. # Shortcut. Avoid buffer data copies when:
  198. # - We have no data in our buffer.
  199. # AND
  200. # - Our call to recv returned exactly the
  201. # number of bytes we were asked to read.
  202. return data
  203. if n == left:
  204. buf.write(data)
  205. del data # explicit free
  206. break
  207. assert n <= left, "_recv(%d) returned %d bytes" % (left, n)
  208. buf.write(data)
  209. buf_len += n
  210. del data # explicit free
  211. #assert buf_len == buf.tell()
  212. buf.seek(start)
  213. return buf.read()
  214. def recv(self, size):
  215. assert size > 0
  216. buf = self._rbuf
  217. start = buf.tell()
  218. buf.seek(0, SEEK_END)
  219. buf_len = buf.tell()
  220. buf.seek(start)
  221. left = buf_len - start
  222. if not left:
  223. # only read from the wire if our read buffer is exhausted
  224. data = self._recv(self._rbufsize)
  225. if len(data) == size:
  226. # shortcut: skip the buffer if we read exactly size bytes
  227. return data
  228. buf = StringIO()
  229. buf.write(data)
  230. buf.seek(0)
  231. del data # explicit free
  232. self._rbuf = buf
  233. return buf.read(size)
  234. def extract_capabilities(text):
  235. """Extract a capabilities list from a string, if present.
  236. :param text: String to extract from
  237. :return: Tuple with text with capabilities removed and list of capabilities
  238. """
  239. if not "\0" in text:
  240. return text, []
  241. text, capabilities = text.rstrip().split("\0")
  242. return (text, capabilities.strip().split(" "))
  243. def extract_want_line_capabilities(text):
  244. """Extract a capabilities list from a want line, if present.
  245. Note that want lines have capabilities separated from the rest of the line
  246. by a space instead of a null byte. Thus want lines have the form:
  247. want obj-id cap1 cap2 ...
  248. :param text: Want line to extract from
  249. :return: Tuple with text with capabilities removed and list of capabilities
  250. """
  251. split_text = text.rstrip().split(" ")
  252. if len(split_text) < 3:
  253. return text, []
  254. return (" ".join(split_text[:2]), split_text[2:])
  255. def ack_type(capabilities):
  256. """Extract the ack type from a capabilities list."""
  257. if 'multi_ack_detailed' in capabilities:
  258. return MULTI_ACK_DETAILED
  259. elif 'multi_ack' in capabilities:
  260. return MULTI_ACK
  261. return SINGLE_ACK