protocol.py 17 KB

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