protocol.py 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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 published 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. __all__ = [
  24. "CAPABILITIES_REF",
  25. "CAPABILITY_AGENT",
  26. "CAPABILITY_ALLOW_REACHABLE_SHA1_IN_WANT",
  27. "CAPABILITY_ALLOW_TIP_SHA1_IN_WANT",
  28. "CAPABILITY_ATOMIC",
  29. "CAPABILITY_DEEPEN_NOT",
  30. "CAPABILITY_DEEPEN_RELATIVE",
  31. "CAPABILITY_DEEPEN_SINCE",
  32. "CAPABILITY_DELETE_REFS",
  33. "CAPABILITY_FETCH",
  34. "CAPABILITY_FILTER",
  35. "CAPABILITY_INCLUDE_TAG",
  36. "CAPABILITY_MULTI_ACK",
  37. "CAPABILITY_MULTI_ACK_DETAILED",
  38. "CAPABILITY_NO_DONE",
  39. "CAPABILITY_NO_PROGRESS",
  40. "CAPABILITY_OBJECT_FORMAT",
  41. "CAPABILITY_OFS_DELTA",
  42. "CAPABILITY_QUIET",
  43. "CAPABILITY_REPORT_STATUS",
  44. "CAPABILITY_SHALLOW",
  45. "CAPABILITY_SIDE_BAND",
  46. "CAPABILITY_SIDE_BAND_64K",
  47. "CAPABILITY_SYMREF",
  48. "CAPABILITY_THIN_PACK",
  49. "COMMAND_DEEPEN",
  50. "COMMAND_DEEPEN_NOT",
  51. "COMMAND_DEEPEN_SINCE",
  52. "COMMAND_DONE",
  53. "COMMAND_FILTER",
  54. "COMMAND_HAVE",
  55. "COMMAND_SHALLOW",
  56. "COMMAND_UNSHALLOW",
  57. "COMMAND_WANT",
  58. "COMMON_CAPABILITIES",
  59. "DEFAULT_GIT_PROTOCOL_VERSION_FETCH",
  60. "DEFAULT_GIT_PROTOCOL_VERSION_SEND",
  61. "DEPTH_INFINITE",
  62. "GIT_PROTOCOL_VERSIONS",
  63. "KNOWN_RECEIVE_CAPABILITIES",
  64. "KNOWN_UPLOAD_CAPABILITIES",
  65. "MULTI_ACK",
  66. "MULTI_ACK_DETAILED",
  67. "NAK_LINE",
  68. "PEELED_TAG_SUFFIX",
  69. "SIDE_BAND_CHANNEL_DATA",
  70. "SIDE_BAND_CHANNEL_FATAL",
  71. "SIDE_BAND_CHANNEL_PROGRESS",
  72. "SINGLE_ACK",
  73. "TCP_GIT_PORT",
  74. "BufferedPktLineWriter",
  75. "PktLineParser",
  76. "Protocol",
  77. "ReceivableProtocol",
  78. "ack_type",
  79. "agent_string",
  80. "capability_agent",
  81. "capability_object_format",
  82. "capability_symref",
  83. "extract_capabilities",
  84. "extract_capability_names",
  85. "extract_want_line_capabilities",
  86. "find_capability",
  87. "format_ack_line",
  88. "format_capability_line",
  89. "format_cmd_pkt",
  90. "format_ref_line",
  91. "format_shallow_line",
  92. "format_unshallow_line",
  93. "parse_capability",
  94. "parse_cmd_pkt",
  95. "pkt_line",
  96. "pkt_seq",
  97. "serialize_refs",
  98. "split_peeled_refs",
  99. "strip_peeled_refs",
  100. "symref_capabilities",
  101. "write_info_refs",
  102. ]
  103. import types
  104. from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
  105. from io import BytesIO
  106. from os import SEEK_END
  107. from typing import TYPE_CHECKING
  108. import dulwich
  109. from .errors import GitProtocolError, HangupException
  110. from .objects import ObjectID
  111. if TYPE_CHECKING:
  112. from .pack import ObjectContainer
  113. from .refs import Ref
  114. TCP_GIT_PORT = 9418
  115. # Git protocol version 0 is the original Git protocol, which lacked a
  116. # version number until Git protocol version 1 was introduced by Brandon
  117. # Williams in 2017.
  118. #
  119. # Protocol version 1 is simply the original v0 protocol with the addition of
  120. # a single packet line, which precedes the ref advertisement, indicating the
  121. # protocol version being used. This was done in preparation for protocol v2.
  122. #
  123. # Git protocol version 2 was first introduced by Brandon Williams in 2018 and
  124. # adds many features. See the gitprotocol-v2(5) manual page for details.
  125. # As of 2024, Git only implements version 2 during 'git fetch' and still uses
  126. # version 0 during 'git push'.
  127. GIT_PROTOCOL_VERSIONS = [0, 1, 2]
  128. DEFAULT_GIT_PROTOCOL_VERSION_FETCH = 2
  129. DEFAULT_GIT_PROTOCOL_VERSION_SEND = 0
  130. # Suffix used in the Git protocol to indicate peeled tag references
  131. PEELED_TAG_SUFFIX = b"^{}"
  132. ZERO_SHA: ObjectID = ObjectID(b"0" * 40)
  133. SINGLE_ACK = 0
  134. MULTI_ACK = 1
  135. MULTI_ACK_DETAILED = 2
  136. # pack data
  137. SIDE_BAND_CHANNEL_DATA = 1
  138. # progress messages
  139. SIDE_BAND_CHANNEL_PROGRESS = 2
  140. # fatal error message just before stream aborts
  141. SIDE_BAND_CHANNEL_FATAL = 3
  142. CAPABILITY_ATOMIC = b"atomic"
  143. CAPABILITY_DEEPEN_SINCE = b"deepen-since"
  144. CAPABILITY_DEEPEN_NOT = b"deepen-not"
  145. CAPABILITY_DEEPEN_RELATIVE = b"deepen-relative"
  146. CAPABILITY_DELETE_REFS = b"delete-refs"
  147. CAPABILITY_INCLUDE_TAG = b"include-tag"
  148. CAPABILITY_MULTI_ACK = b"multi_ack"
  149. CAPABILITY_MULTI_ACK_DETAILED = b"multi_ack_detailed"
  150. CAPABILITY_NO_DONE = b"no-done"
  151. CAPABILITY_NO_PROGRESS = b"no-progress"
  152. CAPABILITY_OFS_DELTA = b"ofs-delta"
  153. CAPABILITY_QUIET = b"quiet"
  154. CAPABILITY_REPORT_STATUS = b"report-status"
  155. CAPABILITY_SHALLOW = b"shallow"
  156. CAPABILITY_SIDE_BAND = b"side-band"
  157. CAPABILITY_SIDE_BAND_64K = b"side-band-64k"
  158. CAPABILITY_THIN_PACK = b"thin-pack"
  159. CAPABILITY_AGENT = b"agent"
  160. CAPABILITY_SYMREF = b"symref"
  161. CAPABILITY_ALLOW_TIP_SHA1_IN_WANT = b"allow-tip-sha1-in-want"
  162. CAPABILITY_ALLOW_REACHABLE_SHA1_IN_WANT = b"allow-reachable-sha1-in-want"
  163. CAPABILITY_FETCH = b"fetch"
  164. CAPABILITY_FILTER = b"filter"
  165. CAPABILITY_OBJECT_FORMAT = b"object-format"
  166. # Magic ref that is used to attach capabilities to when
  167. # there are no refs. Should always be ste to ZERO_SHA.
  168. CAPABILITIES_REF = b"capabilities^{}"
  169. COMMON_CAPABILITIES = [
  170. CAPABILITY_OFS_DELTA,
  171. CAPABILITY_SIDE_BAND,
  172. CAPABILITY_SIDE_BAND_64K,
  173. CAPABILITY_AGENT,
  174. CAPABILITY_NO_PROGRESS,
  175. ]
  176. KNOWN_UPLOAD_CAPABILITIES = set(
  177. [
  178. *COMMON_CAPABILITIES,
  179. CAPABILITY_THIN_PACK,
  180. CAPABILITY_MULTI_ACK,
  181. CAPABILITY_MULTI_ACK_DETAILED,
  182. CAPABILITY_INCLUDE_TAG,
  183. CAPABILITY_DEEPEN_SINCE,
  184. CAPABILITY_SYMREF,
  185. CAPABILITY_SHALLOW,
  186. CAPABILITY_DEEPEN_NOT,
  187. CAPABILITY_DEEPEN_RELATIVE,
  188. CAPABILITY_ALLOW_TIP_SHA1_IN_WANT,
  189. CAPABILITY_ALLOW_REACHABLE_SHA1_IN_WANT,
  190. CAPABILITY_FETCH,
  191. CAPABILITY_FILTER,
  192. ]
  193. )
  194. KNOWN_RECEIVE_CAPABILITIES = set(
  195. [
  196. *COMMON_CAPABILITIES,
  197. CAPABILITY_REPORT_STATUS,
  198. CAPABILITY_DELETE_REFS,
  199. CAPABILITY_QUIET,
  200. CAPABILITY_ATOMIC,
  201. ]
  202. )
  203. DEPTH_INFINITE = 0x7FFFFFFF
  204. NAK_LINE = b"NAK\n"
  205. def agent_string() -> bytes:
  206. """Generate the agent string for dulwich.
  207. Returns:
  208. Agent string as bytes
  209. """
  210. return ("dulwich/" + ".".join(map(str, dulwich.__version__))).encode("ascii")
  211. def capability_agent() -> bytes:
  212. """Generate the agent capability string.
  213. Returns:
  214. Agent capability with dulwich version
  215. """
  216. return CAPABILITY_AGENT + b"=" + agent_string()
  217. def capability_object_format(fmt: str) -> bytes:
  218. """Generate the object-format capability string.
  219. Args:
  220. fmt: Object format name (e.g., "sha1" or "sha256")
  221. Returns:
  222. Object-format capability with format name
  223. """
  224. return CAPABILITY_OBJECT_FORMAT + b"=" + fmt.encode("ascii")
  225. def capability_symref(from_ref: bytes, to_ref: bytes) -> bytes:
  226. """Generate a symref capability string.
  227. Args:
  228. from_ref: Source reference name
  229. to_ref: Target reference name
  230. Returns:
  231. Symref capability string
  232. """
  233. return CAPABILITY_SYMREF + b"=" + from_ref + b":" + to_ref
  234. def extract_capability_names(capabilities: Iterable[bytes]) -> set[bytes]:
  235. """Extract capability names from a list of capabilities.
  236. Args:
  237. capabilities: List of capability strings
  238. Returns:
  239. Set of capability names
  240. """
  241. return {parse_capability(c)[0] for c in capabilities}
  242. def parse_capability(capability: bytes) -> tuple[bytes, bytes | None]:
  243. """Parse a capability string into name and value.
  244. Args:
  245. capability: Capability string
  246. Returns:
  247. Tuple of (capability_name, capability_value)
  248. """
  249. parts = capability.split(b"=", 1)
  250. if len(parts) == 1:
  251. return (parts[0], None)
  252. return (parts[0], parts[1])
  253. def symref_capabilities(symrefs: Iterable[tuple[bytes, bytes]]) -> list[bytes]:
  254. """Generate symref capability strings from symref pairs.
  255. Args:
  256. symrefs: Iterable of (from_ref, to_ref) tuples
  257. Returns:
  258. List of symref capability strings
  259. """
  260. return [capability_symref(*k) for k in symrefs]
  261. COMMAND_DEEPEN = b"deepen"
  262. COMMAND_DEEPEN_SINCE = b"deepen-since"
  263. COMMAND_DEEPEN_NOT = b"deepen-not"
  264. COMMAND_SHALLOW = b"shallow"
  265. COMMAND_UNSHALLOW = b"unshallow"
  266. COMMAND_DONE = b"done"
  267. COMMAND_WANT = b"want"
  268. COMMAND_HAVE = b"have"
  269. COMMAND_FILTER = b"filter"
  270. def format_cmd_pkt(cmd: bytes, *args: bytes) -> bytes:
  271. """Format a command packet.
  272. Args:
  273. cmd: Command name
  274. *args: Command arguments
  275. Returns:
  276. Formatted command packet
  277. """
  278. return cmd + b" " + b"".join([(a + b"\0") for a in args])
  279. def parse_cmd_pkt(line: bytes) -> tuple[bytes, list[bytes]]:
  280. """Parse a command packet.
  281. Args:
  282. line: Command line to parse
  283. Returns:
  284. Tuple of (command, [arguments])
  285. """
  286. splice_at = line.find(b" ")
  287. cmd, args = line[:splice_at], line[splice_at + 1 :]
  288. assert args[-1:] == b"\x00"
  289. return cmd, args[:-1].split(b"\0")
  290. def pkt_line(data: bytes | None) -> bytes:
  291. """Wrap data in a pkt-line.
  292. Args:
  293. data: The data to wrap, as a str or None.
  294. Returns: The data prefixed with its length in pkt-line format; if data was
  295. None, returns the flush-pkt ('0000').
  296. """
  297. if data is None:
  298. return b"0000"
  299. return f"{len(data) + 4:04x}".encode("ascii") + data
  300. def pkt_seq(*seq: bytes | None) -> bytes:
  301. """Wrap a sequence of data in pkt-lines.
  302. Args:
  303. seq: An iterable of strings to wrap.
  304. """
  305. return b"".join([pkt_line(s) for s in seq]) + pkt_line(None)
  306. class Protocol:
  307. """Class for interacting with a remote git process over the wire.
  308. Parts of the git wire protocol use 'pkt-lines' to communicate. A pkt-line
  309. consists of the length of the line as a 4-byte hex string, followed by the
  310. payload data. The length includes the 4-byte header. The special line
  311. '0000' indicates the end of a section of input and is called a 'flush-pkt'.
  312. For details on the pkt-line format, see the cgit distribution:
  313. Documentation/technical/protocol-common.txt
  314. """
  315. def __init__(
  316. self,
  317. read: Callable[[int], bytes],
  318. write: Callable[[bytes], int | None],
  319. close: Callable[[], None] | None = None,
  320. report_activity: Callable[[int, str], None] | None = None,
  321. ) -> None:
  322. """Initialize Protocol.
  323. Args:
  324. read: Function to read bytes from the transport
  325. write: Function to write bytes to the transport
  326. close: Optional function to close the transport
  327. report_activity: Optional function to report activity
  328. """
  329. self.read = read
  330. self.write = write
  331. self._close = close
  332. self.report_activity = report_activity
  333. self._readahead: BytesIO | None = None
  334. def close(self) -> None:
  335. """Close the underlying transport if a close function was provided."""
  336. if self._close:
  337. self._close()
  338. def __enter__(self) -> "Protocol":
  339. """Enter context manager."""
  340. return self
  341. def __exit__(
  342. self,
  343. exc_type: type[BaseException] | None,
  344. exc_val: BaseException | None,
  345. exc_tb: types.TracebackType | None,
  346. ) -> None:
  347. """Exit context manager and close transport."""
  348. self.close()
  349. def read_pkt_line(self) -> bytes | None:
  350. """Reads a pkt-line from the remote git process.
  351. This method may read from the readahead buffer; see unread_pkt_line.
  352. Returns: The next string from the stream, without the length prefix, or
  353. None for a flush-pkt ('0000') or delim-pkt ('0001').
  354. """
  355. if self._readahead is None:
  356. read = self.read
  357. else:
  358. read = self._readahead.read
  359. self._readahead = None
  360. try:
  361. sizestr = read(4)
  362. if not sizestr:
  363. raise HangupException
  364. size = int(sizestr, 16)
  365. if size == 0 or size == 1: # flush-pkt or delim-pkt
  366. if self.report_activity:
  367. self.report_activity(4, "read")
  368. return None
  369. if self.report_activity:
  370. self.report_activity(size, "read")
  371. pkt_contents = read(size - 4)
  372. except ConnectionResetError as exc:
  373. raise HangupException from exc
  374. except OSError as exc:
  375. raise GitProtocolError(str(exc)) from exc
  376. else:
  377. if len(pkt_contents) + 4 != size:
  378. raise GitProtocolError(
  379. f"Length of pkt read {len(pkt_contents) + 4:04x} does not match length prefix {size:04x}"
  380. )
  381. return pkt_contents
  382. def eof(self) -> bool:
  383. """Test whether the protocol stream has reached EOF.
  384. Note that this refers to the actual stream EOF and not just a
  385. flush-pkt.
  386. Returns: True if the stream is at EOF, False otherwise.
  387. """
  388. try:
  389. next_line = self.read_pkt_line()
  390. except HangupException:
  391. return True
  392. self.unread_pkt_line(next_line)
  393. return False
  394. def unread_pkt_line(self, data: bytes | None) -> None:
  395. """Unread a single line of data into the readahead buffer.
  396. This method can be used to unread a single pkt-line into a fixed
  397. readahead buffer.
  398. Args:
  399. data: The data to unread, without the length prefix.
  400. Raises:
  401. ValueError: If more than one pkt-line is unread.
  402. """
  403. if self._readahead is not None:
  404. raise ValueError("Attempted to unread multiple pkt-lines.")
  405. self._readahead = BytesIO(pkt_line(data))
  406. def read_pkt_seq(self) -> Iterable[bytes]:
  407. """Read a sequence of pkt-lines from the remote git process.
  408. Returns: Yields each line of data up to but not including the next
  409. flush-pkt.
  410. """
  411. pkt = self.read_pkt_line()
  412. while pkt:
  413. yield pkt
  414. pkt = self.read_pkt_line()
  415. def write_pkt_line(self, line: bytes | None) -> None:
  416. """Sends a pkt-line to the remote git process.
  417. Args:
  418. line: A string containing the data to send, without the length
  419. prefix.
  420. """
  421. try:
  422. line = pkt_line(line)
  423. self.write(line)
  424. if self.report_activity:
  425. self.report_activity(len(line), "write")
  426. except OSError as exc:
  427. raise GitProtocolError(str(exc)) from exc
  428. def write_sideband(self, channel: int, blob: bytes) -> None:
  429. """Write multiplexed data to the sideband.
  430. Args:
  431. channel: An int specifying the channel to write to.
  432. blob: A blob of data (as a string) to send on this channel.
  433. """
  434. # a pktline can be a max of 65520. a sideband line can therefore be
  435. # 65520-5 = 65515
  436. # WTF: Why have the len in ASCII, but the channel in binary.
  437. while blob:
  438. self.write_pkt_line(bytes(bytearray([channel])) + blob[:65515])
  439. blob = blob[65515:]
  440. def send_cmd(self, cmd: bytes, *args: bytes) -> None:
  441. """Send a command and some arguments to a git server.
  442. Only used for the TCP git protocol (git://).
  443. Args:
  444. cmd: The remote service to access.
  445. args: List of arguments to send to remove service.
  446. """
  447. self.write_pkt_line(format_cmd_pkt(cmd, *args))
  448. def read_cmd(self) -> tuple[bytes, list[bytes]]:
  449. """Read a command and some arguments from the git client.
  450. Only used for the TCP git protocol (git://).
  451. Returns: A tuple of (command, [list of arguments]).
  452. """
  453. line = self.read_pkt_line()
  454. if line is None:
  455. raise GitProtocolError("Expected command, got flush packet")
  456. return parse_cmd_pkt(line)
  457. _RBUFSIZE = 65536 # 64KB buffer for better network I/O performance
  458. class ReceivableProtocol(Protocol):
  459. """Variant of Protocol that allows reading up to a size without blocking.
  460. This class has a recv() method that behaves like socket.recv() in addition
  461. to a read() method.
  462. If you want to read n bytes from the wire and block until exactly n bytes
  463. (or EOF) are read, use read(n). If you want to read at most n bytes from
  464. the wire but don't care if you get less, use recv(n). Note that recv(n)
  465. will still block until at least one byte is read.
  466. """
  467. def __init__(
  468. self,
  469. recv: Callable[[int], bytes],
  470. write: Callable[[bytes], int | None],
  471. close: Callable[[], None] | None = None,
  472. report_activity: Callable[[int, str], None] | None = None,
  473. rbufsize: int = _RBUFSIZE,
  474. ) -> None:
  475. """Initialize ReceivableProtocol.
  476. Args:
  477. recv: Function to receive bytes from the transport
  478. write: Function to write bytes to the transport
  479. close: Optional function to close the transport
  480. report_activity: Optional function to report activity
  481. rbufsize: Read buffer size
  482. """
  483. super().__init__(self.read, write, close=close, report_activity=report_activity)
  484. self._recv = recv
  485. self._rbuf = BytesIO()
  486. self._rbufsize = rbufsize
  487. def read(self, size: int) -> bytes:
  488. """Read bytes from the socket.
  489. Args:
  490. size: Number of bytes to read
  491. Returns:
  492. Bytes read from socket
  493. """
  494. # From _fileobj.read in socket.py in the Python 2.6.5 standard library,
  495. # with the following modifications:
  496. # - omit the size <= 0 branch
  497. # - seek back to start rather than 0 in case some buffer has been
  498. # consumed.
  499. # - use SEEK_END instead of the magic number.
  500. # Copyright (c) 2001-2010 Python Software Foundation; All Rights
  501. # Reserved
  502. # Licensed under the Python Software Foundation License.
  503. # TODO: see if buffer is more efficient than cBytesIO.
  504. assert size > 0
  505. # Our use of BytesIO rather than lists of string objects returned by
  506. # recv() minimizes memory usage and fragmentation that occurs when
  507. # rbufsize is large compared to the typical return value of recv().
  508. buf = self._rbuf
  509. start = buf.tell()
  510. buf.seek(0, SEEK_END)
  511. # buffer may have been partially consumed by recv()
  512. buf_len = buf.tell() - start
  513. if buf_len >= size:
  514. # Already have size bytes in our buffer? Extract and return.
  515. buf.seek(start)
  516. rv = buf.read(size)
  517. self._rbuf = BytesIO()
  518. self._rbuf.write(buf.read())
  519. self._rbuf.seek(0)
  520. return rv
  521. self._rbuf = BytesIO() # reset _rbuf. we consume it via buf.
  522. while True:
  523. left = size - buf_len
  524. # recv() will malloc the amount of memory given as its
  525. # parameter even though it often returns much less data
  526. # than that. The returned data string is short lived
  527. # as we copy it into a BytesIO and free it. This avoids
  528. # fragmentation issues on many platforms.
  529. data = self._recv(left)
  530. if not data:
  531. break
  532. n = len(data)
  533. if n == size and not buf_len:
  534. # Shortcut. Avoid buffer data copies when:
  535. # - We have no data in our buffer.
  536. # AND
  537. # - Our call to recv returned exactly the
  538. # number of bytes we were asked to read.
  539. return data
  540. if n == left:
  541. buf.write(data)
  542. del data # explicit free
  543. break
  544. assert n <= left, f"_recv({left}) returned {n} bytes"
  545. buf.write(data)
  546. buf_len += n
  547. del data # explicit free
  548. # assert buf_len == buf.tell()
  549. buf.seek(start)
  550. return buf.read()
  551. def recv(self, size: int) -> bytes:
  552. """Receive bytes from the socket with buffering.
  553. Args:
  554. size: Maximum number of bytes to receive
  555. Returns:
  556. Bytes received from socket
  557. """
  558. assert size > 0
  559. buf = self._rbuf
  560. start = buf.tell()
  561. buf.seek(0, SEEK_END)
  562. buf_len = buf.tell()
  563. buf.seek(start)
  564. left = buf_len - start
  565. if not left:
  566. # only read from the wire if our read buffer is exhausted
  567. data = self._recv(self._rbufsize)
  568. if len(data) == size:
  569. # shortcut: skip the buffer if we read exactly size bytes
  570. return data
  571. buf = BytesIO()
  572. buf.write(data)
  573. buf.seek(0)
  574. del data # explicit free
  575. self._rbuf = buf
  576. return buf.read(size)
  577. def extract_capabilities(text: bytes) -> tuple[bytes, list[bytes]]:
  578. """Extract a capabilities list from a string, if present.
  579. Args:
  580. text: String to extract from
  581. Returns: Tuple with text with capabilities removed and list of capabilities
  582. """
  583. if b"\0" not in text:
  584. return text, []
  585. text, capabilities = text.rstrip().split(b"\0")
  586. return (text, capabilities.strip().split(b" "))
  587. def extract_want_line_capabilities(text: bytes) -> tuple[bytes, list[bytes]]:
  588. """Extract a capabilities list from a want line, if present.
  589. Note that want lines have capabilities separated from the rest of the line
  590. by a space instead of a null byte. Thus want lines have the form:
  591. want obj-id cap1 cap2 ...
  592. Args:
  593. text: Want line to extract from
  594. Returns: Tuple with text with capabilities removed and list of capabilities
  595. """
  596. split_text = text.rstrip().split(b" ")
  597. if len(split_text) < 3:
  598. return text, []
  599. return (b" ".join(split_text[:2]), split_text[2:])
  600. def ack_type(capabilities: Iterable[bytes]) -> int:
  601. """Extract the ack type from a capabilities list."""
  602. if b"multi_ack_detailed" in capabilities:
  603. return MULTI_ACK_DETAILED
  604. elif b"multi_ack" in capabilities:
  605. return MULTI_ACK
  606. return SINGLE_ACK
  607. def find_capability(
  608. capabilities: Iterable[bytes], *capability_names: bytes
  609. ) -> bytes | None:
  610. """Find a capability value in a list of capabilities.
  611. This function looks for capabilities that may include arguments after an equals sign
  612. and returns only the value part (after the '='). For capabilities without values,
  613. returns the capability name itself.
  614. Args:
  615. capabilities: List of capability strings
  616. capability_names: Capability name(s) to search for
  617. Returns:
  618. The value after '=' if found, or the capability name if no '=', or None if not found
  619. Example:
  620. >>> caps = [b'filter=blob:none', b'agent=git/2.0', b'thin-pack']
  621. >>> find_capability(caps, b'filter')
  622. b'blob:none'
  623. >>> find_capability(caps, b'thin-pack')
  624. b'thin-pack'
  625. >>> find_capability(caps, b'missing')
  626. None
  627. """
  628. for cap in capabilities:
  629. for name in capability_names:
  630. if cap == name:
  631. return cap
  632. elif cap.startswith(name + b"="):
  633. return cap[len(name) + 1 :]
  634. return None
  635. class BufferedPktLineWriter:
  636. """Writer that wraps its data in pkt-lines and has an independent buffer.
  637. Consecutive calls to write() wrap the data in a pkt-line and then buffers
  638. it until enough lines have been written such that their total length
  639. (including length prefix) reach the buffer size.
  640. """
  641. def __init__(
  642. self, write: Callable[[bytes], int | None], bufsize: int = 65515
  643. ) -> None:
  644. """Initialize the BufferedPktLineWriter.
  645. Args:
  646. write: A write callback for the underlying writer.
  647. bufsize: The internal buffer size, including length prefixes.
  648. """
  649. self._write = write
  650. self._bufsize = bufsize
  651. self._wbuf = BytesIO()
  652. self._buflen = 0
  653. def write(self, data: bytes) -> None:
  654. """Write data, wrapping it in a pkt-line."""
  655. line = pkt_line(data)
  656. line_len = len(line)
  657. over = self._buflen + line_len - self._bufsize
  658. if over >= 0:
  659. start = line_len - over
  660. self._wbuf.write(line[:start])
  661. self.flush()
  662. else:
  663. start = 0
  664. saved = line[start:]
  665. self._wbuf.write(saved)
  666. self._buflen += len(saved)
  667. def flush(self) -> None:
  668. """Flush all data from the buffer."""
  669. data = self._wbuf.getvalue()
  670. if data:
  671. self._write(data)
  672. self._len = 0
  673. self._wbuf = BytesIO()
  674. class PktLineParser:
  675. """Packet line parser that hands completed packets off to a callback."""
  676. def __init__(self, handle_pkt: Callable[[bytes | None], None]) -> None:
  677. """Initialize PktLineParser.
  678. Args:
  679. handle_pkt: Callback function to handle completed packets
  680. """
  681. self.handle_pkt = handle_pkt
  682. self._readahead = BytesIO()
  683. def parse(self, data: bytes) -> None:
  684. """Parse a fragment of data and call back for any completed packets."""
  685. self._readahead.write(data)
  686. buf = self._readahead.getvalue()
  687. if len(buf) < 4:
  688. return
  689. while len(buf) >= 4:
  690. size = int(buf[:4], 16)
  691. if size == 0:
  692. self.handle_pkt(None)
  693. buf = buf[4:]
  694. elif size <= len(buf):
  695. self.handle_pkt(buf[4:size])
  696. buf = buf[size:]
  697. else:
  698. break
  699. self._readahead = BytesIO()
  700. self._readahead.write(buf)
  701. def get_tail(self) -> bytes:
  702. """Read back any unused data."""
  703. return self._readahead.getvalue()
  704. def format_capability_line(capabilities: Iterable[bytes]) -> bytes:
  705. """Format a capabilities list for the wire protocol.
  706. Args:
  707. capabilities: List of capability strings
  708. Returns:
  709. Space-separated capabilities as bytes
  710. """
  711. return b"".join([b" " + c for c in capabilities])
  712. def format_ref_line(
  713. ref: bytes, sha: bytes, capabilities: Sequence[bytes] | None = None
  714. ) -> bytes:
  715. """Format a ref advertisement line.
  716. Args:
  717. ref: Reference name
  718. sha: SHA hash
  719. capabilities: Optional list of capabilities
  720. Returns:
  721. Formatted ref line
  722. """
  723. if capabilities is None:
  724. return sha + b" " + ref + b"\n"
  725. else:
  726. return sha + b" " + ref + b"\0" + format_capability_line(capabilities) + b"\n"
  727. def format_shallow_line(sha: bytes) -> bytes:
  728. """Format a shallow line.
  729. Args:
  730. sha: SHA to mark as shallow
  731. Returns:
  732. Formatted shallow line
  733. """
  734. return COMMAND_SHALLOW + b" " + sha
  735. def format_unshallow_line(sha: bytes) -> bytes:
  736. """Format an unshallow line.
  737. Args:
  738. sha: SHA to unshallow
  739. Returns:
  740. Formatted unshallow line
  741. """
  742. return COMMAND_UNSHALLOW + b" " + sha
  743. def format_ack_line(sha: bytes, ack_type: bytes = b"") -> bytes:
  744. """Format an ACK line.
  745. Args:
  746. sha: SHA to acknowledge
  747. ack_type: Optional ACK type (e.g. b"continue")
  748. Returns:
  749. Formatted ACK line
  750. """
  751. if ack_type:
  752. ack_type = b" " + ack_type
  753. return b"ACK " + sha + ack_type + b"\n"
  754. def strip_peeled_refs(
  755. refs: "Mapping[Ref, ObjectID | None]",
  756. ) -> "dict[Ref, ObjectID | None]":
  757. """Remove all peeled refs from a refs dictionary.
  758. Args:
  759. refs: Dictionary of refs (may include peeled refs with ^{} suffix)
  760. Returns:
  761. Dictionary with peeled refs removed
  762. """
  763. return {
  764. ref: sha for (ref, sha) in refs.items() if not ref.endswith(PEELED_TAG_SUFFIX)
  765. }
  766. def split_peeled_refs(
  767. refs: "Mapping[Ref, ObjectID]",
  768. ) -> "tuple[dict[Ref, ObjectID], dict[Ref, ObjectID]]":
  769. """Split peeled refs from regular refs.
  770. Args:
  771. refs: Dictionary of refs (may include peeled refs with ^{} suffix)
  772. Returns:
  773. Tuple of (regular_refs, peeled_refs) where peeled_refs keys have
  774. the ^{} suffix removed
  775. """
  776. from .refs import Ref
  777. peeled: dict[Ref, ObjectID] = {}
  778. regular = {k: v for k, v in refs.items() if not k.endswith(PEELED_TAG_SUFFIX)}
  779. for ref, sha in refs.items():
  780. if ref.endswith(PEELED_TAG_SUFFIX):
  781. # Peeled refs are always ObjectID values
  782. peeled[Ref(ref[: -len(PEELED_TAG_SUFFIX)])] = sha
  783. return regular, peeled
  784. def write_info_refs(
  785. refs: "Mapping[Ref, ObjectID]", store: "ObjectContainer"
  786. ) -> "Iterator[bytes]":
  787. """Generate info refs in the format used by the dumb HTTP protocol.
  788. Args:
  789. refs: Dictionary of refs
  790. store: Object store to peel tags from
  791. Yields:
  792. Lines in info/refs format (sha + tab + refname)
  793. """
  794. from .object_store import peel_sha
  795. from .refs import HEADREF
  796. for name, sha in sorted(refs.items()):
  797. # get_refs() includes HEAD as a special case, but we don't want to
  798. # advertise it
  799. if name == HEADREF:
  800. continue
  801. try:
  802. o = store[sha]
  803. except KeyError:
  804. continue
  805. _unpeeled, peeled = peel_sha(store, sha)
  806. yield o.id + b"\t" + name + b"\n"
  807. if o.id != peeled.id:
  808. yield peeled.id + b"\t" + name + PEELED_TAG_SUFFIX + b"\n"
  809. def serialize_refs(
  810. store: "ObjectContainer", refs: "Mapping[Ref, ObjectID]"
  811. ) -> "dict[bytes, ObjectID]":
  812. """Serialize refs with peeled refs for Git protocol v0/v1.
  813. This function is used to prepare refs for transmission over the Git protocol.
  814. For tags, it includes both the tag object and the dereferenced object.
  815. Args:
  816. store: Object store to peel refs from
  817. refs: Dictionary of ref names to SHAs
  818. Returns:
  819. Dictionary with refs and peeled refs (marked with ^{})
  820. """
  821. import warnings
  822. from .object_store import peel_sha
  823. from .objects import Tag
  824. ret: dict[bytes, ObjectID] = {}
  825. for ref, sha in refs.items():
  826. try:
  827. unpeeled, peeled = peel_sha(store, ObjectID(sha))
  828. except KeyError:
  829. warnings.warn(
  830. "ref {} points at non-present sha {}".format(
  831. ref.decode("utf-8", "replace"), sha.decode("ascii")
  832. ),
  833. UserWarning,
  834. )
  835. continue
  836. else:
  837. if isinstance(unpeeled, Tag):
  838. ret[ref + PEELED_TAG_SUFFIX] = peeled.id
  839. ret[ref] = unpeeled.id
  840. return ret