2
0

protocol.py 19 KB

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