path
stringlengths 9
117
| type
stringclasses 2
values | project
stringclasses 10
values | commit_hash
stringlengths 40
40
| commit_message
stringlengths 1
137
| ground_truth
stringlengths 0
2.74k
| main_code
stringlengths 102
3.37k
| context
stringlengths 0
14.7k
|
---|---|---|---|---|---|---|---|
aioquic.recovery/QuicPacketRecovery.on_packet_sent
|
Modified
|
aiortc~aioquic
|
868a068dbe45379208046385655805fabef546e0
|
[connection] enforce local idle timeout
|
<0>:<del> packet.sent_time = self._get_time()
|
# module: aioquic.recovery
class QuicPacketRecovery:
def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:
<0> packet.sent_time = self._get_time()
<1> space.sent_packets[packet.packet_number] = packet
<2>
<3> if packet.is_ack_eliciting:
<4> space.ack_eliciting_in_flight += 1
<5> if packet.is_crypto_packet:
<6> space.crypto_packet_in_flight += 1
<7> if packet.in_flight:
<8> if packet.is_crypto_packet:
<9> self._time_of_last_sent_crypto_packet = packet.sent_time
<10> if packet.is_ack_eliciting:
<11> self._time_of_last_sent_ack_eliciting_packet = packet.sent_time
<12>
<13> # add packet to bytes in flight
<14> self.bytes_in_flight += packet.sent_bytes
<15>
|
===========unchanged ref 0===========
at: aioquic.packet_builder.QuicSentPacket
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
sent_time: Optional[float] = None
sent_bytes: int = 0
at: aioquic.recovery.QuicPacketRecovery.__init__
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
self.bytes_in_flight = 0
at: aioquic.recovery.QuicPacketRecovery.on_loss_detection_timeout
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packet_acked
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packet_expired
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packets_lost
self.bytes_in_flight -= lost_bytes
at: aioquic.recovery.QuicPacketSpace.__init__
self.ack_eliciting_in_flight = 0
self.crypto_packet_in_flight = 0
===========changed ref 0===========
# module: aioquic.recovery
class QuicPacketRecovery:
+ def on_loss_detection_timeout(self, now: float) -> None:
- def on_loss_detection_timeout(self) -> None:
self._logger.info("Loss detection timeout triggered")
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
+ self.detect_loss(loss_space, now=now)
- self.detect_loss(loss_space)
elif sum(space.crypto_packet_in_flight for space in self.spaces):
# reschedule crypto packets
for space in self.spaces:
for packet_number, packet in list(
filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())
):
# remove packet and update counters
del space.sent_packets[packet_number]
space.ack_eliciting_in_flight -= 1
space.crypto_packet_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
self._crypto_count += 1
else:
self._pto_count += 1
self._send_probe()
===========changed ref 1===========
# module: aioquic.recovery
class QuicPacketRecovery:
def __init__(
- self,
- logger: logging.LoggerAdapter,
- get_time: Callable[[], float],
- send_probe: Callable[[], None],
+ self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._get_time = get_time
self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
===========changed ref 2===========
# module: aioquic.recovery
class QuicPacketRecovery:
+ def detect_loss(self, space: QuicPacketSpace, now: float) -> None:
- def detect_loss(self, space: QuicPacketSpace) -> None:
"""
Check whether any packets should be declared lost.
"""
loss_delay = K_TIME_THRESHOLD * (
max(self._rtt_latest, self._rtt_smoothed)
if self._rtt_initialized
else K_INITIAL_RTT
)
packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD
+ time_threshold = now - loss_delay
- time_threshold = self._get_time() - loss_delay
lost_bytes = 0
lost_largest_time = None
space.loss_time = None
for packet_number, packet in list(space.sent_packets.items()):
if packet_number > space.largest_acked_packet:
break
if packet_number <= packet_threshold or packet.sent_time <= time_threshold:
# remove packet and update counters
del space.sent_packets[packet_number]
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight -= 1
if packet.is_crypto_packet:
space.crypto_packet_in_flight -= 1
if packet.in_flight:
lost_bytes += packet.sent_bytes
lost_largest_time = packet.sent_time
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
else:
packet_loss_time = packet.sent_time + loss_delay
if space.loss_time is None or space.loss_time > packet_loss_time:
space.loss_time = packet_loss_time
if lost_bytes:
+ self.on_packets_lost(lost_bytes, lost_largest_time, now=now)
- self.on</s>
===========changed ref 3===========
# module: aioquic.recovery
class QuicPacketRecovery:
+ def detect_loss(self, space: QuicPacketSpace, now: float) -> None:
- def detect_loss(self, space: QuicPacketSpace) -> None:
# offset: 1
<s>.on_packets_lost(lost_bytes, lost_largest_time, now=now)
- self.on_packets_lost(lost_bytes, lost_largest_time)
|
aioquic.recovery/QuicPacketRecovery.on_packets_lost
|
Modified
|
aiortc~aioquic
|
868a068dbe45379208046385655805fabef546e0
|
[connection] enforce local idle timeout
|
<6>:<add> self._congestion_recovery_start_time = now
<del> self._congestion_recovery_start_time = self._get_time()
|
# module: aioquic.recovery
class QuicPacketRecovery:
+ def on_packets_lost(
+ self, lost_bytes: int, lost_largest_time: float, now: float
+ ) -> None:
- def on_packets_lost(self, lost_bytes: int, lost_largest_time: float) -> None:
<0> # remove lost packets from bytes in flight
<1> self.bytes_in_flight -= lost_bytes
<2>
<3> # start a new congestion event if packet was sent after the
<4> # start of the previous congestion recovery period.
<5> if lost_largest_time > self._congestion_recovery_start_time:
<6> self._congestion_recovery_start_time = self._get_time()
<7> self.congestion_window = max(
<8> int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW
<9> )
<10> self._ssthresh = self.congestion_window
<11>
|
===========unchanged ref 0===========
at: aioquic.recovery
K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE
K_LOSS_REDUCTION_FACTOR = 0.5
at: aioquic.recovery.QuicPacketRecovery.__init__
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
at: aioquic.recovery.QuicPacketRecovery.on_loss_detection_timeout
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packet_acked
self.bytes_in_flight -= packet.sent_bytes
self.congestion_window += (
K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window
)
self.congestion_window += packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packet_expired
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packet_sent
self.bytes_in_flight += packet.sent_bytes
===========changed ref 0===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:
- packet.sent_time = self._get_time()
space.sent_packets[packet.packet_number] = packet
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight += 1
if packet.is_crypto_packet:
space.crypto_packet_in_flight += 1
if packet.in_flight:
if packet.is_crypto_packet:
self._time_of_last_sent_crypto_packet = packet.sent_time
if packet.is_ack_eliciting:
self._time_of_last_sent_ack_eliciting_packet = packet.sent_time
# add packet to bytes in flight
self.bytes_in_flight += packet.sent_bytes
===========changed ref 1===========
# module: aioquic.recovery
class QuicPacketRecovery:
+ def on_loss_detection_timeout(self, now: float) -> None:
- def on_loss_detection_timeout(self) -> None:
self._logger.info("Loss detection timeout triggered")
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
+ self.detect_loss(loss_space, now=now)
- self.detect_loss(loss_space)
elif sum(space.crypto_packet_in_flight for space in self.spaces):
# reschedule crypto packets
for space in self.spaces:
for packet_number, packet in list(
filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())
):
# remove packet and update counters
del space.sent_packets[packet_number]
space.ack_eliciting_in_flight -= 1
space.crypto_packet_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
self._crypto_count += 1
else:
self._pto_count += 1
self._send_probe()
===========changed ref 2===========
# module: aioquic.recovery
class QuicPacketRecovery:
def __init__(
- self,
- logger: logging.LoggerAdapter,
- get_time: Callable[[], float],
- send_probe: Callable[[], None],
+ self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._get_time = get_time
self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
===========changed ref 3===========
# module: aioquic.recovery
class QuicPacketRecovery:
+ def detect_loss(self, space: QuicPacketSpace, now: float) -> None:
- def detect_loss(self, space: QuicPacketSpace) -> None:
"""
Check whether any packets should be declared lost.
"""
loss_delay = K_TIME_THRESHOLD * (
max(self._rtt_latest, self._rtt_smoothed)
if self._rtt_initialized
else K_INITIAL_RTT
)
packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD
+ time_threshold = now - loss_delay
- time_threshold = self._get_time() - loss_delay
lost_bytes = 0
lost_largest_time = None
space.loss_time = None
for packet_number, packet in list(space.sent_packets.items()):
if packet_number > space.largest_acked_packet:
break
if packet_number <= packet_threshold or packet.sent_time <= time_threshold:
# remove packet and update counters
del space.sent_packets[packet_number]
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight -= 1
if packet.is_crypto_packet:
space.crypto_packet_in_flight -= 1
if packet.in_flight:
lost_bytes += packet.sent_bytes
lost_largest_time = packet.sent_time
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
else:
packet_loss_time = packet.sent_time + loss_delay
if space.loss_time is None or space.loss_time > packet_loss_time:
space.loss_time = packet_loss_time
if lost_bytes:
+ self.on_packets_lost(lost_bytes, lost_largest_time, now=now)
- self.on</s>
===========changed ref 4===========
# module: aioquic.recovery
class QuicPacketRecovery:
+ def detect_loss(self, space: QuicPacketSpace, now: float) -> None:
- def detect_loss(self, space: QuicPacketSpace) -> None:
# offset: 1
<s>.on_packets_lost(lost_bytes, lost_largest_time, now=now)
- self.on_packets_lost(lost_bytes, lost_largest_time)
|
aioquic.connection/QuicConnection._connect
|
Modified
|
aiortc~aioquic
|
868a068dbe45379208046385655805fabef546e0
|
[connection] enforce local idle timeout
|
<5>:<add> self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
<0> """
<1> Start the client handshake.
<2> """
<3> assert self.is_client
<4>
<5> self._initialize(self.peer_cid)
<6>
<7> self.tls.handle_message(b"", self.send_buffer)
<8> self._push_crypto_data()
<9> self._send_pending()
<10>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
at: aioquic.connection.QuicConnection
supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20]
_stream_can_send(stream_id: int) -> bool
at: aioquic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
===========changed ref 0===========
# module: aioquic.connection
@dataclass
class QuicReceiveContext:
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
+ time: float
===========changed ref 1===========
# module: aioquic.recovery
class QuicPacketRecovery:
+ def on_packets_lost(
+ self, lost_bytes: int, lost_largest_time: float, now: float
+ ) -> None:
- def on_packets_lost(self, lost_bytes: int, lost_largest_time: float) -> None:
# remove lost packets from bytes in flight
self.bytes_in_flight -= lost_bytes
# start a new congestion event if packet was sent after the
# start of the previous congestion recovery period.
if lost_largest_time > self._congestion_recovery_start_time:
+ self._congestion_recovery_start_time = now
- self._congestion_recovery_start_time = self._get_time()
self.congestion_window = max(
int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW
)
self._ssthresh = self.congestion_window
===========changed ref 2===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:
- packet.sent_time = self._get_time()
space.sent_packets[packet.packet_number] = packet
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight += 1
if packet.is_crypto_packet:
space.crypto_packet_in_flight += 1
if packet.in_flight:
if packet.is_crypto_packet:
self._time_of_last_sent_crypto_packet = packet.sent_time
if packet.is_ack_eliciting:
self._time_of_last_sent_ack_eliciting_packet = packet.sent_time
# add packet to bytes in flight
self.bytes_in_flight += packet.sent_bytes
===========changed ref 3===========
# module: aioquic.recovery
class QuicPacketRecovery:
def __init__(
- self,
- logger: logging.LoggerAdapter,
- get_time: Callable[[], float],
- send_probe: Callable[[], None],
+ self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._get_time = get_time
self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
===========changed ref 4===========
# module: aioquic.recovery
class QuicPacketRecovery:
+ def on_loss_detection_timeout(self, now: float) -> None:
- def on_loss_detection_timeout(self) -> None:
self._logger.info("Loss detection timeout triggered")
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
+ self.detect_loss(loss_space, now=now)
- self.detect_loss(loss_space)
elif sum(space.crypto_packet_in_flight for space in self.spaces):
# reschedule crypto packets
for space in self.spaces:
for packet_number, packet in list(
filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())
):
# remove packet and update counters
del space.sent_packets[packet_number]
space.ack_eliciting_in_flight -= 1
space.crypto_packet_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
self._crypto_count += 1
else:
self._pto_count += 1
self._send_probe()
===========changed ref 5===========
# module: aioquic.recovery
class QuicPacketRecovery:
+ def detect_loss(self, space: QuicPacketSpace, now: float) -> None:
- def detect_loss(self, space: QuicPacketSpace) -> None:
"""
Check whether any packets should be declared lost.
"""
loss_delay = K_TIME_THRESHOLD * (
max(self._rtt_latest, self._rtt_smoothed)
if self._rtt_initialized
else K_INITIAL_RTT
)
packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD
+ time_threshold = now - loss_delay
- time_threshold = self._get_time() - loss_delay
lost_bytes = 0
lost_largest_time = None
space.loss_time = None
for packet_number, packet in list(space.sent_packets.items()):
if packet_number > space.largest_acked_packet:
break
if packet_number <= packet_threshold or packet.sent_time <= time_threshold:
# remove packet and update counters
del space.sent_packets[packet_number]
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight -= 1
if packet.is_crypto_packet:
space.crypto_packet_in_flight -= 1
if packet.in_flight:
lost_bytes += packet.sent_bytes
lost_largest_time = packet.sent_time
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
else:
packet_loss_time = packet.sent_time + loss_delay
if space.loss_time is None or space.loss_time > packet_loss_time:
space.loss_time = packet_loss_time
if lost_bytes:
+ self.on_packets_lost(lost_bytes, lost_largest_time, now=now)
- self.on</s>
|
aioquic.connection/QuicConnection._handle_ack_frame
|
Modified
|
aiortc~aioquic
|
868a068dbe45379208046385655805fabef546e0
|
[connection] enforce local idle timeout
|
<13>:<add> now=context.time,
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_ack_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle an ACK frame.
<2> """
<3> ack_rangeset, ack_delay_encoded = pull_ack_frame(buf)
<4> if frame_type == QuicFrameType.ACK_ECN:
<5> pull_uint_var(buf)
<6> pull_uint_var(buf)
<7> pull_uint_var(buf)
<8>
<9> self._loss.on_ack_received(
<10> space=self.spaces[context.epoch],
<11> ack_rangeset=ack_rangeset,
<12> ack_delay_encoded=ack_delay_encoded,
<13> )
<14>
<15> # check if we can discard handshake keys
<16> if (
<17> not self._handshake_confirmed
<18> and self._handshake_complete
<19> and context.epoch == tls.Epoch.ONE_RTT
<20> ):
<21> self._discard_epoch(tls.Epoch.HANDSHAKE)
<22> self._handshake_confirmed = True
<23>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
pull_uint_var(buf: Buffer) -> int
at: aioquic.connection
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
self._loss = QuicPacketRecovery(
logger=self._logger, send_probe=self._send_probe
)
self._packet_number = 0
at: aioquic.connection.QuicConnection._initialize
self.cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self.spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicConnection._send_pending
self._packet_number = builder.packet_number
at: aioquic.connection.QuicReceiveContext
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
time: float
at: aioquic.crypto.CryptoPair
setup_initial(cid: bytes, is_client: bool) -> None
at: aioquic.packet
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
pull_ack_frame(buf: Buffer) -> Tuple[RangeSet, int]
===========unchanged ref 1===========
at: aioquic.recovery.QuicPacketRecovery
on_ack_received(space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int, now: float) -> None
at: aioquic.recovery.QuicPacketRecovery.__init__
self.spaces: List[QuicPacketSpace] = []
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.connection
@dataclass
class QuicReceiveContext:
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
+ time: float
===========changed ref 1===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_ack_received(
+ self,
+ space: QuicPacketSpace,
+ ack_rangeset: RangeSet,
+ ack_delay_encoded: int,
+ now: float,
- self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int
) -> None:
"""
Update metrics as the result of an ACK being received.
"""
- ack_time = self._get_time()
-
is_ack_eliciting = False
largest_acked = ack_rangeset.bounds().stop - 1
largest_newly_acked = None
largest_sent_time = None
if largest_acked > space.largest_acked_packet:
space.largest_acked_packet = largest_acked
for packet_number in sorted(space.sent_packets.keys()):
if packet_number > largest_acked:
break
if packet_number in ack_rangeset:
# remove packet and update counters
packet = space.sent_packets.pop(packet_number)
if packet.is_ack_eliciting:
is_ack_eliciting = True
space.ack_eliciting_in_flight -= 1
if packet.is_crypto_packet:
space.crypto_packet_in_flight -= 1
if packet.in_flight:
self.on_packet_acked(packet)
largest_newly_acked = packet_number
largest_sent_time = packet.sent_time
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.ACKED, *args)
# nothing to do if there are no newly acked packets
if largest_newly_acked is None:
return
if largest_acked == largest_newly_acked and is_ack_eliciting:
+ latest_rtt = now - largest_sent_time
- </s>
===========changed ref 2===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_ack_received(
+ self,
+ space: QuicPacketSpace,
+ ack_rangeset: RangeSet,
+ ack_delay_encoded: int,
+ now: float,
- self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int
) -> None:
# offset: 1
<s>_acked and is_ack_eliciting:
+ latest_rtt = now - largest_sent_time
- latest_rtt = ack_time - largest_sent_time
# decode ACK delay into seconds
ack_delay = max(
(ack_delay_encoded << self.ack_delay_exponent) / 1000000,
self.max_ack_delay / 1000,
)
# update RTT estimate, which cannot be < 1 ms
+ self._rtt_latest = max(latest_rtt, 0.001)
- self._rtt_latest = max(ack_time - largest_sent_time, 0.001)
if self._rtt_latest < self._rtt_min:
self._rtt_min = self._rtt_latest
if self._rtt_latest > self._rtt_min + ack_delay:
self._rtt_latest -= ack_delay
if not self._rtt_initialized:
self._rtt_initialized = True
self._rtt_variance = latest_rtt / 2
self._rtt_smoothed = latest_rtt
else:
self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(
self._rtt_min - self._rtt_latest
)
self._rtt_smoothed = (
7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest
)
+ self.detect_loss(</s>
===========changed ref 3===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_ack_received(
+ self,
+ space: QuicPacketSpace,
+ ack_rangeset: RangeSet,
+ ack_delay_encoded: int,
+ now: float,
- self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int
) -> None:
# offset: 2
<s> now=now)
- self.detect_loss(space)
self._crypto_count = 0
self._pto_count = 0
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
+ self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
|
aioquic.connection/QuicConnection._send_pending
|
Modified
|
aiortc~aioquic
|
868a068dbe45379208046385655805fabef546e0
|
[connection] enforce local idle timeout
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
<0> network_path = self._network_paths[0]
<1>
<2> self.__send_pending_task = None
<3> if self.__state == QuicConnectionState.DRAINING:
<4> return
<5>
<6> # build datagrams
<7> builder = QuicPacketBuilder(
<8> host_cid=self.host_cid,
<9> packet_number=self._packet_number,
<10> pad_first_datagram=(
<11> self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT
<12> ),
<13> peer_cid=self.peer_cid,
<14> peer_token=self.peer_token,
<15> spin_bit=self._spin_bit,
<16> version=self._version,
<17> )
<18> if self.__close:
<19> for epoch, packet_type in (
<20> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
<21> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
<22> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
<23> ):
<24> crypto = self.cryptos[epoch]
<25> if crypto.send.is_valid():
<26> builder.start_packet(packet_type, crypto)
<27> write_close_frame(builder, **self.__close)
<28> builder.end_packet()
<29> self.__close = None
<30> break
<31> else:
<32> if not self._handshake_confirmed:
<33> for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
<34> self._write_handshake(builder, epoch)
<35> self._write_application(builder, network_path)
<36> datagrams, packets = builder.flush()
<37>
<38> if datagrams:
<39> self._packet_number = builder.packet_number
<40>
<41> # send datagrams
<42> for datagram in datagrams:
<43> self._transport.</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
network_path.bytes_sent += len(datagram)
# register packets
sent_handshake = False
for packet in packets:
self._loss.on_packet_sent(
packet=packet, space=self.spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm loss timer
self._set_loss_detection_timer()
===========unchanged ref 0===========
at: aioquic.buffer.Buffer
seek(pos: int) -> None
at: aioquic.connection
write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None
QuicConnectionId(cid: bytes, sequence_number: int, stateless_reset_token: bytes=b"", was_sent: bool=False)
QuicConnectionState()
at: aioquic.connection.QuicConnection
_write_application(builder: QuicPacketBuilder, network_path: QuicNetworkPath) -> None
_write_handshake(builder: QuicPacketBuilder, epoch: tls.Epoch) -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self.peer_cid = os.urandom(8)
self.peer_token = b""
self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
self.__close: Optional[Dict] = None
self._handshake_confirmed = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self.host_cid = self._host_cids[0].cid
self._host_cid_seq = 1
self._network_paths: List[QuicNetworkPath] = []
self._packet_number = 0
self._spin_bit = False
self.__send_pending_task: Optional[asyncio.Handle] = None
self.__state = QuicConnectionState.FIRSTFLIGHT
self._version: Optional[int] = None
at: aioquic.connection.QuicConnection._consume_connection_id
self.peer_cid = connection_id.cid
===========unchanged ref 1===========
at: aioquic.connection.QuicConnection._handle_ack_frame
self._handshake_confirmed = True
at: aioquic.connection.QuicConnection._initialize
self.cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self.send_buffer = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
self._packet_number = 0
at: aioquic.connection.QuicConnection._payload_received
is_ack_eliciting = False
is_ack_eliciting = True
at: aioquic.connection.QuicConnection._send_pending
self._packet_number = builder.packet_number
at: aioquic.connection.QuicConnection._send_soon
self.__send_pending_task = self._loop.call_soon(self._send_pending)
at: aioquic.connection.QuicConnection._set_state
self.__state = state
at: aioquic.connection.QuicConnection.close
self.__close = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
at: aioquic.connection.QuicConnection.connect
self._network_paths = [QuicNetworkPath(addr, is_validated=True)]
self._version = max(self.supported_versions)
self._version = protocol_version
at: aioquic.connection.QuicConnection.datagram_received
self._version = QuicProtocolVersion(header.version)
self._version = QuicProtocolVersion(max(common))
self.peer_cid = header.source_cid
===========unchanged ref 2===========
self.peer_token = header.token
self._network_paths = [network_path]
self._spin_bit = self._spin_bit_peer
self._spin_bit = not self._spin_bit_peer
self.host_cid = context.host_cid
at: aioquic.connection.QuicConnectionId
cid: bytes
sequence_number: int
stateless_reset_token: bytes = b""
was_sent: bool = False
at: aioquic.crypto.CryptoContext
is_valid() -> bool
at: aioquic.crypto.CryptoPair.__init__
self.send = CryptoContext()
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
at: aioquic.packet_builder.QuicPacketBuilder
flush() -> Tuple[List[bytes], List[QuicSentPacket]]
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.stream.QuicStream
write(data: bytes) -> None
at: aioquic.tls
Epoch()
at: os
urandom(size: int, /) -> bytes
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
- def _on_loss_detection_timeout(self) -> None:
- self._loss_timer = None
- self._loss.on_loss_detection_timeout()
- self._send_pending()
-
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _on_timeout(self) -> None:
+ self._timer = None
+ self._timer_at = None
+
+ # idle timeout
+ if self._loop.time() >= self._idle_timeout_at:
+ self._logger.info("Idle timeout expired")
+ self._set_state(QuicConnectionState.DRAINING)
+ self.connection_lost(None)
+ for epoch in self.spaces.keys():
+ self._discard_epoch(epoch)
+ return
+
+ # loss detection timeout
+ self._loss.on_loss_detection_timeout(now=self._loop.time())
+ self._send_pending()
+
|
|
aioquic.connection/QuicConnection._parse_transport_parameters
|
Modified
|
aiortc~aioquic
|
868a068dbe45379208046385655805fabef546e0
|
[connection] enforce local idle timeout
|
<19>:<add> self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0
<del> self._remote_idle_timeout = quic_transport_parameters.idle_timeout
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _parse_transport_parameters(
self, data: bytes, from_session_ticket: bool = False
) -> None:
<0> quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data))
<1>
<2> # validate remote parameters
<3> if (
<4> self.is_client
<5> and not from_session_ticket
<6> and (
<7> quic_transport_parameters.original_connection_id
<8> != self._original_connection_id
<9> )
<10> ):
<11> raise QuicConnectionError(
<12> error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
<13> frame_type=QuicFrameType.CRYPTO,
<14> reason_phrase="original_connection_id does not match",
<15> )
<16>
<17> # store remote parameters
<18> if quic_transport_parameters.idle_timeout is not None:
<19> self._remote_idle_timeout = quic_transport_parameters.idle_timeout
<20> for param in ["ack_delay_exponent", "max_ack_delay"]:
<21> value = getattr(quic_transport_parameters, param)
<22> if value is not None:
<23> setattr(self._loss, param, value)
<24> for param in [
<25> "max_data",
<26> "max_stream_data_bidi_local",
<27> "max_stream_data_bidi_remote",
<28> "max_stream_data_uni",
<29> "max_streams_bidi",
<30> "max_streams_uni",
<31> ]:
<32> value = getattr(quic_transport_parameters, "initial_" + param)
<33> if value is not None:
<34> setattr(self, "_remote_" + param, value)
<35>
<36> # wakeup waiters
<37> if not self._parameters_available.is_set():
<38> self._parameters_available.set()
<39>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.connection
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
at: aioquic.connection.QuicConnection
_send_pending(self) -> None
_send_pending() -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._loop = asyncio.get_event_loop()
self._loss = QuicPacketRecovery(
logger=self._logger, send_probe=self._send_probe
)
self._original_connection_id = original_connection_id
self.__send_pending_task: Optional[asyncio.Handle] = None
self._probe_pending = False
at: aioquic.connection.QuicConnection._initialize
self.spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicConnection._send_pending
self.__send_pending_task = None
datagrams, packets = builder.flush()
at: aioquic.connection.QuicConnection._write_application
self._probe_pending = False
at: aioquic.connection.QuicConnection.datagram_received
self._original_connection_id = self.peer_cid
at: aioquic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
pull_quic_transport_parameters(buf: Buffer) -> QuicTransportParameters
===========unchanged ref 1===========
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
at: aioquic.packet.QuicTransportParameters
initial_version: Optional[QuicProtocolVersion] = None
negotiated_version: Optional[QuicProtocolVersion] = None
supported_versions: List[QuicProtocolVersion] = field(default_factory=list)
original_connection_id: Optional[bytes] = None
idle_timeout: Optional[int] = None
stateless_reset_token: Optional[bytes] = None
max_packet_size: Optional[int] = None
initial_max_data: Optional[int] = None
initial_max_stream_data_bidi_local: Optional[int] = None
initial_max_stream_data_bidi_remote: Optional[int] = None
initial_max_stream_data_uni: Optional[int] = None
initial_max_streams_bidi: Optional[int] = None
initial_max_streams_uni: Optional[int] = None
ack_delay_exponent: Optional[int] = None
max_ack_delay: Optional[int] = None
disable_migration: Optional[bool] = False
preferred_address: Optional[bytes] = None
at: aioquic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
at: aioquic.recovery.QuicPacketRecovery
on_packet_sent(packet: QuicSentPacket, space: QuicPacketSpace) -> None
===========unchanged ref 2===========
at: asyncio.events.AbstractEventLoop
call_soon(callback: Callable[..., Any], *args: Any) -> Handle
time() -> float
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
network_path = self._network_paths[0]
self.__send_pending_task = None
if self.__state == QuicConnectionState.DRAINING:
return
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
packet_number=self._packet_number,
pad_first_datagram=(
self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT
),
peer_cid=self.peer_cid,
peer_token=self.peer_token,
spin_bit=self._spin_bit,
version=self._version,
)
if self.__close:
for epoch, packet_type in (
(tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
):
crypto = self.cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
write_close_frame(builder, **self.__close)
builder.end_packet()
self.__close = None
break
else:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch)
self._write_application(builder, network_path)
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# send datagrams
for datagram in datagrams:
self._transport.sendto(datagram, network_path.addr)
network_path.bytes_sent += len(datagram)
# register packets
+ now = self._loop.time()</s>
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
<s> network_path.bytes_sent += len(datagram)
# register packets
+ now = self._loop.time()
sent_handshake = False
for packet in packets:
+ packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self.spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
+ # arm timer
- # arm loss timer
+ self._set_timer()
- self._set_loss_detection_timer()
===========changed ref 2===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:
- packet.sent_time = self._get_time()
space.sent_packets[packet.packet_number] = packet
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight += 1
if packet.is_crypto_packet:
space.crypto_packet_in_flight += 1
if packet.in_flight:
if packet.is_crypto_packet:
self._time_of_last_sent_crypto_packet = packet.sent_time
if packet.is_ack_eliciting:
self._time_of_last_sent_ack_eliciting_packet = packet.sent_time
# add packet to bytes in flight
self.bytes_in_flight += packet.sent_bytes
|
aioquic.connection/QuicConnection._serialize_transport_parameters
|
Modified
|
aiortc~aioquic
|
868a068dbe45379208046385655805fabef546e0
|
[connection] enforce local idle timeout
|
<1>:<add> idle_timeout=int(self._local_idle_timeout * 1000),
<del> idle_timeout=self._local_idle_timeout,
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _serialize_transport_parameters(self) -> bytes:
<0> quic_transport_parameters = QuicTransportParameters(
<1> idle_timeout=self._local_idle_timeout,
<2> initial_max_data=self._local_max_data,
<3> initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local,
<4> initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote,
<5> initial_max_stream_data_uni=self._local_max_stream_data_uni,
<6> initial_max_streams_bidi=self._local_max_streams_bidi,
<7> initial_max_streams_uni=self._local_max_streams_uni,
<8> ack_delay_exponent=10,
<9> )
<10> if not self.is_client:
<11> quic_transport_parameters.original_connection_id = (
<12> self._original_connection_id
<13> )
<14>
<15> buf = Buffer(capacity=512)
<16> push_quic_transport_parameters(buf, quic_transport_parameters)
<17> return buf.data
<18>
|
===========unchanged ref 0===========
at: aioquic.connection.QuicConnection.__init__
self._loss = QuicPacketRecovery(
logger=self._logger, send_probe=self._send_probe
)
self._remote_idle_timeout = 0.0 # seconds
at: aioquic.connection.QuicConnection._parse_transport_parameters
quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data))
at: aioquic.packet.QuicTransportParameters
idle_timeout: Optional[int] = None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
- def _on_loss_detection_timeout(self) -> None:
- self._loss_timer = None
- self._loss.on_loss_detection_timeout()
- self._send_pending()
-
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _on_timeout(self) -> None:
+ self._timer = None
+ self._timer_at = None
+
+ # idle timeout
+ if self._loop.time() >= self._idle_timeout_at:
+ self._logger.info("Idle timeout expired")
+ self._set_state(QuicConnectionState.DRAINING)
+ self.connection_lost(None)
+ for epoch in self.spaces.keys():
+ self._discard_epoch(epoch)
+ return
+
+ # loss detection timeout
+ self._loss.on_loss_detection_timeout(now=self._loop.time())
+ self._send_pending()
+
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _parse_transport_parameters(
self, data: bytes, from_session_ticket: bool = False
) -> None:
quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data))
# validate remote parameters
if (
self.is_client
and not from_session_ticket
and (
quic_transport_parameters.original_connection_id
!= self._original_connection_id
)
):
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="original_connection_id does not match",
)
# store remote parameters
if quic_transport_parameters.idle_timeout is not None:
+ self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0
- self._remote_idle_timeout = quic_transport_parameters.idle_timeout
for param in ["ack_delay_exponent", "max_ack_delay"]:
value = getattr(quic_transport_parameters, param)
if value is not None:
setattr(self._loss, param, value)
for param in [
"max_data",
"max_stream_data_bidi_local",
"max_stream_data_bidi_remote",
"max_stream_data_uni",
"max_streams_bidi",
"max_streams_uni",
]:
value = getattr(quic_transport_parameters, "initial_" + param)
if value is not None:
setattr(self, "_remote_" + param, value)
# wakeup waiters
if not self._parameters_available.is_set():
self._parameters_available.set()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
network_path = self._network_paths[0]
self.__send_pending_task = None
if self.__state == QuicConnectionState.DRAINING:
return
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
packet_number=self._packet_number,
pad_first_datagram=(
self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT
),
peer_cid=self.peer_cid,
peer_token=self.peer_token,
spin_bit=self._spin_bit,
version=self._version,
)
if self.__close:
for epoch, packet_type in (
(tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
):
crypto = self.cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
write_close_frame(builder, **self.__close)
builder.end_packet()
self.__close = None
break
else:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch)
self._write_application(builder, network_path)
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# send datagrams
for datagram in datagrams:
self._transport.sendto(datagram, network_path.addr)
network_path.bytes_sent += len(datagram)
# register packets
+ now = self._loop.time()</s>
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
<s> network_path.bytes_sent += len(datagram)
# register packets
+ now = self._loop.time()
sent_handshake = False
for packet in packets:
+ packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self.spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
+ # arm timer
- # arm loss timer
+ self._set_timer()
- self._set_loss_detection_timer()
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_ack_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle an ACK frame.
"""
ack_rangeset, ack_delay_encoded = pull_ack_frame(buf)
if frame_type == QuicFrameType.ACK_ECN:
pull_uint_var(buf)
pull_uint_var(buf)
pull_uint_var(buf)
self._loss.on_ack_received(
space=self.spaces[context.epoch],
ack_rangeset=ack_rangeset,
ack_delay_encoded=ack_delay_encoded,
+ now=context.time,
)
# check if we can discard handshake keys
if (
not self._handshake_confirmed
and self._handshake_complete
and context.epoch == tls.Epoch.ONE_RTT
):
self._discard_epoch(tls.Epoch.HANDSHAKE)
self._handshake_confirmed = True
|
tests.test_connection/client_receive_context
|
Modified
|
aiortc~aioquic
|
868a068dbe45379208046385655805fabef546e0
|
[connection] enforce local idle timeout
|
<1>:<add> epoch=epoch,
<add> host_cid=client.host_cid,
<add> network_path=client._network_paths[0],
<add> time=asyncio.get_event_loop().time(),
<del> epoch=epoch, host_cid=client.host_cid, network_path=client._network_paths[0]
|
# module: tests.test_connection
def client_receive_context(client, epoch=tls.Epoch.ONE_RTT):
<0> return QuicReceiveContext(
<1> epoch=epoch, host_cid=client.host_cid, network_path=client._network_paths[0]
<2> )
<3>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)
at: aioquic.connection.QuicConnection.__init__
self.host_cid = self._host_cids[0].cid
at: aioquic.connection.QuicConnection.datagram_received
self.host_cid = context.host_cid
at: aioquic.connection.QuicReceiveContext
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
time: float
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.connection
@dataclass
class QuicReceiveContext:
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
+ time: float
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
- def _on_loss_detection_timeout(self) -> None:
- self._loss_timer = None
- self._loss.on_loss_detection_timeout()
- self._send_pending()
-
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
+ self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _on_timeout(self) -> None:
+ self._timer = None
+ self._timer_at = None
+
+ # idle timeout
+ if self._loop.time() >= self._idle_timeout_at:
+ self._logger.info("Idle timeout expired")
+ self._set_state(QuicConnectionState.DRAINING)
+ self.connection_lost(None)
+ for epoch in self.spaces.keys():
+ self._discard_epoch(epoch)
+ return
+
+ # loss detection timeout
+ self._loss.on_loss_detection_timeout(now=self._loop.time())
+ self._send_pending()
+
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
- def _set_loss_detection_timer(self) -> None:
- # stop timer
- if self._loss_timer is not None:
- self._loss_timer.cancel()
- self._loss_timer = None
-
- # re-arm timer
- if self.__state not in [
- QuicConnectionState.CLOSING,
- QuicConnectionState.DRAINING,
- ]:
- loss_time = self._loss.get_loss_detection_time()
- if loss_time is not None:
- self._loss_timer = self._loop.call_at(
- loss_time, self._on_loss_detection_timeout
- )
-
===========changed ref 5===========
# module: aioquic.recovery
class QuicPacketRecovery:
+ def on_packets_lost(
+ self, lost_bytes: int, lost_largest_time: float, now: float
+ ) -> None:
- def on_packets_lost(self, lost_bytes: int, lost_largest_time: float) -> None:
# remove lost packets from bytes in flight
self.bytes_in_flight -= lost_bytes
# start a new congestion event if packet was sent after the
# start of the previous congestion recovery period.
if lost_largest_time > self._congestion_recovery_start_time:
+ self._congestion_recovery_start_time = now
- self._congestion_recovery_start_time = self._get_time()
self.congestion_window = max(
int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW
)
self._ssthresh = self.congestion_window
===========changed ref 6===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:
- packet.sent_time = self._get_time()
space.sent_packets[packet.packet_number] = packet
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight += 1
if packet.is_crypto_packet:
space.crypto_packet_in_flight += 1
if packet.in_flight:
if packet.is_crypto_packet:
self._time_of_last_sent_crypto_packet = packet.sent_time
if packet.is_ack_eliciting:
self._time_of_last_sent_ack_eliciting_packet = packet.sent_time
# add packet to bytes in flight
self.bytes_in_flight += packet.sent_bytes
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _set_timer(self) -> None:
+ # determine earliest timeout
+ if self.__state not in [
+ QuicConnectionState.CLOSING,
+ QuicConnectionState.DRAINING,
+ ]:
+ timer_at = self._idle_timeout_at
+ loss_at = self._loss.get_loss_detection_time()
+ if loss_at is not None and loss_at < timer_at:
+ timer_at = loss_at
+ else:
+ timer_at = None
+
+ # re-arm timer
+ if self._timer is not None and self._timer_at != timer_at:
+ self._timer.cancel()
+ self._timer = None
+ if self._timer is None and timer_at is not None:
+ self._timer = self._loop.call_at(timer_at, self._on_timeout)
+ self._timer_at = timer_at
+
===========changed ref 8===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_ack_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle an ACK frame.
"""
ack_rangeset, ack_delay_encoded = pull_ack_frame(buf)
if frame_type == QuicFrameType.ACK_ECN:
pull_uint_var(buf)
pull_uint_var(buf)
pull_uint_var(buf)
self._loss.on_ack_received(
space=self.spaces[context.epoch],
ack_rangeset=ack_rangeset,
ack_delay_encoded=ack_delay_encoded,
+ now=context.time,
)
# check if we can discard handshake keys
if (
not self._handshake_confirmed
and self._handshake_complete
and context.epoch == tls.Epoch.ONE_RTT
):
self._discard_epoch(tls.Epoch.HANDSHAKE)
self._handshake_confirmed = True
|
aioquic.recovery/QuicPacketRecovery.__init__
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<5>:<del> self._logger = logger
|
# module: aioquic.recovery
class QuicPacketRecovery:
- def __init__(
- self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
- ) -> None:
+ def __init__(self, send_probe: Callable[[], None]) -> None:
<0> self.ack_delay_exponent = 3
<1> self.max_ack_delay = 25 # ms
<2> self.spaces: List[QuicPacketSpace] = []
<3>
<4> # callbacks
<5> self._logger = logger
<6> self._send_probe = send_probe
<7>
<8> # loss detection
<9> self._crypto_count = 0
<10> self._pto_count = 0
<11> self._rtt_initialized = False
<12> self._rtt_latest = 0.0
<13> self._rtt_min = math.inf
<14> self._rtt_smoothed = 0.0
<15> self._rtt_variance = 0.0
<16> self._time_of_last_sent_ack_eliciting_packet = 0.0
<17> self._time_of_last_sent_crypto_packet = 0.0
<18>
<19> # congestion control
<20> self.bytes_in_flight = 0
<21> self.congestion_window = K_INITIAL_WINDOW
<22> self._congestion_recovery_start_time = 0.0
<23> self._ssthresh = math.inf
<24>
|
===========unchanged ref 0===========
at: aioquic.recovery
K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE
QuicPacketSpace()
at: aioquic.recovery.QuicPacketRecovery.on_ack_received
self._rtt_latest = max(latest_rtt, 0.001)
self._rtt_latest -= ack_delay
self._rtt_min = self._rtt_latest
self._rtt_initialized = True
self._rtt_variance = latest_rtt / 2
self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(
self._rtt_min - self._rtt_latest
)
self._rtt_smoothed = latest_rtt
self._rtt_smoothed = (
7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest
)
self._crypto_count = 0
self._pto_count = 0
at: aioquic.recovery.QuicPacketRecovery.on_loss_detection_timeout
self.bytes_in_flight -= packet.sent_bytes
self._crypto_count += 1
self._pto_count += 1
at: aioquic.recovery.QuicPacketRecovery.on_packet_acked
self.bytes_in_flight -= packet.sent_bytes
self.congestion_window += (
K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window
)
self.congestion_window += packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packet_expired
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packet_sent
self._time_of_last_sent_crypto_packet = packet.sent_time
self._time_of_last_sent_ack_eliciting_packet = packet.sent_time
===========unchanged ref 1===========
self.bytes_in_flight += packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packets_lost
self.bytes_in_flight -= lost_bytes
self._congestion_recovery_start_time = now
self.congestion_window = max(
int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW
)
self._ssthresh = self.congestion_window
at: math
inf: float
at: typing
List = _alias(list, 1, inst=False, name='List')
|
aioquic.recovery/QuicPacketRecovery.on_loss_detection_timeout
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<0>:<del> self._logger.info("Loss detection timeout triggered")
|
# module: aioquic.recovery
class QuicPacketRecovery:
def on_loss_detection_timeout(self, now: float) -> None:
<0> self._logger.info("Loss detection timeout triggered")
<1> loss_space = self.get_earliest_loss_time()
<2> if loss_space is not None:
<3> self.detect_loss(loss_space, now=now)
<4> elif sum(space.crypto_packet_in_flight for space in self.spaces):
<5> # reschedule crypto packets
<6> for space in self.spaces:
<7> for packet_number, packet in list(
<8> filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())
<9> ):
<10> # remove packet and update counters
<11> del space.sent_packets[packet_number]
<12> space.ack_eliciting_in_flight -= 1
<13> space.crypto_packet_in_flight -= 1
<14> if packet.in_flight:
<15> self.bytes_in_flight -= packet.sent_bytes
<16>
<17> # trigger callbacks
<18> for handler, args in packet.delivery_handlers:
<19> handler(QuicDeliveryState.LOST, *args)
<20> self._crypto_count += 1
<21> else:
<22> self._pto_count += 1
<23> self._send_probe()
<24>
|
===========unchanged ref 0===========
at: aioquic.packet_builder
QuicDeliveryState()
QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(
default_factory=list
))
at: aioquic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
at: aioquic.recovery.QuicPacketRecovery.__init__
self.spaces: List[QuicPacketSpace] = []
self._send_probe = send_probe
self._crypto_count = 0
self._pto_count = 0
self.bytes_in_flight = 0
at: aioquic.recovery.QuicPacketRecovery.on_ack_received
self._crypto_count = 0
self._pto_count = 0
at: aioquic.recovery.QuicPacketRecovery.on_packet_expired
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packet_sent
self.bytes_in_flight += packet.sent_bytes
at: aioquic.recovery.QuicPacketRecovery.on_packets_lost
self.bytes_in_flight -= lost_bytes
at: aioquic.recovery.QuicPacketSpace.__init__
self.ack_eliciting_in_flight = 0
self.crypto_packet_in_flight = 0
self.sent_packets: Dict[int, QuicSentPacket] = {}
===========changed ref 0===========
# module: aioquic.recovery
class QuicPacketRecovery:
- def __init__(
- self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
- ) -> None:
+ def __init__(self, send_probe: Callable[[], None]) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
|
aioquic.connection/QuicConnection.close
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<3>:<add> if self._state not in [
<del> if self.__state not in [
<7>:<add> self._close_pending = {
<del> self.__close = {
<21>:<add> for epoch in self._spaces.keys():
<del> for epoch in self.spaces.keys():
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
<0> """
<1> Close the connection.
<2> """
<3> if self.__state not in [
<4> QuicConnectionState.CLOSING,
<5> QuicConnectionState.DRAINING,
<6> ]:
<7> self.__close = {
<8> "error_code": error_code,
<9> "frame_type": frame_type,
<10> "reason_phrase": reason_phrase,
<11> }
<12> self._set_state(QuicConnectionState.CLOSING)
<13> self.connection_lost(
<14> maybe_connection_error(
<15> error_code=error_code,
<16> frame_type=frame_type,
<17> reason_phrase=reason_phrase,
<18> )
<19> )
<20> self._send_pending()
<21> for epoch in self.spaces.keys():
<22> self._discard_epoch(epoch)
<23>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionState()
maybe_connection_error(error_code: int, frame_type: Optional[int], reason_phrase: str) -> Optional[QuicConnectionError]
at: aioquic.connection.QuicConnection
supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20]
connection_lost(exc: Exception) -> None
_send_pending(self) -> None
_send_pending() -> None
_set_state(self, state: QuicConnectionState) -> None
_set_state(state: QuicConnectionState) -> None
at: aioquic.connection.QuicConnection.__init__
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._state = QuicConnectionState.FIRSTFLIGHT
self._close_pending: Optional[Dict] = None
at: aioquic.connection.QuicConnection._initialize
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicConnection._send_pending
self._close_pending = None
at: aioquic.connection.QuicConnection._set_state
self._state = state
at: aioquic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
===========changed ref 0===========
# module: aioquic.recovery
class QuicPacketRecovery:
- def __init__(
- self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
- ) -> None:
+ def __init__(self, send_probe: Callable[[], None]) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
===========changed ref 1===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_loss_detection_timeout(self, now: float) -> None:
- self._logger.info("Loss detection timeout triggered")
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
self.detect_loss(loss_space, now=now)
elif sum(space.crypto_packet_in_flight for space in self.spaces):
# reschedule crypto packets
for space in self.spaces:
for packet_number, packet in list(
filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())
):
# remove packet and update counters
del space.sent_packets[packet_number]
space.ack_eliciting_in_flight -= 1
space.crypto_packet_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
self._crypto_count += 1
else:
self._pto_count += 1
self._send_probe()
===========changed ref 2===========
<s>[bytes] = None,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
if is_client:
assert (
original_connection_id is None
), "Cannot set original_connection_id for a client"
else:
assert certificate is not None, "SSL certificate is required for a server"
assert private_key is not None, "SSL private key is required for a server"
- self.alpn_protocols = alpn_protocols
- self.certificate = certificate
self.is_client = is_client
- self.peer_cid = os.urandom(8)
- self._peer_cid_seq: Optional[int] = None
- self._peer_cid_available: List[QuicConnectionId] = []
- self.peer_token = b""
- self.private_key = private_key
- self.secrets_log_file = secrets_log_file
- self.server_name = server_name
- self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
if supported_versions is not None:
self.supported_versions = supported_versions
# counters for debugging
self._stateless_retry_count = 0
self._version_negotiation_count = 0
+ # TLS configuration
+ self._alpn_protocols = alpn_protocols
+ self._certificate = certificate
+ self._private_key = private_key
+ self._secrets_log_file = secrets_log_file
+ self._server_name = server_name
+
- self._loop = asyncio.get_event_loop()
- self.__</s>
|
aioquic.connection/QuicConnection.create_stream
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<9>:<add> while stream_id in self._streams:
<del> while stream_id in self.streams:
<27>:<add> stream = self._streams[stream_id] = QuicStream(
<del> stream = self.streams[stream_id] = QuicStream(
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def create_stream(
self, is_unidirectional: bool = False
) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
<0> """
<1> Create a QUIC stream and return a pair of (reader, writer) objects.
<2>
<3> The returned reader and writer objects are instances of :class:`asyncio.StreamReader`
<4> and :class:`asyncio.StreamWriter` classes.
<5> """
<6> await self._parameters_available.wait()
<7>
<8> stream_id = (int(is_unidirectional) << 1) | int(not self.is_client)
<9> while stream_id in self.streams:
<10> stream_id += 4
<11>
<12> # determine limits
<13> if is_unidirectional:
<14> max_stream_data_local = 0
<15> max_stream_data_remote = self._remote_max_stream_data_uni
<16> max_streams = self._remote_max_streams_uni
<17> else:
<18> max_stream_data_local = self._local_max_stream_data_bidi_local
<19> max_stream_data_remote = self._remote_max_stream_data_bidi_remote
<20> max_streams = self._remote_max_streams_bidi
<21>
<22> # check max streams
<23> if stream_id // 4 >= max_streams:
<24> raise ValueError("Too many streams open")
<25>
<26> # create stream
<27> stream = self.streams[stream_id] = QuicStream(
<28> connection=self,
<29> stream_id=stream_id,
<30> max_stream_data_local=max_stream_data_local,
<31> max_stream_data_remote=max_stream_data_remote,
<32> )
<33>
<34> return stream.reader, stream.writer
<35>
|
===========unchanged ref 0===========
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW
self._parameters_available = asyncio.Event()
self._remote_max_stream_data_bidi_remote = 0
self._remote_max_stream_data_uni = 0
self._remote_max_streams_bidi = 0
self._remote_max_streams_uni = 0
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
at: aioquic.connection.QuicConnection._handle_max_streams_bidi_frame
self._remote_max_streams_bidi = max_streams
at: aioquic.connection.QuicConnection._handle_max_streams_uni_frame
self._remote_max_streams_uni = max_streams
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: asyncio.locks.Event
wait() -> bool
at: asyncio.streams
StreamWriter(transport: transports.BaseTransport, protocol: protocols.BaseProtocol, reader: Optional[StreamReader], loop: events.AbstractEventLoop)
StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...)
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
+ if self._state not in [
- if self.__state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
+ self._close_pending = {
- self.__close = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
self._set_state(QuicConnectionState.CLOSING)
self.connection_lost(
maybe_connection_error(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
)
self._send_pending()
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
===========changed ref 1===========
# module: aioquic.recovery
class QuicPacketRecovery:
- def __init__(
- self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
- ) -> None:
+ def __init__(self, send_probe: Callable[[], None]) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
===========changed ref 2===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_loss_detection_timeout(self, now: float) -> None:
- self._logger.info("Loss detection timeout triggered")
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
self.detect_loss(loss_space, now=now)
elif sum(space.crypto_packet_in_flight for space in self.spaces):
# reschedule crypto packets
for space in self.spaces:
for packet_number, packet in list(
filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())
):
# remove packet and update counters
del space.sent_packets[packet_number]
space.ack_eliciting_in_flight -= 1
space.crypto_packet_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
self._crypto_count += 1
else:
self._pto_count += 1
self._send_probe()
===========changed ref 3===========
<s>[bytes] = None,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
if is_client:
assert (
original_connection_id is None
), "Cannot set original_connection_id for a client"
else:
assert certificate is not None, "SSL certificate is required for a server"
assert private_key is not None, "SSL private key is required for a server"
- self.alpn_protocols = alpn_protocols
- self.certificate = certificate
self.is_client = is_client
- self.peer_cid = os.urandom(8)
- self._peer_cid_seq: Optional[int] = None
- self._peer_cid_available: List[QuicConnectionId] = []
- self.peer_token = b""
- self.private_key = private_key
- self.secrets_log_file = secrets_log_file
- self.server_name = server_name
- self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
if supported_versions is not None:
self.supported_versions = supported_versions
# counters for debugging
self._stateless_retry_count = 0
self._version_negotiation_count = 0
+ # TLS configuration
+ self._alpn_protocols = alpn_protocols
+ self._certificate = certificate
+ self._private_key = private_key
+ self._secrets_log_file = secrets_log_file
+ self._server_name = server_name
+
- self._loop = asyncio.get_event_loop()
- self.__</s>
|
aioquic.connection/QuicConnection.request_key_update
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<4>:<add> self._cryptos[tls.Epoch.ONE_RTT].update_key()
<del> self.cryptos[tls.Epoch.ONE_RTT].update_key()
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
<0> """
<1> Request an update of the encryption keys.
<2> """
<3> assert self._handshake_complete, "cannot change key before handshake completes"
<4> self.cryptos[tls.Epoch.ONE_RTT].update_key()
<5>
|
===========unchanged ref 0===========
at: aioquic.connection.QuicConnection.__init__
self._handshake_complete = False
at: aioquic.connection.QuicConnection._handle_crypto_frame
self._handshake_complete = True
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
+ if self._state not in [
- if self.__state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
+ self._close_pending = {
- self.__close = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
self._set_state(QuicConnectionState.CLOSING)
self.connection_lost(
maybe_connection_error(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
)
self._send_pending()
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def create_stream(
self, is_unidirectional: bool = False
) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
"""
Create a QUIC stream and return a pair of (reader, writer) objects.
The returned reader and writer objects are instances of :class:`asyncio.StreamReader`
and :class:`asyncio.StreamWriter` classes.
"""
await self._parameters_available.wait()
stream_id = (int(is_unidirectional) << 1) | int(not self.is_client)
+ while stream_id in self._streams:
- while stream_id in self.streams:
stream_id += 4
# determine limits
if is_unidirectional:
max_stream_data_local = 0
max_stream_data_remote = self._remote_max_stream_data_uni
max_streams = self._remote_max_streams_uni
else:
max_stream_data_local = self._local_max_stream_data_bidi_local
max_stream_data_remote = self._remote_max_stream_data_bidi_remote
max_streams = self._remote_max_streams_bidi
# check max streams
if stream_id // 4 >= max_streams:
raise ValueError("Too many streams open")
# create stream
+ stream = self._streams[stream_id] = QuicStream(
- stream = self.streams[stream_id] = QuicStream(
connection=self,
stream_id=stream_id,
max_stream_data_local=max_stream_data_local,
max_stream_data_remote=max_stream_data_remote,
)
return stream.reader, stream.writer
===========changed ref 2===========
# module: aioquic.recovery
class QuicPacketRecovery:
- def __init__(
- self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
- ) -> None:
+ def __init__(self, send_probe: Callable[[], None]) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
===========changed ref 3===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_loss_detection_timeout(self, now: float) -> None:
- self._logger.info("Loss detection timeout triggered")
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
self.detect_loss(loss_space, now=now)
elif sum(space.crypto_packet_in_flight for space in self.spaces):
# reschedule crypto packets
for space in self.spaces:
for packet_number, packet in list(
filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())
):
# remove packet and update counters
del space.sent_packets[packet_number]
space.ack_eliciting_in_flight -= 1
space.crypto_packet_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
self._crypto_count += 1
else:
self._pto_count += 1
self._send_probe()
===========changed ref 4===========
<s>[bytes] = None,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
if is_client:
assert (
original_connection_id is None
), "Cannot set original_connection_id for a client"
else:
assert certificate is not None, "SSL certificate is required for a server"
assert private_key is not None, "SSL private key is required for a server"
- self.alpn_protocols = alpn_protocols
- self.certificate = certificate
self.is_client = is_client
- self.peer_cid = os.urandom(8)
- self._peer_cid_seq: Optional[int] = None
- self._peer_cid_available: List[QuicConnectionId] = []
- self.peer_token = b""
- self.private_key = private_key
- self.secrets_log_file = secrets_log_file
- self.server_name = server_name
- self.streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
if supported_versions is not None:
self.supported_versions = supported_versions
# counters for debugging
self._stateless_retry_count = 0
self._version_negotiation_count = 0
+ # TLS configuration
+ self._alpn_protocols = alpn_protocols
+ self._certificate = certificate
+ self._private_key = private_key
+ self._secrets_log_file = secrets_log_file
+ self._server_name = server_name
+
- self._loop = asyncio.get_event_loop()
- self.__</s>
|
aioquic.connection/QuicConnection.connection_lost
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<0>:<add> for stream in self._streams.values():
<del> for stream in self.streams.values():
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
<0> for stream in self.streams.values():
<1> stream.connection_lost(exc)
<2>
|
===========unchanged ref 0===========
at: aioquic.connection.QuicConnection.__init__
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
at: asyncio.protocols.BaseProtocol
__slots__ = ()
connection_lost(self, exc: Optional[Exception]) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
+ if self._state not in [
- if self.__state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
+ self._close_pending = {
- self.__close = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
self._set_state(QuicConnectionState.CLOSING)
self.connection_lost(
maybe_connection_error(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
)
self._send_pending()
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def create_stream(
self, is_unidirectional: bool = False
) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
"""
Create a QUIC stream and return a pair of (reader, writer) objects.
The returned reader and writer objects are instances of :class:`asyncio.StreamReader`
and :class:`asyncio.StreamWriter` classes.
"""
await self._parameters_available.wait()
stream_id = (int(is_unidirectional) << 1) | int(not self.is_client)
+ while stream_id in self._streams:
- while stream_id in self.streams:
stream_id += 4
# determine limits
if is_unidirectional:
max_stream_data_local = 0
max_stream_data_remote = self._remote_max_stream_data_uni
max_streams = self._remote_max_streams_uni
else:
max_stream_data_local = self._local_max_stream_data_bidi_local
max_stream_data_remote = self._remote_max_stream_data_bidi_remote
max_streams = self._remote_max_streams_bidi
# check max streams
if stream_id // 4 >= max_streams:
raise ValueError("Too many streams open")
# create stream
+ stream = self._streams[stream_id] = QuicStream(
- stream = self.streams[stream_id] = QuicStream(
connection=self,
stream_id=stream_id,
max_stream_data_local=max_stream_data_local,
max_stream_data_remote=max_stream_data_remote,
)
return stream.reader, stream.writer
===========changed ref 3===========
# module: aioquic.recovery
class QuicPacketRecovery:
- def __init__(
- self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
- ) -> None:
+ def __init__(self, send_probe: Callable[[], None]) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
===========changed ref 4===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_loss_detection_timeout(self, now: float) -> None:
- self._logger.info("Loss detection timeout triggered")
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
self.detect_loss(loss_space, now=now)
elif sum(space.crypto_packet_in_flight for space in self.spaces):
# reschedule crypto packets
for space in self.spaces:
for packet_number, packet in list(
filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())
):
# remove packet and update counters
del space.sent_packets[packet_number]
space.ack_eliciting_in_flight -= 1
space.crypto_packet_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
self._crypto_count += 1
else:
self._pto_count += 1
self._send_probe()
|
aioquic.connection/QuicConnection._connect
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<6>:<add> self._initialize(self._peer_cid)
<del> self._initialize(self.peer_cid)
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
<0> """
<1> Start the client handshake.
<2> """
<3> assert self.is_client
<4>
<5> self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
<6> self._initialize(self.peer_cid)
<7>
<8> self.tls.handle_message(b"", self.send_buffer)
<9> self._push_crypto_data()
<10> self._send_pending()
<11>
|
===========unchanged ref 0===========
at: aioquic.connection.QuicConnection
_initialize(self, peer_cid: bytes) -> None
_initialize(peer_cid: bytes) -> None
_push_crypto_data() -> None
_push_crypto_data(self) -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._idle_timeout_at: Optional[float] = None
self._local_idle_timeout = 60.0 # seconds
self._loop = asyncio.get_event_loop()
self._peer_cid = os.urandom(8)
at: aioquic.connection.QuicConnection._consume_connection_id
self._peer_cid = connection_id.cid
at: aioquic.connection.QuicConnection._initialize
self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
self.send_buffer = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
at: aioquic.connection.QuicConnection.datagram_received
self._peer_cid = header.source_cid
self._idle_timeout_at = now + self._local_idle_timeout
at: aioquic.tls.Context
handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None
at: asyncio.events.AbstractEventLoop
time() -> float
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
+ if self._state not in [
- if self.__state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
+ self._close_pending = {
- self.__close = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
self._set_state(QuicConnectionState.CLOSING)
self.connection_lost(
maybe_connection_error(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
)
self._send_pending()
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def create_stream(
self, is_unidirectional: bool = False
) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
"""
Create a QUIC stream and return a pair of (reader, writer) objects.
The returned reader and writer objects are instances of :class:`asyncio.StreamReader`
and :class:`asyncio.StreamWriter` classes.
"""
await self._parameters_available.wait()
stream_id = (int(is_unidirectional) << 1) | int(not self.is_client)
+ while stream_id in self._streams:
- while stream_id in self.streams:
stream_id += 4
# determine limits
if is_unidirectional:
max_stream_data_local = 0
max_stream_data_remote = self._remote_max_stream_data_uni
max_streams = self._remote_max_streams_uni
else:
max_stream_data_local = self._local_max_stream_data_bidi_local
max_stream_data_remote = self._remote_max_stream_data_bidi_remote
max_streams = self._remote_max_streams_bidi
# check max streams
if stream_id // 4 >= max_streams:
raise ValueError("Too many streams open")
# create stream
+ stream = self._streams[stream_id] = QuicStream(
- stream = self.streams[stream_id] = QuicStream(
connection=self,
stream_id=stream_id,
max_stream_data_local=max_stream_data_local,
max_stream_data_remote=max_stream_data_remote,
)
return stream.reader, stream.writer
===========changed ref 4===========
# module: aioquic.recovery
class QuicPacketRecovery:
- def __init__(
- self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
- ) -> None:
+ def __init__(self, send_probe: Callable[[], None]) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
===========changed ref 5===========
# module: aioquic.recovery
class QuicPacketRecovery:
def on_loss_detection_timeout(self, now: float) -> None:
- self._logger.info("Loss detection timeout triggered")
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
self.detect_loss(loss_space, now=now)
elif sum(space.crypto_packet_in_flight for space in self.spaces):
# reschedule crypto packets
for space in self.spaces:
for packet_number, packet in list(
filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())
):
# remove packet and update counters
del space.sent_packets[packet_number]
space.ack_eliciting_in_flight -= 1
space.crypto_packet_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
self._crypto_count += 1
else:
self._pto_count += 1
self._send_probe()
|
aioquic.connection/QuicConnection._consume_connection_id
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<11>:<add> self._peer_cid = connection_id.cid
<del> self.peer_cid = connection_id.cid
<13>:<add> "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
<del> "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
<0> """
<1> Switch to the next available connection ID and retire
<2> the previous one.
<3> """
<4> if self._peer_cid_available:
<5> # retire previous CID
<6> self._retire_connection_ids.append(self._peer_cid_seq)
<7>
<8> # assign new CID
<9> connection_id = self._peer_cid_available.pop(0)
<10> self._peer_cid_seq = connection_id.sequence_number
<11> self.peer_cid = connection_id.cid
<12> self._logger.info(
<13> "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
<14> )
<15>
|
===========unchanged ref 0===========
at: aioquic.connection
dump_cid(cid: bytes) -> str
at: aioquic.connection.QuicConnection.__init__
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._peer_cid = os.urandom(8)
self._peer_cid_seq: Optional[int] = None
self._peer_cid_available: List[QuicConnectionId] = []
self._retire_connection_ids: List[int] = []
at: aioquic.connection.QuicConnection.datagram_received
self._peer_cid = header.source_cid
self._peer_cid_seq = 0
at: aioquic.connection.QuicConnectionId
cid: bytes
sequence_number: int
stateless_reset_token: bytes = b""
was_sent: bool = False
at: logging.LoggerAdapter
logger: Logger
extra: Mapping[str, Any]
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
+ if self._state not in [
- if self.__state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
+ self._close_pending = {
- self.__close = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
self._set_state(QuicConnectionState.CLOSING)
self.connection_lost(
maybe_connection_error(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
)
self._send_pending()
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def create_stream(
self, is_unidirectional: bool = False
) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
"""
Create a QUIC stream and return a pair of (reader, writer) objects.
The returned reader and writer objects are instances of :class:`asyncio.StreamReader`
and :class:`asyncio.StreamWriter` classes.
"""
await self._parameters_available.wait()
stream_id = (int(is_unidirectional) << 1) | int(not self.is_client)
+ while stream_id in self._streams:
- while stream_id in self.streams:
stream_id += 4
# determine limits
if is_unidirectional:
max_stream_data_local = 0
max_stream_data_remote = self._remote_max_stream_data_uni
max_streams = self._remote_max_streams_uni
else:
max_stream_data_local = self._local_max_stream_data_bidi_local
max_stream_data_remote = self._remote_max_stream_data_bidi_remote
max_streams = self._remote_max_streams_bidi
# check max streams
if stream_id // 4 >= max_streams:
raise ValueError("Too many streams open")
# create stream
+ stream = self._streams[stream_id] = QuicStream(
- stream = self.streams[stream_id] = QuicStream(
connection=self,
stream_id=stream_id,
max_stream_data_local=max_stream_data_local,
max_stream_data_remote=max_stream_data_remote,
)
return stream.reader, stream.writer
===========changed ref 5===========
# module: aioquic.recovery
class QuicPacketRecovery:
- def __init__(
- self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
- ) -> None:
+ def __init__(self, send_probe: Callable[[], None]) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
|
aioquic.connection/QuicConnection._discard_epoch
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<1>:<add> self._cryptos[epoch].teardown()
<del> self.cryptos[epoch].teardown()
<2>:<add> self._loss.discard_space(self._spaces[epoch])
<del> self._loss.discard_space(self.spaces[epoch])
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
<0> self._logger.debug("Discarding epoch %s", epoch)
<1> self.cryptos[epoch].teardown()
<2> self._loss.discard_space(self.spaces[epoch])
<3>
|
===========unchanged ref 0===========
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
at: aioquic.crypto.CryptoPair
teardown() -> None
at: aioquic.tls
Epoch()
at: logging.LoggerAdapter
debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
"""
if self._peer_cid_available:
# retire previous CID
self._retire_connection_ids.append(self._peer_cid_seq)
# assign new CID
connection_id = self._peer_cid_available.pop(0)
self._peer_cid_seq = connection_id.sequence_number
+ self._peer_cid = connection_id.cid
- self.peer_cid = connection_id.cid
self._logger.info(
+ "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
- "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
+ if self._state not in [
- if self.__state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
+ self._close_pending = {
- self.__close = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
self._set_state(QuicConnectionState.CLOSING)
self.connection_lost(
maybe_connection_error(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
)
self._send_pending()
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def create_stream(
self, is_unidirectional: bool = False
) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
"""
Create a QUIC stream and return a pair of (reader, writer) objects.
The returned reader and writer objects are instances of :class:`asyncio.StreamReader`
and :class:`asyncio.StreamWriter` classes.
"""
await self._parameters_available.wait()
stream_id = (int(is_unidirectional) << 1) | int(not self.is_client)
+ while stream_id in self._streams:
- while stream_id in self.streams:
stream_id += 4
# determine limits
if is_unidirectional:
max_stream_data_local = 0
max_stream_data_remote = self._remote_max_stream_data_uni
max_streams = self._remote_max_streams_uni
else:
max_stream_data_local = self._local_max_stream_data_bidi_local
max_stream_data_remote = self._remote_max_stream_data_bidi_remote
max_streams = self._remote_max_streams_bidi
# check max streams
if stream_id // 4 >= max_streams:
raise ValueError("Too many streams open")
# create stream
+ stream = self._streams[stream_id] = QuicStream(
- stream = self.streams[stream_id] = QuicStream(
connection=self,
stream_id=stream_id,
max_stream_data_local=max_stream_data_local,
max_stream_data_remote=max_stream_data_remote,
)
return stream.reader, stream.writer
===========changed ref 6===========
# module: aioquic.recovery
class QuicPacketRecovery:
- def __init__(
- self, logger: logging.LoggerAdapter, send_probe: Callable[[], None]
- ) -> None:
+ def __init__(self, send_probe: Callable[[], None]) -> None:
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
- self._logger = logger
self._send_probe = send_probe
# loss detection
self._crypto_count = 0
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
self._time_of_last_sent_crypto_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh = math.inf
|
aioquic.connection/QuicConnection._get_or_create_stream
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<3>:<add> stream = self._streams.get(stream_id, None)
<del> stream = self.streams.get(stream_id, None)
<33>:<add> stream = self._streams[stream_id] = QuicStream(
<del> stream = self.streams[stream_id] = QuicStream(
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _get_or_create_stream(self, frame_type: int, stream_id: int) -> QuicStream:
<0> """
<1> Get or create a stream in response to a received frame.
<2> """
<3> stream = self.streams.get(stream_id, None)
<4> if stream is None:
<5> # check initiator
<6> if stream_is_client_initiated(stream_id) == self.is_client:
<7> raise QuicConnectionError(
<8> error_code=QuicErrorCode.STREAM_STATE_ERROR,
<9> frame_type=frame_type,
<10> reason_phrase="Wrong stream initiator",
<11> )
<12>
<13> # determine limits
<14> if stream_is_unidirectional(stream_id):
<15> max_stream_data_local = self._local_max_stream_data_uni
<16> max_stream_data_remote = 0
<17> max_streams = self._local_max_streams_uni
<18> else:
<19> max_stream_data_local = self._local_max_stream_data_bidi_remote
<20> max_stream_data_remote = self._remote_max_stream_data_bidi_local
<21> max_streams = self._local_max_streams_bidi
<22>
<23> # check max streams
<24> if stream_id // 4 >= max_streams:
<25> raise QuicConnectionError(
<26> error_code=QuicErrorCode.STREAM_LIMIT_ERROR,
<27> frame_type=frame_type,
<28> reason_phrase="Too many streams open",
<29> )
<30>
<31> # create stream
<32> self._logger.info("Stream %d created by peer" % stream_id)
<33> stream = self.streams[stream_id] = QuicStream(
<34> connection=self,
<35> stream_id=stream_id,
<36> max_stream_data_local=max_stream_data_local,
<37> max_stream_data_remote=max_stream_data_remote,
<38> )</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _get_or_create_stream(self, frame_type: int, stream_id: int) -> QuicStream:
# offset: 1
return stream
===========unchanged ref 0===========
at: aioquic.connection
stream_is_client_initiated(stream_id: int) -> bool
stream_is_unidirectional(stream_id: int) -> bool
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW
self._local_max_stream_data_uni = MAX_DATA_WINDOW
self._local_max_streams_bidi = 128
self._local_max_streams_uni = 128
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._remote_max_stream_data_bidi_local = 0
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
self._stream_handler = lambda r, w: None
self._stream_handler = stream_handler
at: aioquic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.stream.QuicStream.__init__
self.reader = asyncio.StreamReader()
self.reader = None
self.writer = None
self.writer = asyncio.StreamWriter(self, None, self.reader, None)
at: logging.LoggerAdapter
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========unchanged ref 1===========
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
"""
if self._peer_cid_available:
# retire previous CID
self._retire_connection_ids.append(self._peer_cid_seq)
# assign new CID
connection_id = self._peer_cid_available.pop(0)
self._peer_cid_seq = connection_id.sequence_number
+ self._peer_cid = connection_id.cid
- self.peer_cid = connection_id.cid
self._logger.info(
+ "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
- "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
+ if self._state not in [
- if self.__state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
+ self._close_pending = {
- self.__close = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
self._set_state(QuicConnectionState.CLOSING)
self.connection_lost(
maybe_connection_error(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
)
self._send_pending()
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
|
aioquic.connection/QuicConnection._initialize
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<2>:<add> self.tls.alpn_protocols = self._alpn_protocols
<del> self.tls.alpn_protocols = self.alpn_protocols
<3>:<add> self.tls.certificate = self._certificate
<del> self.tls.certificate = self.certificate
<4>:<add> self.tls.certificate_private_key = self._private_key
<del> self.tls.certificate_private_key = self.private_key
<11>:<add> self.tls.server_name = self._server_name
<del> self.tls.server_name = self.server_name
<18>:<add> and self._session_ticket.server_name == self._server_name
<del> and self._session_ticket.server_name == self.server_name
<39>:<add> self._cryptos = {
<del> self.cryptos
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _initialize(self, peer_cid: bytes) -> None:
<0> # TLS
<1> self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
<2> self.tls.alpn_protocols = self.alpn_protocols
<3> self.tls.certificate = self.certificate
<4> self.tls.certificate_private_key = self.private_key
<5> self.tls.handshake_extensions = [
<6> (
<7> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,
<8> self._serialize_transport_parameters(),
<9> )
<10> ]
<11> self.tls.server_name = self.server_name
<12>
<13> # TLS session resumption
<14> if (
<15> self.is_client
<16> and self._session_ticket is not None
<17> and self._session_ticket.is_valid
<18> and self._session_ticket.server_name == self.server_name
<19> ):
<20> self.tls.session_ticket = self._session_ticket
<21>
<22> # parse saved QUIC transport parameters - for 0-RTT
<23> if self._session_ticket.max_early_data_size == 0xFFFFFFFF:
<24> for ext_type, ext_data in self._session_ticket.other_extensions:
<25> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
<26> self._parse_transport_parameters(
<27> ext_data, from_session_ticket=True
<28> )
<29> break
<30>
<31> # TLS callbacks
<32> if self._session_ticket_fetcher is not None:
<33> self.tls.get_session_ticket_cb = self._session_ticket_fetcher
<34> if self._session_ticket_handler is not None:
<35> self.tls.new_session_ticket_cb = self._session_ticket_handler
<36> self.tls.update_traffic_key_cb = self._update_traffic_key
<37>
<38> # packet spaces
<39> self.cryptos</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _initialize(self, peer_cid: bytes) -> None:
# offset: 1
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self.send_buffer = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
self.spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
self.streams[tls.Epoch.INITIAL] = QuicStream()
self.streams[tls.Epoch.HANDSHAKE] = QuicStream()
self.streams[tls.Epoch.ONE_RTT] = QuicStream()
self.cryptos[tls.Epoch.INITIAL].setup_initial(
cid=peer_cid, is_client=self.is_client
)
self._loss.spaces = list(self.spaces.values())
self._packet_number = 0
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.connection.QuicConnection
_parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None
_serialize_transport_parameters() -> bytes
_update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None
_update_traffic_key(self, direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._alpn_protocols = alpn_protocols
self._certificate = certificate
self._private_key = private_key
self._server_name = server_name
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._session_ticket = session_ticket
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
self._session_ticket_fetcher = session_ticket_fetcher
self._session_ticket_handler = session_ticket_handler
at: aioquic.crypto
CryptoPair()
at: aioquic.crypto.CryptoPair
setup_initial(cid: bytes, is_client: bool) -> None
at: aioquic.recovery
QuicPacketSpace()
at: aioquic.recovery.QuicPacketRecovery.__init__
self.spaces: List[QuicPacketSpace] = []
===========unchanged ref 1===========
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.tls
Epoch()
ExtensionType(x: Union[str, bytes, bytearray], base: int)
ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None)
at: aioquic.tls.Context.__init__
self.alpn_protocols: Optional[List[str]] = None
self.certificate: Optional[x509.Certificate] = None
self.certificate_private_key: Optional[
Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]
] = None
self.handshake_extensions: List[Extension] = []
self.session_ticket: Optional[SessionTicket] = None
self.server_name: Optional[str] = None
self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None
self.new_session_ticket_cb: Optional[SessionTicketHandler] = None
self.update_traffic_key_cb: Callable[
[Direction, Epoch, CipherSuite, bytes], None
] = lambda d, e, c, s: None
at: aioquic.tls.SessionTicket
age_add: int
cipher_suite: CipherSuite
not_valid_after: datetime.datetime
not_valid_before: datetime.datetime
resumption_secret: bytes
server_name: str
ticket: bytes
max_early_data_size: Optional[int] = None
other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
"""
if self._peer_cid_available:
# retire previous CID
self._retire_connection_ids.append(self._peer_cid_seq)
# assign new CID
connection_id = self._peer_cid_available.pop(0)
self._peer_cid_seq = connection_id.sequence_number
+ self._peer_cid = connection_id.cid
- self.peer_cid = connection_id.cid
self._logger.info(
+ "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
- "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
|
aioquic.connection/QuicConnection._handle_ack_frame
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<10>:<add> space=self._spaces[context.epoch],
<del> space=self.spaces[context.epoch],
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_ack_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle an ACK frame.
<2> """
<3> ack_rangeset, ack_delay_encoded = pull_ack_frame(buf)
<4> if frame_type == QuicFrameType.ACK_ECN:
<5> pull_uint_var(buf)
<6> pull_uint_var(buf)
<7> pull_uint_var(buf)
<8>
<9> self._loss.on_ack_received(
<10> space=self.spaces[context.epoch],
<11> ack_rangeset=ack_rangeset,
<12> ack_delay_encoded=ack_delay_encoded,
<13> now=context.time,
<14> )
<15>
<16> # check if we can discard handshake keys
<17> if (
<18> not self._handshake_confirmed
<19> and self._handshake_complete
<20> and context.epoch == tls.Epoch.ONE_RTT
<21> ):
<22> self._discard_epoch(tls.Epoch.HANDSHAKE)
<23> self._handshake_confirmed = True
<24>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
pull_uint_var(buf: Buffer) -> int
at: aioquic.connection
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)
at: aioquic.connection.QuicConnection
_discard_epoch(self, epoch: tls.Epoch) -> None
_discard_epoch(epoch: tls.Epoch) -> None
at: aioquic.connection.QuicConnection.__init__
self._handshake_complete = False
self._handshake_confirmed = False
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
at: aioquic.connection.QuicConnection._handle_ack_frame
self._handshake_confirmed = True
at: aioquic.connection.QuicConnection._handle_crypto_frame
self._handshake_complete = True
at: aioquic.connection.QuicConnection._initialize
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicReceiveContext
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
time: float
at: aioquic.packet
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
pull_ack_frame(buf: Buffer) -> Tuple[RangeSet, int]
===========unchanged ref 1===========
at: aioquic.recovery.QuicPacketRecovery
on_ack_received(space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int, now: float) -> None
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
"""
if self._peer_cid_available:
# retire previous CID
self._retire_connection_ids.append(self._peer_cid_seq)
# assign new CID
connection_id = self._peer_cid_available.pop(0)
self._peer_cid_seq = connection_id.sequence_number
+ self._peer_cid = connection_id.cid
- self.peer_cid = connection_id.cid
self._logger.info(
+ "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
- "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _get_or_create_stream(self, frame_type: int, stream_id: int) -> QuicStream:
"""
Get or create a stream in response to a received frame.
"""
+ stream = self._streams.get(stream_id, None)
- stream = self.streams.get(stream_id, None)
if stream is None:
# check initiator
if stream_is_client_initiated(stream_id) == self.is_client:
raise QuicConnectionError(
error_code=QuicErrorCode.STREAM_STATE_ERROR,
frame_type=frame_type,
reason_phrase="Wrong stream initiator",
)
# determine limits
if stream_is_unidirectional(stream_id):
max_stream_data_local = self._local_max_stream_data_uni
max_stream_data_remote = 0
max_streams = self._local_max_streams_uni
else:
max_stream_data_local = self._local_max_stream_data_bidi_remote
max_stream_data_remote = self._remote_max_stream_data_bidi_local
max_streams = self._local_max_streams_bidi
# check max streams
if stream_id // 4 >= max_streams:
raise QuicConnectionError(
error_code=QuicErrorCode.STREAM_LIMIT_ERROR,
frame_type=frame_type,
reason_phrase="Too many streams open",
)
# create stream
self._logger.info("Stream %d created by peer" % stream_id)
+ stream = self._streams[stream_id] = QuicStream(
- stream = self.streams[stream_id] = QuicStream(
connection=self,
stream_id=stream_id,
max_stream_data_local=max_stream_data_local,
max_stream_data_remote=max_stream_data_remote,
)
</s>
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _get_or_create_stream(self, frame_type: int, stream_id: int) -> QuicStream:
# offset: 1
<s>_stream_data_local,
max_stream_data_remote=max_stream_data_remote,
)
self._stream_handler(stream.reader, stream.writer)
return stream
|
aioquic.connection/QuicConnection._handle_crypto_frame
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<3>:<add> stream = self._streams[context.epoch]
<del> stream = self.streams[context.epoch]
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a CRYPTO frame.
<2> """
<3> stream = self.streams[context.epoch]
<4> stream.add_frame(pull_crypto_frame(buf))
<5> data = stream.pull_data()
<6> if data:
<7> # pass data to TLS layer
<8> try:
<9> self.tls.handle_message(data, self.send_buffer)
<10> self._push_crypto_data()
<11> except tls.Alert as exc:
<12> raise QuicConnectionError(
<13> error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
<14> frame_type=QuicFrameType.CRYPTO,
<15> reason_phrase=str(exc),
<16> )
<17>
<18> # parse transport parameters
<19> if (
<20> not self._parameters_received
<21> and self.tls.received_extensions is not None
<22> ):
<23> for ext_type, ext_data in self.tls.received_extensions:
<24> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
<25> self._parse_transport_parameters(ext_data)
<26> self._parameters_received = True
<27> break
<28> assert (
<29> self._parameters_received
<30> ), "No QUIC transport parameters received"
<31> self._logger.info("ALPN negotiated protocol %s", self.alpn_protocol)
<32>
<33> # update current epoch
<34> if not self._handshake_complete and self.tls.state in [
<35> tls.State.CLIENT_POST_HANDSHAKE,
<36> tls.State.SERVER_POST_HANDSHAKE,
<37> ]:
<38> self._handshake_complete = True
<39> self._replenish_connection_ids()
<40> # wakeup waiter
<41> if not self._connected.is_set():
<42> self._connected.</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
# offset: 1
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.connection
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)
at: aioquic.connection.QuicConnection
_replenish_connection_ids() -> None
_push_crypto_data() -> None
_push_crypto_data(self) -> None
_parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None
at: aioquic.connection.QuicConnection.__init__
self._connected = asyncio.Event()
self._handshake_complete = False
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._parameters_received = False
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
at: aioquic.connection.QuicConnection._initialize
self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
self.send_buffer = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
at: aioquic.connection.QuicReceiveContext
epoch: tls.Epoch
at: aioquic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
===========unchanged ref 1===========
pull_crypto_frame(buf: Buffer) -> QuicStreamFrame
at: aioquic.stream.QuicStream
add_frame(frame: QuicStreamFrame) -> None
pull_data() -> bytes
at: aioquic.tls
Alert(*args: object)
State()
ExtensionType(x: Union[str, bytes, bytearray], base: int)
ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: aioquic.tls.Alert
description: AlertDescription
at: aioquic.tls.Context
handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None
at: aioquic.tls.Context.__init__
self.received_extensions: Optional[List[Extension]] = None
self.state = State.CLIENT_HANDSHAKE_START
self.state = State.SERVER_EXPECT_CLIENT_HELLO
at: aioquic.tls.Context._client_handle_encrypted_extensions
self.received_extensions = encrypted_extensions.other_extensions
at: aioquic.tls.Context._server_handle_hello
self.received_extensions = peer_hello.other_extensions
at: aioquic.tls.Context._set_state
self.state = state
at: asyncio.locks.Event
is_set() -> bool
at: logging.LoggerAdapter
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_ack_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle an ACK frame.
"""
ack_rangeset, ack_delay_encoded = pull_ack_frame(buf)
if frame_type == QuicFrameType.ACK_ECN:
pull_uint_var(buf)
pull_uint_var(buf)
pull_uint_var(buf)
self._loss.on_ack_received(
+ space=self._spaces[context.epoch],
- space=self.spaces[context.epoch],
ack_rangeset=ack_rangeset,
ack_delay_encoded=ack_delay_encoded,
now=context.time,
)
# check if we can discard handshake keys
if (
not self._handshake_confirmed
and self._handshake_complete
and context.epoch == tls.Epoch.ONE_RTT
):
self._discard_epoch(tls.Epoch.HANDSHAKE)
self._handshake_confirmed = True
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
"""
if self._peer_cid_available:
# retire previous CID
self._retire_connection_ids.append(self._peer_cid_seq)
# assign new CID
connection_id = self._peer_cid_available.pop(0)
self._peer_cid_seq = connection_id.sequence_number
+ self._peer_cid = connection_id.cid
- self.peer_cid = connection_id.cid
self._logger.info(
+ "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
- "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
)
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
|
aioquic.connection/QuicConnection._on_timeout
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<8>:<add> for epoch in self._spaces.keys():
<del> for epoch in self.spaces.keys():
<13>:<add> self._logger.info("Loss detection triggered")
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
<0> self._timer = None
<1> self._timer_at = None
<2>
<3> # idle timeout
<4> if self._loop.time() >= self._idle_timeout_at:
<5> self._logger.info("Idle timeout expired")
<6> self._set_state(QuicConnectionState.DRAINING)
<7> self.connection_lost(None)
<8> for epoch in self.spaces.keys():
<9> self._discard_epoch(epoch)
<10> return
<11>
<12> # loss detection timeout
<13> self._loss.on_loss_detection_timeout(now=self._loop.time())
<14> self._send_pending()
<15>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionState()
at: aioquic.connection.QuicConnection
connection_lost(exc: Exception) -> None
_discard_epoch(self, epoch: tls.Epoch) -> None
_discard_epoch(epoch: tls.Epoch) -> None
_set_state(self, state: QuicConnectionState) -> None
_set_state(state: QuicConnectionState) -> None
at: aioquic.connection.QuicConnection.__init__
self._idle_timeout_at: Optional[float] = None
self._loop = asyncio.get_event_loop()
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._timer: Optional[asyncio.TimerHandle] = None
self._timer_at: Optional[float] = None
at: aioquic.connection.QuicConnection._connect
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
at: aioquic.connection.QuicConnection._initialize
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicConnection._set_timer
self._timer = None
self._timer = self._loop.call_at(timer_at, self._on_timeout)
self._timer_at = timer_at
at: aioquic.connection.QuicConnection.datagram_received
self._idle_timeout_at = now + self._local_idle_timeout
at: asyncio.events.AbstractEventLoop
time() -> float
===========unchanged ref 1===========
at: logging.LoggerAdapter
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_ack_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle an ACK frame.
"""
ack_rangeset, ack_delay_encoded = pull_ack_frame(buf)
if frame_type == QuicFrameType.ACK_ECN:
pull_uint_var(buf)
pull_uint_var(buf)
pull_uint_var(buf)
self._loss.on_ack_received(
+ space=self._spaces[context.epoch],
- space=self.spaces[context.epoch],
ack_rangeset=ack_rangeset,
ack_delay_encoded=ack_delay_encoded,
now=context.time,
)
# check if we can discard handshake keys
if (
not self._handshake_confirmed
and self._handshake_complete
and context.epoch == tls.Epoch.ONE_RTT
):
self._discard_epoch(tls.Epoch.HANDSHAKE)
self._handshake_confirmed = True
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CRYPTO frame.
"""
+ stream = self._streams[context.epoch]
- stream = self.streams[context.epoch]
stream.add_frame(pull_crypto_frame(buf))
data = stream.pull_data()
if data:
# pass data to TLS layer
try:
self.tls.handle_message(data, self.send_buffer)
self._push_crypto_data()
except tls.Alert as exc:
raise QuicConnectionError(
error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
frame_type=QuicFrameType.CRYPTO,
reason_phrase=str(exc),
)
# parse transport parameters
if (
not self._parameters_received
and self.tls.received_extensions is not None
):
for ext_type, ext_data in self.tls.received_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(ext_data)
self._parameters_received = True
break
assert (
self._parameters_received
), "No QUIC transport parameters received"
self._logger.info("ALPN negotiated protocol %s", self.alpn_protocol)
# update current epoch
if not self._handshake_complete and self.tls.state in [
tls.State.CLIENT_POST_HANDSHAKE,
tls.State.SERVER_POST_HANDSHAKE,
]:
self._handshake_complete = True
self._replenish_connection_ids()
# wakeup waiter
if not self._connected.is_set():
self._connected.set()
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
"""
if self._peer_cid_available:
# retire previous CID
self._retire_connection_ids.append(self._peer_cid_seq)
# assign new CID
connection_id = self._peer_cid_available.pop(0)
self._peer_cid_seq = connection_id.sequence_number
+ self._peer_cid = connection_id.cid
- self.peer_cid = connection_id.cid
self._logger.info(
+ "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
- "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
)
|
aioquic.connection/QuicConnection._push_crypto_data
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<1>:<add> self._streams[epoch].write(buf.data)
<del> self.streams[epoch].write(buf.data)
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
<0> for epoch, buf in self.send_buffer.items():
<1> self.streams[epoch].write(buf.data)
<2> buf.seek(0)
<3>
|
===========unchanged ref 0===========
at: aioquic.connection.QuicConnection.__init__
self._host_cid_seq = 1
at: aioquic.connection.QuicConnection._initialize
self.send_buffer = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_ack_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle an ACK frame.
"""
ack_rangeset, ack_delay_encoded = pull_ack_frame(buf)
if frame_type == QuicFrameType.ACK_ECN:
pull_uint_var(buf)
pull_uint_var(buf)
pull_uint_var(buf)
self._loss.on_ack_received(
+ space=self._spaces[context.epoch],
- space=self.spaces[context.epoch],
ack_rangeset=ack_rangeset,
ack_delay_encoded=ack_delay_encoded,
now=context.time,
)
# check if we can discard handshake keys
if (
not self._handshake_confirmed
and self._handshake_complete
and context.epoch == tls.Epoch.ONE_RTT
):
self._discard_epoch(tls.Epoch.HANDSHAKE)
self._handshake_confirmed = True
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CRYPTO frame.
"""
+ stream = self._streams[context.epoch]
- stream = self.streams[context.epoch]
stream.add_frame(pull_crypto_frame(buf))
data = stream.pull_data()
if data:
# pass data to TLS layer
try:
self.tls.handle_message(data, self.send_buffer)
self._push_crypto_data()
except tls.Alert as exc:
raise QuicConnectionError(
error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
frame_type=QuicFrameType.CRYPTO,
reason_phrase=str(exc),
)
# parse transport parameters
if (
not self._parameters_received
and self.tls.received_extensions is not None
):
for ext_type, ext_data in self.tls.received_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(ext_data)
self._parameters_received = True
break
assert (
self._parameters_received
), "No QUIC transport parameters received"
self._logger.info("ALPN negotiated protocol %s", self.alpn_protocol)
# update current epoch
if not self._handshake_complete and self.tls.state in [
tls.State.CLIENT_POST_HANDSHAKE,
tls.State.SERVER_POST_HANDSHAKE,
]:
self._handshake_complete = True
self._replenish_connection_ids()
# wakeup waiter
if not self._connected.is_set():
self._connected.set()
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
"""
if self._peer_cid_available:
# retire previous CID
self._retire_connection_ids.append(self._peer_cid_seq)
# assign new CID
connection_id = self._peer_cid_available.pop(0)
self._peer_cid_seq = connection_id.sequence_number
+ self._peer_cid = connection_id.cid
- self.peer_cid = connection_id.cid
self._logger.info(
+ "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
- "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
)
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
|
aioquic.connection/QuicConnection._send_pending
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<2>:<add> self._send_task = None
<del> self.__send_pending_task = None
<3>:<add> if self._state == QuicConnectionState.DRAINING:
<del> if self.__state == QuicConnectionState.DRAINING:
<11>:<add> self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
<del> self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT
<13>:<add> peer_cid=self._peer_cid,
<del> peer_cid=self.peer_cid,
<14>:<add> peer_token=self._peer_token,
<del> peer_token=self.peer_token,
<18>:<add> if self._close_pending:
<del> if self.__close:
<24>:<add> crypto = self._cryptos[epoch]
<del> crypto = self.cryptos[epoch]
<27>:<add> write_close_frame(builder, **self._close_pending)
<del> write_close_frame(builder, **self.__close)
<29>:<add> self._close_pending = None
<del> self.__close = None
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
<0> network_path = self._network_paths[0]
<1>
<2> self.__send_pending_task = None
<3> if self.__state == QuicConnectionState.DRAINING:
<4> return
<5>
<6> # build datagrams
<7> builder = QuicPacketBuilder(
<8> host_cid=self.host_cid,
<9> packet_number=self._packet_number,
<10> pad_first_datagram=(
<11> self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT
<12> ),
<13> peer_cid=self.peer_cid,
<14> peer_token=self.peer_token,
<15> spin_bit=self._spin_bit,
<16> version=self._version,
<17> )
<18> if self.__close:
<19> for epoch, packet_type in (
<20> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
<21> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
<22> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
<23> ):
<24> crypto = self.cryptos[epoch]
<25> if crypto.send.is_valid():
<26> builder.start_packet(packet_type, crypto)
<27> write_close_frame(builder, **self.__close)
<28> builder.end_packet()
<29> self.__close = None
<30> break
<31> else:
<32> if not self._handshake_confirmed:
<33> for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
<34> self._write_handshake(builder, epoch)
<35> self._write_application(builder, network_path)
<36> datagrams, packets = builder.flush()
<37>
<38> if datagrams:
<39> self._packet_number = builder.packet_number
<40>
<41> # send datagrams
<42> for datagram in datagrams:
<43> self._transport.</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
network_path.bytes_sent += len(datagram)
# register packets
now = self._loop.time()
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self.spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm timer
self._set_timer()
===========unchanged ref 0===========
at: aioquic.connection
write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None
QuicConnectionState()
at: aioquic.connection.QuicConnection
_discard_epoch(self, epoch: tls.Epoch) -> None
_discard_epoch(epoch: tls.Epoch) -> None
_write_application(self, builder: QuicPacketBuilder, network_path: QuicNetworkPath) -> None
_write_application(builder: QuicPacketBuilder, network_path: QuicNetworkPath) -> None
_write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None
_write_handshake(builder: QuicPacketBuilder, epoch: tls.Epoch) -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._handshake_confirmed = False
self.host_cid = self._host_cids[0].cid
self._loop = asyncio.get_event_loop()
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._network_paths: List[QuicNetworkPath] = []
self._packet_number = 0
self._peer_cid = os.urandom(8)
self._peer_token = b""
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._spin_bit = False
self._state = QuicConnectionState.FIRSTFLIGHT
self._transport: Optional[asyncio.DatagramTransport] = None
self._version: Optional[int] = None
self._close_pending: Optional[Dict] = None
self._send_task: Optional[asyncio.Handle] = None
===========unchanged ref 1===========
at: aioquic.connection.QuicConnection._consume_connection_id
self._peer_cid = connection_id.cid
at: aioquic.connection.QuicConnection._handle_ack_frame
self._handshake_confirmed = True
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
self._packet_number = 0
at: aioquic.connection.QuicConnection._send_soon
self._send_task = self._loop.call_soon(self._send_pending)
at: aioquic.connection.QuicConnection._set_state
self._state = state
at: aioquic.connection.QuicConnection.close
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
at: aioquic.connection.QuicConnection.connect
self._network_paths = [QuicNetworkPath(addr, is_validated=True)]
self._version = max(self.supported_versions)
self._version = protocol_version
at: aioquic.connection.QuicConnection.connection_made
self._transport = cast(asyncio.DatagramTransport, transport)
at: aioquic.connection.QuicConnection.datagram_received
self._version = QuicProtocolVersion(header.version)
self._version = QuicProtocolVersion(max(common))
self._peer_cid = header.source_cid
self._peer_token = header.token
self._network_paths = [network_path]
===========unchanged ref 2===========
self._spin_bit = self._spin_bit_peer
self._spin_bit = not self._spin_bit_peer
self.host_cid = context.host_cid
at: aioquic.connection.QuicNetworkPath
addr: NetworkAddress
bytes_received: int = 0
bytes_sent: int = 0
is_validated: bool = False
local_challenge: Optional[bytes] = None
remote_challenge: Optional[bytes] = None
at: aioquic.crypto.CryptoContext
is_valid() -> bool
at: aioquic.crypto.CryptoPair.__init__
self.send = CryptoContext()
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
at: aioquic.packet_builder.QuicPacketBuilder
flush() -> Tuple[List[bytes], List[QuicSentPacket]]
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
===========unchanged ref 3===========
at: aioquic.tls
Epoch()
at: asyncio.transports.DatagramTransport
__slots__ = ()
sendto(data: Any, addr: Optional[_Address]=...) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
|
aioquic.connection/QuicConnection._send_soon
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<0>:<add> if self._send_task is None:
<del> if self.__send_pending_task is None:
<1>:<add> self._send_task = self._loop.call_soon(self._send_pending)
<del> self.__send_pending_task = self._loop.call_soon(self._send_pending)
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
<0> if self.__send_pending_task is None:
<1> self.__send_pending_task = self._loop.call_soon(self._send_pending)
<2>
|
===========unchanged ref 0===========
at: aioquic.connection.QuicConnection.__init__
self._probe_pending = False
at: aioquic.connection.QuicConnection._write_application
self._probe_pending = False
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
network_path = self._network_paths[0]
+ self._send_task = None
- self.__send_pending_task = None
+ if self._state == QuicConnectionState.DRAINING:
- if self.__state == QuicConnectionState.DRAINING:
return
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
packet_number=self._packet_number,
pad_first_datagram=(
+ self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
- self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT
),
+ peer_cid=self._peer_cid,
- peer_cid=self.peer_cid,
+ peer_token=self._peer_token,
- peer_token=self.peer_token,
spin_bit=self._spin_bit,
version=self._version,
)
+ if self._close_pending:
- if self.__close:
for epoch, packet_type in (
(tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
):
+ crypto = self._cryptos[epoch]
- crypto = self.cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
+ write_close_frame(builder, **self._close_pending)
- write_close_frame(builder, **self.__close)
builder.end_packet()
+ self._close_pending = None
- self.__close = None
break
else:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch</s>
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
<s>
else:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch)
self._write_application(builder, network_path)
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# send datagrams
for datagram in datagrams:
self._transport.sendto(datagram, network_path.addr)
network_path.bytes_sent += len(datagram)
# register packets
now = self._loop.time()
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
+ packet=packet, space=self._spaces[packet.epoch]
- packet=packet, space=self.spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm timer
self._set_timer()
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_ack_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle an ACK frame.
"""
ack_rangeset, ack_delay_encoded = pull_ack_frame(buf)
if frame_type == QuicFrameType.ACK_ECN:
pull_uint_var(buf)
pull_uint_var(buf)
pull_uint_var(buf)
self._loss.on_ack_received(
+ space=self._spaces[context.epoch],
- space=self.spaces[context.epoch],
ack_rangeset=ack_rangeset,
ack_delay_encoded=ack_delay_encoded,
now=context.time,
)
# check if we can discard handshake keys
if (
not self._handshake_confirmed
and self._handshake_complete
and context.epoch == tls.Epoch.ONE_RTT
):
self._discard_epoch(tls.Epoch.HANDSHAKE)
self._handshake_confirmed = True
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
|
aioquic.connection/QuicConnection._set_state
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<0>:<add> self._logger.info("%s -> %s", self._state, state)
<del> self._logger.info("%s -> %s", self.__state, state)
<1>:<add> self._state = state
<del> self.__state = state
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_state(self, state: QuicConnectionState) -> None:
<0> self._logger.info("%s -> %s", self.__state, state)
<1> self.__state = state
<2>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionState()
at: aioquic.connection.QuicConnection._serialize_transport_parameters
buf = Buffer(capacity=512)
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
+ if self._send_task is None:
- if self.__send_pending_task is None:
+ self._send_task = self._loop.call_soon(self._send_pending)
- self.__send_pending_task = self._loop.call_soon(self._send_pending)
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
network_path = self._network_paths[0]
+ self._send_task = None
- self.__send_pending_task = None
+ if self._state == QuicConnectionState.DRAINING:
- if self.__state == QuicConnectionState.DRAINING:
return
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
packet_number=self._packet_number,
pad_first_datagram=(
+ self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
- self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT
),
+ peer_cid=self._peer_cid,
- peer_cid=self.peer_cid,
+ peer_token=self._peer_token,
- peer_token=self.peer_token,
spin_bit=self._spin_bit,
version=self._version,
)
+ if self._close_pending:
- if self.__close:
for epoch, packet_type in (
(tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
):
+ crypto = self._cryptos[epoch]
- crypto = self.cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
+ write_close_frame(builder, **self._close_pending)
- write_close_frame(builder, **self.__close)
builder.end_packet()
+ self._close_pending = None
- self.__close = None
break
else:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch</s>
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
<s>
else:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch)
self._write_application(builder, network_path)
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# send datagrams
for datagram in datagrams:
self._transport.sendto(datagram, network_path.addr)
network_path.bytes_sent += len(datagram)
# register packets
now = self._loop.time()
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
+ packet=packet, space=self._spaces[packet.epoch]
- packet=packet, space=self.spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm timer
self._set_timer()
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_ack_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle an ACK frame.
"""
ack_rangeset, ack_delay_encoded = pull_ack_frame(buf)
if frame_type == QuicFrameType.ACK_ECN:
pull_uint_var(buf)
pull_uint_var(buf)
pull_uint_var(buf)
self._loss.on_ack_received(
+ space=self._spaces[context.epoch],
- space=self.spaces[context.epoch],
ack_rangeset=ack_rangeset,
ack_delay_encoded=ack_delay_encoded,
now=context.time,
)
# check if we can discard handshake keys
if (
not self._handshake_confirmed
and self._handshake_complete
and context.epoch == tls.Epoch.ONE_RTT
):
self._discard_epoch(tls.Epoch.HANDSHAKE)
self._handshake_confirmed = True
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
|
aioquic.connection/QuicConnection._set_timer
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<1>:<add> if self._state not in [
<del> if self.__state not in [
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_timer(self) -> None:
<0> # determine earliest timeout
<1> if self.__state not in [
<2> QuicConnectionState.CLOSING,
<3> QuicConnectionState.DRAINING,
<4> ]:
<5> timer_at = self._idle_timeout_at
<6> loss_at = self._loss.get_loss_detection_time()
<7> if loss_at is not None and loss_at < timer_at:
<8> timer_at = loss_at
<9> else:
<10> timer_at = None
<11>
<12> # re-arm timer
<13> if self._timer is not None and self._timer_at != timer_at:
<14> self._timer.cancel()
<15> self._timer = None
<16> if self._timer is None and timer_at is not None:
<17> self._timer = self._loop.call_at(timer_at, self._on_timeout)
<18> self._timer_at = timer_at
<19>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionState()
at: aioquic.connection.QuicConnection.__init__
self._idle_timeout_at: Optional[float] = None
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._state = QuicConnectionState.FIRSTFLIGHT
self._timer: Optional[asyncio.TimerHandle] = None
self._timer_at: Optional[float] = None
at: aioquic.connection.QuicConnection._connect
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
at: aioquic.connection.QuicConnection._on_timeout
self._timer = None
self._timer_at = None
at: aioquic.connection.QuicConnection._set_timer
self._timer_at = timer_at
at: aioquic.connection.QuicConnection.datagram_received
self._idle_timeout_at = now + self._local_idle_timeout
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_state(self, state: QuicConnectionState) -> None:
+ self._logger.info("%s -> %s", self._state, state)
- self._logger.info("%s -> %s", self.__state, state)
+ self._state = state
- self.__state = state
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
+ if self._send_task is None:
- if self.__send_pending_task is None:
+ self._send_task = self._loop.call_soon(self._send_pending)
- self.__send_pending_task = self._loop.call_soon(self._send_pending)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
network_path = self._network_paths[0]
+ self._send_task = None
- self.__send_pending_task = None
+ if self._state == QuicConnectionState.DRAINING:
- if self.__state == QuicConnectionState.DRAINING:
return
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
packet_number=self._packet_number,
pad_first_datagram=(
+ self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
- self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT
),
+ peer_cid=self._peer_cid,
- peer_cid=self.peer_cid,
+ peer_token=self._peer_token,
- peer_token=self.peer_token,
spin_bit=self._spin_bit,
version=self._version,
)
+ if self._close_pending:
- if self.__close:
for epoch, packet_type in (
(tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
):
+ crypto = self._cryptos[epoch]
- crypto = self.cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
+ write_close_frame(builder, **self._close_pending)
- write_close_frame(builder, **self.__close)
builder.end_packet()
+ self._close_pending = None
- self.__close = None
break
else:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch</s>
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
<s>
else:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch)
self._write_application(builder, network_path)
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# send datagrams
for datagram in datagrams:
self._transport.sendto(datagram, network_path.addr)
network_path.bytes_sent += len(datagram)
# register packets
now = self._loop.time()
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
+ packet=packet, space=self._spaces[packet.epoch]
- packet=packet, space=self.spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm timer
self._set_timer()
|
aioquic.connection/QuicConnection._update_traffic_key
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<4>:<add> if self._secrets_log_file is not None:
<del> if self.secrets_log_file is not None:
<7>:<add> self._secrets_log_file.write(
<del> self.secrets_log_file.write(
<10>:<add> self._secrets_log_file.flush()
<del> self.secrets_log_file.flush()
<12>:<add> crypto = self._cryptos[epoch]
<del> crypto = self.cryptos[epoch]
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _update_traffic_key(
self,
direction: tls.Direction,
epoch: tls.Epoch,
cipher_suite: tls.CipherSuite,
secret: bytes,
) -> None:
<0> """
<1> Callback which is invoked by the TLS engine when new traffic keys are
<2> available.
<3> """
<4> if self.secrets_log_file is not None:
<5> label_row = self.is_client == (direction == tls.Direction.DECRYPT)
<6> label = SECRETS_LABELS[label_row][epoch.value]
<7> self.secrets_log_file.write(
<8> "%s %s %s\n" % (label, self.tls.client_random.hex(), secret.hex())
<9> )
<10> self.secrets_log_file.flush()
<11>
<12> crypto = self.cryptos[epoch]
<13> if direction == tls.Direction.ENCRYPT:
<14> crypto.send.setup(cipher_suite, secret)
<15> else:
<16> crypto.recv.setup(cipher_suite, secret)
<17>
|
===========unchanged ref 0===========
at: aioquic.connection
SECRETS_LABELS = [
[
None,
"QUIC_CLIENT_EARLY_TRAFFIC_SECRET",
"QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET",
"QUIC_CLIENT_TRAFFIC_SECRET_0",
],
[
None,
None,
"QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET",
"QUIC_SERVER_TRAFFIC_SECRET_0",
],
]
stream_is_unidirectional(stream_id: int) -> bool
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._secrets_log_file = secrets_log_file
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
at: aioquic.connection.QuicConnection._initialize
self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
at: aioquic.tls
Direction()
Epoch()
CipherSuite(x: Union[str, bytes, bytearray], base: int)
CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: enum.Enum
name: str
value: Any
_name_: str
_value_: Any
_member_names_: List[str] # undocumented
_member_map_: Dict[str, Enum] # undocumented
_value2member_map_: Dict[int, Enum] # undocumented
_ignore_: Union[str, List[str]]
_order_: str
===========unchanged ref 1===========
__order__: str
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_state(self, state: QuicConnectionState) -> None:
+ self._logger.info("%s -> %s", self._state, state)
- self._logger.info("%s -> %s", self.__state, state)
+ self._state = state
- self.__state = state
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
+ if self._send_task is None:
- if self.__send_pending_task is None:
+ self._send_task = self._loop.call_soon(self._send_pending)
- self.__send_pending_task = self._loop.call_soon(self._send_pending)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_timer(self) -> None:
# determine earliest timeout
+ if self._state not in [
- if self.__state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
timer_at = self._idle_timeout_at
loss_at = self._loss.get_loss_detection_time()
if loss_at is not None and loss_at < timer_at:
timer_at = loss_at
else:
timer_at = None
# re-arm timer
if self._timer is not None and self._timer_at != timer_at:
self._timer.cancel()
self._timer = None
if self._timer is None and timer_at is not None:
self._timer = self._loop.call_at(timer_at, self._on_timeout)
self._timer_at = timer_at
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
network_path = self._network_paths[0]
+ self._send_task = None
- self.__send_pending_task = None
+ if self._state == QuicConnectionState.DRAINING:
- if self.__state == QuicConnectionState.DRAINING:
return
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
packet_number=self._packet_number,
pad_first_datagram=(
+ self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
- self.is_client and self.__state == QuicConnectionState.FIRSTFLIGHT
),
+ peer_cid=self._peer_cid,
- peer_cid=self.peer_cid,
+ peer_token=self._peer_token,
- peer_token=self.peer_token,
spin_bit=self._spin_bit,
version=self._version,
)
+ if self._close_pending:
- if self.__close:
for epoch, packet_type in (
(tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
):
+ crypto = self._cryptos[epoch]
- crypto = self.cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
+ write_close_frame(builder, **self._close_pending)
- write_close_frame(builder, **self.__close)
builder.end_packet()
+ self._close_pending = None
- self.__close = None
break
else:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch</s>
|
aioquic.connection/QuicConnection._write_application
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<1>:<add> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
<del> if self.cryptos[tls.Epoch.ONE_RTT].send.is_valid():
<2>:<add> crypto = self._cryptos[tls.Epoch.ONE_RTT]
<del> crypto = self.cryptos[tls.Epoch.ONE_RTT]
<5>:<add> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
<del> elif self.cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
<6>:<add> crypto = self._cryptos[tls.Epoch.ZERO_RTT]
<del> crypto = self.cryptos[tls.Epoch.ZERO_RTT]
<10>:<add> space = self._spaces[tls.Epoch.ONE_RTT]
<del> space = self.spaces[tls.Epoch.ONE_RTT]
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, network_path: QuicNetworkPath
) -> None:
<0> crypto_stream_id: Optional[tls.Epoch] = None
<1> if self.cryptos[tls.Epoch.ONE_RTT].send.is_valid():
<2> crypto = self.cryptos[tls.Epoch.ONE_RTT]
<3> crypto_stream_id = tls.Epoch.ONE_RTT
<4> packet_type = PACKET_TYPE_ONE_RTT
<5> elif self.cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
<6> crypto = self.cryptos[tls.Epoch.ZERO_RTT]
<7> packet_type = PACKET_TYPE_ZERO_RTT
<8> else:
<9> return
<10> space = self.spaces[tls.Epoch.ONE_RTT]
<11>
<12> buf = builder.buffer
<13>
<14> while (
<15> builder.flight_bytes + self._loss.bytes_in_flight
<16> < self._loss.congestion_window
<17> ) or self._probe_pending:
<18> # write header
<19> builder.start_packet(packet_type, crypto)
<20>
<21> if self._handshake_complete:
<22> # ACK
<23> if space.ack_required and space.ack_queue:
<24> builder.start_frame(QuicFrameType.ACK)
<25> push_ack_frame(buf, space.ack_queue, 0)
<26> space.ack_required = False
<27>
<28> # PATH CHALLENGE
<29> if (
<30> not network_path.is_validated
<31> and network_path.local_challenge is None
<32> ):
<33> self._logger.info(
<34> "Network path %s sending challenge", network_path.addr
<35> )
<36> network_path.local_challenge = os.urandom(8)
<37> builder.start_frame(QuicFrameType.PATH_CHALLENGE)
<38> push_</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, network_path: QuicNetworkPath
) -> None:
# offset: 1
# PATH RESPONSE
if network_path.remote_challenge is not None:
builder.start_frame(QuicFrameType.PATH_RESPONSE)
push_bytes(buf, network_path.remote_challenge)
network_path.remote_challenge = None
# NEW_CONNECTION_ID
for connection_id in self._host_cids:
if not connection_id.was_sent:
builder.start_frame(
QuicFrameType.NEW_CONNECTION_ID,
self._on_new_connection_id_delivery,
(connection_id,),
)
push_new_connection_id_frame(
buf,
connection_id.sequence_number,
connection_id.cid,
connection_id.stateless_reset_token,
)
connection_id.was_sent = True
self._connection_id_issued_handler(connection_id.cid)
# RETIRE_CONNECTION_ID
while self._retire_connection_ids:
sequence_number = self._retire_connection_ids.pop(0)
builder.start_frame(
QuicFrameType.RETIRE_CONNECTION_ID,
self._on_retire_connection_id_delivery,
(sequence_number,),
)
push_uint_var(buf, sequence_number)
# connection-level limits
self._write_connection_limits(builder=builder, space=space)
# stream-level limits
for stream_id, stream in self.streams.items():
if isinstance(stream_id, int):
self._write_stream_limits(
builder=builder, space=space, stream=stream
)
# PING (user-request)
if self._ping_pending:
self._logger.info("Sending PING in packet %d",</s>
===========below chunk 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, network_path: QuicNetworkPath
) -> None:
# offset: 2
<s> (user-request)
if self._ping_pending:
self._logger.info("Sending PING in packet %d", builder.packet_number)
builder.start_frame(QuicFrameType.PING, self._on_ping_delivery)
self._ping_pending = False
# PING (probe)
if self._probe_pending:
self._logger.info("Sending probe")
builder.start_frame(QuicFrameType.PING)
self._probe_pending = False
for stream_id, stream in self.streams.items():
# CRYPTO
if stream_id == crypto_stream_id:
write_crypto_frame(builder=builder, space=space, stream=stream)
# STREAM
elif isinstance(stream_id, int):
self._remote_max_data_used += write_stream_frame(
builder=builder,
space=space,
stream=stream,
max_offset=min(
stream._send_highest
+ self._remote_max_data
- self._remote_max_data_used,
stream.max_stream_data_remote,
),
)
if not builder.end_packet():
break
===========unchanged ref 0===========
at: aioquic.buffer
push_bytes(buf: Buffer, v: bytes) -> None
push_uint_var(buf: Buffer, value: int) -> None
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int
QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None)
at: aioquic.connection.QuicConnection
_on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None
_on_ping_delivery(delivery: QuicDeliveryState) -> None
_on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None
_write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None
_write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._handshake_complete = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
===========unchanged ref 1===========
self._remote_max_data = 0
self._remote_max_data_used = 0
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
self._ping_pending = False
self._probe_pending = False
self._retire_connection_ids: List[int] = []
self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None
at: aioquic.connection.QuicConnection._handle_crypto_frame
self._handshake_complete = True
at: aioquic.connection.QuicConnection._handle_max_data_frame
self._remote_max_data = max_data
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicConnection._on_ping_delivery
self._ping_pending = True
at: aioquic.connection.QuicConnection._send_probe
self._probe_pending = True
at: aioquic.connection.QuicConnection._update_traffic_key
crypto = self._cryptos[epoch]
at: aioquic.connection.QuicConnection.ping
self._ping_pending = True
at: aioquic.connection.QuicNetworkPath
addr: NetworkAddress
is_validated: bool = False
local_challenge: Optional[bytes] = None
remote_challenge: Optional[bytes] = None
|
aioquic.connection/QuicConnection._write_handshake
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<0>:<add> crypto = self._cryptos[epoch]
<del> crypto = self.cryptos[epoch]
<5>:<add> space = self._spaces[epoch]
<del> space = self.spaces[epoch]
<24>:<add> write_crypto_frame(
<add> builder=builder, space=space, stream=self._streams[epoch]
<del> write_crypto_frame(builder=builder, space=space, stream=self.streams[epoch])
<25>:<add> )
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None:
<0> crypto = self.cryptos[epoch]
<1> if not crypto.send.is_valid():
<2> return
<3>
<4> buf = builder.buffer
<5> space = self.spaces[epoch]
<6>
<7> while (
<8> builder.flight_bytes + self._loss.bytes_in_flight
<9> < self._loss.congestion_window
<10> ):
<11> if epoch == tls.Epoch.INITIAL:
<12> packet_type = PACKET_TYPE_INITIAL
<13> else:
<14> packet_type = PACKET_TYPE_HANDSHAKE
<15> builder.start_packet(packet_type, crypto)
<16>
<17> # ACK
<18> if space.ack_required and space.ack_queue:
<19> builder.start_frame(QuicFrameType.ACK)
<20> push_ack_frame(buf, space.ack_queue, 0)
<21> space.ack_required = False
<22>
<23> # CRYPTO
<24> write_crypto_frame(builder=builder, space=space, stream=self.streams[epoch])
<25>
<26> if not builder.end_packet():
<27> break
<28>
|
===========unchanged ref 0===========
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
push_ack_frame(buf: Buffer, rangeset: RangeSet, delay: int) -> None
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
===========unchanged ref 1===========
at: aioquic.packet_builder.QuicPacketBuilder
start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None
start_packet(packet_type: int, crypto: CryptoPair) -> None
at: aioquic.packet_builder.QuicPacketBuilder.__init__
self.buffer = Buffer(PACKET_MAX_SIZE)
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_state(self, state: QuicConnectionState) -> None:
+ self._logger.info("%s -> %s", self._state, state)
- self._logger.info("%s -> %s", self.__state, state)
+ self._state = state
- self.__state = state
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
+ if self._send_task is None:
- if self.__send_pending_task is None:
+ self._send_task = self._loop.call_soon(self._send_pending)
- self.__send_pending_task = self._loop.call_soon(self._send_pending)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_timer(self) -> None:
# determine earliest timeout
+ if self._state not in [
- if self.__state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
timer_at = self._idle_timeout_at
loss_at = self._loss.get_loss_detection_time()
if loss_at is not None and loss_at < timer_at:
timer_at = loss_at
else:
timer_at = None
# re-arm timer
if self._timer is not None and self._timer_at != timer_at:
self._timer.cancel()
self._timer = None
if self._timer is None and timer_at is not None:
self._timer = self._loop.call_at(timer_at, self._on_timeout)
self._timer_at = timer_at
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _update_traffic_key(
self,
direction: tls.Direction,
epoch: tls.Epoch,
cipher_suite: tls.CipherSuite,
secret: bytes,
) -> None:
"""
Callback which is invoked by the TLS engine when new traffic keys are
available.
"""
+ if self._secrets_log_file is not None:
- if self.secrets_log_file is not None:
label_row = self.is_client == (direction == tls.Direction.DECRYPT)
label = SECRETS_LABELS[label_row][epoch.value]
+ self._secrets_log_file.write(
- self.secrets_log_file.write(
"%s %s %s\n" % (label, self.tls.client_random.hex(), secret.hex())
)
+ self._secrets_log_file.flush()
- self.secrets_log_file.flush()
+ crypto = self._cryptos[epoch]
- crypto = self.cryptos[epoch]
if direction == tls.Direction.ENCRYPT:
crypto.send.setup(cipher_suite, secret)
else:
crypto.recv.setup(cipher_suite, secret)
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
|
tests.test_connection/QuicConnectionTest.test_decryption_error
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<6>:<add> server._cryptos[tls.Epoch.ONE_RTT].send.setup(
<del> server.cryptos[tls.Epoch.ONE_RTT].send.setup(
|
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_decryption_error(self):
<0> with client_and_server() as (client, server):
<1> run(client.wait_connected())
<2> self.assertEqual(client._transport.sent, 4)
<3> self.assertEqual(server._transport.sent, 3)
<4>
<5> # mess with encryption key
<6> server.cryptos[tls.Epoch.ONE_RTT].send.setup(
<7> tls.CipherSuite.AES_128_GCM_SHA256, bytes(48)
<8> )
<9>
<10> # close
<11> server.close(error_code=QuicErrorCode.NO_ERROR)
<12> self.assertEqual(client._transport.sent, 4)
<13> self.assertEqual(server._transport.sent, 4)
<14> run(asyncio.sleep(0))
<15>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: aioquic.tls
Epoch()
CipherSuite(x: Union[str, bytes, bytearray], base: int)
CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: asyncio.tasks
sleep(delay: float, result: _T=..., *, loop: Optional[AbstractEventLoop]=...) -> Future[_T]
at: tests.test_connection
client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})
at: tests.utils
run(coro)
at: unittest.case.TestCase
failureException: Type[BaseException]
longMessage: bool
maxDiff: Optional[int]
_testMethodName: str
_testMethodDoc: str
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_state(self, state: QuicConnectionState) -> None:
+ self._logger.info("%s -> %s", self._state, state)
- self._logger.info("%s -> %s", self.__state, state)
+ self._state = state
- self.__state = state
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
+ if self._send_task is None:
- if self.__send_pending_task is None:
+ self._send_task = self._loop.call_soon(self._send_pending)
- self.__send_pending_task = self._loop.call_soon(self._send_pending)
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 8===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
"""
if self._peer_cid_available:
# retire previous CID
self._retire_connection_ids.append(self._peer_cid_seq)
# assign new CID
connection_id = self._peer_cid_available.pop(0)
self._peer_cid_seq = connection_id.sequence_number
+ self._peer_cid = connection_id.cid
- self.peer_cid = connection_id.cid
self._logger.info(
+ "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
- "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
)
===========changed ref 9===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_timer(self) -> None:
# determine earliest timeout
+ if self._state not in [
- if self.__state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
timer_at = self._idle_timeout_at
loss_at = self._loss.get_loss_detection_time()
if loss_at is not None and loss_at < timer_at:
timer_at = loss_at
else:
timer_at = None
# re-arm timer
if self._timer is not None and self._timer_at != timer_at:
self._timer.cancel()
self._timer = None
if self._timer is None and timer_at is not None:
self._timer = self._loop.call_at(timer_at, self._on_timeout)
self._timer_at = timer_at
|
tests.test_connection/QuicConnectionTest.test_datagram_received_wrong_version
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<4>:<add> host_cid=client._peer_cid,
<del> host_cid=client.peer_cid,
|
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_wrong_version(self):
<0> client, client_transport = create_standalone_client()
<1> self.assertEqual(client_transport.sent, 1)
<2>
<3> builder = QuicPacketBuilder(
<4> host_cid=client.peer_cid,
<5> peer_cid=client.host_cid,
<6> version=0xFF000011, # DRAFT_16
<7> )
<8> crypto = CryptoPair()
<9> crypto.setup_initial(client.host_cid, is_client=False)
<10> builder.start_packet(PACKET_TYPE_INITIAL, crypto)
<11> push_bytes(builder.buffer, bytes(1200))
<12> builder.end_packet()
<13>
<14> for datagram in builder.flush()[0]:
<15> client.datagram_received(datagram, SERVER_ADDR)
<16> self.assertEqual(client_transport.sent, 1)
<17>
|
===========unchanged ref 0===========
at: aioquic.buffer
push_bytes(buf: Buffer, v: bytes) -> None
at: aioquic.connection.QuicConnection.__init__
self.host_cid = self._host_cids[0].cid
self._peer_cid = os.urandom(8)
at: aioquic.connection.QuicConnection._consume_connection_id
self._peer_cid = connection_id.cid
at: aioquic.connection.QuicConnection.datagram_received
self._peer_cid = header.source_cid
self.host_cid = context.host_cid
at: aioquic.crypto
CryptoPair()
at: aioquic.crypto.CryptoPair
setup_initial(cid: bytes, is_client: bool) -> None
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
at: aioquic.packet_builder.QuicPacketBuilder
flush() -> Tuple[List[bytes], List[QuicSentPacket]]
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.packet_builder.QuicPacketBuilder.__init__
self.buffer = Buffer(PACKET_MAX_SIZE)
at: tests.test_connection
SERVER_ADDR = ("2.3.4.5", 4433)
create_standalone_client()
at: tests.test_connection.FakeTransport.sendto
self.sent += 1
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_decryption_error(self):
with client_and_server() as (client, server):
run(client.wait_connected())
self.assertEqual(client._transport.sent, 4)
self.assertEqual(server._transport.sent, 3)
# mess with encryption key
+ server._cryptos[tls.Epoch.ONE_RTT].send.setup(
- server.cryptos[tls.Epoch.ONE_RTT].send.setup(
tls.CipherSuite.AES_128_GCM_SHA256, bytes(48)
)
# close
server.close(error_code=QuicErrorCode.NO_ERROR)
self.assertEqual(client._transport.sent, 4)
self.assertEqual(server._transport.sent, 4)
run(asyncio.sleep(0))
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_state(self, state: QuicConnectionState) -> None:
+ self._logger.info("%s -> %s", self._state, state)
- self._logger.info("%s -> %s", self.__state, state)
+ self._state = state
- self.__state = state
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
+ if self._send_task is None:
- if self.__send_pending_task is None:
+ self._send_task = self._loop.call_soon(self._send_pending)
- self.__send_pending_task = self._loop.call_soon(self._send_pending)
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 8===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 9===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
"""
if self._peer_cid_available:
# retire previous CID
self._retire_connection_ids.append(self._peer_cid_seq)
# assign new CID
connection_id = self._peer_cid_available.pop(0)
self._peer_cid_seq = connection_id.sequence_number
+ self._peer_cid = connection_id.cid
- self.peer_cid = connection_id.cid
self._logger.info(
+ "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
- "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
)
|
tests.test_connection/QuicConnectionTest.test_datagram_received_retry
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<8>:<add> original_destination_cid=client._peer_cid,
<del> original_destination_cid=client.peer_cid,
|
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_retry(self):
<0> client, client_transport = create_standalone_client()
<1> self.assertEqual(client_transport.sent, 1)
<2>
<3> client.datagram_received(
<4> encode_quic_retry(
<5> version=QuicProtocolVersion.DRAFT_20,
<6> source_cid=binascii.unhexlify("85abb547bf28be97"),
<7> destination_cid=client.host_cid,
<8> original_destination_cid=client.peer_cid,
<9> retry_token=bytes(16),
<10> ),
<11> SERVER_ADDR,
<12> )
<13> self.assertEqual(client_transport.sent, 2)
<14>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)
QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes
at: binascii
unhexlify(hexstr: _Ascii, /) -> bytes
at: tests.test_connection
SERVER_ADDR = ("2.3.4.5", 4433)
create_standalone_client()
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_wrong_version(self):
client, client_transport = create_standalone_client()
self.assertEqual(client_transport.sent, 1)
builder = QuicPacketBuilder(
+ host_cid=client._peer_cid,
- host_cid=client.peer_cid,
peer_cid=client.host_cid,
version=0xFF000011, # DRAFT_16
)
crypto = CryptoPair()
crypto.setup_initial(client.host_cid, is_client=False)
builder.start_packet(PACKET_TYPE_INITIAL, crypto)
push_bytes(builder.buffer, bytes(1200))
builder.end_packet()
for datagram in builder.flush()[0]:
client.datagram_received(datagram, SERVER_ADDR)
self.assertEqual(client_transport.sent, 1)
===========changed ref 1===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_decryption_error(self):
with client_and_server() as (client, server):
run(client.wait_connected())
self.assertEqual(client._transport.sent, 4)
self.assertEqual(server._transport.sent, 3)
# mess with encryption key
+ server._cryptos[tls.Epoch.ONE_RTT].send.setup(
- server.cryptos[tls.Epoch.ONE_RTT].send.setup(
tls.CipherSuite.AES_128_GCM_SHA256, bytes(48)
)
# close
server.close(error_code=QuicErrorCode.NO_ERROR)
self.assertEqual(client._transport.sent, 4)
self.assertEqual(server._transport.sent, 4)
run(asyncio.sleep(0))
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_state(self, state: QuicConnectionState) -> None:
+ self._logger.info("%s -> %s", self._state, state)
- self._logger.info("%s -> %s", self.__state, state)
+ self._state = state
- self.__state = state
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
+ if self._send_task is None:
- if self.__send_pending_task is None:
+ self._send_task = self._loop.call_soon(self._send_pending)
- self.__send_pending_task = self._loop.call_soon(self._send_pending)
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 8===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 9===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 10===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _consume_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
"""
if self._peer_cid_available:
# retire previous CID
self._retire_connection_ids.append(self._peer_cid_seq)
# assign new CID
connection_id = self._peer_cid_available.pop(0)
self._peer_cid_seq = connection_id.sequence_number
+ self._peer_cid = connection_id.cid
- self.peer_cid = connection_id.cid
self._logger.info(
+ "Migrating to %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq
- "Migrating to %s (%d)", dump_cid(self.peer_cid), self._peer_cid_seq
)
|
tests.test_connection/QuicConnectionTest.test_datagram_received_retry_wrong_destination_cid
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<8>:<add> original_destination_cid=client._peer_cid,
<del> original_destination_cid=client.peer_cid,
|
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_retry_wrong_destination_cid(self):
<0> client, client_transport = create_standalone_client()
<1> self.assertEqual(client_transport.sent, 1)
<2>
<3> client.datagram_received(
<4> encode_quic_retry(
<5> version=QuicProtocolVersion.DRAFT_20,
<6> source_cid=binascii.unhexlify("85abb547bf28be97"),
<7> destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"),
<8> original_destination_cid=client.peer_cid,
<9> retry_token=bytes(16),
<10> ),
<11> SERVER_ADDR,
<12> )
<13> self.assertEqual(client_transport.sent, 1)
<14>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)
QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes
at: binascii
unhexlify(hexstr: _Ascii, /) -> bytes
at: tests.test_connection
SERVER_ADDR = ("2.3.4.5", 4433)
create_standalone_client()
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_retry(self):
client, client_transport = create_standalone_client()
self.assertEqual(client_transport.sent, 1)
client.datagram_received(
encode_quic_retry(
version=QuicProtocolVersion.DRAFT_20,
source_cid=binascii.unhexlify("85abb547bf28be97"),
destination_cid=client.host_cid,
+ original_destination_cid=client._peer_cid,
- original_destination_cid=client.peer_cid,
retry_token=bytes(16),
),
SERVER_ADDR,
)
self.assertEqual(client_transport.sent, 2)
===========changed ref 1===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_wrong_version(self):
client, client_transport = create_standalone_client()
self.assertEqual(client_transport.sent, 1)
builder = QuicPacketBuilder(
+ host_cid=client._peer_cid,
- host_cid=client.peer_cid,
peer_cid=client.host_cid,
version=0xFF000011, # DRAFT_16
)
crypto = CryptoPair()
crypto.setup_initial(client.host_cid, is_client=False)
builder.start_packet(PACKET_TYPE_INITIAL, crypto)
push_bytes(builder.buffer, bytes(1200))
builder.end_packet()
for datagram in builder.flush()[0]:
client.datagram_received(datagram, SERVER_ADDR)
self.assertEqual(client_transport.sent, 1)
===========changed ref 2===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_decryption_error(self):
with client_and_server() as (client, server):
run(client.wait_connected())
self.assertEqual(client._transport.sent, 4)
self.assertEqual(server._transport.sent, 3)
# mess with encryption key
+ server._cryptos[tls.Epoch.ONE_RTT].send.setup(
- server.cryptos[tls.Epoch.ONE_RTT].send.setup(
tls.CipherSuite.AES_128_GCM_SHA256, bytes(48)
)
# close
server.close(error_code=QuicErrorCode.NO_ERROR)
self.assertEqual(client._transport.sent, 4)
self.assertEqual(server._transport.sent, 4)
run(asyncio.sleep(0))
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_state(self, state: QuicConnectionState) -> None:
+ self._logger.info("%s -> %s", self._state, state)
- self._logger.info("%s -> %s", self.__state, state)
+ self._state = state
- self.__state = state
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
+ if self._send_task is None:
- if self.__send_pending_task is None:
+ self._send_task = self._loop.call_soon(self._send_pending)
- self.__send_pending_task = self._loop.call_soon(self._send_pending)
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 8===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 9===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 10===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
|
tests.test_connection/QuicConnectionTest.test_version_negotiation_fail
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<6>:<add> source_cid=client._peer_cid,
<del> source_cid=client.peer_cid,
|
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_version_negotiation_fail(self):
<0> client, client_transport = create_standalone_client()
<1> self.assertEqual(client_transport.sent, 1)
<2>
<3> # no common version, no retry
<4> client.datagram_received(
<5> encode_quic_version_negotiation(
<6> source_cid=client.peer_cid,
<7> destination_cid=client.host_cid,
<8> supported_versions=[0xFF000011], # DRAFT_16
<9> ),
<10> SERVER_ADDR,
<11> )
<12> self.assertEqual(client_transport.sent, 1)
<13>
|
===========unchanged ref 0===========
at: aioquic.packet
encode_quic_version_negotiation(source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion]) -> bytes
at: tests.test_connection
SERVER_ADDR = ("2.3.4.5", 4433)
create_standalone_client()
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_retry_wrong_destination_cid(self):
client, client_transport = create_standalone_client()
self.assertEqual(client_transport.sent, 1)
client.datagram_received(
encode_quic_retry(
version=QuicProtocolVersion.DRAFT_20,
source_cid=binascii.unhexlify("85abb547bf28be97"),
destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"),
+ original_destination_cid=client._peer_cid,
- original_destination_cid=client.peer_cid,
retry_token=bytes(16),
),
SERVER_ADDR,
)
self.assertEqual(client_transport.sent, 1)
===========changed ref 1===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_retry(self):
client, client_transport = create_standalone_client()
self.assertEqual(client_transport.sent, 1)
client.datagram_received(
encode_quic_retry(
version=QuicProtocolVersion.DRAFT_20,
source_cid=binascii.unhexlify("85abb547bf28be97"),
destination_cid=client.host_cid,
+ original_destination_cid=client._peer_cid,
- original_destination_cid=client.peer_cid,
retry_token=bytes(16),
),
SERVER_ADDR,
)
self.assertEqual(client_transport.sent, 2)
===========changed ref 2===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_wrong_version(self):
client, client_transport = create_standalone_client()
self.assertEqual(client_transport.sent, 1)
builder = QuicPacketBuilder(
+ host_cid=client._peer_cid,
- host_cid=client.peer_cid,
peer_cid=client.host_cid,
version=0xFF000011, # DRAFT_16
)
crypto = CryptoPair()
crypto.setup_initial(client.host_cid, is_client=False)
builder.start_packet(PACKET_TYPE_INITIAL, crypto)
push_bytes(builder.buffer, bytes(1200))
builder.end_packet()
for datagram in builder.flush()[0]:
client.datagram_received(datagram, SERVER_ADDR)
self.assertEqual(client_transport.sent, 1)
===========changed ref 3===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_decryption_error(self):
with client_and_server() as (client, server):
run(client.wait_connected())
self.assertEqual(client._transport.sent, 4)
self.assertEqual(server._transport.sent, 3)
# mess with encryption key
+ server._cryptos[tls.Epoch.ONE_RTT].send.setup(
- server.cryptos[tls.Epoch.ONE_RTT].send.setup(
tls.CipherSuite.AES_128_GCM_SHA256, bytes(48)
)
# close
server.close(error_code=QuicErrorCode.NO_ERROR)
self.assertEqual(client._transport.sent, 4)
self.assertEqual(server._transport.sent, 4)
run(asyncio.sleep(0))
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_state(self, state: QuicConnectionState) -> None:
+ self._logger.info("%s -> %s", self._state, state)
- self._logger.info("%s -> %s", self.__state, state)
+ self._state = state
- self.__state = state
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
+ if self._send_task is None:
- if self.__send_pending_task is None:
+ self._send_task = self._loop.call_soon(self._send_pending)
- self.__send_pending_task = self._loop.call_soon(self._send_pending)
===========changed ref 8===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 9===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 10===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 11===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
if self._loop.time() >= self._idle_timeout_at:
self._logger.info("Idle timeout expired")
self._set_state(QuicConnectionState.DRAINING)
self.connection_lost(None)
+ for epoch in self._spaces.keys():
- for epoch in self.spaces.keys():
self._discard_epoch(epoch)
return
# loss detection timeout
+ self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
|
tests.test_connection/QuicConnectionTest.test_version_negotiation_ok
|
Modified
|
aiortc~aioquic
|
ad4e914d4b4b60f0dee8df2d062f7bb5af5cb176
|
[connection] mark more attributes as private
|
<6>:<add> source_cid=client._peer_cid,
<del> source_cid=client.peer_cid,
|
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_version_negotiation_ok(self):
<0> client, client_transport = create_standalone_client()
<1> self.assertEqual(client_transport.sent, 1)
<2>
<3> # found a common version, retry
<4> client.datagram_received(
<5> encode_quic_version_negotiation(
<6> source_cid=client.peer_cid,
<7> destination_cid=client.host_cid,
<8> supported_versions=[QuicProtocolVersion.DRAFT_19],
<9> ),
<10> SERVER_ADDR,
<11> )
<12> self.assertEqual(client_transport.sent, 2)
<13>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)
QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
encode_quic_version_negotiation(source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion]) -> bytes
at: tests.test_connection
SERVER_ADDR = ("2.3.4.5", 4433)
create_standalone_client()
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_version_negotiation_fail(self):
client, client_transport = create_standalone_client()
self.assertEqual(client_transport.sent, 1)
# no common version, no retry
client.datagram_received(
encode_quic_version_negotiation(
+ source_cid=client._peer_cid,
- source_cid=client.peer_cid,
destination_cid=client.host_cid,
supported_versions=[0xFF000011], # DRAFT_16
),
SERVER_ADDR,
)
self.assertEqual(client_transport.sent, 1)
===========changed ref 1===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_retry_wrong_destination_cid(self):
client, client_transport = create_standalone_client()
self.assertEqual(client_transport.sent, 1)
client.datagram_received(
encode_quic_retry(
version=QuicProtocolVersion.DRAFT_20,
source_cid=binascii.unhexlify("85abb547bf28be97"),
destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"),
+ original_destination_cid=client._peer_cid,
- original_destination_cid=client.peer_cid,
retry_token=bytes(16),
),
SERVER_ADDR,
)
self.assertEqual(client_transport.sent, 1)
===========changed ref 2===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_retry(self):
client, client_transport = create_standalone_client()
self.assertEqual(client_transport.sent, 1)
client.datagram_received(
encode_quic_retry(
version=QuicProtocolVersion.DRAFT_20,
source_cid=binascii.unhexlify("85abb547bf28be97"),
destination_cid=client.host_cid,
+ original_destination_cid=client._peer_cid,
- original_destination_cid=client.peer_cid,
retry_token=bytes(16),
),
SERVER_ADDR,
)
self.assertEqual(client_transport.sent, 2)
===========changed ref 3===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_datagram_received_wrong_version(self):
client, client_transport = create_standalone_client()
self.assertEqual(client_transport.sent, 1)
builder = QuicPacketBuilder(
+ host_cid=client._peer_cid,
- host_cid=client.peer_cid,
peer_cid=client.host_cid,
version=0xFF000011, # DRAFT_16
)
crypto = CryptoPair()
crypto.setup_initial(client.host_cid, is_client=False)
builder.start_packet(PACKET_TYPE_INITIAL, crypto)
push_bytes(builder.buffer, bytes(1200))
builder.end_packet()
for datagram in builder.flush()[0]:
client.datagram_received(datagram, SERVER_ADDR)
self.assertEqual(client_transport.sent, 1)
===========changed ref 4===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_decryption_error(self):
with client_and_server() as (client, server):
run(client.wait_connected())
self.assertEqual(client._transport.sent, 4)
self.assertEqual(server._transport.sent, 3)
# mess with encryption key
+ server._cryptos[tls.Epoch.ONE_RTT].send.setup(
- server.cryptos[tls.Epoch.ONE_RTT].send.setup(
tls.CipherSuite.AES_128_GCM_SHA256, bytes(48)
)
# close
server.close(error_code=QuicErrorCode.NO_ERROR)
self.assertEqual(client._transport.sent, 4)
self.assertEqual(server._transport.sent, 4)
run(asyncio.sleep(0))
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ for stream in self._streams.values():
- for stream in self.streams.values():
stream.connection_lost(exc)
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
for epoch, buf in self.send_buffer.items():
+ self._streams[epoch].write(buf.data)
- self.streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_state(self, state: QuicConnectionState) -> None:
+ self._logger.info("%s -> %s", self._state, state)
- self._logger.info("%s -> %s", self.__state, state)
+ self._state = state
- self.__state = state
===========changed ref 8===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_soon(self) -> None:
+ if self._send_task is None:
- if self.__send_pending_task is None:
+ self._send_task = self._loop.call_soon(self._send_pending)
- self.__send_pending_task = self._loop.call_soon(self._send_pending)
===========changed ref 9===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _discard_epoch(self, epoch: tls.Epoch) -> None:
self._logger.debug("Discarding epoch %s", epoch)
+ self._cryptos[epoch].teardown()
- self.cryptos[epoch].teardown()
+ self._loss.discard_space(self._spaces[epoch])
- self._loss.discard_space(self.spaces[epoch])
===========changed ref 10===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def request_key_update(self) -> None:
"""
Request an update of the encryption keys.
"""
assert self._handshake_complete, "cannot change key before handshake completes"
+ self._cryptos[tls.Epoch.ONE_RTT].update_key()
- self.cryptos[tls.Epoch.ONE_RTT].update_key()
===========changed ref 11===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
+ self._initialize(self._peer_cid)
- self._initialize(self.peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
|
aioquic.connection/QuicConnection.close
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<12>:<del> self._set_state(QuicConnectionState.CLOSING)
<13>:<del> self.connection_lost(
<14>:<del> maybe_connection_error(
<15>:<del> error_code=error_code,
<16>:<del> frame_type=frame_type,
<17>:<del> reason_phrase=reason_phrase,
<18>:<del> )
<19>:<del> )
<21>:<del> for epoch in self._spaces.keys():
<22>:<del> self._discard_epoch(epoch)
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
<0> """
<1> Close the connection.
<2> """
<3> if self._state not in [
<4> QuicConnectionState.CLOSING,
<5> QuicConnectionState.DRAINING,
<6> ]:
<7> self._close_pending = {
<8> "error_code": error_code,
<9> "frame_type": frame_type,
<10> "reason_phrase": reason_phrase,
<11> }
<12> self._set_state(QuicConnectionState.CLOSING)
<13> self.connection_lost(
<14> maybe_connection_error(
<15> error_code=error_code,
<16> frame_type=frame_type,
<17> reason_phrase=reason_phrase,
<18> )
<19> )
<20> self._send_pending()
<21> for epoch in self._spaces.keys():
<22> self._discard_epoch(epoch)
<23>
|
===========unchanged ref 0===========
at: aioquic.connection
NetworkAddress = Any
QuicConnectionState()
QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None)
at: aioquic.connection.QuicConnection
supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20]
_send_pending(self) -> None
_send_pending() -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._connect_called = False
self._network_paths: List[QuicNetworkPath] = []
self._state = QuicConnectionState.FIRSTFLIGHT
self._version: Optional[int] = None
self._close_pending: Optional[Dict] = None
at: aioquic.connection.QuicConnection._send_pending
self._close_pending = None
at: aioquic.connection.QuicConnection._set_state
self._state = state
at: aioquic.connection.QuicConnection.datagram_received
self._version = QuicProtocolVersion(header.version)
self._version = QuicProtocolVersion(max(common))
self._network_paths = [network_path]
at: aioquic.connection.QuicNetworkPath
addr: NetworkAddress
bytes_received: int = 0
bytes_sent: int = 0
is_validated: bool = False
local_challenge: Optional[bytes] = None
remote_challenge: Optional[bytes] = None
===========changed ref 0===========
# module: aioquic.connection
- def maybe_connection_error(
- error_code: int, frame_type: Optional[int], reason_phrase: str
- ) -> Optional[QuicConnectionError]:
- if error_code != QuicErrorCode.NO_ERROR:
- return QuicConnectionError(
- error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
- )
- else:
- return None
-
===========changed ref 1===========
<s>[bytes] = None,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
if is_client:
assert (
original_connection_id is None
), "Cannot set original_connection_id for a client"
else:
assert certificate is not None, "SSL certificate is required for a server"
assert private_key is not None, "SSL private key is required for a server"
+ loop = asyncio.get_event_loop()
self.is_client = is_client
if supported_versions is not None:
self.supported_versions = supported_versions
# counters for debugging
self._stateless_retry_count = 0
self._version_negotiation_count = 0
# TLS configuration
self._alpn_protocols = alpn_protocols
self._certificate = certificate
self._private_key = private_key
self._secrets_log_file = secrets_log_file
self._server_name = server_name
+ self._close_at: Optional[float] = None
+ self._close_exception: Optional[Exception] = None
+ self._closed = asyncio.Event()
self._connect_called = False
+ self._connected_waiter = loop.create_future()
- self._connected = asyncio.Event()
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._handshake_complete = False
self._handshake_confirmed = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=</s>
===========changed ref 2===========
<s>,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
# offset: 1
<s>Id(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self.host_cid = self._host_cids[0].cid
self._host_cid_seq = 1
- self._idle_timeout_at: Optional[float] = None
self._local_idle_timeout = 60.0 # seconds
self._local_max_data = MAX_DATA_WINDOW
self._local_max_data_sent = MAX_DATA_WINDOW
self._local_max_data_used = 0
self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW
self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW
self._local_max_stream_data_uni = MAX_DATA_WINDOW
self._local_max_streams_bidi = 128
self._local_max_streams_uni = 128
+ self._loop = loop
- self._loop = asyncio.get_event_loop()
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._loss_detection_at: Optional[float] = None
self._network_paths</s>
|
aioquic.connection/QuicConnection.wait_connected
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<3>:<add> await asyncio.shield(self._connected_waiter)
<del> await self._connected.wait()
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def wait_connected(self) -> None:
<0> """
<1> Wait for the TLS handshake to complete.
<2> """
<3> await self._connected.wait()
<4>
|
===========unchanged ref 0===========
at: _asyncio.Future
done()
set_exception(exception, /)
at: aioquic.connection.QuicConnection.__init__
self._closed = asyncio.Event()
self._connected_waiter = loop.create_future()
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
at: aioquic.stream.QuicStream
connection_lost(exc: Exception) -> None
at: asyncio.futures.Future
_state = _PENDING
_result = None
_exception = None
_loop = None
_source_traceback = None
_cancel_message = None
_cancelled_exc = None
_asyncio_future_blocking = False
__log_traceback = False
__class_getitem__ = classmethod(GenericAlias)
done() -> bool
set_exception(exception: Union[type, BaseException], /) -> None
__iter__ = __await__ # make compatible with 'yield from'.
at: asyncio.locks.Event
set() -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def wait_closed(self) -> None:
+ """
+ Wait for the connection to be closed.
+ """
+ await self._closed.wait()
+
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
if self._state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
- self._set_state(QuicConnectionState.CLOSING)
- self.connection_lost(
- maybe_connection_error(
- error_code=error_code,
- frame_type=frame_type,
- reason_phrase=reason_phrase,
- )
- )
self._send_pending()
- for epoch in self._spaces.keys():
- self._discard_epoch(epoch)
===========changed ref 2===========
# module: aioquic.connection
- def maybe_connection_error(
- error_code: int, frame_type: Optional[int], reason_phrase: str
- ) -> Optional[QuicConnectionError]:
- if error_code != QuicErrorCode.NO_ERROR:
- return QuicConnectionError(
- error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
- )
- else:
- return None
-
===========changed ref 3===========
<s>[bytes] = None,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
if is_client:
assert (
original_connection_id is None
), "Cannot set original_connection_id for a client"
else:
assert certificate is not None, "SSL certificate is required for a server"
assert private_key is not None, "SSL private key is required for a server"
+ loop = asyncio.get_event_loop()
self.is_client = is_client
if supported_versions is not None:
self.supported_versions = supported_versions
# counters for debugging
self._stateless_retry_count = 0
self._version_negotiation_count = 0
# TLS configuration
self._alpn_protocols = alpn_protocols
self._certificate = certificate
self._private_key = private_key
self._secrets_log_file = secrets_log_file
self._server_name = server_name
+ self._close_at: Optional[float] = None
+ self._close_exception: Optional[Exception] = None
+ self._closed = asyncio.Event()
self._connect_called = False
+ self._connected_waiter = loop.create_future()
- self._connected = asyncio.Event()
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._handshake_complete = False
self._handshake_confirmed = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=</s>
===========changed ref 4===========
<s>,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
# offset: 1
<s>Id(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self.host_cid = self._host_cids[0].cid
self._host_cid_seq = 1
- self._idle_timeout_at: Optional[float] = None
self._local_idle_timeout = 60.0 # seconds
self._local_max_data = MAX_DATA_WINDOW
self._local_max_data_sent = MAX_DATA_WINDOW
self._local_max_data_used = 0
self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW
self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW
self._local_max_stream_data_uni = MAX_DATA_WINDOW
self._local_max_streams_bidi = 128
self._local_max_streams_uni = 128
+ self._loop = loop
- self._loop = asyncio.get_event_loop()
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._loss_detection_at: Optional[float] = None
self._network_paths</s>
|
aioquic.connection/QuicConnection.connection_lost
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<0>:<add> self._logger.info("Connection closed")
<add> for epoch in self._spaces.keys():
<add> self._discard_epoch(epoch)
<2>:<add> if not self._connected_waiter.done():
<add> self._connected_waiter.set_exception(exc)
<add> self._closed.set()
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
<0> for stream in self._streams.values():
<1> stream.connection_lost(exc)
<2>
|
===========unchanged ref 0===========
at: aioquic.connection
NetworkAddress = Any
at: aioquic.connection.QuicConnection.__init__
self._transport: Optional[asyncio.DatagramTransport] = None
at: asyncio.protocols.BaseProtocol
__slots__ = ()
connection_made(self, transport: transports.BaseTransport) -> None
at: asyncio.protocols.DatagramProtocol
__slots__ = ()
datagram_received(self, data: bytes, addr: Tuple[str, int]) -> None
at: asyncio.transports
BaseTransport(extra: Optional[Mapping[Any, Any]]=...)
DatagramTransport(extra: Optional[Mapping[Any, Any]]=...)
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
Text = str
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def wait_connected(self) -> None:
"""
Wait for the TLS handshake to complete.
"""
+ await asyncio.shield(self._connected_waiter)
- await self._connected.wait()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def wait_closed(self) -> None:
+ """
+ Wait for the connection to be closed.
+ """
+ await self._closed.wait()
+
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
if self._state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
- self._set_state(QuicConnectionState.CLOSING)
- self.connection_lost(
- maybe_connection_error(
- error_code=error_code,
- frame_type=frame_type,
- reason_phrase=reason_phrase,
- )
- )
self._send_pending()
- for epoch in self._spaces.keys():
- self._discard_epoch(epoch)
===========changed ref 3===========
# module: aioquic.connection
- def maybe_connection_error(
- error_code: int, frame_type: Optional[int], reason_phrase: str
- ) -> Optional[QuicConnectionError]:
- if error_code != QuicErrorCode.NO_ERROR:
- return QuicConnectionError(
- error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
- )
- else:
- return None
-
===========changed ref 4===========
<s>[bytes] = None,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
if is_client:
assert (
original_connection_id is None
), "Cannot set original_connection_id for a client"
else:
assert certificate is not None, "SSL certificate is required for a server"
assert private_key is not None, "SSL private key is required for a server"
+ loop = asyncio.get_event_loop()
self.is_client = is_client
if supported_versions is not None:
self.supported_versions = supported_versions
# counters for debugging
self._stateless_retry_count = 0
self._version_negotiation_count = 0
# TLS configuration
self._alpn_protocols = alpn_protocols
self._certificate = certificate
self._private_key = private_key
self._secrets_log_file = secrets_log_file
self._server_name = server_name
+ self._close_at: Optional[float] = None
+ self._close_exception: Optional[Exception] = None
+ self._closed = asyncio.Event()
self._connect_called = False
+ self._connected_waiter = loop.create_future()
- self._connected = asyncio.Event()
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._handshake_complete = False
self._handshake_confirmed = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=</s>
===========changed ref 5===========
<s>,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
# offset: 1
<s>Id(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self.host_cid = self._host_cids[0].cid
self._host_cid_seq = 1
- self._idle_timeout_at: Optional[float] = None
self._local_idle_timeout = 60.0 # seconds
self._local_max_data = MAX_DATA_WINDOW
self._local_max_data_sent = MAX_DATA_WINDOW
self._local_max_data_used = 0
self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW
self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW
self._local_max_stream_data_uni = MAX_DATA_WINDOW
self._local_max_streams_bidi = 128
self._local_max_streams_uni = 128
+ self._loop = loop
- self._loop = asyncio.get_event_loop()
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._loss_detection_at: Optional[float] = None
self._network_paths</s>
|
aioquic.connection/QuicConnection._connect
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<5>:<add> self._close_at = self._loop.time() + self._local_idle_timeout
<del> self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
<0> """
<1> Start the client handshake.
<2> """
<3> assert self.is_client
<4>
<5> self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
<6> self._initialize(self._peer_cid)
<7>
<8> self.tls.handle_message(b"", self.send_buffer)
<9> self._push_crypto_data()
<10> self._send_pending()
<11>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionState()
at: aioquic.connection.QuicConnection
_set_state(self, state: QuicConnectionState) -> None
_set_state(state: QuicConnectionState) -> None
at: aioquic.connection.QuicConnection.__init__
self._close_at: Optional[float] = None
self._loop = loop
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
at: aioquic.connection.QuicConnection._connect
self._close_at = self._loop.time() + self._local_idle_timeout
at: aioquic.connection.QuicConnection.datagram_received
self._close_at = now + self._local_idle_timeout
at: aioquic.recovery.QuicPacketRecovery
get_probe_timeout() -> float
at: asyncio.events.AbstractEventLoop
time() -> float
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def wait_connected(self) -> None:
"""
Wait for the TLS handshake to complete.
"""
+ await asyncio.shield(self._connected_waiter)
- await self._connected.wait()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def wait_closed(self) -> None:
+ """
+ Wait for the connection to be closed.
+ """
+ await self._closed.wait()
+
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ self._logger.info("Connection closed")
+ for epoch in self._spaces.keys():
+ self._discard_epoch(epoch)
for stream in self._streams.values():
stream.connection_lost(exc)
+ if not self._connected_waiter.done():
+ self._connected_waiter.set_exception(exc)
+ self._closed.set()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
if self._state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
- self._set_state(QuicConnectionState.CLOSING)
- self.connection_lost(
- maybe_connection_error(
- error_code=error_code,
- frame_type=frame_type,
- reason_phrase=reason_phrase,
- )
- )
self._send_pending()
- for epoch in self._spaces.keys():
- self._discard_epoch(epoch)
===========changed ref 4===========
# module: aioquic.connection
- def maybe_connection_error(
- error_code: int, frame_type: Optional[int], reason_phrase: str
- ) -> Optional[QuicConnectionError]:
- if error_code != QuicErrorCode.NO_ERROR:
- return QuicConnectionError(
- error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
- )
- else:
- return None
-
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
"""
Handle an incoming datagram.
"""
# stop handling packets when closing
if self._state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]:
return
data = cast(bytes, data)
buf = Buffer(data=data)
now = self._loop.time()
while not buf.eof():
start_off = buf.tell()
header = pull_quic_header(buf, host_cid_length=len(self.host_cid))
# check destination CID matches
destination_cid_seq: Optional[int] = None
for connection_id in self._host_cids:
if header.destination_cid == connection_id.cid:
destination_cid_seq = connection_id.sequence_number
break
if self.is_client and destination_cid_seq is None:
return
# check protocol version
if self.is_client and header.version == QuicProtocolVersion.NEGOTIATION:
# version negotiation
versions = []
while not buf.eof():
versions.append(pull_uint32(buf))
common = set(self.supported_versions).intersection(versions)
if not common:
self._logger.error("Could not find a common protocol version")
+ self.connection_lost(
+ QuicConnectionError(
+ error_code=QuicErrorCode.INTERNAL_ERROR,
+ frame_type=None,
+ reason_phrase="Could not find a common protocol version",
+ )
+ )
return
self._version = QuicProtocolVersion(max(common))
self._version_negotiation_count += 1
self._logger.info("Retrying with %s", self._version)
self._connect()
return
elif (
header.version is not None
and header.version not in self.supported_versions
</s>
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
# offset: 1
<s>()
return
elif (
header.version is not None
and header.version not in self.supported_versions
):
# unsupported version
return
if self.is_client and header.packet_type == PACKET_TYPE_RETRY:
# stateless retry
if (
header.destination_cid == self.host_cid
and header.original_destination_cid == self._peer_cid
and not self._stateless_retry_count
):
self._original_connection_id = self._peer_cid
self._peer_cid = header.source_cid
self._peer_token = header.token
self._stateless_retry_count += 1
self._logger.info("Performing stateless retry")
self._connect()
return
network_path = self._find_network_path(addr)
# server initialization
if not self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT:
assert (
header.packet_type == PACKET_TYPE_INITIAL
), "first packet must be INITIAL"
self._network_paths = [network_path]
self._version = QuicProtocolVersion(header.version)
self._initialize(header.destination_cid)
# determine crypto and packet space
epoch = get_epoch(header.packet_type)
crypto = self._cryptos[epoch]
if epoch == tls.Epoch.ZERO_RTT:
space = self._spaces[tls.Epoch.ONE_RTT]
else:
space = self._spaces[epoch]
# decrypt packet
encrypted_off = buf.tell() - start_off
end_off = buf.tell() + header.rest_length
</s>
|
aioquic.connection/QuicConnection._handle_connection_close_frame
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<11>:<del> self._set_state(QuicConnectionState.DRAINING)
<12>:<del> self.connection_lost(
<13>:<del> maybe_connection_error(
<14>:<add> if error_code != QuicErrorCode.NO_ERROR:
<add> self._close_exception = QuicConnectionError(
<18>:<add> self._close(is_initiator=False)
<del> )
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a CONNECTION_CLOSE frame.
<2> """
<3> if frame_type == QuicFrameType.TRANSPORT_CLOSE:
<4> error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
<5> else:
<6> error_code, reason_phrase = pull_application_close_frame(buf)
<7> frame_type = None
<8> self._logger.info(
<9> "Connection close code 0x%X, reason %s", error_code, reason_phrase
<10> )
<11> self._set_state(QuicConnectionState.DRAINING)
<12> self.connection_lost(
<13> maybe_connection_error(
<14> error_code=error_code,
<15> frame_type=frame_type,
<16> reason_phrase=reason_phrase,
<17> )
<18> )
<19>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.connection
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)
at: aioquic.connection.QuicConnection
_discard_epoch(epoch: tls.Epoch) -> None
at: aioquic.connection.QuicConnection.__init__
self._handshake_complete = False
self._handshake_confirmed = False
at: aioquic.connection.QuicConnection._handle_crypto_frame
self._handshake_complete = True
at: aioquic.connection.QuicReceiveContext
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
time: float
at: aioquic.packet
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]
pull_application_close_frame(buf: Buffer) -> Tuple[int, str]
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _close(self, is_initiator: bool) -> None:
+ """
+ Start the close procedure.
+ """
+ self._close_at = self._loop.time() + 3 * self._loss.get_probe_timeout()
+ if is_initiator:
+ self._set_state(QuicConnectionState.CLOSING)
+ else:
+ self._set_state(QuicConnectionState.DRAINING)
+
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
+ self._close_at = self._loop.time() + self._local_idle_timeout
- self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
self._initialize(self._peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def wait_connected(self) -> None:
"""
Wait for the TLS handshake to complete.
"""
+ await asyncio.shield(self._connected_waiter)
- await self._connected.wait()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def wait_closed(self) -> None:
+ """
+ Wait for the connection to be closed.
+ """
+ await self._closed.wait()
+
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ self._logger.info("Connection closed")
+ for epoch in self._spaces.keys():
+ self._discard_epoch(epoch)
for stream in self._streams.values():
stream.connection_lost(exc)
+ if not self._connected_waiter.done():
+ self._connected_waiter.set_exception(exc)
+ self._closed.set()
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
if self._state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
- self._set_state(QuicConnectionState.CLOSING)
- self.connection_lost(
- maybe_connection_error(
- error_code=error_code,
- frame_type=frame_type,
- reason_phrase=reason_phrase,
- )
- )
self._send_pending()
- for epoch in self._spaces.keys():
- self._discard_epoch(epoch)
===========changed ref 6===========
# module: aioquic.connection
- def maybe_connection_error(
- error_code: int, frame_type: Optional[int], reason_phrase: str
- ) -> Optional[QuicConnectionError]:
- if error_code != QuicErrorCode.NO_ERROR:
- return QuicConnectionError(
- error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
- )
- else:
- return None
-
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
"""
Handle an incoming datagram.
"""
# stop handling packets when closing
if self._state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]:
return
data = cast(bytes, data)
buf = Buffer(data=data)
now = self._loop.time()
while not buf.eof():
start_off = buf.tell()
header = pull_quic_header(buf, host_cid_length=len(self.host_cid))
# check destination CID matches
destination_cid_seq: Optional[int] = None
for connection_id in self._host_cids:
if header.destination_cid == connection_id.cid:
destination_cid_seq = connection_id.sequence_number
break
if self.is_client and destination_cid_seq is None:
return
# check protocol version
if self.is_client and header.version == QuicProtocolVersion.NEGOTIATION:
# version negotiation
versions = []
while not buf.eof():
versions.append(pull_uint32(buf))
common = set(self.supported_versions).intersection(versions)
if not common:
self._logger.error("Could not find a common protocol version")
+ self.connection_lost(
+ QuicConnectionError(
+ error_code=QuicErrorCode.INTERNAL_ERROR,
+ frame_type=None,
+ reason_phrase="Could not find a common protocol version",
+ )
+ )
return
self._version = QuicProtocolVersion(max(common))
self._version_negotiation_count += 1
self._logger.info("Retrying with %s", self._version)
self._connect()
return
elif (
header.version is not None
and header.version not in self.supported_versions
</s>
|
aioquic.connection/QuicConnection._handle_crypto_frame
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<41>:<del> if not self._connected.is_set():
<42>:<add> self._connected_waiter.set_result(None)
<del> self._connected.
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a CRYPTO frame.
<2> """
<3> stream = self._streams[context.epoch]
<4> stream.add_frame(pull_crypto_frame(buf))
<5> data = stream.pull_data()
<6> if data:
<7> # pass data to TLS layer
<8> try:
<9> self.tls.handle_message(data, self.send_buffer)
<10> self._push_crypto_data()
<11> except tls.Alert as exc:
<12> raise QuicConnectionError(
<13> error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
<14> frame_type=QuicFrameType.CRYPTO,
<15> reason_phrase=str(exc),
<16> )
<17>
<18> # parse transport parameters
<19> if (
<20> not self._parameters_received
<21> and self.tls.received_extensions is not None
<22> ):
<23> for ext_type, ext_data in self.tls.received_extensions:
<24> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
<25> self._parse_transport_parameters(ext_data)
<26> self._parameters_received = True
<27> break
<28> assert (
<29> self._parameters_received
<30> ), "No QUIC transport parameters received"
<31> self._logger.info("ALPN negotiated protocol %s", self.alpn_protocol)
<32>
<33> # update current epoch
<34> if not self._handshake_complete and self.tls.state in [
<35> tls.State.CLIENT_POST_HANDSHAKE,
<36> tls.State.SERVER_POST_HANDSHAKE,
<37> ]:
<38> self._handshake_complete = True
<39> self._replenish_connection_ids()
<40> # wakeup waiter
<41> if not self._connected.is_set():
<42> self._connected.</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
# offset: 1
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.connection
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)
at: aioquic.connection.QuicConnection
_close(self, is_initiator: bool) -> None
_close(is_initiator: bool) -> None
_push_crypto_data() -> None
_push_crypto_data(self) -> None
_parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None
at: aioquic.connection.QuicConnection.__init__
self._close_exception: Optional[Exception] = None
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._parameters_received = False
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
at: aioquic.connection.QuicConnection._handle_connection_close_frame
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
error_code, reason_phrase = pull_application_close_frame(buf)
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
frame_type = None
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
error_code, reason_phrase = pull_application_close_frame(buf)
at: aioquic.connection.QuicConnection._initialize
self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
===========unchanged ref 1===========
self.send_buffer = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
at: aioquic.connection.QuicConnection.datagram_received
self._close_exception = exc
at: aioquic.connection.QuicReceiveContext
epoch: tls.Epoch
at: aioquic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
pull_crypto_frame(buf: Buffer) -> QuicStreamFrame
at: aioquic.stream.QuicStream
add_frame(frame: QuicStreamFrame) -> None
pull_data() -> bytes
at: aioquic.tls
Alert(*args: object)
ExtensionType(x: Union[str, bytes, bytearray], base: int)
ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: aioquic.tls.Alert
description: AlertDescription
at: aioquic.tls.Context
handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None
at: aioquic.tls.Context.__init__
self.received_extensions: Optional[List[Extension]] = None
at: aioquic.tls.Context._client_handle_encrypted_extensions
self.received_extensions = encrypted_extensions.other_extensions
at: aioquic.tls.Context._server_handle_hello
self.received_extensions = peer_hello.other_extensions
at: logging.LoggerAdapter
logger: Logger
extra: Mapping[str, Any]
===========unchanged ref 2===========
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _close(self, is_initiator: bool) -> None:
+ """
+ Start the close procedure.
+ """
+ self._close_at = self._loop.time() + 3 * self._loss.get_probe_timeout()
+ if is_initiator:
+ self._set_state(QuicConnectionState.CLOSING)
+ else:
+ self._set_state(QuicConnectionState.DRAINING)
+
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CONNECTION_CLOSE frame.
"""
if frame_type == QuicFrameType.TRANSPORT_CLOSE:
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
else:
error_code, reason_phrase = pull_application_close_frame(buf)
frame_type = None
self._logger.info(
"Connection close code 0x%X, reason %s", error_code, reason_phrase
)
- self._set_state(QuicConnectionState.DRAINING)
- self.connection_lost(
- maybe_connection_error(
+ if error_code != QuicErrorCode.NO_ERROR:
+ self._close_exception = QuicConnectionError(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
+ self._close(is_initiator=False)
- )
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
+ self._close_at = self._loop.time() + self._local_idle_timeout
- self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
self._initialize(self._peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def wait_connected(self) -> None:
"""
Wait for the TLS handshake to complete.
"""
+ await asyncio.shield(self._connected_waiter)
- await self._connected.wait()
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def wait_closed(self) -> None:
+ """
+ Wait for the connection to be closed.
+ """
+ await self._closed.wait()
+
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ self._logger.info("Connection closed")
+ for epoch in self._spaces.keys():
+ self._discard_epoch(epoch)
for stream in self._streams.values():
stream.connection_lost(exc)
+ if not self._connected_waiter.done():
+ self._connected_waiter.set_exception(exc)
+ self._closed.set()
|
aioquic.connection/QuicConnection._on_timeout
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<4>:<add> if self._loop.time() >= self._close_at:
<del> if self._loop.time() >= self._idle_timeout_at:
<5>:<del> self._logger.info("Idle timeout expired")
<6>:<del> self._set_state(QuicConnectionState.DRAINING)
<7>:<add> self.connection_lost(self._close_exception)
<del> self.connection_lost(None)
<8>:<del> for epoch in self._spaces.keys():
<9>:<del> self._discard_epoch(epoch)
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
<0> self._timer = None
<1> self._timer_at = None
<2>
<3> # idle timeout
<4> if self._loop.time() >= self._idle_timeout_at:
<5> self._logger.info("Idle timeout expired")
<6> self._set_state(QuicConnectionState.DRAINING)
<7> self.connection_lost(None)
<8> for epoch in self._spaces.keys():
<9> self._discard_epoch(epoch)
<10> return
<11>
<12> # loss detection timeout
<13> self._logger.info("Loss detection triggered")
<14> self._loss.on_loss_detection_timeout(now=self._loop.time())
<15> self._send_pending()
<16>
|
===========unchanged ref 0===========
at: aioquic.connection.QuicConnection
connection_lost(exc: Exception) -> None
at: aioquic.connection.QuicConnection.__init__
self._close_at: Optional[float] = None
self._close_exception: Optional[Exception] = None
self._loop = loop
self._timer: Optional[asyncio.TimerHandle] = None
self._timer_at: Optional[float] = None
self._retire_connection_ids: List[int] = []
at: aioquic.connection.QuicConnection._close
self._close_at = self._loop.time() + 3 * self._loss.get_probe_timeout()
at: aioquic.connection.QuicConnection._connect
self._close_at = self._loop.time() + self._local_idle_timeout
at: aioquic.connection.QuicConnection._handle_connection_close_frame
self._close_exception = QuicConnectionError(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
at: aioquic.connection.QuicConnection._set_timer
self._timer = None
self._timer = self._loop.call_at(timer_at, self._on_timeout)
self._timer_at = timer_at
at: aioquic.connection.QuicConnection.datagram_received
self._close_exception = exc
self._close_at = now + self._local_idle_timeout
at: aioquic.packet_builder
QuicDeliveryState()
at: asyncio.events.AbstractEventLoop
time() -> float
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ self._logger.info("Connection closed")
+ for epoch in self._spaces.keys():
+ self._discard_epoch(epoch)
for stream in self._streams.values():
stream.connection_lost(exc)
+ if not self._connected_waiter.done():
+ self._connected_waiter.set_exception(exc)
+ self._closed.set()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CONNECTION_CLOSE frame.
"""
if frame_type == QuicFrameType.TRANSPORT_CLOSE:
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
else:
error_code, reason_phrase = pull_application_close_frame(buf)
frame_type = None
self._logger.info(
"Connection close code 0x%X, reason %s", error_code, reason_phrase
)
- self._set_state(QuicConnectionState.DRAINING)
- self.connection_lost(
- maybe_connection_error(
+ if error_code != QuicErrorCode.NO_ERROR:
+ self._close_exception = QuicConnectionError(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
+ self._close(is_initiator=False)
- )
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _close(self, is_initiator: bool) -> None:
+ """
+ Start the close procedure.
+ """
+ self._close_at = self._loop.time() + 3 * self._loss.get_probe_timeout()
+ if is_initiator:
+ self._set_state(QuicConnectionState.CLOSING)
+ else:
+ self._set_state(QuicConnectionState.DRAINING)
+
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
+ self._close_at = self._loop.time() + self._local_idle_timeout
- self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
self._initialize(self._peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CRYPTO frame.
"""
stream = self._streams[context.epoch]
stream.add_frame(pull_crypto_frame(buf))
data = stream.pull_data()
if data:
# pass data to TLS layer
try:
self.tls.handle_message(data, self.send_buffer)
self._push_crypto_data()
except tls.Alert as exc:
raise QuicConnectionError(
error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
frame_type=QuicFrameType.CRYPTO,
reason_phrase=str(exc),
)
# parse transport parameters
if (
not self._parameters_received
and self.tls.received_extensions is not None
):
for ext_type, ext_data in self.tls.received_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(ext_data)
self._parameters_received = True
break
assert (
self._parameters_received
), "No QUIC transport parameters received"
self._logger.info("ALPN negotiated protocol %s", self.alpn_protocol)
# update current epoch
if not self._handshake_complete and self.tls.state in [
tls.State.CLIENT_POST_HANDSHAKE,
tls.State.SERVER_POST_HANDSHAKE,
]:
self._handshake_complete = True
self._replenish_connection_ids()
# wakeup waiter
- if not self._connected.is_set():
+ self._connected_waiter.set_result(None)
- self._connected.set()
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def wait_connected(self) -> None:
"""
Wait for the TLS handshake to complete.
"""
+ await asyncio.shield(self._connected_waiter)
- await self._connected.wait()
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def wait_closed(self) -> None:
+ """
+ Wait for the connection to be closed.
+ """
+ await self._closed.wait()
+
|
aioquic.connection/QuicConnection._send_pending
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<3>:<add> if self._state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]:
<del> if self._state == QuicConnectionState.DRAINING:
<31>:<add> self._close(is_initiator=True)
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
<0> network_path = self._network_paths[0]
<1>
<2> self._send_task = None
<3> if self._state == QuicConnectionState.DRAINING:
<4> return
<5>
<6> # build datagrams
<7> builder = QuicPacketBuilder(
<8> host_cid=self.host_cid,
<9> packet_number=self._packet_number,
<10> pad_first_datagram=(
<11> self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
<12> ),
<13> peer_cid=self._peer_cid,
<14> peer_token=self._peer_token,
<15> spin_bit=self._spin_bit,
<16> version=self._version,
<17> )
<18> if self._close_pending:
<19> for epoch, packet_type in (
<20> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
<21> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
<22> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
<23> ):
<24> crypto = self._cryptos[epoch]
<25> if crypto.send.is_valid():
<26> builder.start_packet(packet_type, crypto)
<27> write_close_frame(builder, **self._close_pending)
<28> builder.end_packet()
<29> self._close_pending = None
<30> break
<31> else:
<32> if not self._handshake_confirmed:
<33> for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
<34> self._write_handshake(builder, epoch)
<35> self._write_application(builder, network_path)
<36> datagrams, packets = builder.flush()
<37>
<38> if datagrams:
<39> self._packet_number = builder.packet_number
<40>
<41> # send datagrams
<42> for datagram in datagrams:
<43> </s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
network_path.bytes_sent += len(datagram)
# register packets
now = self._loop.time()
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm timer
self._set_timer()
===========unchanged ref 0===========
at: aioquic.buffer.Buffer
seek(pos: int) -> None
at: aioquic.connection
write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None
QuicConnectionState()
at: aioquic.connection.QuicConnection
_close(self, is_initiator: bool) -> None
_close(is_initiator: bool) -> None
_write_application(builder: QuicPacketBuilder, network_path: QuicNetworkPath) -> None
_write_handshake(builder: QuicPacketBuilder, epoch: tls.Epoch) -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._handshake_confirmed = False
self.host_cid = self._host_cids[0].cid
self._loop = loop
self._network_paths: List[QuicNetworkPath] = []
self._packet_number = 0
self._peer_cid = os.urandom(8)
self._peer_token = b""
self._spin_bit = False
self._state = QuicConnectionState.FIRSTFLIGHT
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
self._transport: Optional[asyncio.DatagramTransport] = None
self._version: Optional[int] = None
self._close_pending: Optional[Dict] = None
self._send_task: Optional[asyncio.Handle] = None
at: aioquic.connection.QuicConnection._consume_connection_id
self._peer_cid = connection_id.cid
at: aioquic.connection.QuicConnection._handle_ack_frame
self._handshake_confirmed = True
===========unchanged ref 1===========
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self.send_buffer = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
self._packet_number = 0
at: aioquic.connection.QuicConnection._send_soon
self._send_task = self._loop.call_soon(self._send_pending)
at: aioquic.connection.QuicConnection._set_state
self._state = state
at: aioquic.connection.QuicConnection.close
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
at: aioquic.connection.QuicConnection.connect
self._network_paths = [QuicNetworkPath(addr, is_validated=True)]
self._version = max(self.supported_versions)
self._version = protocol_version
at: aioquic.connection.QuicConnection.connection_made
self._transport = cast(asyncio.DatagramTransport, transport)
at: aioquic.connection.QuicConnection.datagram_received
self._version = QuicProtocolVersion(header.version)
self._version = QuicProtocolVersion(max(common))
self._peer_cid = header.source_cid
self._peer_token = header.token
self._network_paths = [network_path]
self._spin_bit = self._spin_bit_peer
self._spin_bit = not self._spin_bit_peer
self.host_cid = context.host_cid
===========unchanged ref 2===========
at: aioquic.connection.QuicNetworkPath
addr: NetworkAddress
bytes_sent: int = 0
at: aioquic.crypto.CryptoContext
is_valid() -> bool
at: aioquic.crypto.CryptoPair.__init__
self.send = CryptoContext()
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
at: aioquic.packet_builder.QuicPacketBuilder
flush() -> Tuple[List[bytes], List[QuicSentPacket]]
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
at: aioquic.stream.QuicStream
write(data: bytes) -> None
at: aioquic.tls
Epoch()
at: asyncio.events.AbstractEventLoop
time() -> float
at: asyncio.transports.DatagramTransport
__slots__ = ()
sendto(data: Any, addr: Optional[_Address]=...) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _close(self, is_initiator: bool) -> None:
+ """
+ Start the close procedure.
+ """
+ self._close_at = self._loop.time() + 3 * self._loss.get_probe_timeout()
+ if is_initiator:
+ self._set_state(QuicConnectionState.CLOSING)
+ else:
+ self._set_state(QuicConnectionState.DRAINING)
+
|
aioquic.connection/QuicConnection._set_timer
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<1>:<add> timer_at = self._close_at
<5>:<del> timer_at = self._idle_timeout_at
<9>:<del> else:
<10>:<del> timer_at = None
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_timer(self) -> None:
<0> # determine earliest timeout
<1> if self._state not in [
<2> QuicConnectionState.CLOSING,
<3> QuicConnectionState.DRAINING,
<4> ]:
<5> timer_at = self._idle_timeout_at
<6> loss_at = self._loss.get_loss_detection_time()
<7> if loss_at is not None and loss_at < timer_at:
<8> timer_at = loss_at
<9> else:
<10> timer_at = None
<11>
<12> # re-arm timer
<13> if self._timer is not None and self._timer_at != timer_at:
<14> self._timer.cancel()
<15> self._timer = None
<16> if self._timer is None and timer_at is not None:
<17> self._timer = self._loop.call_at(timer_at, self._on_timeout)
<18> self._timer_at = timer_at
<19>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionState()
at: aioquic.connection.QuicConnection.__init__
self._close_at: Optional[float] = None
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._state = QuicConnectionState.FIRSTFLIGHT
self._timer: Optional[asyncio.TimerHandle] = None
self._timer_at: Optional[float] = None
at: aioquic.connection.QuicConnection._close
self._close_at = self._loop.time() + 3 * self._loss.get_probe_timeout()
at: aioquic.connection.QuicConnection._connect
self._close_at = self._loop.time() + self._local_idle_timeout
at: aioquic.connection.QuicConnection._on_timeout
self._timer = None
self._timer_at = None
at: aioquic.connection.QuicConnection._serialize_transport_parameters
quic_transport_parameters = QuicTransportParameters(
idle_timeout=int(self._local_idle_timeout * 1000),
initial_max_data=self._local_max_data,
initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local,
initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote,
initial_max_stream_data_uni=self._local_max_stream_data_uni,
initial_max_streams_bidi=self._local_max_streams_bidi,
initial_max_streams_uni=self._local_max_streams_uni,
ack_delay_exponent=10,
)
buf = Buffer(capacity=512)
===========unchanged ref 1===========
at: aioquic.connection.QuicConnection._set_timer
self._timer = None
self._timer = self._loop.call_at(timer_at, self._on_timeout)
self._timer_at = timer_at
at: aioquic.connection.QuicConnection.datagram_received
self._close_at = now + self._local_idle_timeout
at: aioquic.packet
push_quic_transport_parameters(buf: Buffer, params: QuicTransportParameters) -> None
at: logging.LoggerAdapter
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
+ if self._loop.time() >= self._close_at:
- if self._loop.time() >= self._idle_timeout_at:
- self._logger.info("Idle timeout expired")
- self._set_state(QuicConnectionState.DRAINING)
+ self.connection_lost(self._close_exception)
- self.connection_lost(None)
- for epoch in self._spaces.keys():
- self._discard_epoch(epoch)
return
# loss detection timeout
self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
network_path = self._network_paths[0]
self._send_task = None
+ if self._state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]:
- if self._state == QuicConnectionState.DRAINING:
return
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
packet_number=self._packet_number,
pad_first_datagram=(
self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
),
peer_cid=self._peer_cid,
peer_token=self._peer_token,
spin_bit=self._spin_bit,
version=self._version,
)
if self._close_pending:
for epoch, packet_type in (
(tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
):
crypto = self._cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
write_close_frame(builder, **self._close_pending)
builder.end_packet()
self._close_pending = None
break
+ self._close(is_initiator=True)
else:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch)
self._write_application(builder, network_path)
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# send datagrams
for datagram in datagrams:
self._transport</s>
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
<s>number = builder.packet_number
# send datagrams
for datagram in datagrams:
self._transport.sendto(datagram, network_path.addr)
network_path.bytes_sent += len(datagram)
# register packets
now = self._loop.time()
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm timer
self._set_timer()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CONNECTION_CLOSE frame.
"""
if frame_type == QuicFrameType.TRANSPORT_CLOSE:
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
else:
error_code, reason_phrase = pull_application_close_frame(buf)
frame_type = None
self._logger.info(
"Connection close code 0x%X, reason %s", error_code, reason_phrase
)
- self._set_state(QuicConnectionState.DRAINING)
- self.connection_lost(
- maybe_connection_error(
+ if error_code != QuicErrorCode.NO_ERROR:
+ self._close_exception = QuicConnectionError(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
+ self._close(is_initiator=False)
- )
|
aioquic.client/connect
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<s>manager
async def connect(
host: str,
port: int,
*,
alpn_protocols: Optional[List[str]] = None,
protocol_version: Optional[int] = None,
secrets_log_file: Optional[TextIO] = None,
session_ticket: Optional[SessionTicket] = None,
session_ticket_handler: Optional[SessionTicketHandler] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> AsyncGenerator[QuicConnection, None]:
<0> """
<1> Connect to a QUIC server at the given `host` and `port`.
<2>
<3> :meth:`connect()` returns an awaitable. Awaiting it yields a
<4> :class:`~aioquic.QuicConnection` which can be used to create streams.
<5>
<6> :func:`connect` also accepts the following optional arguments:
<7>
<8> * ``alpn_protocols`` is a list of ALPN protocols to offer in the
<9> ClientHello.
<10> * ``secrets_log_file`` is a file-like object in which to log traffic
<11> secrets. This is useful to analyze traffic captures with Wireshark.
<12> * ``session_ticket`` is a TLS session ticket which should be used for
<13> resumption.
<14> * ``session_ticket_handler`` is a callback which is invoked by the TLS
<15> engine when a new session ticket is received.
<16> * ``stream_handler`` is a callback which is invoked whenever a stream is
<17> created. It must accept two arguments: a :class:`asyncio.StreamReader`
<18> and a :class:`asyncio.StreamWriter`.
<19> """
<20> loop = asyncio.get_event_loop()
<21>
<22> # if host is not an IP address, pass it to enable SNI
<23> try:
<24> ipaddress.ip_address(host)
<25> server_name = None
<26> except ValueError:
<27> server_name = host
<28>
<29> # lookup remote address
<30> infos = await loop.getaddrinfo(host, port, type=socket.SOCK_DGRAM)
<31> addr = infos[0][4]</s>
|
===========below chunk 0===========
<s>(
host: str,
port: int,
*,
alpn_protocols: Optional[List[str]] = None,
protocol_version: Optional[int] = None,
secrets_log_file: Optional[TextIO] = None,
session_ticket: Optional[SessionTicket] = None,
session_ticket_handler: Optional[SessionTicketHandler] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> AsyncGenerator[QuicConnection, None]:
# offset: 1
addr = ("::ffff:" + addr[0], addr[1], 0, 0)
# connect
_, protocol = await loop.create_datagram_endpoint(
lambda: QuicConnection(
alpn_protocols=alpn_protocols,
is_client=True,
secrets_log_file=secrets_log_file,
server_name=server_name,
session_ticket=session_ticket,
session_ticket_handler=session_ticket_handler,
stream_handler=stream_handler,
),
local_addr=("::", 0),
)
protocol = cast(QuicConnection, protocol)
protocol.connect(addr, protocol_version=protocol_version)
await protocol.wait_connected()
try:
yield protocol
finally:
protocol.close()
===========unchanged ref 0===========
at: _asyncio
get_event_loop()
at: aioquic.connection
QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None]
QuicConnection(*, is_client: bool=True, certificate: Any=None, private_key: Any=None, alpn_protocols: Optional[List[str]]=None, original_connection_id: Optional[bytes]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None, supported_versions: Optional[List[QuicProtocolVersion]]=None, stream_handler: Optional[QuicStreamHandler]=None)
at: aioquic.connection.QuicConnection
supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20]
close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None
connect(addr: NetworkAddress, protocol_version: Optional[int]=None) -> None
wait_connected() -> None
at: aioquic.tls
SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))
SessionTicketHandler = Callable[[SessionTicket], None]
at: asyncio.events
get_event_loop() -> AbstractEventLoop
===========unchanged ref 1===========
at: asyncio.events.AbstractEventLoop
getaddrinfo(host: Optional[str], port: Union[str, int, None], *, family: int=..., type: int=..., proto: int=..., flags: int=...) -> List[Tuple[AddressFamily, SocketKind, int, str, Union[Tuple[str, int], Tuple[str, int, int, int]]]]
create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair
at: contextlib
asynccontextmanager(func: Callable[..., AsyncIterator[_T]]) -> Callable[..., AsyncContextManager[_T]]
at: ipaddress
ip_address(address: object) -> Any
at: socket
SOCK_DGRAM: SocketKind
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
List = _alias(list, 1, inst=False, name='List')
AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
TextIO()
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def wait_connected(self) -> None:
"""
Wait for the TLS handshake to complete.
"""
+ await asyncio.shield(self._connected_waiter)
- await self._connected.wait()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
if self._state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
- self._set_state(QuicConnectionState.CLOSING)
- self.connection_lost(
- maybe_connection_error(
- error_code=error_code,
- frame_type=frame_type,
- reason_phrase=reason_phrase,
- )
- )
self._send_pending()
- for epoch in self._spaces.keys():
- self._discard_epoch(epoch)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def wait_closed(self) -> None:
+ """
+ Wait for the connection to be closed.
+ """
+ await self._closed.wait()
+
===========changed ref 3===========
# module: aioquic.connection
- def maybe_connection_error(
- error_code: int, frame_type: Optional[int], reason_phrase: str
- ) -> Optional[QuicConnectionError]:
- if error_code != QuicErrorCode.NO_ERROR:
- return QuicConnectionError(
- error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
- )
- else:
- return None
-
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _close(self, is_initiator: bool) -> None:
+ """
+ Start the close procedure.
+ """
+ self._close_at = self._loop.time() + 3 * self._loss.get_probe_timeout()
+ if is_initiator:
+ self._set_state(QuicConnectionState.CLOSING)
+ else:
+ self._set_state(QuicConnectionState.DRAINING)
+
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ self._logger.info("Connection closed")
+ for epoch in self._spaces.keys():
+ self._discard_epoch(epoch)
for stream in self._streams.values():
stream.connection_lost(exc)
+ if not self._connected_waiter.done():
+ self._connected_waiter.set_exception(exc)
+ self._closed.set()
|
|
tests.test_connection/QuicConnectionTest.test_tls_error
|
Modified
|
aiortc~aioquic
|
f8d36973505bb878c7d07514110a6b385e56cc40
|
[connection] rework shutdown
|
<11>:<add> with self.assertRaises(QuicConnectionError) as cm:
<add> run(server.wait_connected())
<add> self.assertEqual(cm.exception.error_code, 326)
<add> self.assertEqual(cm.exception.frame_type, QuicFrameType.CRYPTO)
<add> self.assertEqual(
<add> cm.exception.reason_phrase, "No supported protocol version"
<add> )
<del> run(asyncio.sleep(0))
<12>:<del> self.assertEqual(client._transport.sent, 1)
<13>:<del> self.assertEqual(server._transport.sent, 1)
|
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_tls_error(self):
<0> def patch(client):
<1> real_initialize = client._initialize
<2>
<3> def patched_initialize(peer_cid: bytes):
<4> real_initialize(peer_cid)
<5> client.tls._supported_versions = [tls.TLS_VERSION_1_3_DRAFT_28]
<6>
<7> client._initialize = patched_initialize
<8>
<9> # handshake fails
<10> with client_and_server(client_patch=patch) as (client, server):
<11> run(asyncio.sleep(0))
<12> self.assertEqual(client._transport.sent, 1)
<13> self.assertEqual(server._transport.sent, 1)
<14>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
at: aioquic.tls
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
at: tests.test_connection
client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})
at: tests.utils
run(coro)
at: unittest.case.TestCase
failureException: Type[BaseException]
longMessage: bool
maxDiff: Optional[int]
_testMethodName: str
_testMethodDoc: str
assertEqual(first: Any, second: Any, msg: Any=...) -> None
assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]
assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None
at: unittest.case._AssertRaisesContext.__exit__
self.exception = exc_value.with_traceback(None)
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def wait_closed(self) -> None:
+ """
+ Wait for the connection to be closed.
+ """
+ await self._closed.wait()
+
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def wait_connected(self) -> None:
"""
Wait for the TLS handshake to complete.
"""
+ await asyncio.shield(self._connected_waiter)
- await self._connected.wait()
===========changed ref 2===========
# module: aioquic.connection
- def maybe_connection_error(
- error_code: int, frame_type: Optional[int], reason_phrase: str
- ) -> Optional[QuicConnectionError]:
- if error_code != QuicErrorCode.NO_ERROR:
- return QuicConnectionError(
- error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
- )
- else:
- return None
-
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _close(self, is_initiator: bool) -> None:
+ """
+ Start the close procedure.
+ """
+ self._close_at = self._loop.time() + 3 * self._loss.get_probe_timeout()
+ if is_initiator:
+ self._set_state(QuicConnectionState.CLOSING)
+ else:
+ self._set_state(QuicConnectionState.DRAINING)
+
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
# asyncio.DatagramProtocol
def connection_lost(self, exc: Exception) -> None:
+ self._logger.info("Connection closed")
+ for epoch in self._spaces.keys():
+ self._discard_epoch(epoch)
for stream in self._streams.values():
stream.connection_lost(exc)
+ if not self._connected_waiter.done():
+ self._connected_waiter.set_exception(exc)
+ self._closed.set()
===========changed ref 5===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
+ self._close_at = self._loop.time() + self._local_idle_timeout
- self._idle_timeout_at = self._loop.time() + self._local_idle_timeout
self._initialize(self._peer_cid)
self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 6===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _on_timeout(self) -> None:
self._timer = None
self._timer_at = None
# idle timeout
+ if self._loop.time() >= self._close_at:
- if self._loop.time() >= self._idle_timeout_at:
- self._logger.info("Idle timeout expired")
- self._set_state(QuicConnectionState.DRAINING)
+ self.connection_lost(self._close_exception)
- self.connection_lost(None)
- for epoch in self._spaces.keys():
- self._discard_epoch(epoch)
return
# loss detection timeout
self._logger.info("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=self._loop.time())
self._send_pending()
===========changed ref 7===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
if self._state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
- self._set_state(QuicConnectionState.CLOSING)
- self.connection_lost(
- maybe_connection_error(
- error_code=error_code,
- frame_type=frame_type,
- reason_phrase=reason_phrase,
- )
- )
self._send_pending()
- for epoch in self._spaces.keys():
- self._discard_epoch(epoch)
===========changed ref 8===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_timer(self) -> None:
# determine earliest timeout
+ timer_at = self._close_at
if self._state not in [
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
]:
- timer_at = self._idle_timeout_at
loss_at = self._loss.get_loss_detection_time()
if loss_at is not None and loss_at < timer_at:
timer_at = loss_at
- else:
- timer_at = None
# re-arm timer
if self._timer is not None and self._timer_at != timer_at:
self._timer.cancel()
self._timer = None
if self._timer is None and timer_at is not None:
self._timer = self._loop.call_at(timer_at, self._on_timeout)
self._timer_at = timer_at
|
aioquic.crypto/AEAD.decrypt
|
Modified
|
aiortc~aioquic
|
d2e80b03c71769a9abaa184f4e0defc67101a92c
|
[crypto] add a missing test
|
<1>:<add>
<add> tag_length = 16
<add> assert len(data) >= tag_length
<7>:<del> tag_length = 16
<8>:<del> if len(data) < tag_length:
<9>:<del> raise InvalidTag
|
# module: aioquic.crypto
class AEAD:
def decrypt(self, nonce: bytes, data: bytes, associated_data: bytes) -> bytes:
<0> global backend
<1>
<2> if self._decrypt_ctx is None:
<3> self._decrypt_ctx = self._create_ctx(len(nonce), 0)
<4> ctx = self._decrypt_ctx
<5>
<6> outlen = backend._ffi.new("int *")
<7> tag_length = 16
<8> if len(data) < tag_length:
<9> raise InvalidTag
<10> tag = data[-tag_length:]
<11> data = data[:-tag_length]
<12>
<13> res = backend._lib.EVP_CIPHER_CTX_ctrl(
<14> ctx, backend._lib.EVP_CTRL_AEAD_SET_TAG, tag_length, tag
<15> )
<16> backend.openssl_assert(res != 0)
<17>
<18> res = backend._lib.EVP_CipherInit_ex(
<19> ctx,
<20> backend._ffi.NULL,
<21> backend._ffi.NULL,
<22> self._key_ptr,
<23> backend._ffi.from_buffer(nonce),
<24> 0,
<25> )
<26> backend.openssl_assert(res != 0)
<27>
<28> res = backend._lib.EVP_CipherUpdate(
<29> ctx, backend._ffi.NULL, outlen, associated_data, len(associated_data)
<30> )
<31> backend.openssl_assert(res != 0)
<32>
<33> buf = backend._ffi.new("unsigned char[]", len(data))
<34> res = backend._lib.EVP_CipherUpdate(ctx, buf, outlen, data, len(data))
<35> backend.openssl_assert(res != 0)
<36> processed_data = backend._ffi.buffer(buf, outlen[0])[:]
<37>
<38> res = backend._lib.EVP_CipherFinal_ex(ctx, backend._ffi.NULL, outlen)
<39> if res == 0:
<40> backend._consume_errors()
<41> raise InvalidTag</s>
|
===========below chunk 0===========
# module: aioquic.crypto
class AEAD:
def decrypt(self, nonce: bytes, data: bytes, associated_data: bytes) -> bytes:
# offset: 1
return processed_data
===========unchanged ref 0===========
at: aioquic.crypto.AEAD
_create_ctx(nonce_length: int, operation: int) -> Any
at: aioquic.crypto.AEAD.__init__
self._decrypt_ctx = None
self._key_ptr = backend._ffi.from_buffer(key)
|
aioquic.connection/QuicConnection._send_pending
|
Modified
|
aiortc~aioquic
|
1bba21d2dcb7b3a8a93466ac963d6aecb1bedd14
|
Limit transmission on un-validated network paths (closes: #12)
|
<33>:<add> # data is limited by congestion control and whether the network path is validated
<add> max_bytes = self._loss.congestion_window - self._loss.bytes_in_flight
<add> if not network_path.is_validated:
<add> max_bytes = min(
<add> max_bytes, network_path.bytes_received * 3 - network_path.bytes_sent
<add> )
<add>
<35>:<add> self._write_handshake(builder, epoch, max_bytes)
<del> self._write_handshake(builder, epoch)
<36>:<add> self._write_application(builder, max_bytes, network_path)
<del> self._write_application(builder, network_path)
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
<0> network_path = self._network_paths[0]
<1>
<2> self._send_task = None
<3> if self._state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]:
<4> return
<5>
<6> # build datagrams
<7> builder = QuicPacketBuilder(
<8> host_cid=self.host_cid,
<9> packet_number=self._packet_number,
<10> pad_first_datagram=(
<11> self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
<12> ),
<13> peer_cid=self._peer_cid,
<14> peer_token=self._peer_token,
<15> spin_bit=self._spin_bit,
<16> version=self._version,
<17> )
<18> if self._close_pending:
<19> for epoch, packet_type in (
<20> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
<21> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
<22> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
<23> ):
<24> crypto = self._cryptos[epoch]
<25> if crypto.send.is_valid():
<26> builder.start_packet(packet_type, crypto)
<27> write_close_frame(builder, **self._close_pending)
<28> builder.end_packet()
<29> self._close_pending = None
<30> break
<31> self._close(is_initiator=True)
<32> else:
<33> if not self._handshake_confirmed:
<34> for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
<35> self._write_handshake(builder, epoch)
<36> self._write_application(builder, network_path)
<37> datagrams, packets = builder.flush()
<38>
<39> if datagrams:
<40> self._packet_number = builder.packet_number
</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
# send datagrams
for datagram in datagrams:
self._transport.sendto(datagram, network_path.addr)
network_path.bytes_sent += len(datagram)
# register packets
now = self._loop.time()
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm timer
self._set_timer()
===========unchanged ref 0===========
at: aioquic.connection
write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None
QuicConnectionState()
at: aioquic.connection.QuicConnection
supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20]
_close(is_initiator: bool) -> None
_write_application(builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath) -> None
_write_application(self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath) -> None
_write_handshake(builder: QuicPacketBuilder, epoch: tls.Epoch, max_bytes: int) -> None
_write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch, max_bytes: int) -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._handshake_confirmed = False
self.host_cid = self._host_cids[0].cid
self._loop = loop
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._network_paths: List[QuicNetworkPath] = []
self._packet_number = 0
self._peer_cid = os.urandom(8)
self._peer_token = b""
self._spin_bit = False
self._state = QuicConnectionState.FIRSTFLIGHT
self._transport: Optional[asyncio.DatagramTransport] = None
self._version: Optional[int] = None
self._close_pending: Optional[Dict] = None
self._send_task: Optional[asyncio.Handle] = None
===========unchanged ref 1===========
at: aioquic.connection.QuicConnection._consume_connection_id
self._peer_cid = connection_id.cid
at: aioquic.connection.QuicConnection._handle_ack_frame
self._handshake_confirmed = True
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._packet_number = 0
at: aioquic.connection.QuicConnection._send_soon
self._send_task = self._loop.call_soon(self._send_pending)
at: aioquic.connection.QuicConnection._set_state
self._state = state
at: aioquic.connection.QuicConnection.close
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
at: aioquic.connection.QuicConnection.connect
self._network_paths = [QuicNetworkPath(addr, is_validated=True)]
self._version = max(self.supported_versions)
self._version = protocol_version
at: aioquic.connection.QuicConnection.connection_made
self._transport = cast(asyncio.DatagramTransport, transport)
at: aioquic.connection.QuicConnection.datagram_received
self._version = QuicProtocolVersion(header.version)
self._version = QuicProtocolVersion(max(common))
self._peer_cid = header.source_cid
self._peer_token = header.token
self._network_paths = [network_path]
self._spin_bit = self._spin_bit_peer
self._spin_bit = not self._spin_bit_peer
self.host_cid = context.host_cid
===========unchanged ref 2===========
at: aioquic.connection.QuicNetworkPath
addr: NetworkAddress
bytes_received: int = 0
bytes_sent: int = 0
is_validated: bool = False
local_challenge: Optional[bytes] = None
remote_challenge: Optional[bytes] = None
at: aioquic.crypto.CryptoContext
is_valid() -> bool
at: aioquic.crypto.CryptoPair.__init__
self.send = CryptoContext()
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
at: aioquic.packet_builder.QuicPacketBuilder
flush() -> Tuple[List[bytes], List[QuicSentPacket]]
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
at: aioquic.recovery.QuicPacketRecovery.__init__
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
|
aioquic.connection/QuicConnection._write_application
|
Modified
|
aiortc~aioquic
|
1bba21d2dcb7b3a8a93466ac963d6aecb1bedd14
|
Limit transmission on un-validated network paths (closes: #12)
|
<14>:<del> while (
<15>:<del> builder.flight_bytes + self._loss.bytes_in_flight
<16>:<del> < self._loss.congestion_window
<17>:<del> ) or self._probe_pending:
<18>:<add> while builder.flight_bytes < max_bytes or self._probe_pending:
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
+ self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
- self, builder: QuicPacketBuilder, network_path: QuicNetworkPath
) -> None:
<0> crypto_stream_id: Optional[tls.Epoch] = None
<1> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
<2> crypto = self._cryptos[tls.Epoch.ONE_RTT]
<3> crypto_stream_id = tls.Epoch.ONE_RTT
<4> packet_type = PACKET_TYPE_ONE_RTT
<5> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
<6> crypto = self._cryptos[tls.Epoch.ZERO_RTT]
<7> packet_type = PACKET_TYPE_ZERO_RTT
<8> else:
<9> return
<10> space = self._spaces[tls.Epoch.ONE_RTT]
<11>
<12> buf = builder.buffer
<13>
<14> while (
<15> builder.flight_bytes + self._loss.bytes_in_flight
<16> < self._loss.congestion_window
<17> ) or self._probe_pending:
<18> # write header
<19> builder.start_packet(packet_type, crypto)
<20>
<21> if self._handshake_complete:
<22> # ACK
<23> if space.ack_required and space.ack_queue:
<24> builder.start_frame(QuicFrameType.ACK)
<25> push_ack_frame(buf, space.ack_queue, 0)
<26> space.ack_required = False
<27>
<28> # PATH CHALLENGE
<29> if (
<30> not network_path.is_validated
<31> and network_path.local_challenge is None
<32> ):
<33> self._logger.info(
<34> "Network path %s sending challenge", network_path.addr
<35> )
<36> network_path.local_challenge = os.urandom(8</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
+ self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
- self, builder: QuicPacketBuilder, network_path: QuicNetworkPath
) -> None:
# offset: 1
builder.start_frame(QuicFrameType.PATH_CHALLENGE)
push_bytes(buf, network_path.local_challenge)
# PATH RESPONSE
if network_path.remote_challenge is not None:
builder.start_frame(QuicFrameType.PATH_RESPONSE)
push_bytes(buf, network_path.remote_challenge)
network_path.remote_challenge = None
# NEW_CONNECTION_ID
for connection_id in self._host_cids:
if not connection_id.was_sent:
builder.start_frame(
QuicFrameType.NEW_CONNECTION_ID,
self._on_new_connection_id_delivery,
(connection_id,),
)
push_new_connection_id_frame(
buf,
connection_id.sequence_number,
connection_id.cid,
connection_id.stateless_reset_token,
)
connection_id.was_sent = True
self._connection_id_issued_handler(connection_id.cid)
# RETIRE_CONNECTION_ID
while self._retire_connection_ids:
sequence_number = self._retire_connection_ids.pop(0)
builder.start_frame(
QuicFrameType.RETIRE_CONNECTION_ID,
self._on_retire_connection_id_delivery,
(sequence_number,),
)
push_uint_var(buf, sequence_number)
# connection-level limits
self._write_connection_limits(builder=builder, space=space)
# stream-level limits
for stream_id, stream in self._streams.items():
if isinstance(stream_id, int</s>
===========below chunk 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
+ self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
- self, builder: QuicPacketBuilder, network_path: QuicNetworkPath
) -> None:
# offset: 2
<s> # stream-level limits
for stream_id, stream in self._streams.items():
if isinstance(stream_id, int):
self._write_stream_limits(
builder=builder, space=space, stream=stream
)
# PING (user-request)
if self._ping_pending:
self._logger.info("Sending PING in packet %d", builder.packet_number)
builder.start_frame(QuicFrameType.PING, self._on_ping_delivery)
self._ping_pending = False
# PING (probe)
if self._probe_pending:
self._logger.info("Sending probe")
builder.start_frame(QuicFrameType.PING)
self._probe_pending = False
for stream_id, stream in self._streams.items():
# CRYPTO
if stream_id == crypto_stream_id:
write_crypto_frame(builder=builder, space=space, stream=stream)
# STREAM
elif isinstance(stream_id, int):
self._remote_max_data_used += write_stream_frame(
builder=builder,
space=space,
stream=stream,
max_offset=min(
stream._send_highest
+ self._remote_max_data
- self._remote_max_data_used,
stream.max_stream_data_remote,
),
)
if not builder.end_packet():
break
===========unchanged ref 0===========
at: aioquic.buffer
push_bytes(buf: Buffer, v: bytes) -> None
push_uint_var(buf: Buffer, value: int) -> None
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int
QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None)
at: aioquic.connection.QuicConnection
_on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None
_on_ping_delivery(delivery: QuicDeliveryState) -> None
_on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None
_write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None
_write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._handshake_complete = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._remote_max_data = 0
self._remote_max_data_used = 0
===========unchanged ref 1===========
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
self._ping_pending = False
self._probe_pending = False
self._retire_connection_ids: List[int] = []
self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None
at: aioquic.connection.QuicConnection._handle_crypto_frame
self._handshake_complete = True
at: aioquic.connection.QuicConnection._handle_max_data_frame
self._remote_max_data = max_data
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicConnection._on_ping_delivery
self._ping_pending = True
at: aioquic.connection.QuicConnection._send_probe
self._probe_pending = True
at: aioquic.connection.QuicConnection.ping
self._ping_pending = True
at: aioquic.connection.QuicConnectionId
cid: bytes
sequence_number: int
stateless_reset_token: bytes = b""
was_sent: bool = False
at: aioquic.connection.QuicNetworkPath
addr: NetworkAddress
is_validated: bool = False
local_challenge: Optional[bytes] = None
remote_challenge: Optional[bytes] = None
at: aioquic.crypto.CryptoContext
is_valid() -> bool
|
aioquic.connection/QuicConnection._write_handshake
|
Modified
|
aiortc~aioquic
|
1bba21d2dcb7b3a8a93466ac963d6aecb1bedd14
|
Limit transmission on un-validated network paths (closes: #12)
|
<7>:<del> while (
<8>:<del> builder.flight_bytes + self._loss.bytes_in_flight
<9>:<del> < self._loss.congestion_window
<10>:<del> ):
<11>:<add> while builder.flight_bytes < max_bytes:
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
+ def _write_handshake(
+ self, builder: QuicPacketBuilder, epoch: tls.Epoch, max_bytes: int
+ ) -> None:
- def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None:
<0> crypto = self._cryptos[epoch]
<1> if not crypto.send.is_valid():
<2> return
<3>
<4> buf = builder.buffer
<5> space = self._spaces[epoch]
<6>
<7> while (
<8> builder.flight_bytes + self._loss.bytes_in_flight
<9> < self._loss.congestion_window
<10> ):
<11> if epoch == tls.Epoch.INITIAL:
<12> packet_type = PACKET_TYPE_INITIAL
<13> else:
<14> packet_type = PACKET_TYPE_HANDSHAKE
<15> builder.start_packet(packet_type, crypto)
<16>
<17> # ACK
<18> if space.ack_required and space.ack_queue:
<19> builder.start_frame(QuicFrameType.ACK)
<20> push_ack_frame(buf, space.ack_queue, 0)
<21> space.ack_required = False
<22>
<23> # CRYPTO
<24> write_crypto_frame(
<25> builder=builder, space=space, stream=self._streams[epoch]
<26> )
<27>
<28> if not builder.end_packet():
<29> break
<30>
|
===========unchanged ref 0===========
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._streams: Dict[Union[tls.Epoch, int], QuicStream] = {}
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.crypto.CryptoContext
is_valid() -> bool
at: aioquic.crypto.CryptoPair.__init__
self.send = CryptoContext()
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
push_ack_frame(buf: Buffer, rangeset: RangeSet, delay: int) -> None
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
===========unchanged ref 1===========
at: aioquic.packet_builder.QuicPacketBuilder
start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.packet_builder.QuicPacketBuilder.__init__
self.buffer = Buffer(PACKET_MAX_SIZE)
at: aioquic.recovery.QuicPacketSpace.__init__
self.ack_queue = RangeSet()
self.ack_required = False
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
network_path = self._network_paths[0]
self._send_task = None
if self._state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]:
return
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
packet_number=self._packet_number,
pad_first_datagram=(
self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
),
peer_cid=self._peer_cid,
peer_token=self._peer_token,
spin_bit=self._spin_bit,
version=self._version,
)
if self._close_pending:
for epoch, packet_type in (
(tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
):
crypto = self._cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
write_close_frame(builder, **self._close_pending)
builder.end_packet()
self._close_pending = None
break
self._close(is_initiator=True)
else:
+ # data is limited by congestion control and whether the network path is validated
+ max_bytes = self._loss.congestion_window - self._loss.bytes_in_flight
+ if not network_path.is_validated:
+ max_bytes = min(
+ max_bytes, network_path.bytes_received * 3 - network_path.bytes_sent
+ )
+
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
+ self</s>
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
<s>._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
+ self._write_handshake(builder, epoch, max_bytes)
- self._write_handshake(builder, epoch)
+ self._write_application(builder, max_bytes, network_path)
- self._write_application(builder, network_path)
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# send datagrams
for datagram in datagrams:
self._transport.sendto(datagram, network_path.addr)
network_path.bytes_sent += len(datagram)
# register packets
now = self._loop.time()
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm timer
self._set_timer()
|
aioquic.recovery/QuicPacketRecovery.detect_loss
|
Modified
|
aiortc~aioquic
|
98e77723c9f9b9306a5325b63ab93ed091d91fd2
|
[recovery] speed up loss detection code
|
<13>:<add> lost_packets = []
<14>:<add> for packet_number, packet in space.sent_packets.items():
<del> for packet_number, packet in list(space.sent_packets.items()):
<19>:<del> # remove packet and update counters
<20>:<del> del space.sent_packets[packet_number]
<21>:<del> if packet.is_ack_eliciting:
<22>:<del> space.ack_eliciting_in_flight -= 1
<23>:<del> if packet.is_crypto_packet:
<24>:<del> space.crypto_packet_in_flight -= 1
<25>:<del> if packet.in_flight:
<26>:<del> lost_bytes += packet.sent_bytes
<27>:<del> lost_largest_time = packet.sent_time
<28>:<del>
<29>:<del> # trigger callbacks
<30>:<del> for handler, args in packet.delivery_handlers:
<31>:<del> handler(QuicDeliveryState.LOST, *args)
<32>:<add> lost_packets.append(packet)
<37>:<add> for packet in lost_packets:
<add> # remove packet and update counters
<add> del space.sent_packets[packet.packet_number]
<add> if packet.is_ack_eliciting:
<add> space.ack_eliciting_in_flight -= 1
<add> if packet.is_crypto_packet:
<add> space.crypto_packet_in_flight -= 1
<add> if packet.in_flight:
<add> lost_bytes += packet.sent_bytes
<add> lost_largest_time = packet.sent_time
<add>
<add> # trigger callbacks
<add> for handler, args in packet.delivery_handlers:
<add> handler(QuicDeliveryState.LOST, *args)
|
# module: aioquic.recovery
class QuicPacketRecovery:
def detect_loss(self, space: QuicPacketSpace, now: float) -> None:
<0> """
<1> Check whether any packets should be declared lost.
<2> """
<3> loss_delay = K_TIME_THRESHOLD * (
<4> max(self._rtt_latest, self._rtt_smoothed)
<5> if self._rtt_initialized
<6> else K_INITIAL_RTT
<7> )
<8> packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD
<9> time_threshold = now - loss_delay
<10>
<11> lost_bytes = 0
<12> lost_largest_time = None
<13> space.loss_time = None
<14> for packet_number, packet in list(space.sent_packets.items()):
<15> if packet_number > space.largest_acked_packet:
<16> break
<17>
<18> if packet_number <= packet_threshold or packet.sent_time <= time_threshold:
<19> # remove packet and update counters
<20> del space.sent_packets[packet_number]
<21> if packet.is_ack_eliciting:
<22> space.ack_eliciting_in_flight -= 1
<23> if packet.is_crypto_packet:
<24> space.crypto_packet_in_flight -= 1
<25> if packet.in_flight:
<26> lost_bytes += packet.sent_bytes
<27> lost_largest_time = packet.sent_time
<28>
<29> # trigger callbacks
<30> for handler, args in packet.delivery_handlers:
<31> handler(QuicDeliveryState.LOST, *args)
<32> else:
<33> packet_loss_time = packet.sent_time + loss_delay
<34> if space.loss_time is None or space.loss_time > packet_loss_time:
<35> space.loss_time = packet_loss_time
<36>
<37> if lost_bytes:
<38> self.on_packets_lost(lost_bytes, lost_largest_time, now=now)
<39>
|
===========unchanged ref 0===========
at: aioquic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
at: aioquic.recovery
K_PACKET_THRESHOLD = 3
K_INITIAL_RTT = 0.5 # seconds
K_TIME_THRESHOLD = 9 / 8
QuicPacketSpace()
at: aioquic.recovery.QuicPacketRecovery.__init__
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_smoothed = 0.0
at: aioquic.recovery.QuicPacketRecovery.on_ack_received
self._rtt_latest = max(latest_rtt, 0.001)
self._rtt_latest -= ack_delay
self._rtt_initialized = True
self._rtt_smoothed = latest_rtt
self._rtt_smoothed = (
7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest
)
at: aioquic.recovery.QuicPacketSpace.__init__
self.ack_eliciting_in_flight = 0
self.crypto_packet_in_flight = 0
self.largest_acked_packet = 0
self.loss_time: Optional[float] = None
self.sent_packets: Dict[int, QuicSentPacket] = {}
|
aioquic.connection/QuicConnection._connect
|
Modified
|
aiortc~aioquic
|
df649764a8faac4fb6e087d85752628e639800c3
|
[connection] separate crypto streams from regular streams
|
<8>:<add> self.tls.handle_message(b"", self._crypto_buffers)
<del> self.tls.handle_message(b"", self.send_buffer)
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
<0> """
<1> Start the client handshake.
<2> """
<3> assert self.is_client
<4>
<5> self._close_at = self._loop.time() + self._local_idle_timeout
<6> self._initialize(self._peer_cid)
<7>
<8> self.tls.handle_message(b"", self.send_buffer)
<9> self._push_crypto_data()
<10> self._send_pending()
<11>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionState()
at: aioquic.connection.QuicConnection
supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20]
_initialize(self, peer_cid: bytes) -> None
_initialize(peer_cid: bytes) -> None
_set_state(state: QuicConnectionState) -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._close_at: Optional[float] = None
self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}
self._local_idle_timeout = 60.0 # seconds
self._loop = loop
self._peer_cid = os.urandom(8)
at: aioquic.connection.QuicConnection._close
self._close_at = self._loop.time() + 3 * self._loss.get_probe_timeout()
at: aioquic.connection.QuicConnection._consume_connection_id
self._peer_cid = connection_id.cid
at: aioquic.connection.QuicConnection._initialize
self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
self._crypto_buffers = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
at: aioquic.connection.QuicConnection.datagram_received
self._peer_cid = header.source_cid
self._close_at = now + self._local_idle_timeout
at: aioquic.tls.Context
handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None
at: asyncio.events.AbstractEventLoop
time() -> float
===========changed ref 0===========
<s>[bytes] = None,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
if is_client:
assert (
original_connection_id is None
), "Cannot set original_connection_id for a client"
else:
assert certificate is not None, "SSL certificate is required for a server"
assert private_key is not None, "SSL private key is required for a server"
loop = asyncio.get_event_loop()
self.is_client = is_client
if supported_versions is not None:
self.supported_versions = supported_versions
# counters for debugging
self._stateless_retry_count = 0
self._version_negotiation_count = 0
# TLS configuration
self._alpn_protocols = alpn_protocols
self._certificate = certificate
self._private_key = private_key
self._secrets_log_file = secrets_log_file
self._server_name = server_name
self._close_at: Optional[float] = None
self._close_exception: Optional[Exception] = None
self._closed = asyncio.Event()
self._connect_called = False
self._connected_waiter = loop.create_future()
+ self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
- self._cryptos: Dict[Union[tls.Epoch, int], CryptoPair] = {}
+ self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}
+ self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._handshake_complete = False
self._handshake_confirmed = False
</s>
===========changed ref 1===========
<s>,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
# offset: 1
<s>.Epoch, QuicStream] = {}
self._handshake_complete = False
self._handshake_confirmed = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self.host_cid = self._host_cids[0].cid
self._host_cid_seq = 1
self._local_idle_timeout = 60.0 # seconds
self._local_max_data = MAX_DATA_WINDOW
self._local_max_data_sent = MAX_DATA_WINDOW
self._local_max_data_used = 0
self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW
self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW
self._local_max_stream_data_uni = MAX_DATA_WINDOW
self._local_max_streams_bidi = 128
self._local_max_streams_uni = 128
self._loop = loop
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._loss_detection_at: Optional[</s>
===========changed ref 2===========
<s>,
secrets_log_file: TextIO = None,
server_name: Optional[str] = None,
session_ticket: Optional[tls.SessionTicket] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
supported_versions: Optional[List[QuicProtocolVersion]] = None,
stream_handler: Optional[QuicStreamHandler] = None,
) -> None:
# offset: 2
<s> = None
self._network_paths: List[QuicNetworkPath] = []
self._original_connection_id = original_connection_id
self._packet_number = 0
self._parameters_available = asyncio.Event()
self._parameters_received = False
self._peer_cid = os.urandom(8)
self._peer_cid_seq: Optional[int] = None
self._peer_cid_available: List[QuicConnectionId] = []
self._peer_token = b""
self._ping_waiter: Optional[asyncio.Future[None]] = None
self._remote_idle_timeout = 0.0 # seconds
self._remote_max_data = 0
self._remote_max_data_used = 0
self._remote_max_stream_data_bidi_local = 0
self._remote_max_stream_data_bidi_remote = 0
self._remote_max_stream_data_uni = 0
self._remote_max_streams_bidi = 0
self._remote_max_streams_uni = 0
self._session_ticket = session_ticket
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._spin_bit = False
self._spin_bit_peer = False
self._spin_highest_pn = 0
self._state = QuicConnectionState.FIRSTFLIGHT
+ self._streams: Dict[int</s>
|
aioquic.connection/QuicConnection._initialize
|
Modified
|
aiortc~aioquic
|
df649764a8faac4fb6e087d85752628e639800c3
|
[connection] separate crypto streams from regular streams
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _initialize(self, peer_cid: bytes) -> None:
<0> # TLS
<1> self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
<2> self.tls.alpn_protocols = self._alpn_protocols
<3> self.tls.certificate = self._certificate
<4> self.tls.certificate_private_key = self._private_key
<5> self.tls.handshake_extensions = [
<6> (
<7> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,
<8> self._serialize_transport_parameters(),
<9> )
<10> ]
<11> self.tls.server_name = self._server_name
<12>
<13> # TLS session resumption
<14> if (
<15> self.is_client
<16> and self._session_ticket is not None
<17> and self._session_ticket.is_valid
<18> and self._session_ticket.server_name == self._server_name
<19> ):
<20> self.tls.session_ticket = self._session_ticket
<21>
<22> # parse saved QUIC transport parameters - for 0-RTT
<23> if self._session_ticket.max_early_data_size == 0xFFFFFFFF:
<24> for ext_type, ext_data in self._session_ticket.other_extensions:
<25> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
<26> self._parse_transport_parameters(
<27> ext_data, from_session_ticket=True
<28> )
<29> break
<30>
<31> # TLS callbacks
<32> if self._session_ticket_fetcher is not None:
<33> self.tls.get_session_ticket_cb = self._session_ticket_fetcher
<34> if self._session_ticket_handler is not None:
<35> self.tls.new_session_ticket_cb = self._session_ticket_handler
<36> self.tls.update_traffic_key_cb = self._update_traffic_key
<37>
<38> # packet spaces
<39> self._cryptos</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _initialize(self, peer_cid: bytes) -> None:
# offset: 1
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self.send_buffer = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
self._streams[tls.Epoch.INITIAL] = QuicStream()
self._streams[tls.Epoch.HANDSHAKE] = QuicStream()
self._streams[tls.Epoch.ONE_RTT] = QuicStream()
self._cryptos[tls.Epoch.INITIAL].setup_initial(
cid=peer_cid, is_client=self.is_client
)
self._loss.spaces = list(self._spaces.values())
self._packet_number = 0
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.connection.QuicConnection
_parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None
_serialize_transport_parameters() -> bytes
_update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._alpn_protocols = alpn_protocols
self._certificate = certificate
self._private_key = private_key
self._server_name = server_name
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._session_ticket = session_ticket
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._session_ticket_fetcher = session_ticket_fetcher
self._session_ticket_handler = session_ticket_handler
at: aioquic.connection.QuicConnection._get_or_create_stream
stream = self._streams[stream_id] = QuicStream(
connection=self,
stream_id=stream_id,
max_stream_data_local=max_stream_data_local,
max_stream_data_remote=max_stream_data_remote,
)
stream = self._streams.get(stream_id, None)
at: aioquic.crypto
CryptoPair()
at: aioquic.crypto.CryptoPair
setup_initial(cid: bytes, is_client: bool) -> None
===========unchanged ref 1===========
at: aioquic.recovery
QuicPacketSpace()
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.tls
Epoch()
ExtensionType(x: Union[str, bytes, bytearray], base: int)
ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None)
at: aioquic.tls.Context.__init__
self.alpn_protocols: Optional[List[str]] = None
self.certificate: Optional[x509.Certificate] = None
self.certificate_private_key: Optional[
Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]
] = None
self.handshake_extensions: List[Extension] = []
self.session_ticket: Optional[SessionTicket] = None
self.server_name: Optional[str] = None
self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None
self.new_session_ticket_cb: Optional[SessionTicketHandler] = None
self.update_traffic_key_cb: Callable[
[Direction, Epoch, CipherSuite, bytes], None
] = lambda d, e, c, s: None
at: aioquic.tls.SessionTicket
age_add: int
cipher_suite: CipherSuite
not_valid_after: datetime.datetime
not_valid_before: datetime.datetime
resumption_secret: bytes
server_name: str
ticket: bytes
max_early_data_size: Optional[int] = None
other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._close_at = self._loop.time() + self._local_idle_timeout
self._initialize(self._peer_cid)
+ self.tls.handle_message(b"", self._crypto_buffers)
- self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
|
|
aioquic.connection/QuicConnection._handle_crypto_frame
|
Modified
|
aiortc~aioquic
|
df649764a8faac4fb6e087d85752628e639800c3
|
[connection] separate crypto streams from regular streams
|
<3>:<add> stream = self._crypto_streams[context.epoch]
<del> stream = self._streams[context.epoch]
<9>:<add> self.tls.handle_message(data, self._crypto_buffers)
<del> self.tls.handle_message(data, self.send_buffer)
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a CRYPTO frame.
<2> """
<3> stream = self._streams[context.epoch]
<4> stream.add_frame(pull_crypto_frame(buf))
<5> data = stream.pull_data()
<6> if data:
<7> # pass data to TLS layer
<8> try:
<9> self.tls.handle_message(data, self.send_buffer)
<10> self._push_crypto_data()
<11> except tls.Alert as exc:
<12> raise QuicConnectionError(
<13> error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
<14> frame_type=QuicFrameType.CRYPTO,
<15> reason_phrase=str(exc),
<16> )
<17>
<18> # parse transport parameters
<19> if (
<20> not self._parameters_received
<21> and self.tls.received_extensions is not None
<22> ):
<23> for ext_type, ext_data in self.tls.received_extensions:
<24> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
<25> self._parse_transport_parameters(ext_data)
<26> self._parameters_received = True
<27> break
<28> assert (
<29> self._parameters_received
<30> ), "No QUIC transport parameters received"
<31> self._logger.info("ALPN negotiated protocol %s", self.alpn_protocol)
<32>
<33> # update current epoch
<34> if not self._handshake_complete and self.tls.state in [
<35> tls.State.CLIENT_POST_HANDSHAKE,
<36> tls.State.SERVER_POST_HANDSHAKE,
<37> ]:
<38> self._handshake_complete = True
<39> self._replenish_connection_ids()
<40> # wakeup waiter
<41> self._connected_waiter.set_result(None)
<42>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.connection
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)
at: aioquic.connection.QuicConnection
_close(is_initiator: bool) -> None
_push_crypto_data() -> None
_parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None
at: aioquic.connection.QuicConnection.__init__
self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._handshake_complete = False
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._parameters_received = False
at: aioquic.connection.QuicConnection._handle_connection_close_frame
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
error_code, reason_phrase = pull_application_close_frame(buf)
at: aioquic.connection.QuicConnection._handle_crypto_frame
self._handshake_complete = True
at: aioquic.connection.QuicConnection._initialize
self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
self._crypto_buffers = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
===========unchanged ref 1===========
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
at: aioquic.connection.QuicReceiveContext
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
time: float
at: aioquic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
pull_crypto_frame(buf: Buffer) -> QuicStreamFrame
at: aioquic.stream.QuicStream
add_frame(frame: QuicStreamFrame) -> None
pull_data() -> bytes
at: aioquic.tls
Alert(*args: object)
State()
ExtensionType(x: Union[str, bytes, bytearray], base: int)
ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: aioquic.tls.Alert
description: AlertDescription
at: aioquic.tls.Context
handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None
at: aioquic.tls.Context.__init__
self.received_extensions: Optional[List[Extension]] = None
self.state = State.CLIENT_HANDSHAKE_START
self.state = State.SERVER_EXPECT_CLIENT_HELLO
at: aioquic.tls.Context._client_handle_encrypted_extensions
self.received_extensions = encrypted_extensions.other_extensions
at: aioquic.tls.Context._server_handle_hello
self.received_extensions = peer_hello.other_extensions
===========unchanged ref 2===========
at: aioquic.tls.Context._set_state
self.state = state
at: logging.LoggerAdapter
logger: Logger
extra: Mapping[str, Any]
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._close_at = self._loop.time() + self._local_idle_timeout
self._initialize(self._peer_cid)
+ self.tls.handle_message(b"", self._crypto_buffers)
- self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _initialize(self, peer_cid: bytes) -> None:
# TLS
self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
self.tls.alpn_protocols = self._alpn_protocols
self.tls.certificate = self._certificate
self.tls.certificate_private_key = self._private_key
self.tls.handshake_extensions = [
(
tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,
self._serialize_transport_parameters(),
)
]
self.tls.server_name = self._server_name
# TLS session resumption
if (
self.is_client
and self._session_ticket is not None
and self._session_ticket.is_valid
and self._session_ticket.server_name == self._server_name
):
self.tls.session_ticket = self._session_ticket
# parse saved QUIC transport parameters - for 0-RTT
if self._session_ticket.max_early_data_size == 0xFFFFFFFF:
for ext_type, ext_data in self._session_ticket.other_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(
ext_data, from_session_ticket=True
)
break
# TLS callbacks
if self._session_ticket_fetcher is not None:
self.tls.get_session_ticket_cb = self._session_ticket_fetcher
if self._session_ticket_handler is not None:
self.tls.new_session_ticket_cb = self._session_ticket_handler
self.tls.update_traffic_key_cb = self._update_traffic_key
# packet spaces
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),</s>
|
aioquic.connection/QuicConnection._push_crypto_data
|
Modified
|
aiortc~aioquic
|
df649764a8faac4fb6e087d85752628e639800c3
|
[connection] separate crypto streams from regular streams
|
<0>:<add> for epoch, buf in self._crypto_buffers.items():
<del> for epoch, buf in self.send_buffer.items():
<1>:<add> self._crypto_streams[epoch].write(buf.data)
<del> self._streams[epoch].write(buf.data)
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
<0> for epoch, buf in self.send_buffer.items():
<1> self._streams[epoch].write(buf.data)
<2> buf.seek(0)
<3>
|
===========unchanged ref 0===========
at: aioquic.connection.QuicConnection.__init__
self._host_cid_seq = 1
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._close_at = self._loop.time() + self._local_idle_timeout
self._initialize(self._peer_cid)
+ self.tls.handle_message(b"", self._crypto_buffers)
- self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CRYPTO frame.
"""
+ stream = self._crypto_streams[context.epoch]
- stream = self._streams[context.epoch]
stream.add_frame(pull_crypto_frame(buf))
data = stream.pull_data()
if data:
# pass data to TLS layer
try:
+ self.tls.handle_message(data, self._crypto_buffers)
- self.tls.handle_message(data, self.send_buffer)
self._push_crypto_data()
except tls.Alert as exc:
raise QuicConnectionError(
error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
frame_type=QuicFrameType.CRYPTO,
reason_phrase=str(exc),
)
# parse transport parameters
if (
not self._parameters_received
and self.tls.received_extensions is not None
):
for ext_type, ext_data in self.tls.received_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(ext_data)
self._parameters_received = True
break
assert (
self._parameters_received
), "No QUIC transport parameters received"
self._logger.info("ALPN negotiated protocol %s", self.alpn_protocol)
# update current epoch
if not self._handshake_complete and self.tls.state in [
tls.State.CLIENT_POST_HANDSHAKE,
tls.State.SERVER_POST_HANDSHAKE,
]:
self._handshake_complete = True
self._replenish_connection_ids()
# wakeup waiter
self._connected_waiter.set_result(None)
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _initialize(self, peer_cid: bytes) -> None:
# TLS
self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
self.tls.alpn_protocols = self._alpn_protocols
self.tls.certificate = self._certificate
self.tls.certificate_private_key = self._private_key
self.tls.handshake_extensions = [
(
tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,
self._serialize_transport_parameters(),
)
]
self.tls.server_name = self._server_name
# TLS session resumption
if (
self.is_client
and self._session_ticket is not None
and self._session_ticket.is_valid
and self._session_ticket.server_name == self._server_name
):
self.tls.session_ticket = self._session_ticket
# parse saved QUIC transport parameters - for 0-RTT
if self._session_ticket.max_early_data_size == 0xFFFFFFFF:
for ext_type, ext_data in self._session_ticket.other_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(
ext_data, from_session_ticket=True
)
break
# TLS callbacks
if self._session_ticket_fetcher is not None:
self.tls.get_session_ticket_cb = self._session_ticket_fetcher
if self._session_ticket_handler is not None:
self.tls.new_session_ticket_cb = self._session_ticket_handler
self.tls.update_traffic_key_cb = self._update_traffic_key
# packet spaces
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),</s>
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _initialize(self, peer_cid: bytes) -> None:
# offset: 1
<s> CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
+ self._crypto_buffers = {
- self.send_buffer = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
+ }
+ self._crypto_streams = {
+ tls.Epoch.INITIAL: QuicStream(),
+ tls.Epoch.HANDSHAKE: QuicStream(),
+ tls.Epoch.ONE_RTT: QuicStream(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
- self._streams[tls.Epoch.INITIAL] = QuicStream()
- self._streams[tls.Epoch.HANDSHAKE] = QuicStream()
- self._streams[tls.Epoch.ONE_RTT] = QuicStream()
self._cryptos[tls.Epoch.INITIAL].setup_initial(
cid=peer_cid, is_client=self.is_client
)
self._loss.spaces = list(self._spaces.values())
self._packet_number = 0
|
aioquic.connection/QuicConnection._write_application
|
Modified
|
aiortc~aioquic
|
df649764a8faac4fb6e087d85752628e639800c3
|
[connection] separate crypto streams from regular streams
|
<0>:<add> crypto_stream: Optional[QuicStream] = None
<del> crypto_stream_id: Optional[tls.Epoch] = None
<3>:<add> crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
<del> crypto_stream_id = tls.Epoch.ONE_RTT
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
<0> crypto_stream_id: Optional[tls.Epoch] = None
<1> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
<2> crypto = self._cryptos[tls.Epoch.ONE_RTT]
<3> crypto_stream_id = tls.Epoch.ONE_RTT
<4> packet_type = PACKET_TYPE_ONE_RTT
<5> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
<6> crypto = self._cryptos[tls.Epoch.ZERO_RTT]
<7> packet_type = PACKET_TYPE_ZERO_RTT
<8> else:
<9> return
<10> space = self._spaces[tls.Epoch.ONE_RTT]
<11>
<12> buf = builder.buffer
<13>
<14> while builder.flight_bytes < max_bytes or self._probe_pending:
<15> # write header
<16> builder.start_packet(packet_type, crypto)
<17>
<18> if self._handshake_complete:
<19> # ACK
<20> if space.ack_required and space.ack_queue:
<21> builder.start_frame(QuicFrameType.ACK)
<22> push_ack_frame(buf, space.ack_queue, 0)
<23> space.ack_required = False
<24>
<25> # PATH CHALLENGE
<26> if (
<27> not network_path.is_validated
<28> and network_path.local_challenge is None
<29> ):
<30> self._logger.info(
<31> "Network path %s sending challenge", network_path.addr
<32> )
<33> network_path.local_challenge = os.urandom(8)
<34> builder.start_frame(QuicFrameType.PATH_CHALLENGE)
<35> push_bytes(buf, network_path.local_challenge)
<36>
<37> # PATH RESPONSE
</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 1
builder.start_frame(QuicFrameType.PATH_RESPONSE)
push_bytes(buf, network_path.remote_challenge)
network_path.remote_challenge = None
# NEW_CONNECTION_ID
for connection_id in self._host_cids:
if not connection_id.was_sent:
builder.start_frame(
QuicFrameType.NEW_CONNECTION_ID,
self._on_new_connection_id_delivery,
(connection_id,),
)
push_new_connection_id_frame(
buf,
connection_id.sequence_number,
connection_id.cid,
connection_id.stateless_reset_token,
)
connection_id.was_sent = True
self._connection_id_issued_handler(connection_id.cid)
# RETIRE_CONNECTION_ID
while self._retire_connection_ids:
sequence_number = self._retire_connection_ids.pop(0)
builder.start_frame(
QuicFrameType.RETIRE_CONNECTION_ID,
self._on_retire_connection_id_delivery,
(sequence_number,),
)
push_uint_var(buf, sequence_number)
# connection-level limits
self._write_connection_limits(builder=builder, space=space)
# stream-level limits
for stream_id, stream in self._streams.items():
if isinstance(stream_id, int):
self._write_stream_limits(
builder=builder, space=space, stream=stream
)
# PING (user-request)
if self._ping_pending:
self._logger.info("Sending PING in packet %d", builder.packet_number)
builder.start_frame(</s>
===========below chunk 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 2
<s>
self._logger.info("Sending PING in packet %d", builder.packet_number)
builder.start_frame(QuicFrameType.PING, self._on_ping_delivery)
self._ping_pending = False
# PING (probe)
if self._probe_pending:
self._logger.info("Sending probe")
builder.start_frame(QuicFrameType.PING)
self._probe_pending = False
for stream_id, stream in self._streams.items():
# CRYPTO
if stream_id == crypto_stream_id:
write_crypto_frame(builder=builder, space=space, stream=stream)
# STREAM
elif isinstance(stream_id, int):
self._remote_max_data_used += write_stream_frame(
builder=builder,
space=space,
stream=stream,
max_offset=min(
stream._send_highest
+ self._remote_max_data
- self._remote_max_data_used,
stream.max_stream_data_remote,
),
)
if not builder.end_packet():
break
===========unchanged ref 0===========
at: aioquic.buffer
push_bytes(buf: Buffer, v: bytes) -> None
push_uint_var(buf: Buffer, value: int) -> None
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int
QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None)
at: aioquic.connection.QuicConnection
_on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None
_on_ping_delivery(delivery: QuicDeliveryState) -> None
_on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None
_write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None
_write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._handshake_complete = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._remote_max_data = 0
===========unchanged ref 1===========
self._remote_max_data_used = 0
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._streams: Dict[int, QuicStream] = {}
self._ping_pending = False
self._probe_pending = False
self._retire_connection_ids: List[int] = []
self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None
at: aioquic.connection.QuicConnection._handle_crypto_frame
self._handshake_complete = True
at: aioquic.connection.QuicConnection._handle_max_data_frame
self._remote_max_data = max_data
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicConnection._on_ping_delivery
self._ping_pending = True
at: aioquic.connection.QuicConnection._send_probe
self._probe_pending = True
at: aioquic.connection.QuicConnection._update_traffic_key
crypto = self._cryptos[epoch]
at: aioquic.connection.QuicConnection.ping
self._ping_pending = True
at: aioquic.connection.QuicConnectionId
cid: bytes
sequence_number: int
stateless_reset_token: bytes = b""
|
aioquic.connection/QuicConnection._write_handshake
|
Modified
|
aiortc~aioquic
|
df649764a8faac4fb6e087d85752628e639800c3
|
[connection] separate crypto streams from regular streams
|
<22>:<add> builder=builder, space=space, stream=self._crypto_streams[epoch]
<del> builder=builder, space=space, stream=self._streams[epoch]
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_handshake(
self, builder: QuicPacketBuilder, epoch: tls.Epoch, max_bytes: int
) -> None:
<0> crypto = self._cryptos[epoch]
<1> if not crypto.send.is_valid():
<2> return
<3>
<4> buf = builder.buffer
<5> space = self._spaces[epoch]
<6>
<7> while builder.flight_bytes < max_bytes:
<8> if epoch == tls.Epoch.INITIAL:
<9> packet_type = PACKET_TYPE_INITIAL
<10> else:
<11> packet_type = PACKET_TYPE_HANDSHAKE
<12> builder.start_packet(packet_type, crypto)
<13>
<14> # ACK
<15> if space.ack_required and space.ack_queue:
<16> builder.start_frame(QuicFrameType.ACK)
<17> push_ack_frame(buf, space.ack_queue, 0)
<18> space.ack_required = False
<19>
<20> # CRYPTO
<21> write_crypto_frame(
<22> builder=builder, space=space, stream=self._streams[epoch]
<23> )
<24>
<25> if not builder.end_packet():
<26> break
<27>
|
===========unchanged ref 0===========
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.crypto.CryptoContext
is_valid() -> bool
at: aioquic.crypto.CryptoPair.__init__
self.send = CryptoContext()
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
push_ack_frame(buf: Buffer, rangeset: RangeSet, delay: int) -> None
===========unchanged ref 1===========
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
at: aioquic.packet_builder.QuicPacketBuilder
start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.packet_builder.QuicPacketBuilder.__init__
self.buffer = Buffer(PACKET_MAX_SIZE)
at: aioquic.recovery.QuicPacketSpace.__init__
self.ack_queue = RangeSet()
self.ack_required = False
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _push_crypto_data(self) -> None:
+ for epoch, buf in self._crypto_buffers.items():
- for epoch, buf in self.send_buffer.items():
+ self._crypto_streams[epoch].write(buf.data)
- self._streams[epoch].write(buf.data)
buf.seek(0)
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _connect(self) -> None:
"""
Start the client handshake.
"""
assert self.is_client
self._close_at = self._loop.time() + self._local_idle_timeout
self._initialize(self._peer_cid)
+ self.tls.handle_message(b"", self._crypto_buffers)
- self.tls.handle_message(b"", self.send_buffer)
self._push_crypto_data()
self._send_pending()
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CRYPTO frame.
"""
+ stream = self._crypto_streams[context.epoch]
- stream = self._streams[context.epoch]
stream.add_frame(pull_crypto_frame(buf))
data = stream.pull_data()
if data:
# pass data to TLS layer
try:
+ self.tls.handle_message(data, self._crypto_buffers)
- self.tls.handle_message(data, self.send_buffer)
self._push_crypto_data()
except tls.Alert as exc:
raise QuicConnectionError(
error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
frame_type=QuicFrameType.CRYPTO,
reason_phrase=str(exc),
)
# parse transport parameters
if (
not self._parameters_received
and self.tls.received_extensions is not None
):
for ext_type, ext_data in self.tls.received_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(ext_data)
self._parameters_received = True
break
assert (
self._parameters_received
), "No QUIC transport parameters received"
self._logger.info("ALPN negotiated protocol %s", self.alpn_protocol)
# update current epoch
if not self._handshake_complete and self.tls.state in [
tls.State.CLIENT_POST_HANDSHAKE,
tls.State.SERVER_POST_HANDSHAKE,
]:
self._handshake_complete = True
self._replenish_connection_ids()
# wakeup waiter
self._connected_waiter.set_result(None)
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
+ crypto_stream: Optional[QuicStream] = None
- crypto_stream_id: Optional[tls.Epoch] = None
if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ONE_RTT]
+ crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
- crypto_stream_id = tls.Epoch.ONE_RTT
packet_type = PACKET_TYPE_ONE_RTT
elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ZERO_RTT]
packet_type = PACKET_TYPE_ZERO_RTT
else:
return
space = self._spaces[tls.Epoch.ONE_RTT]
buf = builder.buffer
while builder.flight_bytes < max_bytes or self._probe_pending:
# write header
builder.start_packet(packet_type, crypto)
if self._handshake_complete:
# ACK
if space.ack_required and space.ack_queue:
builder.start_frame(QuicFrameType.ACK)
push_ack_frame(buf, space.ack_queue, 0)
space.ack_required = False
# PATH CHALLENGE
if (
not network_path.is_validated
and network_path.local_challenge is None
):
self._logger.info(
"Network path %s sending challenge", network_path.addr
)
network_path.local_challenge = os.urandom(8)
builder.start_frame(QuicFrameType.PATH_CHALLENGE)
push_bytes(buf, network_path.local_challenge)
# PATH RESPONSE</s>
|
aioquic.stream/QuicStream.__init__
|
Modified
|
aiortc~aioquic
|
0932423e05e927513d518a90c01eb454e4d60e7d
|
[stream] remove QuicStream.has_data_to_read()
|
<13>:<add> self._recv_buffer_fin: Optional[int] = None
<add> self._recv_buffer_start = 0 # the offset for the start of the buffer
<del> self._recv_fin = False
<15>:<del> self._recv_start = 0 # the offset for the start of the buffer
<21>:<add> self._send_buffer_start = 0 # the offset for the start of the buffer
<add> self._send_buffer_stop = 0 # the offset for the stop of the buffer
<24>:<del> self._send_buffer_start = 0 # the offset for the start of the buffer
<25>:<del> self._send_buffer_stop = 0 # the offset for the stop of the buffer
|
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def __init__(
self,
stream_id: Optional[int] = None,
connection: Optional[Any] = None,
max_stream_data_local: int = 0,
max_stream_data_remote: int = 0,
) -> None:
<0> self._connection = connection
<1> self.max_stream_data_local = max_stream_data_local
<2> self.max_stream_data_local_sent = max_stream_data_local
<3> self.max_stream_data_remote = max_stream_data_remote
<4>
<5> if stream_id is not None:
<6> self.reader = asyncio.StreamReader()
<7> self.writer = asyncio.StreamWriter(self, None, self.reader, None)
<8> else:
<9> self.reader = None
<10> self.writer = None
<11>
<12> self._recv_buffer = bytearray()
<13> self._recv_fin = False
<14> self._recv_highest = 0 # the highest offset ever seen
<15> self._recv_start = 0 # the offset for the start of the buffer
<16> self._recv_ranges = RangeSet()
<17>
<18> self._send_acked = RangeSet()
<19> self._send_buffer = bytearray()
<20> self._send_buffer_fin: Optional[int] = None
<21> self._send_highest = 0
<22> self._send_pending = RangeSet()
<23> self._send_pending_eof = False
<24> self._send_buffer_start = 0 # the offset for the start of the buffer
<25> self._send_buffer_stop = 0 # the offset for the stop of the buffer
<26>
<27> self.__stream_id = stream_id
<28>
|
===========unchanged ref 0===========
at: aioquic.rangeset
RangeSet(ranges: Iterable[range]=[])
at: aioquic.stream.QuicStream.add_frame
self._recv_highest = frame_end
self._recv_buffer += bytearray(gap)
self._recv_buffer_fin = frame_end
at: aioquic.stream.QuicStream.get_frame
self._send_pending_eof = False
self._send_highest = stop
at: aioquic.stream.QuicStream.on_data_delivery
self._send_buffer_start += size
self._send_pending_eof = True
at: aioquic.stream.QuicStream.pull_data
self._recv_buffer = self._recv_buffer[pos:]
self._recv_buffer_start = r.stop
at: aioquic.stream.QuicStream.write
self._send_buffer += data
self._send_buffer_stop += size
at: aioquic.stream.QuicStream.write_eof
self._send_buffer_fin = self._send_buffer_stop
self._send_pending_eof = True
at: asyncio.streams
StreamWriter(transport: transports.BaseTransport, protocol: protocols.BaseProtocol, reader: Optional[StreamReader], loop: events.AbstractEventLoop)
StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...)
at: asyncio.transports.BaseTransport
__slots__ = ('_extra',)
__init__(self, extra: Optional[Mapping[Any, Any]]=...) -> None
|
aioquic.stream/QuicStream.add_frame
|
Modified
|
aiortc~aioquic
|
0932423e05e927513d518a90c01eb454e4d60e7d
|
[stream] remove QuicStream.has_data_to_read()
|
<3>:<add> pos = frame.offset - self._recv_buffer_start
<del> pos = frame.offset - self._recv_start
<8>:<add> if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin:
<del> if self._recv_fin and frame_end > self._recv_highest:
<32>:<add> self._recv_buffer_fin = frame_end
<del> self._recv_fin = True
<35>:<add> data = self.pull_data()
<add> if data:
<del> if self.has_data_to_read():
<36>:<add> self.reader.feed_data(data)
<del> self.reader.feed_data(self.pull_data())
<37>:<add> if self._recv_buffer_start == self._recv_buffer_fin:
<del> if self._recv_fin and not self._recv_ranges:
|
# module: aioquic.stream
class QuicStream(asyncio.Transport):
# reader
def add_frame(self, frame: QuicStreamFrame) -> None:
<0> """
<1> Add a frame of received data.
<2> """
<3> pos = frame.offset - self._recv_start
<4> count = len(frame.data)
<5> frame_end = frame.offset + count
<6>
<7> # we should receive no more data beyond FIN!
<8> if self._recv_fin and frame_end > self._recv_highest:
<9> raise Exception("Data received beyond FIN")
<10>
<11> if pos + count > 0:
<12> # frame has been partially consumed
<13> if pos < 0:
<14> count += pos
<15> frame.data = frame.data[-pos:]
<16> frame.offset -= pos
<17> pos = 0
<18>
<19> # marked received
<20> if count:
<21> self._recv_ranges.add(frame.offset, frame_end)
<22> if frame_end > self._recv_highest:
<23> self._recv_highest = frame_end
<24>
<25> # add data
<26> gap = pos - len(self._recv_buffer)
<27> if gap > 0:
<28> self._recv_buffer += bytearray(gap)
<29> self._recv_buffer[pos : pos + count] = frame.data
<30>
<31> if frame.fin:
<32> self._recv_fin = True
<33>
<34> if self.reader:
<35> if self.has_data_to_read():
<36> self.reader.feed_data(self.pull_data())
<37> if self._recv_fin and not self._recv_ranges:
<38> self.reader.feed_eof()
<39>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicStreamFrame(data: bytes=b"", fin: bool=False, offset: int=0)
at: aioquic.packet.QuicStreamFrame
data: bytes = b""
fin: bool = False
offset: int = 0
at: aioquic.rangeset.RangeSet
add(start: int, stop: Optional[int]=None) -> None
at: aioquic.stream.QuicStream
pull_data() -> bytes
at: aioquic.stream.QuicStream.__init__
self.reader = asyncio.StreamReader()
self.reader = None
self._recv_buffer = bytearray()
self._recv_buffer_fin: Optional[int] = None
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_highest = 0 # the highest offset ever seen
self._recv_ranges = RangeSet()
at: aioquic.stream.QuicStream.pull_data
self._recv_buffer = self._recv_buffer[pos:]
self._recv_buffer_start = r.stop
at: asyncio.streams.StreamReader
_source_traceback = None
feed_data(data: bytes) -> None
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def __init__(
self,
stream_id: Optional[int] = None,
connection: Optional[Any] = None,
max_stream_data_local: int = 0,
max_stream_data_remote: int = 0,
) -> None:
self._connection = connection
self.max_stream_data_local = max_stream_data_local
self.max_stream_data_local_sent = max_stream_data_local
self.max_stream_data_remote = max_stream_data_remote
if stream_id is not None:
self.reader = asyncio.StreamReader()
self.writer = asyncio.StreamWriter(self, None, self.reader, None)
else:
self.reader = None
self.writer = None
self._recv_buffer = bytearray()
+ self._recv_buffer_fin: Optional[int] = None
+ self._recv_buffer_start = 0 # the offset for the start of the buffer
- self._recv_fin = False
self._recv_highest = 0 # the highest offset ever seen
- self._recv_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
self._send_acked = RangeSet()
self._send_buffer = bytearray()
self._send_buffer_fin: Optional[int] = None
+ self._send_buffer_start = 0 # the offset for the start of the buffer
+ self._send_buffer_stop = 0 # the offset for the stop of the buffer
self._send_highest = 0
self._send_pending = RangeSet()
self._send_pending_eof = False
- self._send_buffer_start = 0 # the offset for the start of the buffer
- self._send_buffer_stop = 0 # the offset for the stop of the buffer
self.__stream_id = stream_id
|
aioquic.stream/QuicStream.pull_data
|
Modified
|
aiortc~aioquic
|
0932423e05e927513d518a90c01eb454e4d60e7d
|
[stream] remove QuicStream.has_data_to_read()
|
<3>:<add> try:
<add> has_data_to_read = self._recv_ranges[0].start == self._recv_buffer_start
<add> except IndexError:
<add> has_data_to_read = False
<add> if not has_data_to_read:
<del> if not self.has_data_to_read():
<10>:<add> self._recv_buffer_start = r.stop
<del> self._recv_start = r.stop
|
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def pull_data(self) -> bytes:
<0> """
<1> Pull received data.
<2> """
<3> if not self.has_data_to_read():
<4> return b""
<5>
<6> r = self._recv_ranges.shift()
<7> pos = r.stop - r.start
<8> data = self._recv_buffer[:pos]
<9> self._recv_buffer = self._recv_buffer[pos:]
<10> self._recv_start = r.stop
<11> return data
<12>
|
===========unchanged ref 0===========
at: aioquic.rangeset.RangeSet
shift() -> range
at: aioquic.stream.QuicStream.__init__
self._recv_buffer = bytearray()
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
at: aioquic.stream.QuicStream.add_frame
self._recv_buffer += bytearray(gap)
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
- def has_data_to_read(self) -> bool:
- return (
- bool(self._recv_ranges) and self._recv_ranges[0].start == self._recv_start
- )
-
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
# reader
def add_frame(self, frame: QuicStreamFrame) -> None:
"""
Add a frame of received data.
"""
+ pos = frame.offset - self._recv_buffer_start
- pos = frame.offset - self._recv_start
count = len(frame.data)
frame_end = frame.offset + count
# we should receive no more data beyond FIN!
+ if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin:
- if self._recv_fin and frame_end > self._recv_highest:
raise Exception("Data received beyond FIN")
if pos + count > 0:
# frame has been partially consumed
if pos < 0:
count += pos
frame.data = frame.data[-pos:]
frame.offset -= pos
pos = 0
# marked received
if count:
self._recv_ranges.add(frame.offset, frame_end)
if frame_end > self._recv_highest:
self._recv_highest = frame_end
# add data
gap = pos - len(self._recv_buffer)
if gap > 0:
self._recv_buffer += bytearray(gap)
self._recv_buffer[pos : pos + count] = frame.data
if frame.fin:
+ self._recv_buffer_fin = frame_end
- self._recv_fin = True
if self.reader:
+ data = self.pull_data()
+ if data:
- if self.has_data_to_read():
+ self.reader.feed_data(data)
- self.reader.feed_data(self.pull_data())
+ if self._recv_buffer_start == self._recv_buffer_fin:
- if self._recv_fin and not self._recv_ranges:
self.reader.feed_eof()
===========changed ref 2===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def __init__(
self,
stream_id: Optional[int] = None,
connection: Optional[Any] = None,
max_stream_data_local: int = 0,
max_stream_data_remote: int = 0,
) -> None:
self._connection = connection
self.max_stream_data_local = max_stream_data_local
self.max_stream_data_local_sent = max_stream_data_local
self.max_stream_data_remote = max_stream_data_remote
if stream_id is not None:
self.reader = asyncio.StreamReader()
self.writer = asyncio.StreamWriter(self, None, self.reader, None)
else:
self.reader = None
self.writer = None
self._recv_buffer = bytearray()
+ self._recv_buffer_fin: Optional[int] = None
+ self._recv_buffer_start = 0 # the offset for the start of the buffer
- self._recv_fin = False
self._recv_highest = 0 # the highest offset ever seen
- self._recv_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
self._send_acked = RangeSet()
self._send_buffer = bytearray()
self._send_buffer_fin: Optional[int] = None
+ self._send_buffer_start = 0 # the offset for the start of the buffer
+ self._send_buffer_stop = 0 # the offset for the stop of the buffer
self._send_highest = 0
self._send_pending = RangeSet()
self._send_pending_eof = False
- self._send_buffer_start = 0 # the offset for the start of the buffer
- self._send_buffer_stop = 0 # the offset for the stop of the buffer
self.__stream_id = stream_id
|
tests.test_stream/QuicStreamTest.test_recv_empty
|
Modified
|
aiortc~aioquic
|
0932423e05e927513d518a90c01eb454e4d60e7d
|
[stream] remove QuicStream.has_data_to_read()
|
<3>:<add> self.assertEqual(stream._recv_buffer_start, 0)
<del> self.assertEqual(stream._recv_start, 0)
<9>:<add> self.assertEqual(stream._recv_buffer_start, 0)
<del> self.assertEqual(stream._recv_start, 0)
|
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_empty(self):
<0> stream = QuicStream()
<1> self.assertEqual(bytes(stream._recv_buffer), b"")
<2> self.assertEqual(list(stream._recv_ranges), [])
<3> self.assertEqual(stream._recv_start, 0)
<4>
<5> # empty
<6> self.assertEqual(stream.pull_data(), b"")
<7> self.assertEqual(bytes(stream._recv_buffer), b"")
<8> self.assertEqual(list(stream._recv_ranges), [])
<9> self.assertEqual(stream._recv_start, 0)
<10>
|
===========unchanged ref 0===========
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.stream.QuicStream
pull_data() -> bytes
at: aioquic.stream.QuicStream.__init__
self._recv_buffer = bytearray()
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
at: aioquic.stream.QuicStream.add_frame
self._recv_buffer += bytearray(gap)
at: aioquic.stream.QuicStream.pull_data
self._recv_buffer = self._recv_buffer[pos:]
self._recv_buffer_start = r.stop
at: unittest.case.TestCase
failureException: Type[BaseException]
longMessage: bool
maxDiff: Optional[int]
_testMethodName: str
_testMethodDoc: str
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def pull_data(self) -> bytes:
"""
Pull received data.
"""
+ try:
+ has_data_to_read = self._recv_ranges[0].start == self._recv_buffer_start
+ except IndexError:
+ has_data_to_read = False
+ if not has_data_to_read:
- if not self.has_data_to_read():
return b""
r = self._recv_ranges.shift()
pos = r.stop - r.start
data = self._recv_buffer[:pos]
self._recv_buffer = self._recv_buffer[pos:]
+ self._recv_buffer_start = r.stop
- self._recv_start = r.stop
return data
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
- def has_data_to_read(self) -> bool:
- return (
- bool(self._recv_ranges) and self._recv_ranges[0].start == self._recv_start
- )
-
===========changed ref 2===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def __init__(
self,
stream_id: Optional[int] = None,
connection: Optional[Any] = None,
max_stream_data_local: int = 0,
max_stream_data_remote: int = 0,
) -> None:
self._connection = connection
self.max_stream_data_local = max_stream_data_local
self.max_stream_data_local_sent = max_stream_data_local
self.max_stream_data_remote = max_stream_data_remote
if stream_id is not None:
self.reader = asyncio.StreamReader()
self.writer = asyncio.StreamWriter(self, None, self.reader, None)
else:
self.reader = None
self.writer = None
self._recv_buffer = bytearray()
+ self._recv_buffer_fin: Optional[int] = None
+ self._recv_buffer_start = 0 # the offset for the start of the buffer
- self._recv_fin = False
self._recv_highest = 0 # the highest offset ever seen
- self._recv_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
self._send_acked = RangeSet()
self._send_buffer = bytearray()
self._send_buffer_fin: Optional[int] = None
+ self._send_buffer_start = 0 # the offset for the start of the buffer
+ self._send_buffer_stop = 0 # the offset for the stop of the buffer
self._send_highest = 0
self._send_pending = RangeSet()
self._send_pending_eof = False
- self._send_buffer_start = 0 # the offset for the start of the buffer
- self._send_buffer_stop = 0 # the offset for the stop of the buffer
self.__stream_id = stream_id
===========changed ref 3===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
# reader
def add_frame(self, frame: QuicStreamFrame) -> None:
"""
Add a frame of received data.
"""
+ pos = frame.offset - self._recv_buffer_start
- pos = frame.offset - self._recv_start
count = len(frame.data)
frame_end = frame.offset + count
# we should receive no more data beyond FIN!
+ if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin:
- if self._recv_fin and frame_end > self._recv_highest:
raise Exception("Data received beyond FIN")
if pos + count > 0:
# frame has been partially consumed
if pos < 0:
count += pos
frame.data = frame.data[-pos:]
frame.offset -= pos
pos = 0
# marked received
if count:
self._recv_ranges.add(frame.offset, frame_end)
if frame_end > self._recv_highest:
self._recv_highest = frame_end
# add data
gap = pos - len(self._recv_buffer)
if gap > 0:
self._recv_buffer += bytearray(gap)
self._recv_buffer[pos : pos + count] = frame.data
if frame.fin:
+ self._recv_buffer_fin = frame_end
- self._recv_fin = True
if self.reader:
+ data = self.pull_data()
+ if data:
- if self.has_data_to_read():
+ self.reader.feed_data(data)
- self.reader.feed_data(self.pull_data())
+ if self._recv_buffer_start == self._recv_buffer_fin:
- if self._recv_fin and not self._recv_ranges:
self.reader.feed_eof()
|
tests.test_stream/QuicStreamTest.test_recv_ordered
|
Modified
|
aiortc~aioquic
|
0932423e05e927513d518a90c01eb454e4d60e7d
|
[stream] remove QuicStream.has_data_to_read()
|
<6>:<add> self.assertEqual(stream._recv_buffer_start, 0)
<del> self.assertEqual(stream._recv_start, 0)
<12>:<add> self.assertEqual(stream._recv_buffer_start, 8)
<del> self.assertEqual(stream._recv_start, 8)
<18>:<add> self.assertEqual(stream._recv_buffer_start, 8)
<del> self.assertEqual(stream._recv_start, 8)
<24>:<add> self.assertEqual(stream._recv_buffer_start, 16)
<del> self.assertEqual(stream._recv_start, 16)
|
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_ordered(self):
<0> stream = QuicStream()
<1>
<2> # add data at start
<3> stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
<4> self.assertEqual(bytes(stream._recv_buffer), b"01234567")
<5> self.assertEqual(list(stream._recv_ranges), [range(0, 8)])
<6> self.assertEqual(stream._recv_start, 0)
<7>
<8> # pull data
<9> self.assertEqual(stream.pull_data(), b"01234567")
<10> self.assertEqual(bytes(stream._recv_buffer), b"")
<11> self.assertEqual(list(stream._recv_ranges), [])
<12> self.assertEqual(stream._recv_start, 8)
<13>
<14> # add more data
<15> stream.add_frame(QuicStreamFrame(offset=8, data=b"89012345"))
<16> self.assertEqual(bytes(stream._recv_buffer), b"89012345")
<17> self.assertEqual(list(stream._recv_ranges), [range(8, 16)])
<18> self.assertEqual(stream._recv_start, 8)
<19>
<20> # pull data
<21> self.assertEqual(stream.pull_data(), b"89012345")
<22> self.assertEqual(bytes(stream._recv_buffer), b"")
<23> self.assertEqual(list(stream._recv_ranges), [])
<24> self.assertEqual(stream._recv_start, 16)
<25>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicStreamFrame(data: bytes=b"", fin: bool=False, offset: int=0)
at: aioquic.packet.QuicStreamFrame
data: bytes = b""
fin: bool = False
offset: int = 0
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.stream.QuicStream
add_frame(frame: QuicStreamFrame) -> None
pull_data() -> bytes
at: aioquic.stream.QuicStream.__init__
self._recv_buffer = bytearray()
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
at: aioquic.stream.QuicStream.add_frame
self._recv_buffer += bytearray(gap)
at: aioquic.stream.QuicStream.pull_data
self._recv_buffer = self._recv_buffer[pos:]
self._recv_buffer_start = r.stop
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def pull_data(self) -> bytes:
"""
Pull received data.
"""
+ try:
+ has_data_to_read = self._recv_ranges[0].start == self._recv_buffer_start
+ except IndexError:
+ has_data_to_read = False
+ if not has_data_to_read:
- if not self.has_data_to_read():
return b""
r = self._recv_ranges.shift()
pos = r.stop - r.start
data = self._recv_buffer[:pos]
self._recv_buffer = self._recv_buffer[pos:]
+ self._recv_buffer_start = r.stop
- self._recv_start = r.stop
return data
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
# reader
def add_frame(self, frame: QuicStreamFrame) -> None:
"""
Add a frame of received data.
"""
+ pos = frame.offset - self._recv_buffer_start
- pos = frame.offset - self._recv_start
count = len(frame.data)
frame_end = frame.offset + count
# we should receive no more data beyond FIN!
+ if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin:
- if self._recv_fin and frame_end > self._recv_highest:
raise Exception("Data received beyond FIN")
if pos + count > 0:
# frame has been partially consumed
if pos < 0:
count += pos
frame.data = frame.data[-pos:]
frame.offset -= pos
pos = 0
# marked received
if count:
self._recv_ranges.add(frame.offset, frame_end)
if frame_end > self._recv_highest:
self._recv_highest = frame_end
# add data
gap = pos - len(self._recv_buffer)
if gap > 0:
self._recv_buffer += bytearray(gap)
self._recv_buffer[pos : pos + count] = frame.data
if frame.fin:
+ self._recv_buffer_fin = frame_end
- self._recv_fin = True
if self.reader:
+ data = self.pull_data()
+ if data:
- if self.has_data_to_read():
+ self.reader.feed_data(data)
- self.reader.feed_data(self.pull_data())
+ if self._recv_buffer_start == self._recv_buffer_fin:
- if self._recv_fin and not self._recv_ranges:
self.reader.feed_eof()
===========changed ref 2===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_empty(self):
stream = QuicStream()
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# empty
self.assertEqual(stream.pull_data(), b"")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
===========changed ref 3===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
- def has_data_to_read(self) -> bool:
- return (
- bool(self._recv_ranges) and self._recv_ranges[0].start == self._recv_start
- )
-
===========changed ref 4===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def __init__(
self,
stream_id: Optional[int] = None,
connection: Optional[Any] = None,
max_stream_data_local: int = 0,
max_stream_data_remote: int = 0,
) -> None:
self._connection = connection
self.max_stream_data_local = max_stream_data_local
self.max_stream_data_local_sent = max_stream_data_local
self.max_stream_data_remote = max_stream_data_remote
if stream_id is not None:
self.reader = asyncio.StreamReader()
self.writer = asyncio.StreamWriter(self, None, self.reader, None)
else:
self.reader = None
self.writer = None
self._recv_buffer = bytearray()
+ self._recv_buffer_fin: Optional[int] = None
+ self._recv_buffer_start = 0 # the offset for the start of the buffer
- self._recv_fin = False
self._recv_highest = 0 # the highest offset ever seen
- self._recv_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
self._send_acked = RangeSet()
self._send_buffer = bytearray()
self._send_buffer_fin: Optional[int] = None
+ self._send_buffer_start = 0 # the offset for the start of the buffer
+ self._send_buffer_stop = 0 # the offset for the stop of the buffer
self._send_highest = 0
self._send_pending = RangeSet()
self._send_pending_eof = False
- self._send_buffer_start = 0 # the offset for the start of the buffer
- self._send_buffer_stop = 0 # the offset for the stop of the buffer
self.__stream_id = stream_id
|
tests.test_stream/QuicStreamTest.test_recv_ordered_2
|
Modified
|
aiortc~aioquic
|
0932423e05e927513d518a90c01eb454e4d60e7d
|
[stream] remove QuicStream.has_data_to_read()
|
<6>:<add> self.assertEqual(stream._recv_buffer_start, 0)
<del> self.assertEqual(stream._recv_start, 0)
<12>:<add> self.assertEqual(stream._recv_buffer_start, 0)
<del> self.assertEqual(stream._recv_start, 0)
<18>:<add> self.assertEqual(stream._recv_buffer_start, 16)
<del> self.assertEqual(stream._recv_start, 16)
|
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_ordered_2(self):
<0> stream = QuicStream()
<1>
<2> # add data at start
<3> stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
<4> self.assertEqual(bytes(stream._recv_buffer), b"01234567")
<5> self.assertEqual(list(stream._recv_ranges), [range(0, 8)])
<6> self.assertEqual(stream._recv_start, 0)
<7>
<8> # add more data
<9> stream.add_frame(QuicStreamFrame(offset=8, data=b"89012345"))
<10> self.assertEqual(bytes(stream._recv_buffer), b"0123456789012345")
<11> self.assertEqual(list(stream._recv_ranges), [range(0, 16)])
<12> self.assertEqual(stream._recv_start, 0)
<13>
<14> # pull data
<15> self.assertEqual(stream.pull_data(), b"0123456789012345")
<16> self.assertEqual(bytes(stream._recv_buffer), b"")
<17> self.assertEqual(list(stream._recv_ranges), [])
<18> self.assertEqual(stream._recv_start, 16)
<19>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicStreamFrame(data: bytes=b"", fin: bool=False, offset: int=0)
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.stream.QuicStream
add_frame(frame: QuicStreamFrame) -> None
pull_data() -> bytes
at: aioquic.stream.QuicStream.__init__
self._recv_buffer = bytearray()
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
at: aioquic.stream.QuicStream.add_frame
self._recv_buffer += bytearray(gap)
at: aioquic.stream.QuicStream.pull_data
self._recv_buffer = self._recv_buffer[pos:]
self._recv_buffer_start = r.stop
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def pull_data(self) -> bytes:
"""
Pull received data.
"""
+ try:
+ has_data_to_read = self._recv_ranges[0].start == self._recv_buffer_start
+ except IndexError:
+ has_data_to_read = False
+ if not has_data_to_read:
- if not self.has_data_to_read():
return b""
r = self._recv_ranges.shift()
pos = r.stop - r.start
data = self._recv_buffer[:pos]
self._recv_buffer = self._recv_buffer[pos:]
+ self._recv_buffer_start = r.stop
- self._recv_start = r.stop
return data
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
# reader
def add_frame(self, frame: QuicStreamFrame) -> None:
"""
Add a frame of received data.
"""
+ pos = frame.offset - self._recv_buffer_start
- pos = frame.offset - self._recv_start
count = len(frame.data)
frame_end = frame.offset + count
# we should receive no more data beyond FIN!
+ if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin:
- if self._recv_fin and frame_end > self._recv_highest:
raise Exception("Data received beyond FIN")
if pos + count > 0:
# frame has been partially consumed
if pos < 0:
count += pos
frame.data = frame.data[-pos:]
frame.offset -= pos
pos = 0
# marked received
if count:
self._recv_ranges.add(frame.offset, frame_end)
if frame_end > self._recv_highest:
self._recv_highest = frame_end
# add data
gap = pos - len(self._recv_buffer)
if gap > 0:
self._recv_buffer += bytearray(gap)
self._recv_buffer[pos : pos + count] = frame.data
if frame.fin:
+ self._recv_buffer_fin = frame_end
- self._recv_fin = True
if self.reader:
+ data = self.pull_data()
+ if data:
- if self.has_data_to_read():
+ self.reader.feed_data(data)
- self.reader.feed_data(self.pull_data())
+ if self._recv_buffer_start == self._recv_buffer_fin:
- if self._recv_fin and not self._recv_ranges:
self.reader.feed_eof()
===========changed ref 2===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_empty(self):
stream = QuicStream()
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# empty
self.assertEqual(stream.pull_data(), b"")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
===========changed ref 3===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_ordered(self):
stream = QuicStream()
# add data at start
stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
self.assertEqual(bytes(stream._recv_buffer), b"01234567")
self.assertEqual(list(stream._recv_ranges), [range(0, 8)])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# pull data
self.assertEqual(stream.pull_data(), b"01234567")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 8)
- self.assertEqual(stream._recv_start, 8)
# add more data
stream.add_frame(QuicStreamFrame(offset=8, data=b"89012345"))
self.assertEqual(bytes(stream._recv_buffer), b"89012345")
self.assertEqual(list(stream._recv_ranges), [range(8, 16)])
+ self.assertEqual(stream._recv_buffer_start, 8)
- self.assertEqual(stream._recv_start, 8)
# pull data
self.assertEqual(stream.pull_data(), b"89012345")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 16)
- self.assertEqual(stream._recv_start, 16)
===========changed ref 4===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
- def has_data_to_read(self) -> bool:
- return (
- bool(self._recv_ranges) and self._recv_ranges[0].start == self._recv_start
- )
-
|
tests.test_stream/QuicStreamTest.test_recv_unordered
|
Modified
|
aiortc~aioquic
|
0932423e05e927513d518a90c01eb454e4d60e7d
|
[stream] remove QuicStream.has_data_to_read()
|
<8>:<add> self.assertEqual(stream._recv_buffer_start, 0)
<del> self.assertEqual(stream._recv_start, 0)
<14>:<add> self.assertEqual(stream._recv_buffer_start, 0)
<del> self.assertEqual(stream._recv_start, 0)
<20>:<add> self.assertEqual(stream._recv_buffer_start, 16)
<del> self.assertEqual(stream._recv_start, 16)
|
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_unordered(self):
<0> stream = QuicStream()
<1>
<2> # add data at offset 8
<3> stream.add_frame(QuicStreamFrame(offset=8, data=b"89012345"))
<4> self.assertEqual(
<5> bytes(stream._recv_buffer), b"\x00\x00\x00\x00\x00\x00\x00\x0089012345"
<6> )
<7> self.assertEqual(list(stream._recv_ranges), [range(8, 16)])
<8> self.assertEqual(stream._recv_start, 0)
<9>
<10> # add data at offset 0
<11> stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
<12> self.assertEqual(bytes(stream._recv_buffer), b"0123456789012345")
<13> self.assertEqual(list(stream._recv_ranges), [range(0, 16)])
<14> self.assertEqual(stream._recv_start, 0)
<15>
<16> # pull data
<17> self.assertEqual(stream.pull_data(), b"0123456789012345")
<18> self.assertEqual(bytes(stream._recv_buffer), b"")
<19> self.assertEqual(list(stream._recv_ranges), [])
<20> self.assertEqual(stream._recv_start, 16)
<21>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicStreamFrame(data: bytes=b"", fin: bool=False, offset: int=0)
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.stream.QuicStream
add_frame(frame: QuicStreamFrame) -> None
pull_data() -> bytes
at: aioquic.stream.QuicStream.__init__
self._recv_buffer = bytearray()
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
at: aioquic.stream.QuicStream.add_frame
self._recv_buffer += bytearray(gap)
at: aioquic.stream.QuicStream.pull_data
self._recv_buffer = self._recv_buffer[pos:]
self._recv_buffer_start = r.stop
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def pull_data(self) -> bytes:
"""
Pull received data.
"""
+ try:
+ has_data_to_read = self._recv_ranges[0].start == self._recv_buffer_start
+ except IndexError:
+ has_data_to_read = False
+ if not has_data_to_read:
- if not self.has_data_to_read():
return b""
r = self._recv_ranges.shift()
pos = r.stop - r.start
data = self._recv_buffer[:pos]
self._recv_buffer = self._recv_buffer[pos:]
+ self._recv_buffer_start = r.stop
- self._recv_start = r.stop
return data
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
# reader
def add_frame(self, frame: QuicStreamFrame) -> None:
"""
Add a frame of received data.
"""
+ pos = frame.offset - self._recv_buffer_start
- pos = frame.offset - self._recv_start
count = len(frame.data)
frame_end = frame.offset + count
# we should receive no more data beyond FIN!
+ if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin:
- if self._recv_fin and frame_end > self._recv_highest:
raise Exception("Data received beyond FIN")
if pos + count > 0:
# frame has been partially consumed
if pos < 0:
count += pos
frame.data = frame.data[-pos:]
frame.offset -= pos
pos = 0
# marked received
if count:
self._recv_ranges.add(frame.offset, frame_end)
if frame_end > self._recv_highest:
self._recv_highest = frame_end
# add data
gap = pos - len(self._recv_buffer)
if gap > 0:
self._recv_buffer += bytearray(gap)
self._recv_buffer[pos : pos + count] = frame.data
if frame.fin:
+ self._recv_buffer_fin = frame_end
- self._recv_fin = True
if self.reader:
+ data = self.pull_data()
+ if data:
- if self.has_data_to_read():
+ self.reader.feed_data(data)
- self.reader.feed_data(self.pull_data())
+ if self._recv_buffer_start == self._recv_buffer_fin:
- if self._recv_fin and not self._recv_ranges:
self.reader.feed_eof()
===========changed ref 2===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_empty(self):
stream = QuicStream()
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# empty
self.assertEqual(stream.pull_data(), b"")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
===========changed ref 3===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_ordered_2(self):
stream = QuicStream()
# add data at start
stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
self.assertEqual(bytes(stream._recv_buffer), b"01234567")
self.assertEqual(list(stream._recv_ranges), [range(0, 8)])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# add more data
stream.add_frame(QuicStreamFrame(offset=8, data=b"89012345"))
self.assertEqual(bytes(stream._recv_buffer), b"0123456789012345")
self.assertEqual(list(stream._recv_ranges), [range(0, 16)])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# pull data
self.assertEqual(stream.pull_data(), b"0123456789012345")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 16)
- self.assertEqual(stream._recv_start, 16)
|
tests.test_stream/QuicStreamTest.test_recv_offset_only
|
Modified
|
aiortc~aioquic
|
0932423e05e927513d518a90c01eb454e4d60e7d
|
[stream] remove QuicStream.has_data_to_read()
|
<6>:<add> self.assertEqual(stream._recv_buffer_start, 0)
<del> self.assertEqual(stream._recv_start, 0)
<14>:<add> self.assertEqual(stream._recv_buffer_start, 0)
<del> self.assertEqual(stream._recv_start, 0)
|
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_offset_only(self):
<0> stream = QuicStream()
<1>
<2> # add data at offset 0
<3> stream.add_frame(QuicStreamFrame(offset=0, data=b""))
<4> self.assertEqual(bytes(stream._recv_buffer), b"")
<5> self.assertEqual(list(stream._recv_ranges), [])
<6> self.assertEqual(stream._recv_start, 0)
<7>
<8> # add data at offset 8
<9> stream.add_frame(QuicStreamFrame(offset=8, data=b""))
<10> self.assertEqual(
<11> bytes(stream._recv_buffer), b"\x00\x00\x00\x00\x00\x00\x00\x00"
<12> )
<13> self.assertEqual(list(stream._recv_ranges), [])
<14> self.assertEqual(stream._recv_start, 0)
<15>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicStreamFrame(data: bytes=b"", fin: bool=False, offset: int=0)
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.stream.QuicStream
add_frame(frame: QuicStreamFrame) -> None
at: aioquic.stream.QuicStream.__init__
self._recv_buffer = bytearray()
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
at: aioquic.stream.QuicStream.add_frame
self._recv_buffer += bytearray(gap)
at: aioquic.stream.QuicStream.pull_data
self._recv_buffer = self._recv_buffer[pos:]
self._recv_buffer_start = r.stop
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
# reader
def add_frame(self, frame: QuicStreamFrame) -> None:
"""
Add a frame of received data.
"""
+ pos = frame.offset - self._recv_buffer_start
- pos = frame.offset - self._recv_start
count = len(frame.data)
frame_end = frame.offset + count
# we should receive no more data beyond FIN!
+ if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin:
- if self._recv_fin and frame_end > self._recv_highest:
raise Exception("Data received beyond FIN")
if pos + count > 0:
# frame has been partially consumed
if pos < 0:
count += pos
frame.data = frame.data[-pos:]
frame.offset -= pos
pos = 0
# marked received
if count:
self._recv_ranges.add(frame.offset, frame_end)
if frame_end > self._recv_highest:
self._recv_highest = frame_end
# add data
gap = pos - len(self._recv_buffer)
if gap > 0:
self._recv_buffer += bytearray(gap)
self._recv_buffer[pos : pos + count] = frame.data
if frame.fin:
+ self._recv_buffer_fin = frame_end
- self._recv_fin = True
if self.reader:
+ data = self.pull_data()
+ if data:
- if self.has_data_to_read():
+ self.reader.feed_data(data)
- self.reader.feed_data(self.pull_data())
+ if self._recv_buffer_start == self._recv_buffer_fin:
- if self._recv_fin and not self._recv_ranges:
self.reader.feed_eof()
===========changed ref 1===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_empty(self):
stream = QuicStream()
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# empty
self.assertEqual(stream.pull_data(), b"")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
===========changed ref 2===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_ordered_2(self):
stream = QuicStream()
# add data at start
stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
self.assertEqual(bytes(stream._recv_buffer), b"01234567")
self.assertEqual(list(stream._recv_ranges), [range(0, 8)])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# add more data
stream.add_frame(QuicStreamFrame(offset=8, data=b"89012345"))
self.assertEqual(bytes(stream._recv_buffer), b"0123456789012345")
self.assertEqual(list(stream._recv_ranges), [range(0, 16)])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# pull data
self.assertEqual(stream.pull_data(), b"0123456789012345")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 16)
- self.assertEqual(stream._recv_start, 16)
===========changed ref 3===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_unordered(self):
stream = QuicStream()
# add data at offset 8
stream.add_frame(QuicStreamFrame(offset=8, data=b"89012345"))
self.assertEqual(
bytes(stream._recv_buffer), b"\x00\x00\x00\x00\x00\x00\x00\x0089012345"
)
self.assertEqual(list(stream._recv_ranges), [range(8, 16)])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# add data at offset 0
stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
self.assertEqual(bytes(stream._recv_buffer), b"0123456789012345")
self.assertEqual(list(stream._recv_ranges), [range(0, 16)])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# pull data
self.assertEqual(stream.pull_data(), b"0123456789012345")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 16)
- self.assertEqual(stream._recv_start, 16)
|
tests.test_stream/QuicStreamTest.test_recv_already_fully_consumed
|
Modified
|
aiortc~aioquic
|
0932423e05e927513d518a90c01eb454e4d60e7d
|
[stream] remove QuicStream.has_data_to_read()
|
<8>:<add> self.assertEqual(stream._recv_buffer_start, 8)
<del> self.assertEqual(stream._recv_start, 8)
<11>:<add> self.assertEqual(stream._recv_buffer_start, 8)
<del> self.assertEqual(stream._recv_start, 8)
|
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_already_fully_consumed(self):
<0> stream = QuicStream()
<1>
<2> stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
<3> self.assertEqual(stream.pull_data(), b"01234567")
<4>
<5> stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
<6> self.assertEqual(bytes(stream._recv_buffer), b"")
<7> self.assertEqual(list(stream._recv_ranges), [])
<8> self.assertEqual(stream._recv_start, 8)
<9>
<10> self.assertEqual(stream.pull_data(), b"")
<11> self.assertEqual(stream._recv_start, 8)
<12>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicStreamFrame(data: bytes=b"", fin: bool=False, offset: int=0)
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.stream.QuicStream
add_frame(frame: QuicStreamFrame) -> None
pull_data() -> bytes
at: aioquic.stream.QuicStream.__init__
self._recv_buffer = bytearray()
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
at: aioquic.stream.QuicStream.add_frame
self._recv_buffer += bytearray(gap)
at: aioquic.stream.QuicStream.pull_data
self._recv_buffer = self._recv_buffer[pos:]
self._recv_buffer_start = r.stop
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def pull_data(self) -> bytes:
"""
Pull received data.
"""
+ try:
+ has_data_to_read = self._recv_ranges[0].start == self._recv_buffer_start
+ except IndexError:
+ has_data_to_read = False
+ if not has_data_to_read:
- if not self.has_data_to_read():
return b""
r = self._recv_ranges.shift()
pos = r.stop - r.start
data = self._recv_buffer[:pos]
self._recv_buffer = self._recv_buffer[pos:]
+ self._recv_buffer_start = r.stop
- self._recv_start = r.stop
return data
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
# reader
def add_frame(self, frame: QuicStreamFrame) -> None:
"""
Add a frame of received data.
"""
+ pos = frame.offset - self._recv_buffer_start
- pos = frame.offset - self._recv_start
count = len(frame.data)
frame_end = frame.offset + count
# we should receive no more data beyond FIN!
+ if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin:
- if self._recv_fin and frame_end > self._recv_highest:
raise Exception("Data received beyond FIN")
if pos + count > 0:
# frame has been partially consumed
if pos < 0:
count += pos
frame.data = frame.data[-pos:]
frame.offset -= pos
pos = 0
# marked received
if count:
self._recv_ranges.add(frame.offset, frame_end)
if frame_end > self._recv_highest:
self._recv_highest = frame_end
# add data
gap = pos - len(self._recv_buffer)
if gap > 0:
self._recv_buffer += bytearray(gap)
self._recv_buffer[pos : pos + count] = frame.data
if frame.fin:
+ self._recv_buffer_fin = frame_end
- self._recv_fin = True
if self.reader:
+ data = self.pull_data()
+ if data:
- if self.has_data_to_read():
+ self.reader.feed_data(data)
- self.reader.feed_data(self.pull_data())
+ if self._recv_buffer_start == self._recv_buffer_fin:
- if self._recv_fin and not self._recv_ranges:
self.reader.feed_eof()
===========changed ref 2===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_offset_only(self):
stream = QuicStream()
# add data at offset 0
stream.add_frame(QuicStreamFrame(offset=0, data=b""))
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# add data at offset 8
stream.add_frame(QuicStreamFrame(offset=8, data=b""))
self.assertEqual(
bytes(stream._recv_buffer), b"\x00\x00\x00\x00\x00\x00\x00\x00"
)
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
===========changed ref 3===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_empty(self):
stream = QuicStream()
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# empty
self.assertEqual(stream.pull_data(), b"")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
===========changed ref 4===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_ordered_2(self):
stream = QuicStream()
# add data at start
stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
self.assertEqual(bytes(stream._recv_buffer), b"01234567")
self.assertEqual(list(stream._recv_ranges), [range(0, 8)])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# add more data
stream.add_frame(QuicStreamFrame(offset=8, data=b"89012345"))
self.assertEqual(bytes(stream._recv_buffer), b"0123456789012345")
self.assertEqual(list(stream._recv_ranges), [range(0, 16)])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# pull data
self.assertEqual(stream.pull_data(), b"0123456789012345")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 16)
- self.assertEqual(stream._recv_start, 16)
|
tests.test_stream/QuicStreamTest.test_recv_already_partially_consumed
|
Modified
|
aiortc~aioquic
|
0932423e05e927513d518a90c01eb454e4d60e7d
|
[stream] remove QuicStream.has_data_to_read()
|
<8>:<add> self.assertEqual(stream._recv_buffer_start, 8)
<del> self.assertEqual(stream._recv_start, 8)
<11>:<add> self.assertEqual(stream._recv_buffer_start, 16)
<del> self.assertEqual(stream._recv_start, 16)
|
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_already_partially_consumed(self):
<0> stream = QuicStream()
<1>
<2> stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
<3> self.assertEqual(stream.pull_data(), b"01234567")
<4>
<5> stream.add_frame(QuicStreamFrame(offset=0, data=b"0123456789012345"))
<6> self.assertEqual(bytes(stream._recv_buffer), b"89012345")
<7> self.assertEqual(list(stream._recv_ranges), [range(8, 16)])
<8> self.assertEqual(stream._recv_start, 8)
<9>
<10> self.assertEqual(stream.pull_data(), b"89012345")
<11> self.assertEqual(stream._recv_start, 16)
<12>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicStreamFrame(data: bytes=b"", fin: bool=False, offset: int=0)
at: aioquic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.stream.QuicStream
add_frame(frame: QuicStreamFrame) -> None
pull_data() -> bytes
at: aioquic.stream.QuicStream.__init__
self._recv_buffer = bytearray()
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_ranges = RangeSet()
at: aioquic.stream.QuicStream.add_frame
self._recv_buffer += bytearray(gap)
at: aioquic.stream.QuicStream.pull_data
self._recv_buffer = self._recv_buffer[pos:]
self._recv_buffer_start = r.stop
at: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def pull_data(self) -> bytes:
"""
Pull received data.
"""
+ try:
+ has_data_to_read = self._recv_ranges[0].start == self._recv_buffer_start
+ except IndexError:
+ has_data_to_read = False
+ if not has_data_to_read:
- if not self.has_data_to_read():
return b""
r = self._recv_ranges.shift()
pos = r.stop - r.start
data = self._recv_buffer[:pos]
self._recv_buffer = self._recv_buffer[pos:]
+ self._recv_buffer_start = r.stop
- self._recv_start = r.stop
return data
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
# reader
def add_frame(self, frame: QuicStreamFrame) -> None:
"""
Add a frame of received data.
"""
+ pos = frame.offset - self._recv_buffer_start
- pos = frame.offset - self._recv_start
count = len(frame.data)
frame_end = frame.offset + count
# we should receive no more data beyond FIN!
+ if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin:
- if self._recv_fin and frame_end > self._recv_highest:
raise Exception("Data received beyond FIN")
if pos + count > 0:
# frame has been partially consumed
if pos < 0:
count += pos
frame.data = frame.data[-pos:]
frame.offset -= pos
pos = 0
# marked received
if count:
self._recv_ranges.add(frame.offset, frame_end)
if frame_end > self._recv_highest:
self._recv_highest = frame_end
# add data
gap = pos - len(self._recv_buffer)
if gap > 0:
self._recv_buffer += bytearray(gap)
self._recv_buffer[pos : pos + count] = frame.data
if frame.fin:
+ self._recv_buffer_fin = frame_end
- self._recv_fin = True
if self.reader:
+ data = self.pull_data()
+ if data:
- if self.has_data_to_read():
+ self.reader.feed_data(data)
- self.reader.feed_data(self.pull_data())
+ if self._recv_buffer_start == self._recv_buffer_fin:
- if self._recv_fin and not self._recv_ranges:
self.reader.feed_eof()
===========changed ref 2===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_already_fully_consumed(self):
stream = QuicStream()
stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
self.assertEqual(stream.pull_data(), b"01234567")
stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567"))
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 8)
- self.assertEqual(stream._recv_start, 8)
self.assertEqual(stream.pull_data(), b"")
+ self.assertEqual(stream._recv_buffer_start, 8)
- self.assertEqual(stream._recv_start, 8)
===========changed ref 3===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_offset_only(self):
stream = QuicStream()
# add data at offset 0
stream.add_frame(QuicStreamFrame(offset=0, data=b""))
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# add data at offset 8
stream.add_frame(QuicStreamFrame(offset=8, data=b""))
self.assertEqual(
bytes(stream._recv_buffer), b"\x00\x00\x00\x00\x00\x00\x00\x00"
)
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
===========changed ref 4===========
# module: tests.test_stream
class QuicStreamTest(TestCase):
def test_recv_empty(self):
stream = QuicStream()
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
# empty
self.assertEqual(stream.pull_data(), b"")
self.assertEqual(bytes(stream._recv_buffer), b"")
self.assertEqual(list(stream._recv_ranges), [])
+ self.assertEqual(stream._recv_buffer_start, 0)
- self.assertEqual(stream._recv_start, 0)
|
aioquic.rangeset/RangeSet.__bool__
|
Modified
|
aiortc~aioquic
|
9290cfdee08b8263343d484cd55c2109473332aa
|
[rangeset] remove RangeSet.__bool__
|
<0>:<add> raise NotImplementedError
<del> return bool(self.__ranges)
|
# module: aioquic.rangeset
class RangeSet(Sequence):
def __bool__(self) -> bool:
<0> return bool(self.__ranges)
<1>
| |
aioquic.connection/QuicConnection._write_application
|
Modified
|
aiortc~aioquic
|
9290cfdee08b8263343d484cd55c2109473332aa
|
[rangeset] remove RangeSet.__bool__
|
<20>:<add> if space.ack_required:
<del> if space.ack_required and space.ack_queue:
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
<0> crypto_stream: Optional[QuicStream] = None
<1> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
<2> crypto = self._cryptos[tls.Epoch.ONE_RTT]
<3> crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
<4> packet_type = PACKET_TYPE_ONE_RTT
<5> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
<6> crypto = self._cryptos[tls.Epoch.ZERO_RTT]
<7> packet_type = PACKET_TYPE_ZERO_RTT
<8> else:
<9> return
<10> space = self._spaces[tls.Epoch.ONE_RTT]
<11>
<12> buf = builder.buffer
<13>
<14> while builder.flight_bytes < max_bytes or self._probe_pending:
<15> # write header
<16> builder.start_packet(packet_type, crypto)
<17>
<18> if self._handshake_complete:
<19> # ACK
<20> if space.ack_required and space.ack_queue:
<21> builder.start_frame(QuicFrameType.ACK)
<22> push_ack_frame(buf, space.ack_queue, 0)
<23> space.ack_required = False
<24>
<25> # PATH CHALLENGE
<26> if (
<27> not network_path.is_validated
<28> and network_path.local_challenge is None
<29> ):
<30> self._logger.info(
<31> "Network path %s sending challenge", network_path.addr
<32> )
<33> network_path.local_challenge = os.urandom(8)
<34> builder.start_frame(QuicFrameType.PATH_CHALLENGE)
<35> push_bytes(buf, network_path.local_challenge)
<36>
<37> #</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 1
if network_path.remote_challenge is not None:
builder.start_frame(QuicFrameType.PATH_RESPONSE)
push_bytes(buf, network_path.remote_challenge)
network_path.remote_challenge = None
# NEW_CONNECTION_ID
for connection_id in self._host_cids:
if not connection_id.was_sent:
builder.start_frame(
QuicFrameType.NEW_CONNECTION_ID,
self._on_new_connection_id_delivery,
(connection_id,),
)
push_new_connection_id_frame(
buf,
connection_id.sequence_number,
connection_id.cid,
connection_id.stateless_reset_token,
)
connection_id.was_sent = True
self._connection_id_issued_handler(connection_id.cid)
# RETIRE_CONNECTION_ID
while self._retire_connection_ids:
sequence_number = self._retire_connection_ids.pop(0)
builder.start_frame(
QuicFrameType.RETIRE_CONNECTION_ID,
self._on_retire_connection_id_delivery,
(sequence_number,),
)
push_uint_var(buf, sequence_number)
# connection-level limits
self._write_connection_limits(builder=builder, space=space)
# stream-level limits
for stream in self._streams.values():
self._write_stream_limits(builder=builder, space=space, stream=stream)
# PING (user-request)
if self._ping_pending:
self._logger.info("Sending PING in packet %d", builder.packet_number)
builder.start_frame(QuicFrameType.</s>
===========below chunk 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 2
<s>.info("Sending PING in packet %d", builder.packet_number)
builder.start_frame(QuicFrameType.PING, self._on_ping_delivery)
self._ping_pending = False
# PING (probe)
if self._probe_pending:
self._logger.info("Sending probe")
builder.start_frame(QuicFrameType.PING)
self._probe_pending = False
# CRYPTO
if crypto_stream is not None:
write_crypto_frame(builder=builder, space=space, stream=crypto_stream)
for stream in self._streams.values():
# STREAM
self._remote_max_data_used += write_stream_frame(
builder=builder,
space=space,
stream=stream,
max_offset=min(
stream._send_highest
+ self._remote_max_data
- self._remote_max_data_used,
stream.max_stream_data_remote,
),
)
if not builder.end_packet():
break
===========unchanged ref 0===========
at: aioquic.buffer
push_bytes(buf: Buffer, v: bytes) -> None
push_uint_var(buf: Buffer, value: int) -> None
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int
QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None)
at: aioquic.connection.QuicConnection
supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20]
_on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None
_on_ping_delivery(delivery: QuicDeliveryState) -> None
_on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None
_write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None
_write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._handshake_complete = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
===========unchanged ref 1===========
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._remote_max_data = 0
self._remote_max_data_used = 0
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._streams: Dict[int, QuicStream] = {}
self._ping_pending = False
self._probe_pending = False
self._retire_connection_ids: List[int] = []
self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None
at: aioquic.connection.QuicConnection._handle_crypto_frame
self._handshake_complete = True
at: aioquic.connection.QuicConnection._handle_max_data_frame
self._remote_max_data = max_data
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicConnection._on_ping_delivery
self._ping_pending = True
at: aioquic.connection.QuicConnection._send_probe
self._probe_pending = True
at: aioquic.connection.QuicConnection.ping
self._ping_pending = True
at: aioquic.connection.QuicConnectionId
cid: bytes
|
aioquic.connection/QuicConnection._write_handshake
|
Modified
|
aiortc~aioquic
|
9290cfdee08b8263343d484cd55c2109473332aa
|
[rangeset] remove RangeSet.__bool__
|
<15>:<add> if space.ack_required:
<del> if space.ack_required and space.ack_queue:
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_handshake(
self, builder: QuicPacketBuilder, epoch: tls.Epoch, max_bytes: int
) -> None:
<0> crypto = self._cryptos[epoch]
<1> if not crypto.send.is_valid():
<2> return
<3>
<4> buf = builder.buffer
<5> space = self._spaces[epoch]
<6>
<7> while builder.flight_bytes < max_bytes:
<8> if epoch == tls.Epoch.INITIAL:
<9> packet_type = PACKET_TYPE_INITIAL
<10> else:
<11> packet_type = PACKET_TYPE_HANDSHAKE
<12> builder.start_packet(packet_type, crypto)
<13>
<14> # ACK
<15> if space.ack_required and space.ack_queue:
<16> builder.start_frame(QuicFrameType.ACK)
<17> push_ack_frame(buf, space.ack_queue, 0)
<18> space.ack_required = False
<19>
<20> # CRYPTO
<21> write_crypto_frame(
<22> builder=builder, space=space, stream=self._crypto_streams[epoch]
<23> )
<24>
<25> if not builder.end_packet():
<26> break
<27>
|
===========unchanged ref 0===========
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.crypto.CryptoContext
is_valid() -> bool
at: aioquic.crypto.CryptoPair.__init__
self.send = CryptoContext()
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
push_ack_frame(buf: Buffer, rangeset: RangeSet, delay: int) -> None
===========unchanged ref 1===========
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
at: aioquic.packet_builder.QuicPacketBuilder
start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.packet_builder.QuicPacketBuilder.__init__
self.buffer = Buffer(PACKET_MAX_SIZE)
at: aioquic.recovery.QuicPacketSpace.__init__
self.ack_queue = RangeSet()
self.ack_required = False
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.rangeset
class RangeSet(Sequence):
def __bool__(self) -> bool:
+ raise NotImplementedError
- return bool(self.__ranges)
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
crypto_stream: Optional[QuicStream] = None
if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ONE_RTT]
crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
packet_type = PACKET_TYPE_ONE_RTT
elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ZERO_RTT]
packet_type = PACKET_TYPE_ZERO_RTT
else:
return
space = self._spaces[tls.Epoch.ONE_RTT]
buf = builder.buffer
while builder.flight_bytes < max_bytes or self._probe_pending:
# write header
builder.start_packet(packet_type, crypto)
if self._handshake_complete:
# ACK
+ if space.ack_required:
- if space.ack_required and space.ack_queue:
builder.start_frame(QuicFrameType.ACK)
push_ack_frame(buf, space.ack_queue, 0)
space.ack_required = False
# PATH CHALLENGE
if (
not network_path.is_validated
and network_path.local_challenge is None
):
self._logger.info(
"Network path %s sending challenge", network_path.addr
)
network_path.local_challenge = os.urandom(8)
builder.start_frame(QuicFrameType.PATH_CHALLENGE)
push_bytes(buf, network_path.local_challenge)
# PATH RESPONSE
if network_path.remote_challenge is not None:
builder.start_frame(QuicFrame</s>
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 1
<s>
# PATH RESPONSE
if network_path.remote_challenge is not None:
builder.start_frame(QuicFrameType.PATH_RESPONSE)
push_bytes(buf, network_path.remote_challenge)
network_path.remote_challenge = None
# NEW_CONNECTION_ID
for connection_id in self._host_cids:
if not connection_id.was_sent:
builder.start_frame(
QuicFrameType.NEW_CONNECTION_ID,
self._on_new_connection_id_delivery,
(connection_id,),
)
push_new_connection_id_frame(
buf,
connection_id.sequence_number,
connection_id.cid,
connection_id.stateless_reset_token,
)
connection_id.was_sent = True
self._connection_id_issued_handler(connection_id.cid)
# RETIRE_CONNECTION_ID
while self._retire_connection_ids:
sequence_number = self._retire_connection_ids.pop(0)
builder.start_frame(
QuicFrameType.RETIRE_CONNECTION_ID,
self._on_retire_connection_id_delivery,
(sequence_number,),
)
push_uint_var(buf, sequence_number)
# connection-level limits
self._write_connection_limits(builder=builder, space=space)
# stream-level limits
for stream in self._streams.values():
self._write_stream_limits(builder=builder, space=space, stream=stream)
# PING (user-request)
if self._</s>
|
tests.test_rangeset/RangeSetTest.test_bool
|
Modified
|
aiortc~aioquic
|
9290cfdee08b8263343d484cd55c2109473332aa
|
[rangeset] remove RangeSet.__bool__
|
<0>:<add> with self.assertRaises(NotImplementedError):
<add> bool(RangeSet())
<del> rangeset = RangeSet()
<1>:<del> self.assertFalse(bool(rangeset))
<3>:<del> rangeset = RangeSet([range(0, 1)])
<4>:<del> self.assertTrue(bool(rangeset))
<5>:<del>
|
# module: tests.test_rangeset
class RangeSetTest(TestCase):
def test_bool(self):
<0> rangeset = RangeSet()
<1> self.assertFalse(bool(rangeset))
<2>
<3> rangeset = RangeSet([range(0, 1)])
<4> self.assertTrue(bool(rangeset))
<5>
|
===========unchanged ref 0===========
at: aioquic.rangeset
RangeSet(ranges: Iterable[range]=[])
at: unittest.case.TestCase
failureException: Type[BaseException]
longMessage: bool
maxDiff: Optional[int]
_testMethodName: str
_testMethodDoc: str
assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]
assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.rangeset
class RangeSet(Sequence):
def __bool__(self) -> bool:
+ raise NotImplementedError
- return bool(self.__ranges)
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_handshake(
self, builder: QuicPacketBuilder, epoch: tls.Epoch, max_bytes: int
) -> None:
crypto = self._cryptos[epoch]
if not crypto.send.is_valid():
return
buf = builder.buffer
space = self._spaces[epoch]
while builder.flight_bytes < max_bytes:
if epoch == tls.Epoch.INITIAL:
packet_type = PACKET_TYPE_INITIAL
else:
packet_type = PACKET_TYPE_HANDSHAKE
builder.start_packet(packet_type, crypto)
# ACK
+ if space.ack_required:
- if space.ack_required and space.ack_queue:
builder.start_frame(QuicFrameType.ACK)
push_ack_frame(buf, space.ack_queue, 0)
space.ack_required = False
# CRYPTO
write_crypto_frame(
builder=builder, space=space, stream=self._crypto_streams[epoch]
)
if not builder.end_packet():
break
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
crypto_stream: Optional[QuicStream] = None
if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ONE_RTT]
crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
packet_type = PACKET_TYPE_ONE_RTT
elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ZERO_RTT]
packet_type = PACKET_TYPE_ZERO_RTT
else:
return
space = self._spaces[tls.Epoch.ONE_RTT]
buf = builder.buffer
while builder.flight_bytes < max_bytes or self._probe_pending:
# write header
builder.start_packet(packet_type, crypto)
if self._handshake_complete:
# ACK
+ if space.ack_required:
- if space.ack_required and space.ack_queue:
builder.start_frame(QuicFrameType.ACK)
push_ack_frame(buf, space.ack_queue, 0)
space.ack_required = False
# PATH CHALLENGE
if (
not network_path.is_validated
and network_path.local_challenge is None
):
self._logger.info(
"Network path %s sending challenge", network_path.addr
)
network_path.local_challenge = os.urandom(8)
builder.start_frame(QuicFrameType.PATH_CHALLENGE)
push_bytes(buf, network_path.local_challenge)
# PATH RESPONSE
if network_path.remote_challenge is not None:
builder.start_frame(QuicFrame</s>
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 1
<s>
# PATH RESPONSE
if network_path.remote_challenge is not None:
builder.start_frame(QuicFrameType.PATH_RESPONSE)
push_bytes(buf, network_path.remote_challenge)
network_path.remote_challenge = None
# NEW_CONNECTION_ID
for connection_id in self._host_cids:
if not connection_id.was_sent:
builder.start_frame(
QuicFrameType.NEW_CONNECTION_ID,
self._on_new_connection_id_delivery,
(connection_id,),
)
push_new_connection_id_frame(
buf,
connection_id.sequence_number,
connection_id.cid,
connection_id.stateless_reset_token,
)
connection_id.was_sent = True
self._connection_id_issued_handler(connection_id.cid)
# RETIRE_CONNECTION_ID
while self._retire_connection_ids:
sequence_number = self._retire_connection_ids.pop(0)
builder.start_frame(
QuicFrameType.RETIRE_CONNECTION_ID,
self._on_retire_connection_id_delivery,
(sequence_number,),
)
push_uint_var(buf, sequence_number)
# connection-level limits
self._write_connection_limits(builder=builder, space=space)
# stream-level limits
for stream in self._streams.values():
self._write_stream_limits(builder=builder, space=space, stream=stream)
# PING (user-request)
if self._</s>
===========changed ref 4===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 2
<s>pending:
self._logger.info("Sending PING in packet %d", builder.packet_number)
builder.start_frame(QuicFrameType.PING, self._on_ping_delivery)
self._ping_pending = False
# PING (probe)
if self._probe_pending:
self._logger.info("Sending probe")
builder.start_frame(QuicFrameType.PING)
self._probe_pending = False
# CRYPTO
if crypto_stream is not None:
write_crypto_frame(builder=builder, space=space, stream=crypto_stream)
for stream in self._streams.values():
# STREAM
self._remote_max_data_used += write_stream_frame(
builder=builder,
space=space,
stream=stream,
max_offset=min(
stream._send_highest
+ self._remote_max_data
- self._remote_max_data_used,
stream.max_stream_data_remote,
),
)
if not builder.end_packet():
break
|
aioquic.recovery/QuicPacketSpace.__init__
|
Modified
|
aiortc~aioquic
|
616a3854563c430827b24141bb22eccae4274976
|
[connection] trim ACK queue when an ACK is "ACK'd"
|
<3>:<add> self.largest_received_packet = 0
|
# module: aioquic.recovery
class QuicPacketSpace:
def __init__(self) -> None:
<0> self.ack_queue = RangeSet()
<1> self.ack_required = False
<2> self.expected_packet_number = 0
<3>
<4> # sent packets and loss
<5> self.ack_eliciting_in_flight = 0
<6> self.crypto_packet_in_flight = 0
<7> self.largest_acked_packet = 0
<8> self.loss_time: Optional[float] = None
<9> self.sent_packets: Dict[int, QuicSentPacket] = {}
<10>
|
===========unchanged ref 0===========
at: aioquic.rangeset
RangeSet(ranges: Iterable[range]=[])
|
aioquic.connection/QuicConnection._write_application
|
Modified
|
aiortc~aioquic
|
616a3854563c430827b24141bb22eccae4274976
|
[connection] trim ACK queue when an ACK is "ACK'd"
|
<21>:<add> builder.start_frame(
<del> builder.start_frame(QuicFrameType.ACK)
<22>:<add> QuicFrameType.ACK,
<add> self._on_ack_delivery,
<add> (space, space.largest_received_packet),
<add> )
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
<0> crypto_stream: Optional[QuicStream] = None
<1> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
<2> crypto = self._cryptos[tls.Epoch.ONE_RTT]
<3> crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
<4> packet_type = PACKET_TYPE_ONE_RTT
<5> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
<6> crypto = self._cryptos[tls.Epoch.ZERO_RTT]
<7> packet_type = PACKET_TYPE_ZERO_RTT
<8> else:
<9> return
<10> space = self._spaces[tls.Epoch.ONE_RTT]
<11>
<12> buf = builder.buffer
<13>
<14> while builder.flight_bytes < max_bytes or self._probe_pending:
<15> # write header
<16> builder.start_packet(packet_type, crypto)
<17>
<18> if self._handshake_complete:
<19> # ACK
<20> if space.ack_required:
<21> builder.start_frame(QuicFrameType.ACK)
<22> push_ack_frame(buf, space.ack_queue, 0)
<23> space.ack_required = False
<24>
<25> # PATH CHALLENGE
<26> if (
<27> not network_path.is_validated
<28> and network_path.local_challenge is None
<29> ):
<30> self._logger.info(
<31> "Network path %s sending challenge", network_path.addr
<32> )
<33> network_path.local_challenge = os.urandom(8)
<34> builder.start_frame(QuicFrameType.PATH_CHALLENGE)
<35> push_bytes(buf, network_path.local_challenge)
<36>
<37> # PATH RESPONSE
<38> if</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 1
builder.start_frame(QuicFrameType.PATH_RESPONSE)
push_bytes(buf, network_path.remote_challenge)
network_path.remote_challenge = None
# NEW_CONNECTION_ID
for connection_id in self._host_cids:
if not connection_id.was_sent:
builder.start_frame(
QuicFrameType.NEW_CONNECTION_ID,
self._on_new_connection_id_delivery,
(connection_id,),
)
push_new_connection_id_frame(
buf,
connection_id.sequence_number,
connection_id.cid,
connection_id.stateless_reset_token,
)
connection_id.was_sent = True
self._connection_id_issued_handler(connection_id.cid)
# RETIRE_CONNECTION_ID
while self._retire_connection_ids:
sequence_number = self._retire_connection_ids.pop(0)
builder.start_frame(
QuicFrameType.RETIRE_CONNECTION_ID,
self._on_retire_connection_id_delivery,
(sequence_number,),
)
push_uint_var(buf, sequence_number)
# connection-level limits
self._write_connection_limits(builder=builder, space=space)
# stream-level limits
for stream in self._streams.values():
self._write_stream_limits(builder=builder, space=space, stream=stream)
# PING (user-request)
if self._ping_pending:
self._logger.info("Sending PING in packet %d", builder.packet_number)
builder.start_frame(QuicFrameType.PING, self._on_ping_delivery)
self._</s>
===========below chunk 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 2
<s>_number)
builder.start_frame(QuicFrameType.PING, self._on_ping_delivery)
self._ping_pending = False
# PING (probe)
if self._probe_pending:
self._logger.info("Sending probe")
builder.start_frame(QuicFrameType.PING)
self._probe_pending = False
# CRYPTO
if crypto_stream is not None:
write_crypto_frame(builder=builder, space=space, stream=crypto_stream)
for stream in self._streams.values():
# STREAM
self._remote_max_data_used += write_stream_frame(
builder=builder,
space=space,
stream=stream,
max_offset=min(
stream._send_highest
+ self._remote_max_data
- self._remote_max_data_used,
stream.max_stream_data_remote,
),
)
if not builder.end_packet():
break
===========unchanged ref 0===========
at: aioquic.buffer
push_bytes(buf: Buffer, v: bytes) -> None
push_uint_var(buf: Buffer, value: int) -> None
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int
QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None)
at: aioquic.connection.QuicConnection
supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20]
_on_ack_delivery(delivery: QuicDeliveryState, space: QuicPacketSpace, highest_acked: int) -> None
_on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None
_on_ping_delivery(delivery: QuicDeliveryState) -> None
_on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None
_write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None
_write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._secrets_log_file = secrets_log_file
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._handshake_complete = False
===========unchanged ref 1===========
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._remote_max_data_used = 0
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._streams: Dict[int, QuicStream] = {}
self._ping_pending = False
self._probe_pending = False
self._retire_connection_ids: List[int] = []
self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None
at: aioquic.connection.QuicConnection._handle_crypto_frame
self._handshake_complete = True
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicConnection._on_ping_delivery
self._ping_pending = True
at: aioquic.connection.QuicConnection._send_probe
self._probe_pending = True
at: aioquic.connection.QuicConnection.ping
self._ping_pending = True
|
aioquic.connection/QuicConnection.close
|
Modified
|
aiortc~aioquic
|
a16048ef96107fe33545cd8e0cf9ed690fe99413
|
[connection] ensure proper shutdown when receiving a CLOSE frame
|
<3>:<add> if self._state not in END_STATES:
<del> if self._state not in [
<4>:<del> QuicConnectionState.CLOSING,
<5>:<del> QuicConnectionState.DRAINING,
<6>:<del> ]:
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
<0> """
<1> Close the connection.
<2> """
<3> if self._state not in [
<4> QuicConnectionState.CLOSING,
<5> QuicConnectionState.DRAINING,
<6> ]:
<7> self._close_pending = {
<8> "error_code": error_code,
<9> "frame_type": frame_type,
<10> "reason_phrase": reason_phrase,
<11> }
<12> self._send_pending()
<13>
|
===========unchanged ref 0===========
at: aioquic.connection
END_STATES = set([QuicConnectionState.CLOSING, QuicConnectionState.DRAINING])
at: aioquic.connection.QuicConnection
supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20]
_send_pending(self) -> None
_send_pending() -> None
at: aioquic.connection.QuicConnection.__init__
self._state = QuicConnectionState.FIRSTFLIGHT
self._close_pending: Optional[Dict] = None
at: aioquic.connection.QuicConnection._initialize
self.tls = tls.Context(is_client=self.is_client, logger=self._logger)
at: aioquic.connection.QuicConnection._send_pending
self._close_pending = None
at: aioquic.connection.QuicConnection._set_state
self._state = state
at: aioquic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: aioquic.tls.Context.__init__
self.alpn_negotiated: Optional[str] = None
at: aioquic.tls.Context._client_handle_encrypted_extensions
self.alpn_negotiated = encrypted_extensions.alpn_protocol
at: aioquic.tls.Context._server_handle_hello
self.alpn_negotiated = negotiate(
self.alpn_protocols,
peer_hello.alpn_protocols,
AlertHandshakeFailure("No common ALPN protocols"),
)
|
aioquic.connection/QuicConnection._handle_connection_close_frame
|
Modified
|
aiortc~aioquic
|
a16048ef96107fe33545cd8e0cf9ed690fe99413
|
[connection] ensure proper shutdown when receiving a CLOSE frame
|
<17>:<add>
<18>:<add> self._set_timer()
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a CONNECTION_CLOSE frame.
<2> """
<3> if frame_type == QuicFrameType.TRANSPORT_CLOSE:
<4> error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
<5> else:
<6> error_code, reason_phrase = pull_application_close_frame(buf)
<7> frame_type = None
<8> self._logger.info(
<9> "Connection close code 0x%X, reason %s", error_code, reason_phrase
<10> )
<11> if error_code != QuicErrorCode.NO_ERROR:
<12> self._close_exception = QuicConnectionError(
<13> error_code=error_code,
<14> frame_type=frame_type,
<15> reason_phrase=reason_phrase,
<16> )
<17> self._close(is_initiator=False)
<18>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.connection
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)
at: aioquic.connection.QuicConnection.__init__
self._close_exception: Optional[Exception] = None
self._handshake_confirmed = False
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
at: aioquic.connection.QuicConnection.datagram_received
self._close_exception = exc
at: aioquic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]
pull_application_close_frame(buf: Buffer) -> Tuple[int, str]
at: logging.LoggerAdapter
logger: Logger
extra: Mapping[str, Any]
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
+ if self._state not in END_STATES:
- if self._state not in [
- QuicConnectionState.CLOSING,
- QuicConnectionState.DRAINING,
- ]:
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
self._send_pending()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
"""
Handle an incoming datagram.
"""
# stop handling packets when closing
+ if self._state in END_STATES:
- if self._state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]:
return
data = cast(bytes, data)
buf = Buffer(data=data)
now = self._loop.time()
while not buf.eof():
start_off = buf.tell()
header = pull_quic_header(buf, host_cid_length=len(self.host_cid))
# check destination CID matches
destination_cid_seq: Optional[int] = None
for connection_id in self._host_cids:
if header.destination_cid == connection_id.cid:
destination_cid_seq = connection_id.sequence_number
break
if self.is_client and destination_cid_seq is None:
return
# check protocol version
if self.is_client and header.version == QuicProtocolVersion.NEGOTIATION:
# version negotiation
versions = []
while not buf.eof():
versions.append(pull_uint32(buf))
common = set(self.supported_versions).intersection(versions)
if not common:
self._logger.error("Could not find a common protocol version")
self.connection_lost(
QuicConnectionError(
error_code=QuicErrorCode.INTERNAL_ERROR,
frame_type=None,
reason_phrase="Could not find a common protocol version",
)
)
return
self._version = QuicProtocolVersion(max(common))
self._version_negotiation_count += 1
self._logger.info("Retrying with %s", self._version)
self._connect()
return
elif (
header.version is not None
and header.version not</s>
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
# offset: 1
<s>version)
self._connect()
return
elif (
header.version is not None
and header.version not in self.supported_versions
):
# unsupported version
return
if self.is_client and header.packet_type == PACKET_TYPE_RETRY:
# stateless retry
if (
header.destination_cid == self.host_cid
and header.original_destination_cid == self._peer_cid
and not self._stateless_retry_count
):
self._original_connection_id = self._peer_cid
self._peer_cid = header.source_cid
self._peer_token = header.token
self._stateless_retry_count += 1
self._logger.info("Performing stateless retry")
self._connect()
return
network_path = self._find_network_path(addr)
# server initialization
if not self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT:
assert (
header.packet_type == PACKET_TYPE_INITIAL
), "first packet must be INITIAL"
self._network_paths = [network_path]
self._version = QuicProtocolVersion(header.version)
self._initialize(header.destination_cid)
# determine crypto and packet space
epoch = get_epoch(header.packet_type)
crypto = self._cryptos[epoch]
if epoch == tls.Epoch.ZERO_RTT:
space = self._spaces[tls.Epoch.ONE_RTT]
else:
space = self._spaces[epoch]
# decrypt packet
encrypted_off = buf.tell() - start_off
end_off = buf.tell()</s>
|
aioquic.connection/QuicConnection._send_pending
|
Modified
|
aiortc~aioquic
|
a16048ef96107fe33545cd8e0cf9ed690fe99413
|
[connection] ensure proper shutdown when receiving a CLOSE frame
|
<3>:<add> if self._state in END_STATES:
<del> if self._state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]:
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
<0> network_path = self._network_paths[0]
<1>
<2> self._send_task = None
<3> if self._state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]:
<4> return
<5>
<6> # build datagrams
<7> builder = QuicPacketBuilder(
<8> host_cid=self.host_cid,
<9> packet_number=self._packet_number,
<10> pad_first_datagram=(
<11> self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
<12> ),
<13> peer_cid=self._peer_cid,
<14> peer_token=self._peer_token,
<15> spin_bit=self._spin_bit,
<16> version=self._version,
<17> )
<18> if self._close_pending:
<19> for epoch, packet_type in (
<20> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
<21> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
<22> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
<23> ):
<24> crypto = self._cryptos[epoch]
<25> if crypto.send.is_valid():
<26> builder.start_packet(packet_type, crypto)
<27> write_close_frame(builder, **self._close_pending)
<28> builder.end_packet()
<29> self._close_pending = None
<30> break
<31> self._close(is_initiator=True)
<32> else:
<33> # data is limited by congestion control and whether the network path is validated
<34> max_bytes = self._loss.congestion_window - self._loss.bytes_in_flight
<35> if not network_path.is_validated:
<36> max_bytes = min(
<37> max_bytes, network_path.bytes_received * 3 - network_path.bytes_sent
<38> )
<39>
<40> </s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch, max_bytes)
self._write_application(builder, max_bytes, network_path)
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# send datagrams
for datagram in datagrams:
self._transport.sendto(datagram, network_path.addr)
network_path.bytes_sent += len(datagram)
# register packets
now = self._loop.time()
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm timer
self._set_timer()
===========unchanged ref 0===========
at: aioquic.buffer.Buffer
seek(pos: int) -> None
at: aioquic.connection
write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None
QuicConnectionState()
END_STATES = set([QuicConnectionState.CLOSING, QuicConnectionState.DRAINING])
at: aioquic.connection.QuicConnection
_close(is_initiator: bool) -> None
_write_application(builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath) -> None
_write_handshake(builder: QuicPacketBuilder, epoch: tls.Epoch, max_bytes: int) -> None
at: aioquic.connection.QuicConnection.__init__
self.is_client = is_client
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._handshake_confirmed = False
self.host_cid = self._host_cids[0].cid
self._loop = loop
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._network_paths: List[QuicNetworkPath] = []
self._packet_number = 0
self._peer_cid = os.urandom(8)
self._peer_token = b""
self._spin_bit = False
self._state = QuicConnectionState.FIRSTFLIGHT
self._transport: Optional[asyncio.DatagramTransport] = None
self._version: Optional[int] = None
self._close_pending: Optional[Dict] = None
self._send_task: Optional[asyncio.Handle] = None
===========unchanged ref 1===========
at: aioquic.connection.QuicConnection._consume_connection_id
self._peer_cid = connection_id.cid
at: aioquic.connection.QuicConnection._handle_ack_frame
self._handshake_confirmed = True
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._crypto_buffers = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
self._packet_number = 0
at: aioquic.connection.QuicConnection._send_soon
self._send_task = self._loop.call_soon(self._send_pending)
at: aioquic.connection.QuicConnection._set_state
self._state = state
at: aioquic.connection.QuicConnection.close
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
at: aioquic.connection.QuicConnection.connect
self._network_paths = [QuicNetworkPath(addr, is_validated=True)]
self._version = max(self.supported_versions)
self._version = protocol_version
at: aioquic.connection.QuicConnection.connection_made
self._transport = cast(asyncio.DatagramTransport, transport)
===========unchanged ref 2===========
at: aioquic.connection.QuicConnection.datagram_received
self._version = QuicProtocolVersion(header.version)
self._version = QuicProtocolVersion(max(common))
self._peer_cid = header.source_cid
self._peer_token = header.token
self._network_paths = [network_path]
self._spin_bit = self._spin_bit_peer
self._spin_bit = not self._spin_bit_peer
self.host_cid = context.host_cid
at: aioquic.connection.QuicNetworkPath
addr: NetworkAddress
bytes_received: int = 0
bytes_sent: int = 0
is_validated: bool = False
local_challenge: Optional[bytes] = None
remote_challenge: Optional[bytes] = None
at: aioquic.crypto.CryptoContext
is_valid() -> bool
at: aioquic.crypto.CryptoPair.__init__
self.send = CryptoContext()
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
at: aioquic.packet_builder.QuicPacketBuilder
flush() -> Tuple[List[bytes], List[QuicSentPacket]]
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
|
aioquic.connection/QuicConnection._set_timer
|
Modified
|
aiortc~aioquic
|
a16048ef96107fe33545cd8e0cf9ed690fe99413
|
[connection] ensure proper shutdown when receiving a CLOSE frame
|
<2>:<add> if self._state not in END_STATES:
<del> if self._state not in [
<3>:<del> QuicConnectionState.CLOSING,
<4>:<del> QuicConnectionState.DRAINING,
<5>:<del> ]:
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_timer(self) -> None:
<0> # determine earliest timeout
<1> timer_at = self._close_at
<2> if self._state not in [
<3> QuicConnectionState.CLOSING,
<4> QuicConnectionState.DRAINING,
<5> ]:
<6> loss_at = self._loss.get_loss_detection_time()
<7> if loss_at is not None and loss_at < timer_at:
<8> timer_at = loss_at
<9>
<10> # re-arm timer
<11> if self._timer is not None and self._timer_at != timer_at:
<12> self._timer.cancel()
<13> self._timer = None
<14> if self._timer is None and timer_at is not None:
<15> self._timer = self._loop.call_at(timer_at, self._on_timeout)
<16> self._timer_at = timer_at
<17>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionState()
END_STATES = set([QuicConnectionState.CLOSING, QuicConnectionState.DRAINING])
at: aioquic.connection.QuicConnection
_on_timeout() -> None
at: aioquic.connection.QuicConnection.__init__
self._close_at: Optional[float] = None
self._loop = loop
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._loss = QuicPacketRecovery(send_probe=self._send_probe)
self._state = QuicConnectionState.FIRSTFLIGHT
self._timer: Optional[asyncio.TimerHandle] = None
self._timer_at: Optional[float] = None
at: aioquic.connection.QuicConnection._close
self._close_at = self._loop.time() + 3 * self._loss.get_probe_timeout()
at: aioquic.connection.QuicConnection._connect
self._close_at = self._loop.time() + self._local_idle_timeout
at: aioquic.connection.QuicConnection._on_timeout
self._timer = None
self._timer_at = None
at: aioquic.connection.QuicConnection._set_timer
self._timer_at = timer_at
at: aioquic.connection.QuicConnection.datagram_received
self._close_at = now + self._local_idle_timeout
at: aioquic.recovery.QuicPacketRecovery
get_loss_detection_time() -> float
at: asyncio.events.AbstractEventLoop
call_at(when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle
at: asyncio.events.TimerHandle
__slots__ = ['_scheduled', '_when']
cancel() -> None
===========unchanged ref 1===========
at: logging.LoggerAdapter
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CONNECTION_CLOSE frame.
"""
if frame_type == QuicFrameType.TRANSPORT_CLOSE:
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
else:
error_code, reason_phrase = pull_application_close_frame(buf)
frame_type = None
self._logger.info(
"Connection close code 0x%X, reason %s", error_code, reason_phrase
)
if error_code != QuicErrorCode.NO_ERROR:
self._close_exception = QuicConnectionError(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
+
self._close(is_initiator=False)
+ self._set_timer()
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
network_path = self._network_paths[0]
self._send_task = None
+ if self._state in END_STATES:
- if self._state in [QuicConnectionState.CLOSING, QuicConnectionState.DRAINING]:
return
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
packet_number=self._packet_number,
pad_first_datagram=(
self.is_client and self._state == QuicConnectionState.FIRSTFLIGHT
),
peer_cid=self._peer_cid,
peer_token=self._peer_token,
spin_bit=self._spin_bit,
version=self._version,
)
if self._close_pending:
for epoch, packet_type in (
(tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
):
crypto = self._cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
write_close_frame(builder, **self._close_pending)
builder.end_packet()
self._close_pending = None
break
self._close(is_initiator=True)
else:
# data is limited by congestion control and whether the network path is validated
max_bytes = self._loss.congestion_window - self._loss.bytes_in_flight
if not network_path.is_validated:
max_bytes = min(
max_bytes, network_path.bytes_received * 3 - network_path.bytes_sent
)
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HAND</s>
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _send_pending(self) -> None:
# offset: 1
<s> )
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch, max_bytes)
self._write_application(builder, max_bytes, network_path)
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# send datagrams
for datagram in datagrams:
self._transport.sendto(datagram, network_path.addr)
network_path.bytes_sent += len(datagram)
# register packets
now = self._loop.time()
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# check if we can discard initial keys
if sent_handshake and self.is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# arm timer
self._set_timer()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
+ if self._state not in END_STATES:
- if self._state not in [
- QuicConnectionState.CLOSING,
- QuicConnectionState.DRAINING,
- ]:
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
self._send_pending()
|
tests.test_connection/QuicConnectionTest.test_tls_error
|
Modified
|
aiortc~aioquic
|
a16048ef96107fe33545cd8e0cf9ed690fe99413
|
[connection] ensure proper shutdown when receiving a CLOSE frame
|
<12>:<add> run(asyncio.gather(client.wait_connected(), server.wait_connected()))
<del> run(server.wait_connected())
|
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_tls_error(self):
<0> def patch(client):
<1> real_initialize = client._initialize
<2>
<3> def patched_initialize(peer_cid: bytes):
<4> real_initialize(peer_cid)
<5> client.tls._supported_versions = [tls.TLS_VERSION_1_3_DRAFT_28]
<6>
<7> client._initialize = patched_initialize
<8>
<9> # handshake fails
<10> with client_and_server(client_patch=patch) as (client, server):
<11> with self.assertRaises(QuicConnectionError) as cm:
<12> run(server.wait_connected())
<13> self.assertEqual(cm.exception.error_code, 326)
<14> self.assertEqual(cm.exception.frame_type, QuicFrameType.CRYPTO)
<15> self.assertEqual(
<16> cm.exception.reason_phrase, "No supported protocol version"
<17> )
<18>
|
===========unchanged ref 0===========
at: aioquic.connection
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
at: aioquic.packet
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
at: aioquic.tls
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
===========unchanged ref 1===========
at: asyncio.tasks
gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[
Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]
]
gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]
gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]
gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]
gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s>
===========unchanged ref 2===========
at: tests.test_connection
client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})
at: tests.utils
run(coro)
at: unittest.case.TestCase
failureException: Type[BaseException]
longMessage: bool
maxDiff: Optional[int]
_testMethodName: str
_testMethodDoc: str
assertEqual(first: Any, second: Any, msg: Any=...) -> None
assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]
assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None
at: unittest.case._AssertRaisesContext.__exit__
self.exception = exc_value.with_traceback(None)
===========changed ref 0===========
# module: aioquic.connection
+ END_STATES = set([QuicConnectionState.CLOSING, QuicConnectionState.DRAINING])
===========changed ref 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
"""
+ if self._state not in END_STATES:
- if self._state not in [
- QuicConnectionState.CLOSING,
- QuicConnectionState.DRAINING,
- ]:
self._close_pending = {
"error_code": error_code,
"frame_type": frame_type,
"reason_phrase": reason_phrase,
}
self._send_pending()
===========changed ref 2===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CONNECTION_CLOSE frame.
"""
if frame_type == QuicFrameType.TRANSPORT_CLOSE:
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
else:
error_code, reason_phrase = pull_application_close_frame(buf)
frame_type = None
self._logger.info(
"Connection close code 0x%X, reason %s", error_code, reason_phrase
)
if error_code != QuicErrorCode.NO_ERROR:
self._close_exception = QuicConnectionError(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
+
self._close(is_initiator=False)
+ self._set_timer()
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _set_timer(self) -> None:
# determine earliest timeout
timer_at = self._close_at
+ if self._state not in END_STATES:
- if self._state not in [
- QuicConnectionState.CLOSING,
- QuicConnectionState.DRAINING,
- ]:
loss_at = self._loss.get_loss_detection_time()
if loss_at is not None and loss_at < timer_at:
timer_at = loss_at
# re-arm timer
if self._timer is not None and self._timer_at != timer_at:
self._timer.cancel()
self._timer = None
if self._timer is None and timer_at is not None:
self._timer = self._loop.call_at(timer_at, self._on_timeout)
self._timer_at = timer_at
|
aioquic.stream/QuicStream.__init__
|
Modified
|
aiortc~aioquic
|
2bf1a6ec65a4b5ee9b5285bef9e7445f350150b8
|
[stream] skip some code when send buffer is known to be empty
|
<4>:<add> self.send_buffer_is_empty = True
|
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def __init__(
self,
stream_id: Optional[int] = None,
connection: Optional[Any] = None,
max_stream_data_local: int = 0,
max_stream_data_remote: int = 0,
) -> None:
<0> self._connection = connection
<1> self.max_stream_data_local = max_stream_data_local
<2> self.max_stream_data_local_sent = max_stream_data_local
<3> self.max_stream_data_remote = max_stream_data_remote
<4>
<5> if stream_id is not None:
<6> self.reader = asyncio.StreamReader()
<7> self.writer = asyncio.StreamWriter(self, None, self.reader, None)
<8> else:
<9> self.reader = None
<10> self.writer = None
<11>
<12> self._recv_buffer = bytearray()
<13> self._recv_buffer_fin: Optional[int] = None
<14> self._recv_buffer_start = 0 # the offset for the start of the buffer
<15> self._recv_highest = 0 # the highest offset ever seen
<16> self._recv_ranges = RangeSet()
<17>
<18> self._send_acked = RangeSet()
<19> self._send_buffer = bytearray()
<20> self._send_buffer_fin: Optional[int] = None
<21> self._send_buffer_start = 0 # the offset for the start of the buffer
<22> self._send_buffer_stop = 0 # the offset for the stop of the buffer
<23> self._send_highest = 0
<24> self._send_pending = RangeSet()
<25> self._send_pending_eof = False
<26>
<27> self.__stream_id = stream_id
<28>
|
===========unchanged ref 0===========
at: aioquic.rangeset
RangeSet(ranges: Iterable[range]=[])
at: aioquic.stream.QuicStream.add_frame
self._recv_highest = frame_end
self._recv_buffer += bytearray(gap)
self._recv_buffer_fin = frame_end
at: aioquic.stream.QuicStream.get_frame
self._send_pending_eof = False
self.send_buffer_is_empty = True
self._send_highest = stop
at: aioquic.stream.QuicStream.on_data_delivery
self.send_buffer_is_empty = False
self._send_buffer_start += size
self._send_pending_eof = True
at: aioquic.stream.QuicStream.pull_data
self._recv_buffer = self._recv_buffer[pos:]
self._recv_buffer_start = r.stop
at: aioquic.stream.QuicStream.write
self.send_buffer_is_empty = False
self._send_buffer += data
self._send_buffer_stop += size
at: aioquic.stream.QuicStream.write_eof
self.send_buffer_is_empty = False
self._send_buffer_fin = self._send_buffer_stop
self._send_pending_eof = True
at: asyncio.streams
StreamWriter(transport: transports.BaseTransport, protocol: protocols.BaseProtocol, reader: Optional[StreamReader], loop: events.AbstractEventLoop)
StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...)
at: asyncio.transports.BaseTransport
__slots__ = ('_extra',)
__init__(self, extra: Optional[Mapping[Any, Any]]=...) -> None
|
aioquic.stream/QuicStream.get_frame
|
Modified
|
aiortc~aioquic
|
2bf1a6ec65a4b5ee9b5285bef9e7445f350150b8
|
[stream] skip some code when send buffer is known to be empty
|
<11>:<add>
<add> self.send_buffer_is_empty = True
|
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def get_frame(
self, max_size: int, max_offset: Optional[int] = None
) -> Optional[QuicStreamFrame]:
<0> """
<1> Get a frame of data to send.
<2> """
<3> # get the first pending data range
<4> try:
<5> r = self._send_pending[0]
<6> except IndexError:
<7> if self._send_pending_eof:
<8> # FIN only
<9> self._send_pending_eof = False
<10> return QuicStreamFrame(fin=True, offset=self._send_buffer_fin)
<11> return None
<12>
<13> # apply flow control
<14> start = r.start
<15> stop = min(r.stop, start + max_size)
<16> if max_offset is not None and stop > max_offset:
<17> stop = max_offset
<18> if stop <= start:
<19> return None
<20>
<21> # create frame
<22> frame = QuicStreamFrame(
<23> data=self._send_buffer[
<24> start - self._send_buffer_start : stop - self._send_buffer_start
<25> ],
<26> offset=start,
<27> )
<28> self._send_pending.subtract(start, stop)
<29>
<30> # track the highest offset ever sent
<31> if stop > self._send_highest:
<32> self._send_highest = stop
<33>
<34> # if the buffer is empty and EOF was written, set the FIN bit
<35> if self._send_buffer_fin == stop:
<36> frame.fin = True
<37> self._send_pending_eof = False
<38>
<39> return frame
<40>
|
===========unchanged ref 0===========
at: aioquic.packet
QuicStreamFrame(data: bytes=b"", fin: bool=False, offset: int=0)
at: aioquic.packet.QuicStreamFrame
data: bytes = b""
fin: bool = False
offset: int = 0
at: aioquic.rangeset.RangeSet
subtract(start: int, stop: int) -> None
at: aioquic.stream.QuicStream.__init__
self.send_buffer_is_empty = True
self._send_buffer = bytearray()
self._send_buffer_fin: Optional[int] = None
self._send_buffer_start = 0 # the offset for the start of the buffer
self._send_highest = 0
self._send_pending = RangeSet()
self._send_pending_eof = False
at: aioquic.stream.QuicStream.on_data_delivery
self.send_buffer_is_empty = False
self._send_buffer_start += size
self._send_pending_eof = True
at: aioquic.stream.QuicStream.write
self.send_buffer_is_empty = False
self._send_buffer += data
at: aioquic.stream.QuicStream.write_eof
self.send_buffer_is_empty = False
self._send_buffer_fin = self._send_buffer_stop
self._send_pending_eof = True
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def __init__(
self,
stream_id: Optional[int] = None,
connection: Optional[Any] = None,
max_stream_data_local: int = 0,
max_stream_data_remote: int = 0,
) -> None:
self._connection = connection
self.max_stream_data_local = max_stream_data_local
self.max_stream_data_local_sent = max_stream_data_local
self.max_stream_data_remote = max_stream_data_remote
+ self.send_buffer_is_empty = True
if stream_id is not None:
self.reader = asyncio.StreamReader()
self.writer = asyncio.StreamWriter(self, None, self.reader, None)
else:
self.reader = None
self.writer = None
self._recv_buffer = bytearray()
self._recv_buffer_fin: Optional[int] = None
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_highest = 0 # the highest offset ever seen
self._recv_ranges = RangeSet()
self._send_acked = RangeSet()
self._send_buffer = bytearray()
self._send_buffer_fin: Optional[int] = None
self._send_buffer_start = 0 # the offset for the start of the buffer
self._send_buffer_stop = 0 # the offset for the stop of the buffer
self._send_highest = 0
self._send_pending = RangeSet()
self._send_pending_eof = False
self.__stream_id = stream_id
|
aioquic.stream/QuicStream.on_data_delivery
|
Modified
|
aiortc~aioquic
|
2bf1a6ec65a4b5ee9b5285bef9e7445f350150b8
|
[stream] skip some code when send buffer is known to be empty
|
<3>:<add> self.send_buffer_is_empty = False
|
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def on_data_delivery(
self, delivery: QuicDeliveryState, start: int, stop: int
) -> None:
<0> """
<1> Callback when sent data is ACK'd.
<2> """
<3> if delivery == QuicDeliveryState.ACKED:
<4> if stop > start:
<5> self._send_acked.add(start, stop)
<6> first_range = self._send_acked[0]
<7> if first_range.start == self._send_buffer_start:
<8> size = first_range.stop - first_range.start
<9> self._send_acked.shift()
<10> self._send_buffer_start += size
<11> del self._send_buffer[:size]
<12> else:
<13> if stop > start:
<14> self._send_pending.add(start, stop)
<15> if stop == self._send_buffer_fin:
<16> self._send_pending_eof = True
<17>
|
===========unchanged ref 0===========
at: aioquic.packet_builder
QuicDeliveryState()
at: aioquic.rangeset.RangeSet
add(start: int, stop: Optional[int]=None) -> None
shift() -> range
at: aioquic.stream.QuicStream.__init__
self.send_buffer_is_empty = True
self._send_acked = RangeSet()
self._send_buffer = bytearray()
self._send_buffer_start = 0 # the offset for the start of the buffer
at: aioquic.stream.QuicStream.get_frame
self.send_buffer_is_empty = True
frame = QuicStreamFrame(
data=self._send_buffer[
start - self._send_buffer_start : stop - self._send_buffer_start
],
offset=start,
)
at: aioquic.stream.QuicStream.write
self.send_buffer_is_empty = False
self._send_buffer += data
at: aioquic.stream.QuicStream.write_eof
self.send_buffer_is_empty = False
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def get_frame(
self, max_size: int, max_offset: Optional[int] = None
) -> Optional[QuicStreamFrame]:
"""
Get a frame of data to send.
"""
# get the first pending data range
try:
r = self._send_pending[0]
except IndexError:
if self._send_pending_eof:
# FIN only
self._send_pending_eof = False
return QuicStreamFrame(fin=True, offset=self._send_buffer_fin)
+
+ self.send_buffer_is_empty = True
return None
# apply flow control
start = r.start
stop = min(r.stop, start + max_size)
if max_offset is not None and stop > max_offset:
stop = max_offset
if stop <= start:
return None
# create frame
frame = QuicStreamFrame(
data=self._send_buffer[
start - self._send_buffer_start : stop - self._send_buffer_start
],
offset=start,
)
self._send_pending.subtract(start, stop)
# track the highest offset ever sent
if stop > self._send_highest:
self._send_highest = stop
# if the buffer is empty and EOF was written, set the FIN bit
if self._send_buffer_fin == stop:
frame.fin = True
self._send_pending_eof = False
return frame
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def __init__(
self,
stream_id: Optional[int] = None,
connection: Optional[Any] = None,
max_stream_data_local: int = 0,
max_stream_data_remote: int = 0,
) -> None:
self._connection = connection
self.max_stream_data_local = max_stream_data_local
self.max_stream_data_local_sent = max_stream_data_local
self.max_stream_data_remote = max_stream_data_remote
+ self.send_buffer_is_empty = True
if stream_id is not None:
self.reader = asyncio.StreamReader()
self.writer = asyncio.StreamWriter(self, None, self.reader, None)
else:
self.reader = None
self.writer = None
self._recv_buffer = bytearray()
self._recv_buffer_fin: Optional[int] = None
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_highest = 0 # the highest offset ever seen
self._recv_ranges = RangeSet()
self._send_acked = RangeSet()
self._send_buffer = bytearray()
self._send_buffer_fin: Optional[int] = None
self._send_buffer_start = 0 # the offset for the start of the buffer
self._send_buffer_stop = 0 # the offset for the stop of the buffer
self._send_highest = 0
self._send_pending = RangeSet()
self._send_pending_eof = False
self.__stream_id = stream_id
|
aioquic.stream/QuicStream.write
|
Modified
|
aiortc~aioquic
|
2bf1a6ec65a4b5ee9b5285bef9e7445f350150b8
|
[stream] skip some code when send buffer is known to be empty
|
<7>:<add> self.send_buffer_is_empty = False
|
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def write(self, data: bytes) -> None:
<0> """
<1> Write some data bytes to the QUIC stream.
<2> """
<3> assert self._send_buffer_fin is None, "cannot call write() after FIN"
<4> size = len(data)
<5>
<6> if size:
<7> self._send_pending.add(
<8> self._send_buffer_stop, self._send_buffer_stop + size
<9> )
<10> self._send_buffer += data
<11> self._send_buffer_stop += size
<12> if self._connection is not None:
<13> self._connection._send_soon()
<14>
|
===========unchanged ref 0===========
at: aioquic.rangeset.RangeSet
add(start: int, stop: Optional[int]=None) -> None
at: aioquic.stream.QuicStream.__init__
self.send_buffer_is_empty = True
self._send_buffer_fin: Optional[int] = None
self._send_buffer_start = 0 # the offset for the start of the buffer
self._send_buffer_stop = 0 # the offset for the stop of the buffer
self._send_pending = RangeSet()
at: aioquic.stream.QuicStream.get_frame
self.send_buffer_is_empty = True
at: aioquic.stream.QuicStream.on_data_delivery
self.send_buffer_is_empty = False
self._send_buffer_start += size
at: aioquic.stream.QuicStream.write
self._send_buffer_stop += size
at: aioquic.stream.QuicStream.write_eof
self.send_buffer_is_empty = False
self._send_buffer_fin = self._send_buffer_stop
at: asyncio.transports.WriteTransport
__slots__ = ()
write(self, data: Any) -> None
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def on_data_delivery(
self, delivery: QuicDeliveryState, start: int, stop: int
) -> None:
"""
Callback when sent data is ACK'd.
"""
+ self.send_buffer_is_empty = False
if delivery == QuicDeliveryState.ACKED:
if stop > start:
self._send_acked.add(start, stop)
first_range = self._send_acked[0]
if first_range.start == self._send_buffer_start:
size = first_range.stop - first_range.start
self._send_acked.shift()
self._send_buffer_start += size
del self._send_buffer[:size]
else:
if stop > start:
self._send_pending.add(start, stop)
if stop == self._send_buffer_fin:
self._send_pending_eof = True
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def get_frame(
self, max_size: int, max_offset: Optional[int] = None
) -> Optional[QuicStreamFrame]:
"""
Get a frame of data to send.
"""
# get the first pending data range
try:
r = self._send_pending[0]
except IndexError:
if self._send_pending_eof:
# FIN only
self._send_pending_eof = False
return QuicStreamFrame(fin=True, offset=self._send_buffer_fin)
+
+ self.send_buffer_is_empty = True
return None
# apply flow control
start = r.start
stop = min(r.stop, start + max_size)
if max_offset is not None and stop > max_offset:
stop = max_offset
if stop <= start:
return None
# create frame
frame = QuicStreamFrame(
data=self._send_buffer[
start - self._send_buffer_start : stop - self._send_buffer_start
],
offset=start,
)
self._send_pending.subtract(start, stop)
# track the highest offset ever sent
if stop > self._send_highest:
self._send_highest = stop
# if the buffer is empty and EOF was written, set the FIN bit
if self._send_buffer_fin == stop:
frame.fin = True
self._send_pending_eof = False
return frame
===========changed ref 2===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def __init__(
self,
stream_id: Optional[int] = None,
connection: Optional[Any] = None,
max_stream_data_local: int = 0,
max_stream_data_remote: int = 0,
) -> None:
self._connection = connection
self.max_stream_data_local = max_stream_data_local
self.max_stream_data_local_sent = max_stream_data_local
self.max_stream_data_remote = max_stream_data_remote
+ self.send_buffer_is_empty = True
if stream_id is not None:
self.reader = asyncio.StreamReader()
self.writer = asyncio.StreamWriter(self, None, self.reader, None)
else:
self.reader = None
self.writer = None
self._recv_buffer = bytearray()
self._recv_buffer_fin: Optional[int] = None
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_highest = 0 # the highest offset ever seen
self._recv_ranges = RangeSet()
self._send_acked = RangeSet()
self._send_buffer = bytearray()
self._send_buffer_fin: Optional[int] = None
self._send_buffer_start = 0 # the offset for the start of the buffer
self._send_buffer_stop = 0 # the offset for the stop of the buffer
self._send_highest = 0
self._send_pending = RangeSet()
self._send_pending_eof = False
self.__stream_id = stream_id
|
aioquic.stream/QuicStream.write_eof
|
Modified
|
aiortc~aioquic
|
2bf1a6ec65a4b5ee9b5285bef9e7445f350150b8
|
[stream] skip some code when send buffer is known to be empty
|
<2>:<add> self.send_buffer_is_empty = False
|
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def write_eof(self) -> None:
<0> assert self._send_buffer_fin is None, "cannot call write_eof() after FIN"
<1>
<2> self._send_buffer_fin = self._send_buffer_stop
<3> self._send_pending_eof = True
<4> if self._connection is not None:
<5> self._connection._send_soon()
<6>
|
===========unchanged ref 0===========
at: aioquic.stream.QuicStream.__init__
self._connection = connection
self._send_buffer = bytearray()
self._send_buffer_fin: Optional[int] = None
self._send_buffer_stop = 0 # the offset for the stop of the buffer
at: aioquic.stream.QuicStream.write
size = len(data)
at: aioquic.stream.QuicStream.write_eof
self._send_buffer_fin = self._send_buffer_stop
at: asyncio.transports.WriteTransport
write_eof(self) -> None
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def write(self, data: bytes) -> None:
"""
Write some data bytes to the QUIC stream.
"""
assert self._send_buffer_fin is None, "cannot call write() after FIN"
size = len(data)
if size:
+ self.send_buffer_is_empty = False
self._send_pending.add(
self._send_buffer_stop, self._send_buffer_stop + size
)
self._send_buffer += data
self._send_buffer_stop += size
if self._connection is not None:
self._connection._send_soon()
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def on_data_delivery(
self, delivery: QuicDeliveryState, start: int, stop: int
) -> None:
"""
Callback when sent data is ACK'd.
"""
+ self.send_buffer_is_empty = False
if delivery == QuicDeliveryState.ACKED:
if stop > start:
self._send_acked.add(start, stop)
first_range = self._send_acked[0]
if first_range.start == self._send_buffer_start:
size = first_range.stop - first_range.start
self._send_acked.shift()
self._send_buffer_start += size
del self._send_buffer[:size]
else:
if stop > start:
self._send_pending.add(start, stop)
if stop == self._send_buffer_fin:
self._send_pending_eof = True
===========changed ref 2===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def get_frame(
self, max_size: int, max_offset: Optional[int] = None
) -> Optional[QuicStreamFrame]:
"""
Get a frame of data to send.
"""
# get the first pending data range
try:
r = self._send_pending[0]
except IndexError:
if self._send_pending_eof:
# FIN only
self._send_pending_eof = False
return QuicStreamFrame(fin=True, offset=self._send_buffer_fin)
+
+ self.send_buffer_is_empty = True
return None
# apply flow control
start = r.start
stop = min(r.stop, start + max_size)
if max_offset is not None and stop > max_offset:
stop = max_offset
if stop <= start:
return None
# create frame
frame = QuicStreamFrame(
data=self._send_buffer[
start - self._send_buffer_start : stop - self._send_buffer_start
],
offset=start,
)
self._send_pending.subtract(start, stop)
# track the highest offset ever sent
if stop > self._send_highest:
self._send_highest = stop
# if the buffer is empty and EOF was written, set the FIN bit
if self._send_buffer_fin == stop:
frame.fin = True
self._send_pending_eof = False
return frame
===========changed ref 3===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def __init__(
self,
stream_id: Optional[int] = None,
connection: Optional[Any] = None,
max_stream_data_local: int = 0,
max_stream_data_remote: int = 0,
) -> None:
self._connection = connection
self.max_stream_data_local = max_stream_data_local
self.max_stream_data_local_sent = max_stream_data_local
self.max_stream_data_remote = max_stream_data_remote
+ self.send_buffer_is_empty = True
if stream_id is not None:
self.reader = asyncio.StreamReader()
self.writer = asyncio.StreamWriter(self, None, self.reader, None)
else:
self.reader = None
self.writer = None
self._recv_buffer = bytearray()
self._recv_buffer_fin: Optional[int] = None
self._recv_buffer_start = 0 # the offset for the start of the buffer
self._recv_highest = 0 # the highest offset ever seen
self._recv_ranges = RangeSet()
self._send_acked = RangeSet()
self._send_buffer = bytearray()
self._send_buffer_fin: Optional[int] = None
self._send_buffer_start = 0 # the offset for the start of the buffer
self._send_buffer_stop = 0 # the offset for the stop of the buffer
self._send_highest = 0
self._send_pending = RangeSet()
self._send_pending_eof = False
self.__stream_id = stream_id
|
aioquic.connection/QuicConnection._write_application
|
Modified
|
aiortc~aioquic
|
2bf1a6ec65a4b5ee9b5285bef9e7445f350150b8
|
[stream] skip some code when send buffer is known to be empty
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
<0> crypto_stream: Optional[QuicStream] = None
<1> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
<2> crypto = self._cryptos[tls.Epoch.ONE_RTT]
<3> crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
<4> packet_type = PACKET_TYPE_ONE_RTT
<5> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
<6> crypto = self._cryptos[tls.Epoch.ZERO_RTT]
<7> packet_type = PACKET_TYPE_ZERO_RTT
<8> else:
<9> return
<10> space = self._spaces[tls.Epoch.ONE_RTT]
<11>
<12> buf = builder.buffer
<13>
<14> while builder.flight_bytes < max_bytes or self._probe_pending:
<15> # write header
<16> builder.start_packet(packet_type, crypto)
<17>
<18> if self._handshake_complete:
<19> # ACK
<20> if space.ack_required:
<21> builder.start_frame(
<22> QuicFrameType.ACK,
<23> self._on_ack_delivery,
<24> (space, space.largest_received_packet),
<25> )
<26> push_ack_frame(buf, space.ack_queue, 0)
<27> space.ack_required = False
<28>
<29> # PATH CHALLENGE
<30> if (
<31> not network_path.is_validated
<32> and network_path.local_challenge is None
<33> ):
<34> self._logger.info(
<35> "Network path %s sending challenge", network_path.addr
<36> )
<37> network_path.local_challenge = os.urandom(8)
<38> builder.start_frame(QuicFrameType.PATH_CH</s>
|
===========below chunk 0===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 1
push_bytes(buf, network_path.local_challenge)
# PATH RESPONSE
if network_path.remote_challenge is not None:
builder.start_frame(QuicFrameType.PATH_RESPONSE)
push_bytes(buf, network_path.remote_challenge)
network_path.remote_challenge = None
# NEW_CONNECTION_ID
for connection_id in self._host_cids:
if not connection_id.was_sent:
builder.start_frame(
QuicFrameType.NEW_CONNECTION_ID,
self._on_new_connection_id_delivery,
(connection_id,),
)
push_new_connection_id_frame(
buf,
connection_id.sequence_number,
connection_id.cid,
connection_id.stateless_reset_token,
)
connection_id.was_sent = True
self._connection_id_issued_handler(connection_id.cid)
# RETIRE_CONNECTION_ID
while self._retire_connection_ids:
sequence_number = self._retire_connection_ids.pop(0)
builder.start_frame(
QuicFrameType.RETIRE_CONNECTION_ID,
self._on_retire_connection_id_delivery,
(sequence_number,),
)
push_uint_var(buf, sequence_number)
# connection-level limits
self._write_connection_limits(builder=builder, space=space)
# stream-level limits
for stream in self._streams.values():
self._write_stream_limits(builder=builder, space=space, stream=stream)
# PING (user-request)
if self._ping_pending:
self._logger.info("Sending PING in packet</s>
===========below chunk 1===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
# offset: 2
<s> # PING (user-request)
if self._ping_pending:
self._logger.info("Sending PING in packet %d", builder.packet_number)
builder.start_frame(QuicFrameType.PING, self._on_ping_delivery)
self._ping_pending = False
# PING (probe)
if self._probe_pending:
self._logger.info("Sending probe")
builder.start_frame(QuicFrameType.PING)
self._probe_pending = False
# CRYPTO
if crypto_stream is not None:
write_crypto_frame(builder=builder, space=space, stream=crypto_stream)
for stream in self._streams.values():
# STREAM
self._remote_max_data_used += write_stream_frame(
builder=builder,
space=space,
stream=stream,
max_offset=min(
stream._send_highest
+ self._remote_max_data
- self._remote_max_data_used,
stream.max_stream_data_remote,
),
)
if not builder.end_packet():
break
===========unchanged ref 0===========
at: aioquic.buffer
push_bytes(buf: Buffer, v: bytes) -> None
push_uint_var(buf: Buffer, value: int) -> None
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int
QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None)
at: aioquic.connection.QuicConnection
supported_versions = [QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20]
_on_ack_delivery(delivery: QuicDeliveryState, space: QuicPacketSpace, highest_acked: int) -> None
_on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None
_on_ping_delivery(delivery: QuicDeliveryState) -> None
_on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None
_write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None
_write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._handshake_complete = False
===========unchanged ref 1===========
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._remote_max_data = 0
self._remote_max_data_used = 0
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._streams: Dict[int, QuicStream] = {}
self._ping_pending = False
self._probe_pending = False
self._retire_connection_ids: List[int] = []
self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None
at: aioquic.connection.QuicConnection._handle_crypto_frame
self._handshake_complete = True
at: aioquic.connection.QuicConnection._handle_max_data_frame
self._remote_max_data = max_data
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.connection.QuicConnection._on_ping_delivery
self._ping_pending = True
|
|
aioquic.connection/QuicConnection._write_handshake
|
Modified
|
aiortc~aioquic
|
2bf1a6ec65a4b5ee9b5285bef9e7445f350150b8
|
[stream] skip some code when send buffer is known to be empty
|
<5>:<add> crypto_stream = self._crypto_streams[epoch]
<21>:<add> if not crypto_stream.send_buffer_is_empty:
<del> write_crypto_frame(
<22>:<add> write_crypto_frame(builder=builder, space=space, stream=crypto_stream)
<del> builder=builder, space=space, stream=self._crypto_streams[epoch]
<23>:<del> )
|
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_handshake(
self, builder: QuicPacketBuilder, epoch: tls.Epoch, max_bytes: int
) -> None:
<0> crypto = self._cryptos[epoch]
<1> if not crypto.send.is_valid():
<2> return
<3>
<4> buf = builder.buffer
<5> space = self._spaces[epoch]
<6>
<7> while builder.flight_bytes < max_bytes:
<8> if epoch == tls.Epoch.INITIAL:
<9> packet_type = PACKET_TYPE_INITIAL
<10> else:
<11> packet_type = PACKET_TYPE_HANDSHAKE
<12> builder.start_packet(packet_type, crypto)
<13>
<14> # ACK
<15> if space.ack_required:
<16> builder.start_frame(QuicFrameType.ACK)
<17> push_ack_frame(buf, space.ack_queue, 0)
<18> space.ack_required = False
<19>
<20> # CRYPTO
<21> write_crypto_frame(
<22> builder=builder, space=space, stream=self._crypto_streams[epoch]
<23> )
<24>
<25> if not builder.end_packet():
<26> break
<27>
|
===========unchanged ref 0===========
at: aioquic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.connection.QuicConnection.__init__
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
at: aioquic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
self._spaces = {
tls.Epoch.INITIAL: QuicPacketSpace(),
tls.Epoch.HANDSHAKE: QuicPacketSpace(),
tls.Epoch.ONE_RTT: QuicPacketSpace(),
}
at: aioquic.crypto.CryptoContext
is_valid() -> bool
at: aioquic.crypto.CryptoPair.__init__
self.send = CryptoContext()
at: aioquic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
push_ack_frame(buf: Buffer, rangeset: RangeSet, delay: int) -> None
===========unchanged ref 1===========
at: aioquic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
at: aioquic.packet_builder.QuicPacketBuilder
start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.packet_builder.QuicPacketBuilder.__init__
self.buffer = Buffer(PACKET_MAX_SIZE)
at: aioquic.recovery.QuicPacketSpace.__init__
self.ack_queue = RangeSet()
self.ack_required = False
at: aioquic.stream.QuicStream.__init__
self.send_buffer_is_empty = True
at: aioquic.stream.QuicStream.get_frame
self.send_buffer_is_empty = True
at: aioquic.stream.QuicStream.on_data_delivery
self.send_buffer_is_empty = False
at: aioquic.stream.QuicStream.write
self.send_buffer_is_empty = False
at: aioquic.stream.QuicStream.write_eof
self.send_buffer_is_empty = False
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def write_eof(self) -> None:
assert self._send_buffer_fin is None, "cannot call write_eof() after FIN"
+ self.send_buffer_is_empty = False
self._send_buffer_fin = self._send_buffer_stop
self._send_pending_eof = True
if self._connection is not None:
self._connection._send_soon()
===========changed ref 1===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def write(self, data: bytes) -> None:
"""
Write some data bytes to the QUIC stream.
"""
assert self._send_buffer_fin is None, "cannot call write() after FIN"
size = len(data)
if size:
+ self.send_buffer_is_empty = False
self._send_pending.add(
self._send_buffer_stop, self._send_buffer_stop + size
)
self._send_buffer += data
self._send_buffer_stop += size
if self._connection is not None:
self._connection._send_soon()
===========changed ref 2===========
# module: aioquic.stream
class QuicStream(asyncio.Transport):
def on_data_delivery(
self, delivery: QuicDeliveryState, start: int, stop: int
) -> None:
"""
Callback when sent data is ACK'd.
"""
+ self.send_buffer_is_empty = False
if delivery == QuicDeliveryState.ACKED:
if stop > start:
self._send_acked.add(start, stop)
first_range = self._send_acked[0]
if first_range.start == self._send_buffer_start:
size = first_range.stop - first_range.start
self._send_acked.shift()
self._send_buffer_start += size
del self._send_buffer[:size]
else:
if stop > start:
self._send_pending.add(start, stop)
if stop == self._send_buffer_fin:
self._send_pending_eof = True
===========changed ref 3===========
# module: aioquic.connection
class QuicConnection(asyncio.DatagramProtocol):
def _write_application(
self, builder: QuicPacketBuilder, max_bytes: int, network_path: QuicNetworkPath
) -> None:
crypto_stream: Optional[QuicStream] = None
if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ONE_RTT]
crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
packet_type = PACKET_TYPE_ONE_RTT
elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ZERO_RTT]
packet_type = PACKET_TYPE_ZERO_RTT
else:
return
space = self._spaces[tls.Epoch.ONE_RTT]
buf = builder.buffer
while builder.flight_bytes < max_bytes or self._probe_pending:
# write header
builder.start_packet(packet_type, crypto)
if self._handshake_complete:
# ACK
if space.ack_required:
builder.start_frame(
QuicFrameType.ACK,
self._on_ack_delivery,
(space, space.largest_received_packet),
)
push_ack_frame(buf, space.ack_queue, 0)
space.ack_required = False
# PATH CHALLENGE
if (
not network_path.is_validated
and network_path.local_challenge is None
):
self._logger.info(
"Network path %s sending challenge", network_path.addr
)
network_path.local_challenge = os.urandom(8)
builder.start_frame(QuicFrameType.PATH_CHALLENGE)
push_bytes(buf, network_path.local_challenge)
# PATH RESPONSE
if network_path.remote_challenge is not None</s>
|
aioquic.crypto/CryptoContext.__init__
|
Modified
|
aiortc~aioquic
|
4c069629f11725691048c7c6e1635b21b75ce2f4
|
[crypto] switch AEAD and some header protection code to C
|
<0>:<add> self.aead: Optional[AEAD]
<del> self.aead: Optional[Any]
<2>:<add> self.hp: Optional[HeaderProtection]
<del> self.hp: Optional[bytes]
<3>:<del> self.hp_encryptor: Optional[Any] = None
|
# module: aioquic.crypto
class CryptoContext:
def __init__(self, key_phase: int = 0) -> None:
<0> self.aead: Optional[Any]
<1> self.cipher_suite: Optional[CipherSuite]
<2> self.hp: Optional[bytes]
<3> self.hp_encryptor: Optional[Any] = None
<4> self.iv: Optional[bytes]
<5> self.key_phase = key_phase
<6> self.secret: Optional[bytes]
<7>
<8> self.teardown()
<9>
|
===========unchanged ref 0===========
at: aioquic.crypto.CryptoContext.__init__
self.aead: Optional[AEAD]
self.cipher_suite: Optional[CipherSuite]
self.hp: Optional[HeaderProtection]
self.iv: Optional[bytes]
self.secret: Optional[bytes]
at: aioquic.crypto.CryptoContext.apply_key_phase
self.aead = crypto.aead
self.iv = crypto.iv
self.secret = crypto.secret
at: aioquic.crypto.CryptoContext.setup
key, self.iv, hp = derive_key_iv_hp(cipher_suite, secret)
self.aead = AEAD(aead_cipher_name, key)
self.cipher_suite = cipher_suite
self.hp = HeaderProtection(hp_cipher_name, hp)
self.secret = secret
===========changed ref 0===========
# module: aioquic.crypto
- class AEAD:
- def __init__(self, cipher_suite: CipherSuite, key: bytes):
- if cipher_suite == CipherSuite.AES_128_GCM_SHA256:
- self._cipher_name = b"aes-128-gcm"
- elif cipher_suite == CipherSuite.AES_256_GCM_SHA384:
- self._cipher_name = b"aes-256-gcm"
- else:
- self._cipher_name = b"chacha20-poly1305"
- self._decrypt_ctx = None
- self._encrypt_ctx = None
- self._key_length = len(key)
- self._key_ptr = backend._ffi.from_buffer(key)
-
===========changed ref 1===========
# module: aioquic.crypto
- class AEAD:
- def _create_ctx(self, nonce_length: int, operation: int) -> Any:
- evp_cipher = backend._lib.EVP_get_cipherbyname(self._cipher_name)
- backend.openssl_assert(evp_cipher != backend._ffi.NULL)
- ctx = backend._lib.EVP_CIPHER_CTX_new()
- ctx = backend._ffi.gc(ctx, backend._lib.EVP_CIPHER_CTX_free)
- res = backend._lib.EVP_CipherInit_ex(
- ctx,
- evp_cipher,
- backend._ffi.NULL,
- backend._ffi.NULL,
- backend._ffi.NULL,
- operation,
- )
- backend.openssl_assert(res != 0)
- res = backend._lib.EVP_CIPHER_CTX_set_key_length(ctx, self._key_length)
- backend.openssl_assert(res != 0)
- res = backend._lib.EVP_CIPHER_CTX_ctrl(
- ctx, backend._lib.EVP_CTRL_AEAD_SET_IVLEN, nonce_length, backend._ffi.NULL
- )
- backend.openssl_assert(res != 0)
- return ctx
-
===========changed ref 2===========
# module: aioquic.crypto
+ CIPHER_SUITES = {
+ CipherSuite.AES_128_GCM_SHA256: (b"aes-128-ecb", b"aes-128-gcm"),
+ CipherSuite.AES_256_GCM_SHA384: (b"aes-256-ecb", b"aes-256-gcm"),
+ CipherSuite.CHACHA20_POLY1305_SHA256: (b"chacha20", b"chacha20-poly1305"),
+ }
INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256
INITIAL_SALT = binascii.unhexlify("ef4fb0abb47470c41befcf8031334fae485e09a0")
SAMPLE_SIZE = 16
===========changed ref 3===========
# module: aioquic.crypto
- class AEAD:
- def encrypt(self, nonce: bytes, data: bytes, associated_data: bytes) -> bytes:
- global backend
-
- if self._encrypt_ctx is None:
- self._encrypt_ctx = self._create_ctx(len(nonce), 1)
- ctx = self._encrypt_ctx
-
- outlen = backend._ffi.new("int *")
- tag_length = 16
- res = backend._lib.EVP_CipherInit_ex(
- ctx,
- backend._ffi.NULL,
- backend._ffi.NULL,
- self._key_ptr,
- backend._ffi.from_buffer(nonce),
- 1,
- )
- backend.openssl_assert(res != 0)
-
- res = backend._lib.EVP_CipherUpdate(
- ctx, backend._ffi.NULL, outlen, associated_data, len(associated_data)
- )
- backend.openssl_assert(res != 0)
-
- buf = backend._ffi.new("unsigned char[]", len(data))
- res = backend._lib.EVP_CipherUpdate(ctx, buf, outlen, data, len(data))
- backend.openssl_assert(res != 0)
- processed_data = backend._ffi.buffer(buf, outlen[0])[:]
-
- res = backend._lib.EVP_CipherFinal_ex(ctx, backend._ffi.NULL, outlen)
- backend.openssl_assert(res != 0)
- backend.openssl_assert(outlen[0] == 0)
- tag_buf = backend._ffi.new("unsigned char[]", tag_length)
- res = backend._lib.EVP_CIPHER_CTX_ctrl(
- ctx, backend._lib.EVP_CTRL_AEAD_GET_TAG, tag_length, tag_buf
- )
- backend.openssl_assert(res != 0)
- tag = backend._ffi.buffer(tag</s>
===========changed ref 4===========
# module: aioquic.crypto
- class AEAD:
- def encrypt(self, nonce: bytes, data: bytes, associated_data: bytes) -> bytes:
# offset: 1
<s>
- )
- backend.openssl_assert(res != 0)
- tag = backend._ffi.buffer(tag_buf)[:]
-
- return processed_data + tag
-
|
aioquic.crypto/CryptoContext.decrypt_packet
|
Modified
|
aiortc~aioquic
|
4c069629f11725691048c7c6e1635b21b75ce2f4
|
[crypto] switch AEAD and some header protection code to C
|
<4>:<del> packet = bytearray(packet)
<7>:<add> mask = self.hp.mask(sample)
<del> mask = self.header_protection_mask(sample)
<8>:<add> packet = bytearray(packet)
<33>:<del> try:
<34>:<add> payload = crypto.aead.decrypt(
<del> payload = crypto.aead.decrypt(
<35>:<add> nonce, bytes(packet[encrypted_offset + pn_length :]), plain_header
<del> nonce, bytes(packet[encrypted_offset + pn_length :]), plain_header
<36>:<add> )
<del> )
<37>:<del> except InvalidTag:
<38>:<del> raise CryptoError("Payload decryption failed")
|
# module: aioquic.crypto
class CryptoContext:
def decrypt_packet(
self, packet: bytes, encrypted_offset: int, expected_packet_number: int
) -> Tuple[bytes, bytes, int, bool]:
<0> if self.aead is None:
<1> raise CryptoError("Decryption key is not available")
<2>
<3> # header protection
<4> packet = bytearray(packet)
<5> sample_offset = encrypted_offset + PACKET_NUMBER_MAX_SIZE
<6> sample = packet[sample_offset : sample_offset + SAMPLE_SIZE]
<7> mask = self.header_protection_mask(sample)
<8>
<9> if is_long_header(packet[0]):
<10> # long header
<11> packet[0] ^= mask[0] & 0x0F
<12> else:
<13> # short header
<14> packet[0] ^= mask[0] & 0x1F
<15>
<16> pn_length = (packet[0] & 0x03) + 1
<17> for i in range(pn_length):
<18> packet[encrypted_offset + i] ^= mask[1 + i]
<19> pn = packet[encrypted_offset : encrypted_offset + pn_length]
<20> plain_header = bytes(packet[: encrypted_offset + pn_length])
<21>
<22> # detect key phase change
<23> crypto = self
<24> if not is_long_header(packet[0]):
<25> key_phase = (packet[0] & 4) >> 2
<26> if key_phase != self.key_phase:
<27> crypto = self.next_key_phase()
<28>
<29> # payload protection
<30> nonce = crypto.iv[:-pn_length] + bytes(
<31> crypto.iv[i - pn_length] ^ pn[i] for i in range(pn_length)
<32> )
<33> try:
<34> payload = crypto.aead.decrypt(
<35> nonce, bytes(packet[encrypted_offset + pn_length :]), plain_header
<36> )
<37> except InvalidTag:
<38> raise CryptoError("Payload decryption failed")
<39>
<40> # packet number
</s>
|
===========below chunk 0===========
# module: aioquic.crypto
class CryptoContext:
def decrypt_packet(
self, packet: bytes, encrypted_offset: int, expected_packet_number: int
) -> Tuple[bytes, bytes, int, bool]:
# offset: 1
for i in range(pn_length):
packet_number = (packet_number << 8) | pn[i]
packet_number = decode_packet_number(
packet_number, pn_length * 8, expected_packet_number
)
return plain_header, payload, packet_number, crypto != self
===========unchanged ref 0===========
at: aioquic.crypto
INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256
INITIAL_SALT = binascii.unhexlify("ef4fb0abb47470c41befcf8031334fae485e09a0")
at: aioquic.crypto.CryptoContext
apply_key_phase(crypto: CryptoContext) -> None
decrypt_packet(packet: bytes, encrypted_offset: int, expected_packet_number: int) -> Tuple[bytes, bytes, int, bool]
encrypt_packet(plain_header: bytes, plain_payload: bytes) -> bytes
next_key_phase() -> CryptoContext
setup(cipher_suite: CipherSuite, secret: bytes) -> None
teardown() -> None
at: aioquic.crypto.CryptoContext.__init__
self.key_phase = key_phase
at: aioquic.crypto.CryptoContext.apply_key_phase
self.key_phase = crypto.key_phase
at: aioquic.crypto.CryptoPair.__init__
self.recv = CryptoContext()
self.send = CryptoContext()
self._update_key_requested = False
at: aioquic.tls
hkdf_expand_label(algorithm: hashes.HashAlgorithm, secret: bytes, label: bytes, hash_value: bytes, length: int) -> bytes
hkdf_extract(algorithm: hashes.HashAlgorithm, salt: bytes, key_material: bytes) -> bytes
cipher_suite_hash(cipher_suite: CipherSuite) -> hashes.HashAlgorithm
===========changed ref 0===========
# module: aioquic.crypto
class CryptoContext:
def __init__(self, key_phase: int = 0) -> None:
+ self.aead: Optional[AEAD]
- self.aead: Optional[Any]
self.cipher_suite: Optional[CipherSuite]
+ self.hp: Optional[HeaderProtection]
- self.hp: Optional[bytes]
- self.hp_encryptor: Optional[Any] = None
self.iv: Optional[bytes]
self.key_phase = key_phase
self.secret: Optional[bytes]
self.teardown()
===========changed ref 1===========
# module: aioquic.crypto
- class AEAD:
- def __init__(self, cipher_suite: CipherSuite, key: bytes):
- if cipher_suite == CipherSuite.AES_128_GCM_SHA256:
- self._cipher_name = b"aes-128-gcm"
- elif cipher_suite == CipherSuite.AES_256_GCM_SHA384:
- self._cipher_name = b"aes-256-gcm"
- else:
- self._cipher_name = b"chacha20-poly1305"
- self._decrypt_ctx = None
- self._encrypt_ctx = None
- self._key_length = len(key)
- self._key_ptr = backend._ffi.from_buffer(key)
-
===========changed ref 2===========
# module: aioquic.crypto
- class AEAD:
- def _create_ctx(self, nonce_length: int, operation: int) -> Any:
- evp_cipher = backend._lib.EVP_get_cipherbyname(self._cipher_name)
- backend.openssl_assert(evp_cipher != backend._ffi.NULL)
- ctx = backend._lib.EVP_CIPHER_CTX_new()
- ctx = backend._ffi.gc(ctx, backend._lib.EVP_CIPHER_CTX_free)
- res = backend._lib.EVP_CipherInit_ex(
- ctx,
- evp_cipher,
- backend._ffi.NULL,
- backend._ffi.NULL,
- backend._ffi.NULL,
- operation,
- )
- backend.openssl_assert(res != 0)
- res = backend._lib.EVP_CIPHER_CTX_set_key_length(ctx, self._key_length)
- backend.openssl_assert(res != 0)
- res = backend._lib.EVP_CIPHER_CTX_ctrl(
- ctx, backend._lib.EVP_CTRL_AEAD_SET_IVLEN, nonce_length, backend._ffi.NULL
- )
- backend.openssl_assert(res != 0)
- return ctx
-
===========changed ref 3===========
# module: aioquic.crypto
+ CIPHER_SUITES = {
+ CipherSuite.AES_128_GCM_SHA256: (b"aes-128-ecb", b"aes-128-gcm"),
+ CipherSuite.AES_256_GCM_SHA384: (b"aes-256-ecb", b"aes-256-gcm"),
+ CipherSuite.CHACHA20_POLY1305_SHA256: (b"chacha20", b"chacha20-poly1305"),
+ }
INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256
INITIAL_SALT = binascii.unhexlify("ef4fb0abb47470c41befcf8031334fae485e09a0")
SAMPLE_SIZE = 16
===========changed ref 4===========
# module: aioquic.crypto
- class AEAD:
- def encrypt(self, nonce: bytes, data: bytes, associated_data: bytes) -> bytes:
- global backend
-
- if self._encrypt_ctx is None:
- self._encrypt_ctx = self._create_ctx(len(nonce), 1)
- ctx = self._encrypt_ctx
-
- outlen = backend._ffi.new("int *")
- tag_length = 16
- res = backend._lib.EVP_CipherInit_ex(
- ctx,
- backend._ffi.NULL,
- backend._ffi.NULL,
- self._key_ptr,
- backend._ffi.from_buffer(nonce),
- 1,
- )
- backend.openssl_assert(res != 0)
-
- res = backend._lib.EVP_CipherUpdate(
- ctx, backend._ffi.NULL, outlen, associated_data, len(associated_data)
- )
- backend.openssl_assert(res != 0)
-
- buf = backend._ffi.new("unsigned char[]", len(data))
- res = backend._lib.EVP_CipherUpdate(ctx, buf, outlen, data, len(data))
- backend.openssl_assert(res != 0)
- processed_data = backend._ffi.buffer(buf, outlen[0])[:]
-
- res = backend._lib.EVP_CipherFinal_ex(ctx, backend._ffi.NULL, outlen)
- backend.openssl_assert(res != 0)
- backend.openssl_assert(outlen[0] == 0)
- tag_buf = backend._ffi.new("unsigned char[]", tag_length)
- res = backend._lib.EVP_CIPHER_CTX_ctrl(
- ctx, backend._lib.EVP_CTRL_AEAD_GET_TAG, tag_length, tag_buf
- )
- backend.openssl_assert(res != 0)
- tag = backend._ffi.buffer(tag</s>
|
aioquic.crypto/CryptoContext.encrypt_packet
|
Modified
|
aiortc~aioquic
|
4c069629f11725691048c7c6e1635b21b75ce2f4
|
[crypto] switch AEAD and some header protection code to C
|
<15>:<add> mask = self.hp.mask(sample)
<del> mask = self.header_protection_mask(sample)
|
# module: aioquic.crypto
class CryptoContext:
def encrypt_packet(self, plain_header: bytes, plain_payload: bytes) -> bytes:
<0> assert self.is_valid(), "Encryption key is not available"
<1>
<2> pn_length = (plain_header[0] & 0x03) + 1
<3> pn_offset = len(plain_header) - pn_length
<4> pn = plain_header[pn_offset : pn_offset + pn_length]
<5>
<6> # payload protection
<7> nonce = self.iv[:-pn_length] + bytes(
<8> self.iv[i - pn_length] ^ pn[i] for i in range(pn_length)
<9> )
<10> protected_payload = self.aead.encrypt(nonce, plain_payload, plain_header)
<11>
<12> # header protection
<13> sample_offset = PACKET_NUMBER_MAX_SIZE - pn_length
<14> sample = protected_payload[sample_offset : sample_offset + SAMPLE_SIZE]
<15> mask = self.header_protection_mask(sample)
<16>
<17> packet = bytearray(plain_header + protected_payload)
<18> if is_long_header(packet[0]):
<19> # long header
<20> packet[0] ^= mask[0] & 0x0F
<21> else:
<22> # short header
<23> packet[0] ^= mask[0] & 0x1F
<24>
<25> for i in range(pn_length):
<26> packet[pn_offset + i] ^= mask[1 + i]
<27>
<28> return bytes(packet)
<29>
|
===========changed ref 0===========
# module: aioquic.crypto
class CryptoContext:
def __init__(self, key_phase: int = 0) -> None:
+ self.aead: Optional[AEAD]
- self.aead: Optional[Any]
self.cipher_suite: Optional[CipherSuite]
+ self.hp: Optional[HeaderProtection]
- self.hp: Optional[bytes]
- self.hp_encryptor: Optional[Any] = None
self.iv: Optional[bytes]
self.key_phase = key_phase
self.secret: Optional[bytes]
self.teardown()
===========changed ref 1===========
# module: aioquic.crypto
- class AEAD:
- def __init__(self, cipher_suite: CipherSuite, key: bytes):
- if cipher_suite == CipherSuite.AES_128_GCM_SHA256:
- self._cipher_name = b"aes-128-gcm"
- elif cipher_suite == CipherSuite.AES_256_GCM_SHA384:
- self._cipher_name = b"aes-256-gcm"
- else:
- self._cipher_name = b"chacha20-poly1305"
- self._decrypt_ctx = None
- self._encrypt_ctx = None
- self._key_length = len(key)
- self._key_ptr = backend._ffi.from_buffer(key)
-
===========changed ref 2===========
# module: aioquic.crypto
- class AEAD:
- def _create_ctx(self, nonce_length: int, operation: int) -> Any:
- evp_cipher = backend._lib.EVP_get_cipherbyname(self._cipher_name)
- backend.openssl_assert(evp_cipher != backend._ffi.NULL)
- ctx = backend._lib.EVP_CIPHER_CTX_new()
- ctx = backend._ffi.gc(ctx, backend._lib.EVP_CIPHER_CTX_free)
- res = backend._lib.EVP_CipherInit_ex(
- ctx,
- evp_cipher,
- backend._ffi.NULL,
- backend._ffi.NULL,
- backend._ffi.NULL,
- operation,
- )
- backend.openssl_assert(res != 0)
- res = backend._lib.EVP_CIPHER_CTX_set_key_length(ctx, self._key_length)
- backend.openssl_assert(res != 0)
- res = backend._lib.EVP_CIPHER_CTX_ctrl(
- ctx, backend._lib.EVP_CTRL_AEAD_SET_IVLEN, nonce_length, backend._ffi.NULL
- )
- backend.openssl_assert(res != 0)
- return ctx
-
===========changed ref 3===========
# module: aioquic.crypto
+ CIPHER_SUITES = {
+ CipherSuite.AES_128_GCM_SHA256: (b"aes-128-ecb", b"aes-128-gcm"),
+ CipherSuite.AES_256_GCM_SHA384: (b"aes-256-ecb", b"aes-256-gcm"),
+ CipherSuite.CHACHA20_POLY1305_SHA256: (b"chacha20", b"chacha20-poly1305"),
+ }
INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256
INITIAL_SALT = binascii.unhexlify("ef4fb0abb47470c41befcf8031334fae485e09a0")
SAMPLE_SIZE = 16
===========changed ref 4===========
# module: aioquic.crypto
class CryptoContext:
def decrypt_packet(
self, packet: bytes, encrypted_offset: int, expected_packet_number: int
) -> Tuple[bytes, bytes, int, bool]:
if self.aead is None:
raise CryptoError("Decryption key is not available")
# header protection
- packet = bytearray(packet)
sample_offset = encrypted_offset + PACKET_NUMBER_MAX_SIZE
sample = packet[sample_offset : sample_offset + SAMPLE_SIZE]
+ mask = self.hp.mask(sample)
- mask = self.header_protection_mask(sample)
+ packet = bytearray(packet)
if is_long_header(packet[0]):
# long header
packet[0] ^= mask[0] & 0x0F
else:
# short header
packet[0] ^= mask[0] & 0x1F
pn_length = (packet[0] & 0x03) + 1
for i in range(pn_length):
packet[encrypted_offset + i] ^= mask[1 + i]
pn = packet[encrypted_offset : encrypted_offset + pn_length]
plain_header = bytes(packet[: encrypted_offset + pn_length])
# detect key phase change
crypto = self
if not is_long_header(packet[0]):
key_phase = (packet[0] & 4) >> 2
if key_phase != self.key_phase:
crypto = self.next_key_phase()
# payload protection
nonce = crypto.iv[:-pn_length] + bytes(
crypto.iv[i - pn_length] ^ pn[i] for i in range(pn_length)
)
- try:
+ payload = crypto.aead.decrypt(
- payload = crypto.aead.decrypt(
+ nonce, bytes(packet[encrypted_offset + pn_length :]), plain_header
- nonce, bytes(packet[encrypted_offset + pn_length :]), plain_header
+ )
- </s>
===========changed ref 5===========
# module: aioquic.crypto
class CryptoContext:
def decrypt_packet(
self, packet: bytes, encrypted_offset: int, expected_packet_number: int
) -> Tuple[bytes, bytes, int, bool]:
# offset: 1
<s>_header
- nonce, bytes(packet[encrypted_offset + pn_length :]), plain_header
+ )
- )
- except InvalidTag:
- raise CryptoError("Payload decryption failed")
# packet number
packet_number = 0
for i in range(pn_length):
packet_number = (packet_number << 8) | pn[i]
packet_number = decode_packet_number(
packet_number, pn_length * 8, expected_packet_number
)
return plain_header, payload, packet_number, crypto != self
|
aioquic.crypto/CryptoContext.setup
|
Modified
|
aiortc~aioquic
|
4c069629f11725691048c7c6e1635b21b75ce2f4
|
[crypto] switch AEAD and some header protection code to C
|
<0>:<del> assert cipher_suite in [
<1>:<del> CipherSuite.AES_128_GCM_SHA256,
<2>:<del> CipherSuite.AES_256_GCM_SHA384,
<3>:<del> CipherSuite.CHACHA20_POLY1305_SHA256,
<4>:<del> ], "unsupported cipher suite"
<5>:<add> hp_cipher_name, aead_cipher_name = CIPHER_SUITES[cipher_suite]
<add>
<add> key, self.iv, hp = derive_key_iv_hp(cipher_suite, secret)
<del> key, self.iv, self.hp = derive_key_iv_hp(cipher_suite, secret)
<6>:<add> self.aead = AEAD(aead_cipher_name, key)
<del> self.aead = AEAD(cipher_suite, key)
<8>:<add> self.hp = HeaderProtection(hp_cipher_name, hp)
<10>:<del> if self.cipher_suite == CipherSuite.CHACHA20_POLY1305_SHA256:
<11>:<del> self.hp_encryptor = None
<12>:<del> else:
<13>:<del> self.hp_encryptor = Cipher(
<14>:<del> algorithms.AES(self.hp), mode=modes.ECB(), backend=default_backend()
<15>:<del> ).encryptor()
<16>:<del>
|
# module: aioquic.crypto
class CryptoContext:
def setup(self, cipher_suite: CipherSuite, secret: bytes) -> None:
<0> assert cipher_suite in [
<1> CipherSuite.AES_128_GCM_SHA256,
<2> CipherSuite.AES_256_GCM_SHA384,
<3> CipherSuite.CHACHA20_POLY1305_SHA256,
<4> ], "unsupported cipher suite"
<5> key, self.iv, self.hp = derive_key_iv_hp(cipher_suite, secret)
<6> self.aead = AEAD(cipher_suite, key)
<7> self.cipher_suite = cipher_suite
<8> self.secret = secret
<9>
<10> if self.cipher_suite == CipherSuite.CHACHA20_POLY1305_SHA256:
<11> self.hp_encryptor = None
<12> else:
<13> self.hp_encryptor = Cipher(
<14> algorithms.AES(self.hp), mode=modes.ECB(), backend=default_backend()
<15> ).encryptor()
<16>
|
===========changed ref 0===========
# module: aioquic.crypto
class CryptoContext:
- def header_protection_mask(self, sample: bytes) -> bytes:
- buf = bytearray(31)
- if self.cipher_suite == CipherSuite.CHACHA20_POLY1305_SHA256:
- encryptor = Cipher(
- algorithms.ChaCha20(key=self.hp, nonce=sample),
- mode=None,
- backend=default_backend(),
- ).encryptor()
- encryptor.update_into(bytes(5), buf)
- else:
- self.hp_encryptor.update_into(sample, buf)
- return buf[:5]
-
===========changed ref 1===========
# module: aioquic.crypto
class CryptoContext:
def __init__(self, key_phase: int = 0) -> None:
+ self.aead: Optional[AEAD]
- self.aead: Optional[Any]
self.cipher_suite: Optional[CipherSuite]
+ self.hp: Optional[HeaderProtection]
- self.hp: Optional[bytes]
- self.hp_encryptor: Optional[Any] = None
self.iv: Optional[bytes]
self.key_phase = key_phase
self.secret: Optional[bytes]
self.teardown()
===========changed ref 2===========
# module: aioquic.crypto
class CryptoContext:
def encrypt_packet(self, plain_header: bytes, plain_payload: bytes) -> bytes:
assert self.is_valid(), "Encryption key is not available"
pn_length = (plain_header[0] & 0x03) + 1
pn_offset = len(plain_header) - pn_length
pn = plain_header[pn_offset : pn_offset + pn_length]
# payload protection
nonce = self.iv[:-pn_length] + bytes(
self.iv[i - pn_length] ^ pn[i] for i in range(pn_length)
)
protected_payload = self.aead.encrypt(nonce, plain_payload, plain_header)
# header protection
sample_offset = PACKET_NUMBER_MAX_SIZE - pn_length
sample = protected_payload[sample_offset : sample_offset + SAMPLE_SIZE]
+ mask = self.hp.mask(sample)
- mask = self.header_protection_mask(sample)
packet = bytearray(plain_header + protected_payload)
if is_long_header(packet[0]):
# long header
packet[0] ^= mask[0] & 0x0F
else:
# short header
packet[0] ^= mask[0] & 0x1F
for i in range(pn_length):
packet[pn_offset + i] ^= mask[1 + i]
return bytes(packet)
===========changed ref 3===========
# module: aioquic.crypto
- class AEAD:
- def __init__(self, cipher_suite: CipherSuite, key: bytes):
- if cipher_suite == CipherSuite.AES_128_GCM_SHA256:
- self._cipher_name = b"aes-128-gcm"
- elif cipher_suite == CipherSuite.AES_256_GCM_SHA384:
- self._cipher_name = b"aes-256-gcm"
- else:
- self._cipher_name = b"chacha20-poly1305"
- self._decrypt_ctx = None
- self._encrypt_ctx = None
- self._key_length = len(key)
- self._key_ptr = backend._ffi.from_buffer(key)
-
===========changed ref 4===========
# module: aioquic.crypto
- class AEAD:
- def _create_ctx(self, nonce_length: int, operation: int) -> Any:
- evp_cipher = backend._lib.EVP_get_cipherbyname(self._cipher_name)
- backend.openssl_assert(evp_cipher != backend._ffi.NULL)
- ctx = backend._lib.EVP_CIPHER_CTX_new()
- ctx = backend._ffi.gc(ctx, backend._lib.EVP_CIPHER_CTX_free)
- res = backend._lib.EVP_CipherInit_ex(
- ctx,
- evp_cipher,
- backend._ffi.NULL,
- backend._ffi.NULL,
- backend._ffi.NULL,
- operation,
- )
- backend.openssl_assert(res != 0)
- res = backend._lib.EVP_CIPHER_CTX_set_key_length(ctx, self._key_length)
- backend.openssl_assert(res != 0)
- res = backend._lib.EVP_CIPHER_CTX_ctrl(
- ctx, backend._lib.EVP_CTRL_AEAD_SET_IVLEN, nonce_length, backend._ffi.NULL
- )
- backend.openssl_assert(res != 0)
- return ctx
-
===========changed ref 5===========
# module: aioquic.crypto
+ CIPHER_SUITES = {
+ CipherSuite.AES_128_GCM_SHA256: (b"aes-128-ecb", b"aes-128-gcm"),
+ CipherSuite.AES_256_GCM_SHA384: (b"aes-256-ecb", b"aes-256-gcm"),
+ CipherSuite.CHACHA20_POLY1305_SHA256: (b"chacha20", b"chacha20-poly1305"),
+ }
INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256
INITIAL_SALT = binascii.unhexlify("ef4fb0abb47470c41befcf8031334fae485e09a0")
SAMPLE_SIZE = 16
===========changed ref 6===========
# module: aioquic.crypto
class CryptoContext:
def decrypt_packet(
self, packet: bytes, encrypted_offset: int, expected_packet_number: int
) -> Tuple[bytes, bytes, int, bool]:
if self.aead is None:
raise CryptoError("Decryption key is not available")
# header protection
- packet = bytearray(packet)
sample_offset = encrypted_offset + PACKET_NUMBER_MAX_SIZE
sample = packet[sample_offset : sample_offset + SAMPLE_SIZE]
+ mask = self.hp.mask(sample)
- mask = self.header_protection_mask(sample)
+ packet = bytearray(packet)
if is_long_header(packet[0]):
# long header
packet[0] ^= mask[0] & 0x0F
else:
# short header
packet[0] ^= mask[0] & 0x1F
pn_length = (packet[0] & 0x03) + 1
for i in range(pn_length):
packet[encrypted_offset + i] ^= mask[1 + i]
pn = packet[encrypted_offset : encrypted_offset + pn_length]
plain_header = bytes(packet[: encrypted_offset + pn_length])
# detect key phase change
crypto = self
if not is_long_header(packet[0]):
key_phase = (packet[0] & 4) >> 2
if key_phase != self.key_phase:
crypto = self.next_key_phase()
# payload protection
nonce = crypto.iv[:-pn_length] + bytes(
crypto.iv[i - pn_length] ^ pn[i] for i in range(pn_length)
)
- try:
+ payload = crypto.aead.decrypt(
- payload = crypto.aead.decrypt(
+ nonce, bytes(packet[encrypted_offset + pn_length :]), plain_header
- nonce, bytes(packet[encrypted_offset + pn_length :]), plain_header
+ )
- </s>
|
aioquic.tls/pull_cipher_suite
|
Modified
|
aiortc~aioquic
|
d2fcbad2c99436b01c87ee9dd23e1223e90fdd15
|
[buffer] make basic operations Buffer methods
|
<0>:<add> return CipherSuite(buf.pull_uint16())
<del> return CipherSuite(pull_uint16(buf))
|
# module: aioquic.tls
# INTEGERS
def pull_cipher_suite(buf: Buffer) -> CipherSuite:
<0> return CipherSuite(pull_uint16(buf))
<1>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.buffer.Buffer
pull_uint8() -> int
at: aioquic.tls
KeyExchangeMode(x: Union[str, bytes, bytearray], base: int)
KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
===========changed ref 0===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint8(self) -> int:
+ """
+ Pull an 8-bit unsigned integer.
+ """
+ try:
+ v = self._data[self._pos]
+ self._pos += 1
+ return v
+ except IndexError:
+ raise BufferReadError
+
===========changed ref 1===========
# module: aioquic.tls
TLS_VERSION_1_2 = 0x0303
TLS_VERSION_1_3 = 0x0304
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
TLS_VERSION_1_3_DRAFT_27 = 0x7F1B
TLS_VERSION_1_3_DRAFT_26 = 0x7F1A
T = TypeVar("T")
-
===========changed ref 2===========
# module: aioquic.buffer
class Buffer:
+ def push_uint8(self, v: int) -> None:
+ """
+ Push an 8-bit unsigned integer.
+ """
+ self._data[self._pos] = v
+ self._pos += 1
+
===========changed ref 3===========
# module: aioquic.buffer
- def push_uint8(buf: Buffer, v: int) -> None:
- """
- Push an 8-bit unsigned integer.
- """
- buf._data[buf._pos] = v
- buf._pos += 1
-
===========changed ref 4===========
# module: aioquic.buffer
class Buffer:
+ def push_uint64(self, v: int) -> None:
+ """
+ Push a 64-bit unsigned integer.
+ """
+ pack_into("!Q", self._data, self._pos, v)
+ self._pos += 8
+
===========changed ref 5===========
# module: aioquic.buffer
class Buffer:
+ def push_uint32(self, v: int) -> None:
+ """
+ Push a 32-bit unsigned integer.
+ """
+ pack_into("!L", self._data, self._pos, v)
+ self._pos += 4
+
===========changed ref 6===========
# module: aioquic.buffer
class Buffer:
+ def push_uint16(self, v: int) -> None:
+ """
+ Push a 16-bit unsigned integer.
+ """
+ pack_into("!H", self._data, self._pos, v)
+ self._pos += 2
+
===========changed ref 7===========
# module: aioquic.buffer
- def push_uint64(buf: Buffer, v: int) -> None:
- """
- Push a 64-bit unsigned integer.
- """
- pack_into("!Q", buf._data, buf._pos, v)
- buf._pos += 8
-
===========changed ref 8===========
# module: aioquic.buffer
- def push_uint32(buf: Buffer, v: int) -> None:
- """
- Push a 32-bit unsigned integer.
- """
- pack_into("!L", buf._data, buf._pos, v)
- buf._pos += 4
-
===========changed ref 9===========
# module: aioquic.buffer
- def push_uint16(buf: Buffer, v: int) -> None:
- """
- Push a 16-bit unsigned integer.
- """
- pack_into("!H", buf._data, buf._pos, v)
- buf._pos += 2
-
===========changed ref 10===========
# module: aioquic.buffer
class Buffer:
+ def push_bytes(self, v: bytes) -> None:
+ """
+ Push bytes.
+ """
+ end = self._pos + len(v)
+ if end > self._length:
+ raise BufferWriteError
+ self._data[self._pos : end] = v
+ self._pos = end
+
===========changed ref 11===========
# module: aioquic.buffer
class Buffer:
+ def pull_bytes(self, length: int) -> bytes:
+ """
+ Pull bytes.
+ """
+ end = self._pos + length
+ if end > self._length:
+ raise BufferReadError
+ v = bytes(self._data[self._pos : end])
+ self._pos = end
+ return v
+
===========changed ref 12===========
# module: aioquic.buffer
- # INTEGERS
-
-
- def pull_uint8(buf: Buffer) -> int:
- """
- Pull an 8-bit unsigned integer.
- """
- try:
- v = buf._data[buf._pos]
- buf._pos += 1
- return v
- except IndexError:
- raise BufferReadError
-
===========changed ref 13===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint64(self) -> int:
+ """
+ Pull a 64-bit unsigned integer.
+ """
+ try:
+ v, = unpack_from("!Q", self._data, self._pos)
+ self._pos += 8
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 14===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint32(self) -> int:
+ """
+ Pull a 32-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!L", self._data, self._pos)
+ self._pos += 4
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 15===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint16(self) -> int:
+ """
+ Pull a 16-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!H", self._data, self._pos)
+ self._pos += 2
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 16===========
# module: aioquic.buffer
- # BYTES
-
-
- def pull_bytes(buf: Buffer, length: int) -> bytes:
- """
- Pull bytes.
- """
- if buf._pos + length > buf._length:
- raise BufferReadError
- v = buf._data[buf._pos : buf._pos + length]
- buf._pos += length
- return bytes(v)
-
===========changed ref 17===========
# module: aioquic.buffer
- def push_bytes(buf: Buffer, v: bytes) -> None:
- """
- Push bytes.
- """
- length = len(v)
- if buf._pos + length > buf._length:
- raise BufferWriteError
- buf._data[buf._pos : buf._pos + length] = v
- buf._pos += length
-
===========changed ref 18===========
# module: aioquic.buffer
- def pull_uint64(buf: Buffer) -> int:
- """
- Pull a 64-bit unsigned integer.
- """
- try:
- v, = unpack_from("!Q", buf._data, buf._pos)
- buf._pos += 8
- return v
- except struct.error:
- raise BufferReadError
-
===========changed ref 19===========
# module: aioquic.buffer
- def pull_uint32(buf: Buffer) -> int:
- """
- Pull a 32-bit unsigned integer.
- """
- try:
- v, = struct.unpack_from("!L", buf._data, buf._pos)
- buf._pos += 4
- return v
- except struct.error:
- raise BufferReadError
-
|
aioquic.tls/pull_compression_method
|
Modified
|
aiortc~aioquic
|
d2fcbad2c99436b01c87ee9dd23e1223e90fdd15
|
[buffer] make basic operations Buffer methods
|
<0>:<add> return CompressionMethod(buf.pull_uint8())
<del> return CompressionMethod(pull_uint8(buf))
|
# module: aioquic.tls
def pull_compression_method(buf: Buffer) -> CompressionMethod:
<0> return CompressionMethod(pull_uint8(buf))
<1>
|
===========unchanged ref 0===========
at: aioquic.buffer.Buffer
pull_uint16() -> int
at: aioquic.tls
Group(x: Union[str, bytes, bytearray], base: int)
Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
===========changed ref 0===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint16(self) -> int:
+ """
+ Pull a 16-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!H", self._data, self._pos)
+ self._pos += 2
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 1===========
# module: aioquic.tls
# INTEGERS
def pull_cipher_suite(buf: Buffer) -> CipherSuite:
+ return CipherSuite(buf.pull_uint16())
- return CipherSuite(pull_uint16(buf))
===========changed ref 2===========
# module: aioquic.tls
TLS_VERSION_1_2 = 0x0303
TLS_VERSION_1_3 = 0x0304
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
TLS_VERSION_1_3_DRAFT_27 = 0x7F1B
TLS_VERSION_1_3_DRAFT_26 = 0x7F1A
T = TypeVar("T")
-
===========changed ref 3===========
# module: aioquic.buffer
class Buffer:
+ def push_uint8(self, v: int) -> None:
+ """
+ Push an 8-bit unsigned integer.
+ """
+ self._data[self._pos] = v
+ self._pos += 1
+
===========changed ref 4===========
# module: aioquic.buffer
- def push_uint8(buf: Buffer, v: int) -> None:
- """
- Push an 8-bit unsigned integer.
- """
- buf._data[buf._pos] = v
- buf._pos += 1
-
===========changed ref 5===========
# module: aioquic.buffer
class Buffer:
+ def push_uint64(self, v: int) -> None:
+ """
+ Push a 64-bit unsigned integer.
+ """
+ pack_into("!Q", self._data, self._pos, v)
+ self._pos += 8
+
===========changed ref 6===========
# module: aioquic.buffer
class Buffer:
+ def push_uint32(self, v: int) -> None:
+ """
+ Push a 32-bit unsigned integer.
+ """
+ pack_into("!L", self._data, self._pos, v)
+ self._pos += 4
+
===========changed ref 7===========
# module: aioquic.buffer
class Buffer:
+ def push_uint16(self, v: int) -> None:
+ """
+ Push a 16-bit unsigned integer.
+ """
+ pack_into("!H", self._data, self._pos, v)
+ self._pos += 2
+
===========changed ref 8===========
# module: aioquic.buffer
- def push_uint64(buf: Buffer, v: int) -> None:
- """
- Push a 64-bit unsigned integer.
- """
- pack_into("!Q", buf._data, buf._pos, v)
- buf._pos += 8
-
===========changed ref 9===========
# module: aioquic.buffer
- def push_uint32(buf: Buffer, v: int) -> None:
- """
- Push a 32-bit unsigned integer.
- """
- pack_into("!L", buf._data, buf._pos, v)
- buf._pos += 4
-
===========changed ref 10===========
# module: aioquic.buffer
- def push_uint16(buf: Buffer, v: int) -> None:
- """
- Push a 16-bit unsigned integer.
- """
- pack_into("!H", buf._data, buf._pos, v)
- buf._pos += 2
-
===========changed ref 11===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint8(self) -> int:
+ """
+ Pull an 8-bit unsigned integer.
+ """
+ try:
+ v = self._data[self._pos]
+ self._pos += 1
+ return v
+ except IndexError:
+ raise BufferReadError
+
===========changed ref 12===========
# module: aioquic.buffer
class Buffer:
+ def push_bytes(self, v: bytes) -> None:
+ """
+ Push bytes.
+ """
+ end = self._pos + len(v)
+ if end > self._length:
+ raise BufferWriteError
+ self._data[self._pos : end] = v
+ self._pos = end
+
===========changed ref 13===========
# module: aioquic.buffer
class Buffer:
+ def pull_bytes(self, length: int) -> bytes:
+ """
+ Pull bytes.
+ """
+ end = self._pos + length
+ if end > self._length:
+ raise BufferReadError
+ v = bytes(self._data[self._pos : end])
+ self._pos = end
+ return v
+
===========changed ref 14===========
# module: aioquic.buffer
- # INTEGERS
-
-
- def pull_uint8(buf: Buffer) -> int:
- """
- Pull an 8-bit unsigned integer.
- """
- try:
- v = buf._data[buf._pos]
- buf._pos += 1
- return v
- except IndexError:
- raise BufferReadError
-
===========changed ref 15===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint64(self) -> int:
+ """
+ Pull a 64-bit unsigned integer.
+ """
+ try:
+ v, = unpack_from("!Q", self._data, self._pos)
+ self._pos += 8
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 16===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint32(self) -> int:
+ """
+ Pull a 32-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!L", self._data, self._pos)
+ self._pos += 4
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 17===========
# module: aioquic.buffer
- # BYTES
-
-
- def pull_bytes(buf: Buffer, length: int) -> bytes:
- """
- Pull bytes.
- """
- if buf._pos + length > buf._length:
- raise BufferReadError
- v = buf._data[buf._pos : buf._pos + length]
- buf._pos += length
- return bytes(v)
-
===========changed ref 18===========
# module: aioquic.buffer
- def push_bytes(buf: Buffer, v: bytes) -> None:
- """
- Push bytes.
- """
- length = len(v)
- if buf._pos + length > buf._length:
- raise BufferWriteError
- buf._data[buf._pos : buf._pos + length] = v
- buf._pos += length
-
===========changed ref 19===========
# module: aioquic.buffer
- def pull_uint64(buf: Buffer) -> int:
- """
- Pull a 64-bit unsigned integer.
- """
- try:
- v, = unpack_from("!Q", buf._data, buf._pos)
- buf._pos += 8
- return v
- except struct.error:
- raise BufferReadError
-
===========changed ref 20===========
# module: aioquic.buffer
- def pull_uint32(buf: Buffer) -> int:
- """
- Pull a 32-bit unsigned integer.
- """
- try:
- v, = struct.unpack_from("!L", buf._data, buf._pos)
- buf._pos += 4
- return v
- except struct.error:
- raise BufferReadError
-
|
aioquic.tls/pull_key_exchange_mode
|
Modified
|
aiortc~aioquic
|
d2fcbad2c99436b01c87ee9dd23e1223e90fdd15
|
[buffer] make basic operations Buffer methods
|
<0>:<add> return KeyExchangeMode(buf.pull_uint8())
<del> return KeyExchangeMode(pull_uint8(buf))
|
# module: aioquic.tls
def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:
<0> return KeyExchangeMode(pull_uint8(buf))
<1>
|
===========unchanged ref 0===========
at: aioquic.buffer.Buffer
pull_uint16() -> int
at: aioquic.tls
SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)
SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
===========changed ref 0===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint16(self) -> int:
+ """
+ Pull a 16-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!H", self._data, self._pos)
+ self._pos += 2
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 1===========
# module: aioquic.tls
def pull_compression_method(buf: Buffer) -> CompressionMethod:
+ return CompressionMethod(buf.pull_uint8())
- return CompressionMethod(pull_uint8(buf))
===========changed ref 2===========
# module: aioquic.tls
# INTEGERS
def pull_cipher_suite(buf: Buffer) -> CipherSuite:
+ return CipherSuite(buf.pull_uint16())
- return CipherSuite(pull_uint16(buf))
===========changed ref 3===========
# module: aioquic.tls
TLS_VERSION_1_2 = 0x0303
TLS_VERSION_1_3 = 0x0304
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
TLS_VERSION_1_3_DRAFT_27 = 0x7F1B
TLS_VERSION_1_3_DRAFT_26 = 0x7F1A
T = TypeVar("T")
-
===========changed ref 4===========
# module: aioquic.buffer
class Buffer:
+ def push_uint8(self, v: int) -> None:
+ """
+ Push an 8-bit unsigned integer.
+ """
+ self._data[self._pos] = v
+ self._pos += 1
+
===========changed ref 5===========
# module: aioquic.buffer
- def push_uint8(buf: Buffer, v: int) -> None:
- """
- Push an 8-bit unsigned integer.
- """
- buf._data[buf._pos] = v
- buf._pos += 1
-
===========changed ref 6===========
# module: aioquic.buffer
class Buffer:
+ def push_uint64(self, v: int) -> None:
+ """
+ Push a 64-bit unsigned integer.
+ """
+ pack_into("!Q", self._data, self._pos, v)
+ self._pos += 8
+
===========changed ref 7===========
# module: aioquic.buffer
class Buffer:
+ def push_uint32(self, v: int) -> None:
+ """
+ Push a 32-bit unsigned integer.
+ """
+ pack_into("!L", self._data, self._pos, v)
+ self._pos += 4
+
===========changed ref 8===========
# module: aioquic.buffer
class Buffer:
+ def push_uint16(self, v: int) -> None:
+ """
+ Push a 16-bit unsigned integer.
+ """
+ pack_into("!H", self._data, self._pos, v)
+ self._pos += 2
+
===========changed ref 9===========
# module: aioquic.buffer
- def push_uint64(buf: Buffer, v: int) -> None:
- """
- Push a 64-bit unsigned integer.
- """
- pack_into("!Q", buf._data, buf._pos, v)
- buf._pos += 8
-
===========changed ref 10===========
# module: aioquic.buffer
- def push_uint32(buf: Buffer, v: int) -> None:
- """
- Push a 32-bit unsigned integer.
- """
- pack_into("!L", buf._data, buf._pos, v)
- buf._pos += 4
-
===========changed ref 11===========
# module: aioquic.buffer
- def push_uint16(buf: Buffer, v: int) -> None:
- """
- Push a 16-bit unsigned integer.
- """
- pack_into("!H", buf._data, buf._pos, v)
- buf._pos += 2
-
===========changed ref 12===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint8(self) -> int:
+ """
+ Pull an 8-bit unsigned integer.
+ """
+ try:
+ v = self._data[self._pos]
+ self._pos += 1
+ return v
+ except IndexError:
+ raise BufferReadError
+
===========changed ref 13===========
# module: aioquic.buffer
class Buffer:
+ def push_bytes(self, v: bytes) -> None:
+ """
+ Push bytes.
+ """
+ end = self._pos + len(v)
+ if end > self._length:
+ raise BufferWriteError
+ self._data[self._pos : end] = v
+ self._pos = end
+
===========changed ref 14===========
# module: aioquic.buffer
class Buffer:
+ def pull_bytes(self, length: int) -> bytes:
+ """
+ Pull bytes.
+ """
+ end = self._pos + length
+ if end > self._length:
+ raise BufferReadError
+ v = bytes(self._data[self._pos : end])
+ self._pos = end
+ return v
+
===========changed ref 15===========
# module: aioquic.buffer
- # INTEGERS
-
-
- def pull_uint8(buf: Buffer) -> int:
- """
- Pull an 8-bit unsigned integer.
- """
- try:
- v = buf._data[buf._pos]
- buf._pos += 1
- return v
- except IndexError:
- raise BufferReadError
-
===========changed ref 16===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint64(self) -> int:
+ """
+ Pull a 64-bit unsigned integer.
+ """
+ try:
+ v, = unpack_from("!Q", self._data, self._pos)
+ self._pos += 8
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 17===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint32(self) -> int:
+ """
+ Pull a 32-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!L", self._data, self._pos)
+ self._pos += 4
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 18===========
# module: aioquic.buffer
- # BYTES
-
-
- def pull_bytes(buf: Buffer, length: int) -> bytes:
- """
- Pull bytes.
- """
- if buf._pos + length > buf._length:
- raise BufferReadError
- v = buf._data[buf._pos : buf._pos + length]
- buf._pos += length
- return bytes(v)
-
===========changed ref 19===========
# module: aioquic.buffer
- def push_bytes(buf: Buffer, v: bytes) -> None:
- """
- Push bytes.
- """
- length = len(v)
- if buf._pos + length > buf._length:
- raise BufferWriteError
- buf._data[buf._pos : buf._pos + length] = v
- buf._pos += length
-
===========changed ref 20===========
# module: aioquic.buffer
- def pull_uint64(buf: Buffer) -> int:
- """
- Pull a 64-bit unsigned integer.
- """
- try:
- v, = unpack_from("!Q", buf._data, buf._pos)
- buf._pos += 8
- return v
- except struct.error:
- raise BufferReadError
-
===========changed ref 21===========
# module: aioquic.buffer
- def pull_uint32(buf: Buffer) -> int:
- """
- Pull a 32-bit unsigned integer.
- """
- try:
- v, = struct.unpack_from("!L", buf._data, buf._pos)
- buf._pos += 4
- return v
- except struct.error:
- raise BufferReadError
-
|
aioquic.tls/pull_group
|
Modified
|
aiortc~aioquic
|
d2fcbad2c99436b01c87ee9dd23e1223e90fdd15
|
[buffer] make basic operations Buffer methods
|
<0>:<add> return Group(buf.pull_uint16())
<del> return Group(pull_uint16(buf))
|
# module: aioquic.tls
def pull_group(buf: Buffer) -> Group:
<0> return Group(pull_uint16(buf))
<1>
|
===========changed ref 0===========
# module: aioquic.tls
def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:
+ return KeyExchangeMode(buf.pull_uint8())
- return KeyExchangeMode(pull_uint8(buf))
===========changed ref 1===========
# module: aioquic.tls
def pull_compression_method(buf: Buffer) -> CompressionMethod:
+ return CompressionMethod(buf.pull_uint8())
- return CompressionMethod(pull_uint8(buf))
===========changed ref 2===========
# module: aioquic.tls
# INTEGERS
def pull_cipher_suite(buf: Buffer) -> CipherSuite:
+ return CipherSuite(buf.pull_uint16())
- return CipherSuite(pull_uint16(buf))
===========changed ref 3===========
# module: aioquic.tls
TLS_VERSION_1_2 = 0x0303
TLS_VERSION_1_3 = 0x0304
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
TLS_VERSION_1_3_DRAFT_27 = 0x7F1B
TLS_VERSION_1_3_DRAFT_26 = 0x7F1A
T = TypeVar("T")
-
===========changed ref 4===========
# module: aioquic.buffer
class Buffer:
+ def push_uint8(self, v: int) -> None:
+ """
+ Push an 8-bit unsigned integer.
+ """
+ self._data[self._pos] = v
+ self._pos += 1
+
===========changed ref 5===========
# module: aioquic.buffer
- def push_uint8(buf: Buffer, v: int) -> None:
- """
- Push an 8-bit unsigned integer.
- """
- buf._data[buf._pos] = v
- buf._pos += 1
-
===========changed ref 6===========
# module: aioquic.buffer
class Buffer:
+ def push_uint64(self, v: int) -> None:
+ """
+ Push a 64-bit unsigned integer.
+ """
+ pack_into("!Q", self._data, self._pos, v)
+ self._pos += 8
+
===========changed ref 7===========
# module: aioquic.buffer
class Buffer:
+ def push_uint32(self, v: int) -> None:
+ """
+ Push a 32-bit unsigned integer.
+ """
+ pack_into("!L", self._data, self._pos, v)
+ self._pos += 4
+
===========changed ref 8===========
# module: aioquic.buffer
class Buffer:
+ def push_uint16(self, v: int) -> None:
+ """
+ Push a 16-bit unsigned integer.
+ """
+ pack_into("!H", self._data, self._pos, v)
+ self._pos += 2
+
===========changed ref 9===========
# module: aioquic.buffer
- def push_uint64(buf: Buffer, v: int) -> None:
- """
- Push a 64-bit unsigned integer.
- """
- pack_into("!Q", buf._data, buf._pos, v)
- buf._pos += 8
-
===========changed ref 10===========
# module: aioquic.buffer
- def push_uint32(buf: Buffer, v: int) -> None:
- """
- Push a 32-bit unsigned integer.
- """
- pack_into("!L", buf._data, buf._pos, v)
- buf._pos += 4
-
===========changed ref 11===========
# module: aioquic.buffer
- def push_uint16(buf: Buffer, v: int) -> None:
- """
- Push a 16-bit unsigned integer.
- """
- pack_into("!H", buf._data, buf._pos, v)
- buf._pos += 2
-
===========changed ref 12===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint8(self) -> int:
+ """
+ Pull an 8-bit unsigned integer.
+ """
+ try:
+ v = self._data[self._pos]
+ self._pos += 1
+ return v
+ except IndexError:
+ raise BufferReadError
+
===========changed ref 13===========
# module: aioquic.buffer
class Buffer:
+ def push_bytes(self, v: bytes) -> None:
+ """
+ Push bytes.
+ """
+ end = self._pos + len(v)
+ if end > self._length:
+ raise BufferWriteError
+ self._data[self._pos : end] = v
+ self._pos = end
+
===========changed ref 14===========
# module: aioquic.buffer
class Buffer:
+ def pull_bytes(self, length: int) -> bytes:
+ """
+ Pull bytes.
+ """
+ end = self._pos + length
+ if end > self._length:
+ raise BufferReadError
+ v = bytes(self._data[self._pos : end])
+ self._pos = end
+ return v
+
===========changed ref 15===========
# module: aioquic.buffer
- # INTEGERS
-
-
- def pull_uint8(buf: Buffer) -> int:
- """
- Pull an 8-bit unsigned integer.
- """
- try:
- v = buf._data[buf._pos]
- buf._pos += 1
- return v
- except IndexError:
- raise BufferReadError
-
===========changed ref 16===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint64(self) -> int:
+ """
+ Pull a 64-bit unsigned integer.
+ """
+ try:
+ v, = unpack_from("!Q", self._data, self._pos)
+ self._pos += 8
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 17===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint32(self) -> int:
+ """
+ Pull a 32-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!L", self._data, self._pos)
+ self._pos += 4
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 18===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint16(self) -> int:
+ """
+ Pull a 16-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!H", self._data, self._pos)
+ self._pos += 2
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 19===========
# module: aioquic.buffer
- # BYTES
-
-
- def pull_bytes(buf: Buffer, length: int) -> bytes:
- """
- Pull bytes.
- """
- if buf._pos + length > buf._length:
- raise BufferReadError
- v = buf._data[buf._pos : buf._pos + length]
- buf._pos += length
- return bytes(v)
-
===========changed ref 20===========
# module: aioquic.buffer
- def push_bytes(buf: Buffer, v: bytes) -> None:
- """
- Push bytes.
- """
- length = len(v)
- if buf._pos + length > buf._length:
- raise BufferWriteError
- buf._data[buf._pos : buf._pos + length] = v
- buf._pos += length
-
===========changed ref 21===========
# module: aioquic.buffer
- def pull_uint64(buf: Buffer) -> int:
- """
- Pull a 64-bit unsigned integer.
- """
- try:
- v, = unpack_from("!Q", buf._data, buf._pos)
- buf._pos += 8
- return v
- except struct.error:
- raise BufferReadError
-
===========changed ref 22===========
# module: aioquic.buffer
- def pull_uint32(buf: Buffer) -> int:
- """
- Pull a 32-bit unsigned integer.
- """
- try:
- v, = struct.unpack_from("!L", buf._data, buf._pos)
- buf._pos += 4
- return v
- except struct.error:
- raise BufferReadError
-
|
aioquic.tls/pull_signature_algorithm
|
Modified
|
aiortc~aioquic
|
d2fcbad2c99436b01c87ee9dd23e1223e90fdd15
|
[buffer] make basic operations Buffer methods
|
<0>:<add> return SignatureAlgorithm(buf.pull_uint16())
<del> return SignatureAlgorithm(pull_uint16(buf))
|
# module: aioquic.tls
def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm:
<0> return SignatureAlgorithm(pull_uint16(buf))
<1>
|
===========unchanged ref 0===========
at: aioquic.buffer.Buffer
pull_bytes(length: int) -> bytes
===========changed ref 0===========
# module: aioquic.buffer
class Buffer:
+ def pull_bytes(self, length: int) -> bytes:
+ """
+ Pull bytes.
+ """
+ end = self._pos + length
+ if end > self._length:
+ raise BufferReadError
+ v = bytes(self._data[self._pos : end])
+ self._pos = end
+ return v
+
===========changed ref 1===========
# module: aioquic.tls
def pull_group(buf: Buffer) -> Group:
+ return Group(buf.pull_uint16())
- return Group(pull_uint16(buf))
===========changed ref 2===========
# module: aioquic.tls
def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:
+ return KeyExchangeMode(buf.pull_uint8())
- return KeyExchangeMode(pull_uint8(buf))
===========changed ref 3===========
# module: aioquic.tls
def pull_compression_method(buf: Buffer) -> CompressionMethod:
+ return CompressionMethod(buf.pull_uint8())
- return CompressionMethod(pull_uint8(buf))
===========changed ref 4===========
# module: aioquic.tls
# INTEGERS
def pull_cipher_suite(buf: Buffer) -> CipherSuite:
+ return CipherSuite(buf.pull_uint16())
- return CipherSuite(pull_uint16(buf))
===========changed ref 5===========
# module: aioquic.tls
TLS_VERSION_1_2 = 0x0303
TLS_VERSION_1_3 = 0x0304
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
TLS_VERSION_1_3_DRAFT_27 = 0x7F1B
TLS_VERSION_1_3_DRAFT_26 = 0x7F1A
T = TypeVar("T")
-
===========changed ref 6===========
# module: aioquic.buffer
class Buffer:
+ def push_uint8(self, v: int) -> None:
+ """
+ Push an 8-bit unsigned integer.
+ """
+ self._data[self._pos] = v
+ self._pos += 1
+
===========changed ref 7===========
# module: aioquic.buffer
- def push_uint8(buf: Buffer, v: int) -> None:
- """
- Push an 8-bit unsigned integer.
- """
- buf._data[buf._pos] = v
- buf._pos += 1
-
===========changed ref 8===========
# module: aioquic.buffer
class Buffer:
+ def push_uint64(self, v: int) -> None:
+ """
+ Push a 64-bit unsigned integer.
+ """
+ pack_into("!Q", self._data, self._pos, v)
+ self._pos += 8
+
===========changed ref 9===========
# module: aioquic.buffer
class Buffer:
+ def push_uint32(self, v: int) -> None:
+ """
+ Push a 32-bit unsigned integer.
+ """
+ pack_into("!L", self._data, self._pos, v)
+ self._pos += 4
+
===========changed ref 10===========
# module: aioquic.buffer
class Buffer:
+ def push_uint16(self, v: int) -> None:
+ """
+ Push a 16-bit unsigned integer.
+ """
+ pack_into("!H", self._data, self._pos, v)
+ self._pos += 2
+
===========changed ref 11===========
# module: aioquic.buffer
- def push_uint64(buf: Buffer, v: int) -> None:
- """
- Push a 64-bit unsigned integer.
- """
- pack_into("!Q", buf._data, buf._pos, v)
- buf._pos += 8
-
===========changed ref 12===========
# module: aioquic.buffer
- def push_uint32(buf: Buffer, v: int) -> None:
- """
- Push a 32-bit unsigned integer.
- """
- pack_into("!L", buf._data, buf._pos, v)
- buf._pos += 4
-
===========changed ref 13===========
# module: aioquic.buffer
- def push_uint16(buf: Buffer, v: int) -> None:
- """
- Push a 16-bit unsigned integer.
- """
- pack_into("!H", buf._data, buf._pos, v)
- buf._pos += 2
-
===========changed ref 14===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint8(self) -> int:
+ """
+ Pull an 8-bit unsigned integer.
+ """
+ try:
+ v = self._data[self._pos]
+ self._pos += 1
+ return v
+ except IndexError:
+ raise BufferReadError
+
===========changed ref 15===========
# module: aioquic.buffer
class Buffer:
+ def push_bytes(self, v: bytes) -> None:
+ """
+ Push bytes.
+ """
+ end = self._pos + len(v)
+ if end > self._length:
+ raise BufferWriteError
+ self._data[self._pos : end] = v
+ self._pos = end
+
===========changed ref 16===========
# module: aioquic.buffer
- # INTEGERS
-
-
- def pull_uint8(buf: Buffer) -> int:
- """
- Pull an 8-bit unsigned integer.
- """
- try:
- v = buf._data[buf._pos]
- buf._pos += 1
- return v
- except IndexError:
- raise BufferReadError
-
===========changed ref 17===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint64(self) -> int:
+ """
+ Pull a 64-bit unsigned integer.
+ """
+ try:
+ v, = unpack_from("!Q", self._data, self._pos)
+ self._pos += 8
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 18===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint32(self) -> int:
+ """
+ Pull a 32-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!L", self._data, self._pos)
+ self._pos += 4
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 19===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint16(self) -> int:
+ """
+ Pull a 16-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!H", self._data, self._pos)
+ self._pos += 2
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 20===========
# module: aioquic.buffer
- # BYTES
-
-
- def pull_bytes(buf: Buffer, length: int) -> bytes:
- """
- Pull bytes.
- """
- if buf._pos + length > buf._length:
- raise BufferReadError
- v = buf._data[buf._pos : buf._pos + length]
- buf._pos += length
- return bytes(v)
-
===========changed ref 21===========
# module: aioquic.buffer
- def push_bytes(buf: Buffer, v: bytes) -> None:
- """
- Push bytes.
- """
- length = len(v)
- if buf._pos + length > buf._length:
- raise BufferWriteError
- buf._data[buf._pos : buf._pos + length] = v
- buf._pos += length
-
===========changed ref 22===========
# module: aioquic.buffer
- def pull_uint64(buf: Buffer) -> int:
- """
- Pull a 64-bit unsigned integer.
- """
- try:
- v, = unpack_from("!Q", buf._data, buf._pos)
- buf._pos += 8
- return v
- except struct.error:
- raise BufferReadError
-
|
aioquic.tls/pull_block
|
Modified
|
aiortc~aioquic
|
d2fcbad2c99436b01c87ee9dd23e1223e90fdd15
|
[buffer] make basic operations Buffer methods
|
<1>:<add> for b in buf.pull_bytes(capacity):
<del> for b in pull_bytes(buf, capacity):
<3>:<add> end = buf.tell() + length
<del> end = buf._pos + length
<5>:<add> assert buf.tell() == end
<del> assert buf._pos == end
|
# module: aioquic.tls
# BLOCKS
@contextmanager
def pull_block(buf: Buffer, capacity: int) -> Generator:
<0> length = 0
<1> for b in pull_bytes(buf, capacity):
<2> length = (length << 8) | b
<3> end = buf._pos + length
<4> yield length
<5> assert buf._pos == end
<6>
|
===========unchanged ref 0===========
at: aioquic.buffer.Buffer
seek(pos: int) -> None
tell() -> int
push_uint8(v: int) -> None
===========changed ref 0===========
# module: aioquic.buffer
class Buffer:
+ def push_uint8(self, v: int) -> None:
+ """
+ Push an 8-bit unsigned integer.
+ """
+ self._data[self._pos] = v
+ self._pos += 1
+
===========changed ref 1===========
# module: aioquic.tls
def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm:
+ return SignatureAlgorithm(buf.pull_uint16())
- return SignatureAlgorithm(pull_uint16(buf))
===========changed ref 2===========
# module: aioquic.tls
def pull_group(buf: Buffer) -> Group:
+ return Group(buf.pull_uint16())
- return Group(pull_uint16(buf))
===========changed ref 3===========
# module: aioquic.tls
def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:
+ return KeyExchangeMode(buf.pull_uint8())
- return KeyExchangeMode(pull_uint8(buf))
===========changed ref 4===========
# module: aioquic.tls
def pull_compression_method(buf: Buffer) -> CompressionMethod:
+ return CompressionMethod(buf.pull_uint8())
- return CompressionMethod(pull_uint8(buf))
===========changed ref 5===========
# module: aioquic.tls
# INTEGERS
def pull_cipher_suite(buf: Buffer) -> CipherSuite:
+ return CipherSuite(buf.pull_uint16())
- return CipherSuite(pull_uint16(buf))
===========changed ref 6===========
# module: aioquic.tls
- push_cipher_suite = push_uint16
- push_compression_method = push_uint8
- push_group = push_uint16
- push_key_exchange_mode = push_uint8
- push_signature_algorithm = push_uint16
-
===========changed ref 7===========
# module: aioquic.tls
TLS_VERSION_1_2 = 0x0303
TLS_VERSION_1_3 = 0x0304
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
TLS_VERSION_1_3_DRAFT_27 = 0x7F1B
TLS_VERSION_1_3_DRAFT_26 = 0x7F1A
T = TypeVar("T")
-
===========changed ref 8===========
# module: aioquic.buffer
- def push_uint8(buf: Buffer, v: int) -> None:
- """
- Push an 8-bit unsigned integer.
- """
- buf._data[buf._pos] = v
- buf._pos += 1
-
===========changed ref 9===========
# module: aioquic.buffer
class Buffer:
+ def push_uint64(self, v: int) -> None:
+ """
+ Push a 64-bit unsigned integer.
+ """
+ pack_into("!Q", self._data, self._pos, v)
+ self._pos += 8
+
===========changed ref 10===========
# module: aioquic.buffer
class Buffer:
+ def push_uint32(self, v: int) -> None:
+ """
+ Push a 32-bit unsigned integer.
+ """
+ pack_into("!L", self._data, self._pos, v)
+ self._pos += 4
+
===========changed ref 11===========
# module: aioquic.buffer
class Buffer:
+ def push_uint16(self, v: int) -> None:
+ """
+ Push a 16-bit unsigned integer.
+ """
+ pack_into("!H", self._data, self._pos, v)
+ self._pos += 2
+
===========changed ref 12===========
# module: aioquic.buffer
- def push_uint64(buf: Buffer, v: int) -> None:
- """
- Push a 64-bit unsigned integer.
- """
- pack_into("!Q", buf._data, buf._pos, v)
- buf._pos += 8
-
===========changed ref 13===========
# module: aioquic.buffer
- def push_uint32(buf: Buffer, v: int) -> None:
- """
- Push a 32-bit unsigned integer.
- """
- pack_into("!L", buf._data, buf._pos, v)
- buf._pos += 4
-
===========changed ref 14===========
# module: aioquic.buffer
- def push_uint16(buf: Buffer, v: int) -> None:
- """
- Push a 16-bit unsigned integer.
- """
- pack_into("!H", buf._data, buf._pos, v)
- buf._pos += 2
-
===========changed ref 15===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint8(self) -> int:
+ """
+ Pull an 8-bit unsigned integer.
+ """
+ try:
+ v = self._data[self._pos]
+ self._pos += 1
+ return v
+ except IndexError:
+ raise BufferReadError
+
===========changed ref 16===========
# module: aioquic.buffer
class Buffer:
+ def push_bytes(self, v: bytes) -> None:
+ """
+ Push bytes.
+ """
+ end = self._pos + len(v)
+ if end > self._length:
+ raise BufferWriteError
+ self._data[self._pos : end] = v
+ self._pos = end
+
===========changed ref 17===========
# module: aioquic.buffer
class Buffer:
+ def pull_bytes(self, length: int) -> bytes:
+ """
+ Pull bytes.
+ """
+ end = self._pos + length
+ if end > self._length:
+ raise BufferReadError
+ v = bytes(self._data[self._pos : end])
+ self._pos = end
+ return v
+
===========changed ref 18===========
# module: aioquic.buffer
- # INTEGERS
-
-
- def pull_uint8(buf: Buffer) -> int:
- """
- Pull an 8-bit unsigned integer.
- """
- try:
- v = buf._data[buf._pos]
- buf._pos += 1
- return v
- except IndexError:
- raise BufferReadError
-
===========changed ref 19===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint64(self) -> int:
+ """
+ Pull a 64-bit unsigned integer.
+ """
+ try:
+ v, = unpack_from("!Q", self._data, self._pos)
+ self._pos += 8
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 20===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint32(self) -> int:
+ """
+ Pull a 32-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!L", self._data, self._pos)
+ self._pos += 4
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 21===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint16(self) -> int:
+ """
+ Pull a 16-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!H", self._data, self._pos)
+ self._pos += 2
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 22===========
# module: aioquic.buffer
- # BYTES
-
-
- def pull_bytes(buf: Buffer, length: int) -> bytes:
- """
- Pull bytes.
- """
- if buf._pos + length > buf._length:
- raise BufferReadError
- v = buf._data[buf._pos : buf._pos + length]
- buf._pos += length
- return bytes(v)
-
===========changed ref 23===========
# module: aioquic.buffer
- def push_bytes(buf: Buffer, v: bytes) -> None:
- """
- Push bytes.
- """
- length = len(v)
- if buf._pos + length > buf._length:
- raise BufferWriteError
- buf._data[buf._pos : buf._pos + length] = v
- buf._pos += length
-
|
aioquic.tls/push_block
|
Modified
|
aiortc~aioquic
|
d2fcbad2c99436b01c87ee9dd23e1223e90fdd15
|
[buffer] make basic operations Buffer methods
|
<4>:<add> start = buf.tell() + capacity
<add> buf.seek(start)
<del> buf._pos += capacity
<5>:<del> start = buf._pos
<7>:<add> end = buf.tell()
<add> length = end - start
<del> length = buf._pos - start
<9>:<add> buf.seek(start - capacity)
<add> buf.push_uint8((length >> (8 * (capacity - 1))) & 0xFF)
<del> buf._data[start - capacity] = (length >> (8 * (capacity - 1))) & 0xFF
<11>:<add> buf.seek(end)
|
# module: aioquic.tls
@contextmanager
def push_block(buf: Buffer, capacity: int) -> Generator:
<0> """
<1> Context manager to push a variable-length block, with `capacity` bytes
<2> to write the length.
<3> """
<4> buf._pos += capacity
<5> start = buf._pos
<6> yield
<7> length = buf._pos - start
<8> while capacity:
<9> buf._data[start - capacity] = (length >> (8 * (capacity - 1))) & 0xFF
<10> capacity -= 1
<11>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.buffer.Buffer
tell() -> int
at: aioquic.tls
T = TypeVar("T")
pull_block(buf: Buffer, capacity: int) -> Generator
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: aioquic.tls
# BLOCKS
@contextmanager
def pull_block(buf: Buffer, capacity: int) -> Generator:
length = 0
+ for b in buf.pull_bytes(capacity):
- for b in pull_bytes(buf, capacity):
length = (length << 8) | b
+ end = buf.tell() + length
- end = buf._pos + length
yield length
+ assert buf.tell() == end
- assert buf._pos == end
===========changed ref 1===========
# module: aioquic.tls
def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm:
+ return SignatureAlgorithm(buf.pull_uint16())
- return SignatureAlgorithm(pull_uint16(buf))
===========changed ref 2===========
# module: aioquic.tls
def pull_group(buf: Buffer) -> Group:
+ return Group(buf.pull_uint16())
- return Group(pull_uint16(buf))
===========changed ref 3===========
# module: aioquic.tls
def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:
+ return KeyExchangeMode(buf.pull_uint8())
- return KeyExchangeMode(pull_uint8(buf))
===========changed ref 4===========
# module: aioquic.tls
def pull_compression_method(buf: Buffer) -> CompressionMethod:
+ return CompressionMethod(buf.pull_uint8())
- return CompressionMethod(pull_uint8(buf))
===========changed ref 5===========
# module: aioquic.tls
# INTEGERS
def pull_cipher_suite(buf: Buffer) -> CipherSuite:
+ return CipherSuite(buf.pull_uint16())
- return CipherSuite(pull_uint16(buf))
===========changed ref 6===========
# module: aioquic.tls
- push_cipher_suite = push_uint16
- push_compression_method = push_uint8
- push_group = push_uint16
- push_key_exchange_mode = push_uint8
- push_signature_algorithm = push_uint16
-
===========changed ref 7===========
# module: aioquic.tls
TLS_VERSION_1_2 = 0x0303
TLS_VERSION_1_3 = 0x0304
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
TLS_VERSION_1_3_DRAFT_27 = 0x7F1B
TLS_VERSION_1_3_DRAFT_26 = 0x7F1A
T = TypeVar("T")
-
===========changed ref 8===========
# module: aioquic.buffer
class Buffer:
+ def push_uint8(self, v: int) -> None:
+ """
+ Push an 8-bit unsigned integer.
+ """
+ self._data[self._pos] = v
+ self._pos += 1
+
===========changed ref 9===========
# module: aioquic.buffer
- def push_uint8(buf: Buffer, v: int) -> None:
- """
- Push an 8-bit unsigned integer.
- """
- buf._data[buf._pos] = v
- buf._pos += 1
-
===========changed ref 10===========
# module: aioquic.buffer
class Buffer:
+ def push_uint64(self, v: int) -> None:
+ """
+ Push a 64-bit unsigned integer.
+ """
+ pack_into("!Q", self._data, self._pos, v)
+ self._pos += 8
+
===========changed ref 11===========
# module: aioquic.buffer
class Buffer:
+ def push_uint32(self, v: int) -> None:
+ """
+ Push a 32-bit unsigned integer.
+ """
+ pack_into("!L", self._data, self._pos, v)
+ self._pos += 4
+
===========changed ref 12===========
# module: aioquic.buffer
class Buffer:
+ def push_uint16(self, v: int) -> None:
+ """
+ Push a 16-bit unsigned integer.
+ """
+ pack_into("!H", self._data, self._pos, v)
+ self._pos += 2
+
===========changed ref 13===========
# module: aioquic.buffer
- def push_uint64(buf: Buffer, v: int) -> None:
- """
- Push a 64-bit unsigned integer.
- """
- pack_into("!Q", buf._data, buf._pos, v)
- buf._pos += 8
-
===========changed ref 14===========
# module: aioquic.buffer
- def push_uint32(buf: Buffer, v: int) -> None:
- """
- Push a 32-bit unsigned integer.
- """
- pack_into("!L", buf._data, buf._pos, v)
- buf._pos += 4
-
===========changed ref 15===========
# module: aioquic.buffer
- def push_uint16(buf: Buffer, v: int) -> None:
- """
- Push a 16-bit unsigned integer.
- """
- pack_into("!H", buf._data, buf._pos, v)
- buf._pos += 2
-
===========changed ref 16===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint8(self) -> int:
+ """
+ Pull an 8-bit unsigned integer.
+ """
+ try:
+ v = self._data[self._pos]
+ self._pos += 1
+ return v
+ except IndexError:
+ raise BufferReadError
+
===========changed ref 17===========
# module: aioquic.buffer
class Buffer:
+ def push_bytes(self, v: bytes) -> None:
+ """
+ Push bytes.
+ """
+ end = self._pos + len(v)
+ if end > self._length:
+ raise BufferWriteError
+ self._data[self._pos : end] = v
+ self._pos = end
+
===========changed ref 18===========
# module: aioquic.buffer
class Buffer:
+ def pull_bytes(self, length: int) -> bytes:
+ """
+ Pull bytes.
+ """
+ end = self._pos + length
+ if end > self._length:
+ raise BufferReadError
+ v = bytes(self._data[self._pos : end])
+ self._pos = end
+ return v
+
===========changed ref 19===========
# module: aioquic.buffer
- # INTEGERS
-
-
- def pull_uint8(buf: Buffer) -> int:
- """
- Pull an 8-bit unsigned integer.
- """
- try:
- v = buf._data[buf._pos]
- buf._pos += 1
- return v
- except IndexError:
- raise BufferReadError
-
===========changed ref 20===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint64(self) -> int:
+ """
+ Pull a 64-bit unsigned integer.
+ """
+ try:
+ v, = unpack_from("!Q", self._data, self._pos)
+ self._pos += 8
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 21===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint32(self) -> int:
+ """
+ Pull a 32-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!L", self._data, self._pos)
+ self._pos += 4
+ return v
+ except struct.error:
+ raise BufferReadError
+
===========changed ref 22===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint16(self) -> int:
+ """
+ Pull a 16-bit unsigned integer.
+ """
+ try:
+ v, = struct.unpack_from("!H", self._data, self._pos)
+ self._pos += 2
+ return v
+ except struct.error:
+ raise BufferReadError
+
|
aioquic.tls/pull_list
|
Modified
|
aiortc~aioquic
|
d2fcbad2c99436b01c87ee9dd23e1223e90fdd15
|
[buffer] make basic operations Buffer methods
|
<5>:<add> end = buf.tell() + length
<del> end = buf._pos + length
<6>:<add> while buf.tell() < end:
<del> while buf._pos < end:
<7>:<add> items.append(func())
<del> items.append(func(buf))
|
# module: aioquic.tls
# LISTS
+ def pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]:
- def pull_list(buf: Buffer, capacity: int, func: Callable[[Buffer], T]) -> List[T]:
<0> """
<1> Pull a list of items.
<2> """
<3> items = []
<4> with pull_block(buf, capacity) as length:
<5> end = buf._pos + length
<6> while buf._pos < end:
<7> items.append(func(buf))
<8> return items
<9>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.tls
T = TypeVar("T")
push_block(buf: Buffer, capacity: int) -> Generator
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
Sequence = _alias(collections.abc.Sequence, 1)
===========changed ref 0===========
# module: aioquic.tls
@contextmanager
def push_block(buf: Buffer, capacity: int) -> Generator:
"""
Context manager to push a variable-length block, with `capacity` bytes
to write the length.
"""
+ start = buf.tell() + capacity
+ buf.seek(start)
- buf._pos += capacity
- start = buf._pos
yield
+ end = buf.tell()
+ length = end - start
- length = buf._pos - start
while capacity:
+ buf.seek(start - capacity)
+ buf.push_uint8((length >> (8 * (capacity - 1))) & 0xFF)
- buf._data[start - capacity] = (length >> (8 * (capacity - 1))) & 0xFF
capacity -= 1
+ buf.seek(end)
===========changed ref 1===========
# module: aioquic.tls
def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm:
+ return SignatureAlgorithm(buf.pull_uint16())
- return SignatureAlgorithm(pull_uint16(buf))
===========changed ref 2===========
# module: aioquic.tls
def pull_group(buf: Buffer) -> Group:
+ return Group(buf.pull_uint16())
- return Group(pull_uint16(buf))
===========changed ref 3===========
# module: aioquic.tls
def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:
+ return KeyExchangeMode(buf.pull_uint8())
- return KeyExchangeMode(pull_uint8(buf))
===========changed ref 4===========
# module: aioquic.tls
def pull_compression_method(buf: Buffer) -> CompressionMethod:
+ return CompressionMethod(buf.pull_uint8())
- return CompressionMethod(pull_uint8(buf))
===========changed ref 5===========
# module: aioquic.tls
# INTEGERS
def pull_cipher_suite(buf: Buffer) -> CipherSuite:
+ return CipherSuite(buf.pull_uint16())
- return CipherSuite(pull_uint16(buf))
===========changed ref 6===========
# module: aioquic.tls
- push_cipher_suite = push_uint16
- push_compression_method = push_uint8
- push_group = push_uint16
- push_key_exchange_mode = push_uint8
- push_signature_algorithm = push_uint16
-
===========changed ref 7===========
# module: aioquic.tls
# BLOCKS
@contextmanager
def pull_block(buf: Buffer, capacity: int) -> Generator:
length = 0
+ for b in buf.pull_bytes(capacity):
- for b in pull_bytes(buf, capacity):
length = (length << 8) | b
+ end = buf.tell() + length
- end = buf._pos + length
yield length
+ assert buf.tell() == end
- assert buf._pos == end
===========changed ref 8===========
# module: aioquic.tls
TLS_VERSION_1_2 = 0x0303
TLS_VERSION_1_3 = 0x0304
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
TLS_VERSION_1_3_DRAFT_27 = 0x7F1B
TLS_VERSION_1_3_DRAFT_26 = 0x7F1A
T = TypeVar("T")
-
===========changed ref 9===========
# module: aioquic.buffer
class Buffer:
+ def push_uint8(self, v: int) -> None:
+ """
+ Push an 8-bit unsigned integer.
+ """
+ self._data[self._pos] = v
+ self._pos += 1
+
===========changed ref 10===========
# module: aioquic.buffer
- def push_uint8(buf: Buffer, v: int) -> None:
- """
- Push an 8-bit unsigned integer.
- """
- buf._data[buf._pos] = v
- buf._pos += 1
-
===========changed ref 11===========
# module: aioquic.buffer
class Buffer:
+ def push_uint64(self, v: int) -> None:
+ """
+ Push a 64-bit unsigned integer.
+ """
+ pack_into("!Q", self._data, self._pos, v)
+ self._pos += 8
+
===========changed ref 12===========
# module: aioquic.buffer
class Buffer:
+ def push_uint32(self, v: int) -> None:
+ """
+ Push a 32-bit unsigned integer.
+ """
+ pack_into("!L", self._data, self._pos, v)
+ self._pos += 4
+
===========changed ref 13===========
# module: aioquic.buffer
class Buffer:
+ def push_uint16(self, v: int) -> None:
+ """
+ Push a 16-bit unsigned integer.
+ """
+ pack_into("!H", self._data, self._pos, v)
+ self._pos += 2
+
===========changed ref 14===========
# module: aioquic.buffer
- def push_uint64(buf: Buffer, v: int) -> None:
- """
- Push a 64-bit unsigned integer.
- """
- pack_into("!Q", buf._data, buf._pos, v)
- buf._pos += 8
-
===========changed ref 15===========
# module: aioquic.buffer
- def push_uint32(buf: Buffer, v: int) -> None:
- """
- Push a 32-bit unsigned integer.
- """
- pack_into("!L", buf._data, buf._pos, v)
- buf._pos += 4
-
===========changed ref 16===========
# module: aioquic.buffer
- def push_uint16(buf: Buffer, v: int) -> None:
- """
- Push a 16-bit unsigned integer.
- """
- pack_into("!H", buf._data, buf._pos, v)
- buf._pos += 2
-
===========changed ref 17===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint8(self) -> int:
+ """
+ Pull an 8-bit unsigned integer.
+ """
+ try:
+ v = self._data[self._pos]
+ self._pos += 1
+ return v
+ except IndexError:
+ raise BufferReadError
+
===========changed ref 18===========
# module: aioquic.buffer
class Buffer:
+ def push_bytes(self, v: bytes) -> None:
+ """
+ Push bytes.
+ """
+ end = self._pos + len(v)
+ if end > self._length:
+ raise BufferWriteError
+ self._data[self._pos : end] = v
+ self._pos = end
+
===========changed ref 19===========
# module: aioquic.buffer
class Buffer:
+ def pull_bytes(self, length: int) -> bytes:
+ """
+ Pull bytes.
+ """
+ end = self._pos + length
+ if end > self._length:
+ raise BufferReadError
+ v = bytes(self._data[self._pos : end])
+ self._pos = end
+ return v
+
===========changed ref 20===========
# module: aioquic.buffer
- # INTEGERS
-
-
- def pull_uint8(buf: Buffer) -> int:
- """
- Pull an 8-bit unsigned integer.
- """
- try:
- v = buf._data[buf._pos]
- buf._pos += 1
- return v
- except IndexError:
- raise BufferReadError
-
===========changed ref 21===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint64(self) -> int:
+ """
+ Pull a 64-bit unsigned integer.
+ """
+ try:
+ v, = unpack_from("!Q", self._data, self._pos)
+ self._pos += 8
+ return v
+ except struct.error:
+ raise BufferReadError
+
|
aioquic.tls/push_list
|
Modified
|
aiortc~aioquic
|
d2fcbad2c99436b01c87ee9dd23e1223e90fdd15
|
[buffer] make basic operations Buffer methods
|
<5>:<add> func(value)
<del> func(buf, value)
|
# module: aioquic.tls
def push_list(
+ buf: Buffer, capacity: int, func: Callable[[T], None], values: Sequence[T]
- buf: Buffer, capacity: int, func: Callable[[Buffer, T], None], values: Sequence[T]
) -> None:
<0> """
<1> Push a list of items.
<2> """
<3> with push_block(buf, capacity):
<4> for value in values:
<5> func(buf, value)
<6>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.buffer.Buffer
pull_bytes(length: int) -> bytes
at: aioquic.tls
pull_block(buf: Buffer, capacity: int) -> Generator
===========changed ref 0===========
# module: aioquic.tls
# BLOCKS
@contextmanager
def pull_block(buf: Buffer, capacity: int) -> Generator:
length = 0
+ for b in buf.pull_bytes(capacity):
- for b in pull_bytes(buf, capacity):
length = (length << 8) | b
+ end = buf.tell() + length
- end = buf._pos + length
yield length
+ assert buf.tell() == end
- assert buf._pos == end
===========changed ref 1===========
# module: aioquic.buffer
class Buffer:
+ def pull_bytes(self, length: int) -> bytes:
+ """
+ Pull bytes.
+ """
+ end = self._pos + length
+ if end > self._length:
+ raise BufferReadError
+ v = bytes(self._data[self._pos : end])
+ self._pos = end
+ return v
+
===========changed ref 2===========
# module: aioquic.tls
def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm:
+ return SignatureAlgorithm(buf.pull_uint16())
- return SignatureAlgorithm(pull_uint16(buf))
===========changed ref 3===========
# module: aioquic.tls
def pull_group(buf: Buffer) -> Group:
+ return Group(buf.pull_uint16())
- return Group(pull_uint16(buf))
===========changed ref 4===========
# module: aioquic.tls
def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:
+ return KeyExchangeMode(buf.pull_uint8())
- return KeyExchangeMode(pull_uint8(buf))
===========changed ref 5===========
# module: aioquic.tls
def pull_compression_method(buf: Buffer) -> CompressionMethod:
+ return CompressionMethod(buf.pull_uint8())
- return CompressionMethod(pull_uint8(buf))
===========changed ref 6===========
# module: aioquic.tls
# INTEGERS
def pull_cipher_suite(buf: Buffer) -> CipherSuite:
+ return CipherSuite(buf.pull_uint16())
- return CipherSuite(pull_uint16(buf))
===========changed ref 7===========
# module: aioquic.tls
# LISTS
+ def pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]:
- def pull_list(buf: Buffer, capacity: int, func: Callable[[Buffer], T]) -> List[T]:
"""
Pull a list of items.
"""
items = []
with pull_block(buf, capacity) as length:
+ end = buf.tell() + length
- end = buf._pos + length
+ while buf.tell() < end:
- while buf._pos < end:
+ items.append(func())
- items.append(func(buf))
return items
===========changed ref 8===========
# module: aioquic.tls
- push_cipher_suite = push_uint16
- push_compression_method = push_uint8
- push_group = push_uint16
- push_key_exchange_mode = push_uint8
- push_signature_algorithm = push_uint16
-
===========changed ref 9===========
# module: aioquic.tls
@contextmanager
def push_block(buf: Buffer, capacity: int) -> Generator:
"""
Context manager to push a variable-length block, with `capacity` bytes
to write the length.
"""
+ start = buf.tell() + capacity
+ buf.seek(start)
- buf._pos += capacity
- start = buf._pos
yield
+ end = buf.tell()
+ length = end - start
- length = buf._pos - start
while capacity:
+ buf.seek(start - capacity)
+ buf.push_uint8((length >> (8 * (capacity - 1))) & 0xFF)
- buf._data[start - capacity] = (length >> (8 * (capacity - 1))) & 0xFF
capacity -= 1
+ buf.seek(end)
===========changed ref 10===========
# module: aioquic.tls
TLS_VERSION_1_2 = 0x0303
TLS_VERSION_1_3 = 0x0304
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
TLS_VERSION_1_3_DRAFT_27 = 0x7F1B
TLS_VERSION_1_3_DRAFT_26 = 0x7F1A
T = TypeVar("T")
-
===========changed ref 11===========
# module: aioquic.buffer
class Buffer:
+ def push_uint8(self, v: int) -> None:
+ """
+ Push an 8-bit unsigned integer.
+ """
+ self._data[self._pos] = v
+ self._pos += 1
+
===========changed ref 12===========
# module: aioquic.buffer
- def push_uint8(buf: Buffer, v: int) -> None:
- """
- Push an 8-bit unsigned integer.
- """
- buf._data[buf._pos] = v
- buf._pos += 1
-
===========changed ref 13===========
# module: aioquic.buffer
class Buffer:
+ def push_uint64(self, v: int) -> None:
+ """
+ Push a 64-bit unsigned integer.
+ """
+ pack_into("!Q", self._data, self._pos, v)
+ self._pos += 8
+
===========changed ref 14===========
# module: aioquic.buffer
class Buffer:
+ def push_uint32(self, v: int) -> None:
+ """
+ Push a 32-bit unsigned integer.
+ """
+ pack_into("!L", self._data, self._pos, v)
+ self._pos += 4
+
===========changed ref 15===========
# module: aioquic.buffer
class Buffer:
+ def push_uint16(self, v: int) -> None:
+ """
+ Push a 16-bit unsigned integer.
+ """
+ pack_into("!H", self._data, self._pos, v)
+ self._pos += 2
+
===========changed ref 16===========
# module: aioquic.buffer
- def push_uint64(buf: Buffer, v: int) -> None:
- """
- Push a 64-bit unsigned integer.
- """
- pack_into("!Q", buf._data, buf._pos, v)
- buf._pos += 8
-
===========changed ref 17===========
# module: aioquic.buffer
- def push_uint32(buf: Buffer, v: int) -> None:
- """
- Push a 32-bit unsigned integer.
- """
- pack_into("!L", buf._data, buf._pos, v)
- buf._pos += 4
-
===========changed ref 18===========
# module: aioquic.buffer
- def push_uint16(buf: Buffer, v: int) -> None:
- """
- Push a 16-bit unsigned integer.
- """
- pack_into("!H", buf._data, buf._pos, v)
- buf._pos += 2
-
===========changed ref 19===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint8(self) -> int:
+ """
+ Pull an 8-bit unsigned integer.
+ """
+ try:
+ v = self._data[self._pos]
+ self._pos += 1
+ return v
+ except IndexError:
+ raise BufferReadError
+
===========changed ref 20===========
# module: aioquic.buffer
class Buffer:
+ def push_bytes(self, v: bytes) -> None:
+ """
+ Push bytes.
+ """
+ end = self._pos + len(v)
+ if end > self._length:
+ raise BufferWriteError
+ self._data[self._pos : end] = v
+ self._pos = end
+
|
aioquic.tls/pull_opaque
|
Modified
|
aiortc~aioquic
|
d2fcbad2c99436b01c87ee9dd23e1223e90fdd15
|
[buffer] make basic operations Buffer methods
|
<4>:<add> return buf.pull_bytes(length)
<del> return pull_bytes(buf, length)
|
# module: aioquic.tls
def pull_opaque(buf: Buffer, capacity: int) -> bytes:
<0> """
<1> Pull an opaque value prefixed by a length.
<2> """
<3> with pull_block(buf, capacity) as length:
<4> return pull_bytes(buf, length)
<5>
|
===========unchanged ref 0===========
at: aioquic.buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.buffer.Buffer
push_bytes(v: bytes) -> None
push_uint16(v: int) -> None
at: contextlib
contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., _GeneratorContextManager[_T]]
at: typing
Generator = _alias(collections.abc.Generator, 3)
===========changed ref 0===========
# module: aioquic.buffer
class Buffer:
+ def push_uint16(self, v: int) -> None:
+ """
+ Push a 16-bit unsigned integer.
+ """
+ pack_into("!H", self._data, self._pos, v)
+ self._pos += 2
+
===========changed ref 1===========
# module: aioquic.buffer
class Buffer:
+ def push_bytes(self, v: bytes) -> None:
+ """
+ Push bytes.
+ """
+ end = self._pos + len(v)
+ if end > self._length:
+ raise BufferWriteError
+ self._data[self._pos : end] = v
+ self._pos = end
+
===========changed ref 2===========
# module: aioquic.tls
def push_list(
+ buf: Buffer, capacity: int, func: Callable[[T], None], values: Sequence[T]
- buf: Buffer, capacity: int, func: Callable[[Buffer, T], None], values: Sequence[T]
) -> None:
"""
Push a list of items.
"""
with push_block(buf, capacity):
for value in values:
+ func(value)
- func(buf, value)
===========changed ref 3===========
# module: aioquic.tls
def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm:
+ return SignatureAlgorithm(buf.pull_uint16())
- return SignatureAlgorithm(pull_uint16(buf))
===========changed ref 4===========
# module: aioquic.tls
def pull_group(buf: Buffer) -> Group:
+ return Group(buf.pull_uint16())
- return Group(pull_uint16(buf))
===========changed ref 5===========
# module: aioquic.tls
def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:
+ return KeyExchangeMode(buf.pull_uint8())
- return KeyExchangeMode(pull_uint8(buf))
===========changed ref 6===========
# module: aioquic.tls
def pull_compression_method(buf: Buffer) -> CompressionMethod:
+ return CompressionMethod(buf.pull_uint8())
- return CompressionMethod(pull_uint8(buf))
===========changed ref 7===========
# module: aioquic.tls
# INTEGERS
def pull_cipher_suite(buf: Buffer) -> CipherSuite:
+ return CipherSuite(buf.pull_uint16())
- return CipherSuite(pull_uint16(buf))
===========changed ref 8===========
# module: aioquic.tls
# LISTS
+ def pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]:
- def pull_list(buf: Buffer, capacity: int, func: Callable[[Buffer], T]) -> List[T]:
"""
Pull a list of items.
"""
items = []
with pull_block(buf, capacity) as length:
+ end = buf.tell() + length
- end = buf._pos + length
+ while buf.tell() < end:
- while buf._pos < end:
+ items.append(func())
- items.append(func(buf))
return items
===========changed ref 9===========
# module: aioquic.tls
- push_cipher_suite = push_uint16
- push_compression_method = push_uint8
- push_group = push_uint16
- push_key_exchange_mode = push_uint8
- push_signature_algorithm = push_uint16
-
===========changed ref 10===========
# module: aioquic.tls
# BLOCKS
@contextmanager
def pull_block(buf: Buffer, capacity: int) -> Generator:
length = 0
+ for b in buf.pull_bytes(capacity):
- for b in pull_bytes(buf, capacity):
length = (length << 8) | b
+ end = buf.tell() + length
- end = buf._pos + length
yield length
+ assert buf.tell() == end
- assert buf._pos == end
===========changed ref 11===========
# module: aioquic.tls
@contextmanager
def push_block(buf: Buffer, capacity: int) -> Generator:
"""
Context manager to push a variable-length block, with `capacity` bytes
to write the length.
"""
+ start = buf.tell() + capacity
+ buf.seek(start)
- buf._pos += capacity
- start = buf._pos
yield
+ end = buf.tell()
+ length = end - start
- length = buf._pos - start
while capacity:
+ buf.seek(start - capacity)
+ buf.push_uint8((length >> (8 * (capacity - 1))) & 0xFF)
- buf._data[start - capacity] = (length >> (8 * (capacity - 1))) & 0xFF
capacity -= 1
+ buf.seek(end)
===========changed ref 12===========
# module: aioquic.tls
TLS_VERSION_1_2 = 0x0303
TLS_VERSION_1_3 = 0x0304
TLS_VERSION_1_3_DRAFT_28 = 0x7F1C
TLS_VERSION_1_3_DRAFT_27 = 0x7F1B
TLS_VERSION_1_3_DRAFT_26 = 0x7F1A
T = TypeVar("T")
-
===========changed ref 13===========
# module: aioquic.buffer
class Buffer:
+ def push_uint8(self, v: int) -> None:
+ """
+ Push an 8-bit unsigned integer.
+ """
+ self._data[self._pos] = v
+ self._pos += 1
+
===========changed ref 14===========
# module: aioquic.buffer
- def push_uint8(buf: Buffer, v: int) -> None:
- """
- Push an 8-bit unsigned integer.
- """
- buf._data[buf._pos] = v
- buf._pos += 1
-
===========changed ref 15===========
# module: aioquic.buffer
class Buffer:
+ def push_uint64(self, v: int) -> None:
+ """
+ Push a 64-bit unsigned integer.
+ """
+ pack_into("!Q", self._data, self._pos, v)
+ self._pos += 8
+
===========changed ref 16===========
# module: aioquic.buffer
class Buffer:
+ def push_uint32(self, v: int) -> None:
+ """
+ Push a 32-bit unsigned integer.
+ """
+ pack_into("!L", self._data, self._pos, v)
+ self._pos += 4
+
===========changed ref 17===========
# module: aioquic.buffer
- def push_uint64(buf: Buffer, v: int) -> None:
- """
- Push a 64-bit unsigned integer.
- """
- pack_into("!Q", buf._data, buf._pos, v)
- buf._pos += 8
-
===========changed ref 18===========
# module: aioquic.buffer
- def push_uint32(buf: Buffer, v: int) -> None:
- """
- Push a 32-bit unsigned integer.
- """
- pack_into("!L", buf._data, buf._pos, v)
- buf._pos += 4
-
===========changed ref 19===========
# module: aioquic.buffer
- def push_uint16(buf: Buffer, v: int) -> None:
- """
- Push a 16-bit unsigned integer.
- """
- pack_into("!H", buf._data, buf._pos, v)
- buf._pos += 2
-
===========changed ref 20===========
# module: aioquic.buffer
class Buffer:
+ def pull_uint8(self) -> int:
+ """
+ Pull an 8-bit unsigned integer.
+ """
+ try:
+ v = self._data[self._pos]
+ self._pos += 1
+ return v
+ except IndexError:
+ raise BufferReadError
+
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.