protocol.py 19 KB

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