protocol.py 19 KB

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