protocol.py 9.9 KB

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