protocol.py 16 KB

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