protocol.py 18 KB

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