protocol.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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) -> 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') or delim-pkt ('0001').
  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 or size == 1: # flush-pkt or delim-pkt
  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. f"Length of pkt read {len(pkt_contents) + 4:04x} does not match length prefix {size:04x}"
  186. )
  187. return pkt_contents
  188. def eof(self):
  189. """Test whether the protocol stream has reached EOF.
  190. Note that this refers to the actual stream EOF and not just a
  191. flush-pkt.
  192. Returns: True if the stream is at EOF, False otherwise.
  193. """
  194. try:
  195. next_line = self.read_pkt_line()
  196. except HangupException:
  197. return True
  198. self.unread_pkt_line(next_line)
  199. return False
  200. def unread_pkt_line(self, data):
  201. """Unread a single line of data into the readahead buffer.
  202. This method can be used to unread a single pkt-line into a fixed
  203. readahead buffer.
  204. Args:
  205. data: The data to unread, without the length prefix.
  206. Raises:
  207. ValueError: If more than one pkt-line is unread.
  208. """
  209. if self._readahead is not None:
  210. raise ValueError("Attempted to unread multiple pkt-lines.")
  211. self._readahead = BytesIO(pkt_line(data))
  212. def read_pkt_seq(self):
  213. """Read a sequence of pkt-lines from the remote git process.
  214. Returns: Yields each line of data up to but not including the next
  215. flush-pkt.
  216. """
  217. pkt = self.read_pkt_line()
  218. while pkt:
  219. yield pkt
  220. pkt = self.read_pkt_line()
  221. def write_pkt_line(self, line):
  222. """Sends a pkt-line to the remote git process.
  223. Args:
  224. line: A string containing the data to send, without the length
  225. prefix.
  226. """
  227. try:
  228. line = pkt_line(line)
  229. self.write(line)
  230. if self.report_activity:
  231. self.report_activity(len(line), "write")
  232. except OSError as exc:
  233. raise GitProtocolError(str(exc)) from exc
  234. def write_sideband(self, channel, blob):
  235. """Write multiplexed data to the sideband.
  236. Args:
  237. channel: An int specifying the channel to write to.
  238. blob: A blob of data (as a string) to send on this channel.
  239. """
  240. # a pktline can be a max of 65520. a sideband line can therefore be
  241. # 65520-5 = 65515
  242. # WTF: Why have the len in ASCII, but the channel in binary.
  243. while blob:
  244. self.write_pkt_line(bytes(bytearray([channel])) + blob[:65515])
  245. blob = blob[65515:]
  246. def send_cmd(self, cmd, *args):
  247. """Send a command and some arguments to a git server.
  248. Only used for the TCP git protocol (git://).
  249. Args:
  250. cmd: The remote service to access.
  251. args: List of arguments to send to remove service.
  252. """
  253. self.write_pkt_line(format_cmd_pkt(cmd, *args))
  254. def read_cmd(self):
  255. """Read a command and some arguments from the git client.
  256. Only used for the TCP git protocol (git://).
  257. Returns: A tuple of (command, [list of arguments]).
  258. """
  259. line = self.read_pkt_line()
  260. return parse_cmd_pkt(line)
  261. _RBUFSIZE = 8192 # Default read buffer size.
  262. class ReceivableProtocol(Protocol):
  263. """Variant of Protocol that allows reading up to a size without blocking.
  264. This class has a recv() method that behaves like socket.recv() in addition
  265. to a read() method.
  266. If you want to read n bytes from the wire and block until exactly n bytes
  267. (or EOF) are read, use read(n). If you want to read at most n bytes from
  268. the wire but don't care if you get less, use recv(n). Note that recv(n)
  269. will still block until at least one byte is read.
  270. """
  271. def __init__(
  272. self, recv, write, close=None, report_activity=None, rbufsize=_RBUFSIZE
  273. ) -> None:
  274. super().__init__(self.read, write, close=close, report_activity=report_activity)
  275. self._recv = recv
  276. self._rbuf = BytesIO()
  277. self._rbufsize = rbufsize
  278. def read(self, size):
  279. # From _fileobj.read in socket.py in the Python 2.6.5 standard library,
  280. # with the following modifications:
  281. # - omit the size <= 0 branch
  282. # - seek back to start rather than 0 in case some buffer has been
  283. # consumed.
  284. # - use SEEK_END instead of the magic number.
  285. # Copyright (c) 2001-2010 Python Software Foundation; All Rights
  286. # Reserved
  287. # Licensed under the Python Software Foundation License.
  288. # TODO: see if buffer is more efficient than cBytesIO.
  289. assert size > 0
  290. # Our use of BytesIO rather than lists of string objects returned by
  291. # recv() minimizes memory usage and fragmentation that occurs when
  292. # rbufsize is large compared to the typical return value of recv().
  293. buf = self._rbuf
  294. start = buf.tell()
  295. buf.seek(0, SEEK_END)
  296. # buffer may have been partially consumed by recv()
  297. buf_len = buf.tell() - start
  298. if buf_len >= size:
  299. # Already have size bytes in our buffer? Extract and return.
  300. buf.seek(start)
  301. rv = buf.read(size)
  302. self._rbuf = BytesIO()
  303. self._rbuf.write(buf.read())
  304. self._rbuf.seek(0)
  305. return rv
  306. self._rbuf = BytesIO() # reset _rbuf. we consume it via buf.
  307. while True:
  308. left = size - buf_len
  309. # recv() will malloc the amount of memory given as its
  310. # parameter even though it often returns much less data
  311. # than that. The returned data string is short lived
  312. # as we copy it into a BytesIO and free it. This avoids
  313. # fragmentation issues on many platforms.
  314. data = self._recv(left)
  315. if not data:
  316. break
  317. n = len(data)
  318. if n == size and not buf_len:
  319. # Shortcut. Avoid buffer data copies when:
  320. # - We have no data in our buffer.
  321. # AND
  322. # - Our call to recv returned exactly the
  323. # number of bytes we were asked to read.
  324. return data
  325. if n == left:
  326. buf.write(data)
  327. del data # explicit free
  328. break
  329. assert n <= left, "_recv(%d) returned %d bytes" % (left, n)
  330. buf.write(data)
  331. buf_len += n
  332. del data # explicit free
  333. # assert buf_len == buf.tell()
  334. buf.seek(start)
  335. return buf.read()
  336. def recv(self, size):
  337. assert size > 0
  338. buf = self._rbuf
  339. start = buf.tell()
  340. buf.seek(0, SEEK_END)
  341. buf_len = buf.tell()
  342. buf.seek(start)
  343. left = buf_len - start
  344. if not left:
  345. # only read from the wire if our read buffer is exhausted
  346. data = self._recv(self._rbufsize)
  347. if len(data) == size:
  348. # shortcut: skip the buffer if we read exactly size bytes
  349. return data
  350. buf = BytesIO()
  351. buf.write(data)
  352. buf.seek(0)
  353. del data # explicit free
  354. self._rbuf = buf
  355. return buf.read(size)
  356. def extract_capabilities(text):
  357. """Extract a capabilities list from a string, if present.
  358. Args:
  359. text: String to extract from
  360. Returns: Tuple with text with capabilities removed and list of capabilities
  361. """
  362. if b"\0" not in text:
  363. return text, []
  364. text, capabilities = text.rstrip().split(b"\0")
  365. return (text, capabilities.strip().split(b" "))
  366. def extract_want_line_capabilities(text):
  367. """Extract a capabilities list from a want line, if present.
  368. Note that want lines have capabilities separated from the rest of the line
  369. by a space instead of a null byte. Thus want lines have the form:
  370. want obj-id cap1 cap2 ...
  371. Args:
  372. text: Want line to extract from
  373. Returns: Tuple with text with capabilities removed and list of capabilities
  374. """
  375. split_text = text.rstrip().split(b" ")
  376. if len(split_text) < 3:
  377. return text, []
  378. return (b" ".join(split_text[:2]), split_text[2:])
  379. def ack_type(capabilities):
  380. """Extract the ack type from a capabilities list."""
  381. if b"multi_ack_detailed" in capabilities:
  382. return MULTI_ACK_DETAILED
  383. elif b"multi_ack" in capabilities:
  384. return MULTI_ACK
  385. return SINGLE_ACK
  386. class BufferedPktLineWriter:
  387. """Writer that wraps its data in pkt-lines and has an independent buffer.
  388. Consecutive calls to write() wrap the data in a pkt-line and then buffers
  389. it until enough lines have been written such that their total length
  390. (including length prefix) reach the buffer size.
  391. """
  392. def __init__(self, write, bufsize=65515) -> None:
  393. """Initialize the BufferedPktLineWriter.
  394. Args:
  395. write: A write callback for the underlying writer.
  396. bufsize: The internal buffer size, including length prefixes.
  397. """
  398. self._write = write
  399. self._bufsize = bufsize
  400. self._wbuf = BytesIO()
  401. self._buflen = 0
  402. def write(self, data):
  403. """Write data, wrapping it in a pkt-line."""
  404. line = pkt_line(data)
  405. line_len = len(line)
  406. over = self._buflen + line_len - self._bufsize
  407. if over >= 0:
  408. start = line_len - over
  409. self._wbuf.write(line[:start])
  410. self.flush()
  411. else:
  412. start = 0
  413. saved = line[start:]
  414. self._wbuf.write(saved)
  415. self._buflen += len(saved)
  416. def flush(self):
  417. """Flush all data from the buffer."""
  418. data = self._wbuf.getvalue()
  419. if data:
  420. self._write(data)
  421. self._len = 0
  422. self._wbuf = BytesIO()
  423. class PktLineParser:
  424. """Packet line parser that hands completed packets off to a callback."""
  425. def __init__(self, handle_pkt) -> None:
  426. self.handle_pkt = handle_pkt
  427. self._readahead = BytesIO()
  428. def parse(self, data):
  429. """Parse a fragment of data and call back for any completed packets."""
  430. self._readahead.write(data)
  431. buf = self._readahead.getvalue()
  432. if len(buf) < 4:
  433. return
  434. while len(buf) >= 4:
  435. size = int(buf[:4], 16)
  436. if size == 0:
  437. self.handle_pkt(None)
  438. buf = buf[4:]
  439. elif size <= len(buf):
  440. self.handle_pkt(buf[4:size])
  441. buf = buf[size:]
  442. else:
  443. break
  444. self._readahead = BytesIO()
  445. self._readahead.write(buf)
  446. def get_tail(self):
  447. """Read back any unused data."""
  448. return self._readahead.getvalue()
  449. def format_capability_line(capabilities):
  450. return b"".join([b" " + c for c in capabilities])
  451. def format_ref_line(ref, sha, capabilities=None):
  452. if capabilities is None:
  453. return sha + b" " + ref + b"\n"
  454. else:
  455. return sha + b" " + ref + b"\0" + format_capability_line(capabilities) + b"\n"
  456. def format_shallow_line(sha):
  457. return COMMAND_SHALLOW + b" " + sha
  458. def format_unshallow_line(sha):
  459. return COMMAND_UNSHALLOW + b" " + sha
  460. def format_ack_line(sha, ack_type=b""):
  461. if ack_type:
  462. ack_type = b" " + ack_type
  463. return b"ACK " + sha + ack_type + b"\n"