protocol.py 16 KB

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