protocol.py 9.9 KB

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