Skip to main content

eq_network_transport/
modern.rs

1use anyhow::{bail, ensure, Result};
2use std::{
3    cell::Cell,
4    collections::{HashMap, VecDeque},
5    io,
6    net::{SocketAddr, UdpSocket},
7    sync::atomic::{AtomicBool, Ordering},
8    time::{Duration, Instant},
9};
10
11const MAX_APPLICATION: usize = 16 * 1024 * 1024;
12const WINDOW: u16 = 2048;
13
14/// A fully reassembled application packet from an EQ UDP session.
15#[derive(Debug)]
16pub struct Application {
17    /// Raw little-endian application opcode.
18    pub opcode: u16,
19    /// Reassembled application body without its opcode.
20    pub body: Vec<u8>,
21}
22
23struct Pending {
24    sequence: u16,
25    packet: Vec<u8>,
26    sent: Instant,
27    attempts: u8,
28}
29
30/// One independent, reliable EQ UDP session. Sequence numbers and CRC state
31/// belong to this socket and are discarded on world/zone transitions.
32pub struct Session {
33    socket: UdpSocket,
34    id: u32,
35    crc_seed: u32,
36    crc_bytes: usize,
37    compression: bool,
38    max_datagram: usize,
39    next_send: u16,
40    next_receive: u16,
41    ack_pending: bool,
42    last_ack: Instant,
43    reorder: HashMap<u16, (u16, Vec<u8>)>,
44    pending: VecDeque<Pending>,
45    fragment: Option<(usize, Vec<u8>)>,
46    applications: VecDeque<Application>,
47    last_receive: Instant,
48    started: Instant,
49    next_stats: Instant,
50    stats_request: Option<(u16, Instant)>,
51    rtt: u32,
52    rtt_min: u32,
53    rtt_max: u32,
54    rtt_sum: u64,
55    rtt_count: u64,
56    sent_count: Cell<u64>,
57    received_count: u64,
58    closed: bool,
59}
60
61impl Session {
62    /// Return the local UDP address selected for this session.
63    ///
64    /// # Errors
65    ///
66    /// Returns an error when the operating system cannot read the socket address.
67    pub fn local_address(&self) -> Result<SocketAddr> {
68        Ok(self.socket.local_addr()?)
69    }
70    /// Return whole seconds since the last valid server datagram.
71    pub fn last_received_seconds(&self) -> u64 {
72        self.last_receive.elapsed().as_secs()
73    }
74    /// Negotiate a new reliable EQ UDP session with the remote endpoint.
75    ///
76    /// # Errors
77    ///
78    /// Returns an error when socket setup, negotiation, or validation fails.
79    pub fn connect(address: SocketAddr, echo_response: bool) -> Result<Self> {
80        Self::connect_cancellable(address, echo_response, &AtomicBool::new(false))
81    }
82
83    /// Negotiate a session while allowing its owner to cancel network waits.
84    ///
85    /// # Errors
86    ///
87    /// Returns an error on cancellation, timeout, socket failure, or an
88    /// unsupported negotiation response.
89    pub fn connect_cancellable(
90        address: SocketAddr,
91        echo_response: bool,
92        stop: &AtomicBool,
93    ) -> Result<Self> {
94        ensure!(!stop.load(Ordering::Relaxed), "shutdown requested");
95        let socket = UdpSocket::bind(if address.is_ipv4() {
96            "0.0.0.0:0"
97        } else {
98            "[::]:0"
99        })?;
100        socket.connect(address)?;
101        socket.set_read_timeout(Some(Duration::from_millis(50)))?;
102        let id = rand::random::<u32>();
103        let mut request = vec![0, 1];
104        request.extend_from_slice(&2u32.to_be_bytes());
105        request.extend_from_slice(&id.to_be_bytes());
106        request.extend_from_slice(&512u32.to_be_bytes());
107        let mut buffer = vec![0; 65536];
108        let deadline = Instant::now() + Duration::from_secs(15);
109        let mut last_send: Option<Instant> = None;
110        loop {
111            ensure!(!stop.load(Ordering::Relaxed), "shutdown requested");
112            ensure!(
113                Instant::now() < deadline,
114                "UDP session negotiation timed out"
115            );
116            if last_send.is_none_or(|sent| sent.elapsed() >= Duration::from_secs(1)) {
117                socket.send(&request)?;
118                last_send = Some(Instant::now());
119            }
120            let n = match socket.recv(&mut buffer) {
121                Ok(n) => n,
122                Err(e) if timed_out(&e) => continue,
123                Err(e) => return Err(e.into()),
124            };
125            if n < 17 || buffer[..2] != [0, 2] || be32(&buffer[2..6]) != id {
126                continue;
127            }
128            let crc_bytes = buffer[10] as usize;
129            ensure!(crc_bytes <= 4, "unsupported CRC size");
130            ensure!(
131                buffer[11] <= 1 && buffer[12] == 0,
132                "unsupported UDP encoding negotiation"
133            );
134            let max_datagram = be32(&buffer[13..17]) as usize;
135            ensure!(
136                (64..=65507).contains(&max_datagram),
137                "invalid negotiated datagram size"
138            );
139            if echo_response {
140                socket.send(&buffer[..n])?;
141            }
142            return Ok(Self {
143                socket,
144                id,
145                crc_seed: be32(&buffer[6..10]),
146                crc_bytes,
147                compression: buffer[11] == 1,
148                max_datagram,
149                next_send: 0,
150                next_receive: 0,
151                ack_pending: false,
152                last_ack: Instant::now(),
153                reorder: HashMap::new(),
154                pending: VecDeque::new(),
155                fragment: None,
156                applications: VecDeque::new(),
157                last_receive: Instant::now(),
158                started: Instant::now(),
159                next_stats: Instant::now() + Duration::from_secs(10),
160                stats_request: None,
161                rtt: 0,
162                rtt_min: 0,
163                rtt_max: 0,
164                rtt_sum: 0,
165                rtt_count: 0,
166                sent_count: Cell::new(1 + u64::from(echo_response)),
167                received_count: 1,
168                closed: false,
169            });
170        }
171    }
172
173    fn datagram(&self, opcode: u16, body: &[u8]) -> Vec<u8> {
174        let mut packet = opcode.to_be_bytes().to_vec();
175        if self.compression {
176            let compressed = miniz_oxide::deflate::compress_to_vec_zlib(body, 6);
177            if compressed.len() < body.len() {
178                packet.push(0x5a);
179                packet.extend(compressed);
180            } else {
181                packet.push(0xa5);
182                packet.extend_from_slice(body);
183            }
184        } else {
185            packet.extend_from_slice(body);
186        }
187        let crc = checksum(self.crc_seed, &packet).to_be_bytes();
188        packet.extend_from_slice(&crc[4 - self.crc_bytes..]);
189        packet
190    }
191
192    fn control(&self, opcode: u16, body: &[u8]) -> Result<()> {
193        self.socket.send(&self.datagram(opcode, body))?;
194        self.sent_count.set(self.sent_count.get() + 1);
195        Ok(())
196    }
197
198    /// Send one reliable application packet, fragmenting it when necessary.
199    ///
200    /// # Errors
201    ///
202    /// Returns an error when the session is closed, a size limit is exceeded,
203    /// or the UDP socket cannot send a packet.
204    pub fn send(&mut self, opcode: u16, body: &[u8]) -> Result<()> {
205        ensure!(!self.closed, "session is closed");
206        ensure!(body.len() <= MAX_APPLICATION - 3, "application too large");
207        let mut application = Vec::with_capacity(body.len() + 3);
208        if opcode.to_le_bytes()[0] == 0 {
209            application.push(0);
210        }
211        application.extend_from_slice(&opcode.to_le_bytes());
212        application.extend_from_slice(body);
213        let capacity = self.max_datagram - 4 - self.crc_bytes - usize::from(self.compression);
214        if application.len() <= capacity {
215            self.reliable(9, &application)?;
216        } else {
217            let mut first = u32::try_from(application.len())?.to_be_bytes().to_vec();
218            first.extend_from_slice(&application[..capacity - 4]);
219            self.reliable(13, &first)?;
220            for part in application[capacity - 4..].chunks(capacity) {
221                self.reliable(13, part)?;
222            }
223        }
224        Ok(())
225    }
226
227    /// Send an unsequenced application packet, used for position heartbeats.
228    ///
229    /// # Errors
230    ///
231    /// Returns an error for an unsupported opcode, an oversized datagram, or a
232    /// UDP socket failure.
233    pub fn send_unreliable(&self, opcode: u16, body: &[u8]) -> Result<()> {
234        ensure!(
235            opcode & 0xff != 0,
236            "unreliable opcode requires nonzero low byte"
237        );
238        let op = opcode.to_le_bytes();
239        let mut packet = vec![op[0]];
240        let mut rest = vec![op[1]];
241        rest.extend_from_slice(body);
242        if self.compression {
243            packet.push(0x5a);
244            packet.extend(miniz_oxide::deflate::compress_to_vec_zlib(&rest, 6));
245        } else {
246            packet.extend(rest);
247        }
248        let crc = checksum(self.crc_seed, &packet).to_be_bytes();
249        packet.extend_from_slice(&crc[4 - self.crc_bytes..]);
250        ensure!(
251            packet.len() <= self.max_datagram,
252            "unreliable packet exceeds datagram limit"
253        );
254        self.socket.send(&packet)?;
255        self.sent_count.set(self.sent_count.get() + 1);
256        Ok(())
257    }
258
259    fn reliable(&mut self, opcode: u16, body: &[u8]) -> Result<()> {
260        ensure!(
261            self.pending.len() < WINDOW as usize,
262            "outgoing reliable window full"
263        );
264        let sequence = self.next_send;
265        let mut framed = sequence.to_be_bytes().to_vec();
266        framed.extend_from_slice(body);
267        let packet = self.datagram(opcode, &framed);
268        self.socket.send(&packet)?;
269        self.sent_count.set(self.sent_count.get() + 1);
270        self.pending.push_back(Pending {
271            sequence,
272            packet,
273            sent: Instant::now(),
274            attempts: 1,
275        });
276        self.next_send = sequence.wrapping_add(1);
277        Ok(())
278    }
279
280    /// Drive retransmits and acknowledgements, returning the next full packet.
281    ///
282    /// # Errors
283    ///
284    /// Returns an error for malformed packets, protocol-limit violations,
285    /// timeouts, or UDP socket failures.
286    pub fn receive(&mut self) -> Result<Option<Application>> {
287        if self.ack_pending && self.last_ack.elapsed() >= Duration::from_millis(100) {
288            self.control(0x15, &self.next_receive.wrapping_sub(1).to_be_bytes())?;
289            self.ack_pending = false;
290            self.last_ack = Instant::now();
291        }
292        if let Some(application) = self.applications.pop_front() {
293            return Ok(Some(application));
294        }
295        ensure!(!self.closed, "server closed session");
296        for pending in &mut self.pending {
297            if pending.sent.elapsed() >= Duration::from_secs(1) {
298                ensure!(
299                    pending.attempts < 15,
300                    "server did not acknowledge a reliable packet"
301                );
302                self.socket.send(&pending.packet)?;
303                self.sent_count.set(self.sent_count.get() + 1);
304                pending.sent = Instant::now();
305                pending.attempts += 1;
306            }
307        }
308        ensure!(
309            self.last_receive.elapsed() < Duration::from_secs(60),
310            "server stopped responding"
311        );
312        if Instant::now() >= self.next_stats {
313            let token =
314                u16::try_from(self.started.elapsed().as_millis() % (u128::from(u16::MAX) + 1))?;
315            let mut stats = token.to_be_bytes().to_vec();
316            let average = u32::try_from(self.rtt_sum.checked_div(self.rtt_count).unwrap_or(0))
317                .unwrap_or(u32::MAX);
318            for value in [self.rtt, average, self.rtt_min, self.rtt_max, self.rtt] {
319                stats.extend_from_slice(&value.to_be_bytes());
320            }
321            stats.extend_from_slice(&self.sent_count.get().to_be_bytes());
322            stats.extend_from_slice(&self.received_count.to_be_bytes());
323            self.control(7, &stats)?;
324            self.stats_request = Some((token, Instant::now()));
325            self.next_stats = Instant::now() + Duration::from_secs(30);
326        }
327        let mut packet = vec![0; 65536];
328        match self.socket.recv(&mut packet) {
329            Ok(n) => {
330                self.received_count += 1;
331                if n < 2 + self.crc_bytes {
332                    return Ok(None);
333                }
334                if packet[..2] == [0, 2] {
335                    return Ok(None);
336                }
337                let end = n - self.crc_bytes;
338                let expected = checksum(self.crc_seed, &packet[..end]).to_be_bytes();
339                if packet[end..n] != expected[4 - self.crc_bytes..] {
340                    return Ok(None);
341                }
342                self.last_receive = Instant::now();
343                self.process(&packet[..end], false, 0)?;
344            }
345            Err(e) if timed_out(&e) => (),
346            Err(e) => return Err(e.into()),
347        }
348        Ok(self.applications.pop_front())
349    }
350
351    // Keeping the opcode dispatch linear makes the session state transitions auditable.
352    #[allow(clippy::too_many_lines)]
353    fn process(&mut self, packet: &[u8], nested: bool, depth: usize) -> Result<()> {
354        ensure!(
355            depth < 8 && packet.len() >= 2,
356            "invalid nested transport packet"
357        );
358        if packet[0] != 0 {
359            let mut application = vec![packet[0]];
360            if !nested && self.compression {
361                match packet[1] {
362                    0xa5 => application.extend_from_slice(&packet[2..]),
363                    0x5a => application.extend(
364                        miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(
365                            &packet[2..],
366                            MAX_APPLICATION,
367                        )
368                        .map_err(|_| anyhow::anyhow!("invalid compressed raw application"))?,
369                    ),
370                    _ => bail!("unsupported raw application encoding"),
371                }
372            } else {
373                application.extend_from_slice(&packet[1..]);
374            }
375            return self.application(&application, depth + 1);
376        }
377        let opcode = u16::from_be_bytes(packet[..2].try_into().unwrap());
378        let decompressed;
379        let mut body = &packet[2..];
380        if !nested && self.compression {
381            ensure!(!body.is_empty(), "missing compression marker");
382            match body[0] {
383                0xa5 => body = &body[1..],
384                0x5a => {
385                    decompressed = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(
386                        &body[1..],
387                        MAX_APPLICATION,
388                    )
389                    .map_err(|_| anyhow::anyhow!("invalid compressed packet"))?;
390                    body = &decompressed;
391                }
392                _ => bail!("unsupported compression marker"),
393            }
394        }
395        match opcode {
396            3 => {
397                for part in split_combined(body)? {
398                    self.process(part, true, depth + 1)?;
399                }
400            }
401            0x19 => {
402                for part in split_combined(body)? {
403                    self.application(part, depth + 1)?;
404                }
405            }
406            9 | 13 => {
407                ensure!(body.len() >= 2, "missing reliable sequence");
408                let sequence = u16::from_be_bytes(body[..2].try_into().unwrap());
409                let distance = sequence.wrapping_sub(self.next_receive);
410                if distance >= 32768 {
411                    self.ack_pending = true;
412                    return Ok(());
413                }
414                ensure!(distance < WINDOW, "incoming reliable window exceeded");
415                self.reorder
416                    .entry(sequence)
417                    .or_insert_with(|| (opcode, body[2..].to_vec()));
418                while let Some((op, part)) = self.reorder.remove(&self.next_receive) {
419                    self.ordered(op, &part)?;
420                    self.next_receive = self.next_receive.wrapping_add(1);
421                }
422                if distance > 0 {
423                    self.control(0x11, &sequence.to_be_bytes())?;
424                }
425                // A single cumulative acknowledgment covers a burst, including
426                // all reliable subpackets in a combined datagram.
427                self.ack_pending = true;
428            }
429            0x15 => {
430                ensure!(body.len() == 2, "invalid cumulative acknowledgment");
431                let ack = u16::from_be_bytes(body.try_into().unwrap());
432                if self.pending.iter().any(|p| p.sequence == ack) {
433                    while let Some(pending) = self.pending.pop_front() {
434                        if pending.sequence == ack {
435                            break;
436                        }
437                    }
438                }
439            }
440            0x11 => {
441                ensure!(body.len() == 2, "invalid out-of-order acknowledgment");
442                let seen = u16::from_be_bytes(body.try_into().unwrap());
443                for pending in &mut self.pending {
444                    if seen.wrapping_sub(pending.sequence) < WINDOW {
445                        self.socket.send(&pending.packet)?;
446                        self.sent_count.set(self.sent_count.get() + 1);
447                        pending.sent = Instant::now();
448                    }
449                }
450            }
451            5 => self.closed = true,
452            8 => {
453                ensure!(body.len() == 38, "invalid session statistics response");
454                if let Some((token, sent)) = self.stats_request {
455                    if body[..2] == token.to_be_bytes() {
456                        self.rtt = u32::try_from(sent.elapsed().as_millis()).unwrap_or(u32::MAX);
457                        self.rtt_min = if self.rtt_count == 0 {
458                            self.rtt
459                        } else {
460                            self.rtt_min.min(self.rtt)
461                        };
462                        self.rtt_max = self.rtt_max.max(self.rtt);
463                        self.rtt_sum += u64::from(self.rtt);
464                        self.rtt_count += 1;
465                        self.stats_request = None;
466                    }
467                }
468            }
469            7 => {
470                ensure!(body.len() == 38, "invalid session statistics request");
471                let mut reply = body[..2].to_vec();
472                let elapsed = u32::try_from(self.started.elapsed().as_millis()).unwrap_or(u32::MAX);
473                reply.extend_from_slice(&elapsed.to_be_bytes());
474                reply.extend_from_slice(&body[22..38]);
475                reply.extend_from_slice(&self.sent_count.get().to_be_bytes());
476                reply.extend_from_slice(&self.received_count.to_be_bytes());
477                self.control(8, &reply)?;
478            }
479            _ => (),
480        }
481        Ok(())
482    }
483
484    fn ordered(&mut self, opcode: u16, body: &[u8]) -> Result<()> {
485        if opcode == 9 {
486            ensure!(
487                self.fragment.is_none(),
488                "ordinary packet interrupted fragment assembly"
489            );
490            return self.application(body, 0);
491        }
492        if let Some((size, collected)) = &mut self.fragment {
493            ensure!(
494                collected.len() + body.len() <= *size,
495                "fragment exceeds declared size"
496            );
497            collected.extend_from_slice(body);
498        } else {
499            ensure!(body.len() >= 4, "missing fragment length");
500            let size = be32(&body[..4]) as usize;
501            ensure!(
502                (2..=MAX_APPLICATION).contains(&size) && body.len() - 4 <= size,
503                "invalid fragment size"
504            );
505            self.fragment = Some((size, body[4..].to_vec()));
506        }
507        if self
508            .fragment
509            .as_ref()
510            .is_some_and(|(size, data)| *size == data.len())
511        {
512            let (_, data) = self.fragment.take().unwrap();
513            self.application(&data, 0)?;
514        }
515        Ok(())
516    }
517
518    fn application(&mut self, mut bytes: &[u8], depth: usize) -> Result<()> {
519        ensure!(
520            depth < 8 && bytes.len() >= 2,
521            "invalid nested application packet"
522        );
523        if bytes[..2] == [0, 0x19] {
524            for part in split_combined(&bytes[2..])? {
525                self.application(part, depth + 1)?;
526            }
527            return Ok(());
528        }
529        if bytes[0] == 0 {
530            bytes = &bytes[1..];
531        }
532        ensure!(bytes.len() >= 2, "truncated escaped application opcode");
533        self.applications.push_back(Application {
534            opcode: u16::from_le_bytes(bytes[..2].try_into().unwrap()),
535            body: bytes[2..].to_vec(),
536        });
537        Ok(())
538    }
539
540    /// Send the session disconnect control packet once.
541    ///
542    /// # Errors
543    ///
544    /// Returns an error when the UDP socket cannot send the disconnect packet.
545    pub fn close(&mut self) -> Result<()> {
546        if !self.closed {
547            self.control(5, &self.id.to_be_bytes())?;
548            self.closed = true;
549        }
550        Ok(())
551    }
552}
553
554impl Drop for Session {
555    fn drop(&mut self) {
556        let _ = self.close();
557    }
558}
559
560fn timed_out(e: &io::Error) -> bool {
561    matches!(
562        e.kind(),
563        io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
564    )
565}
566fn be32(b: &[u8]) -> u32 {
567    u32::from_be_bytes(b.try_into().unwrap())
568}
569fn checksum(seed: u32, packet: &[u8]) -> u32 {
570    let mut hash = crc32fast::Hasher::new();
571    hash.update(&seed.to_le_bytes());
572    hash.update(packet);
573    hash.finalize()
574}
575
576fn split_combined(mut bytes: &[u8]) -> Result<Vec<&[u8]>> {
577    let mut result = Vec::new();
578    while !bytes.is_empty() {
579        let mut length = bytes[0] as usize;
580        bytes = &bytes[1..];
581        if length == 255 {
582            ensure!(bytes.len() >= 2, "truncated combined length");
583            length = u16::from_be_bytes(bytes[..2].try_into().unwrap()) as usize;
584            bytes = &bytes[2..];
585        }
586        ensure!(
587            length > 0 && length <= bytes.len(),
588            "invalid combined length"
589        );
590        result.push(&bytes[..length]);
591        bytes = &bytes[length..];
592    }
593    Ok(result)
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    fn session() -> (Session, UdpSocket) {
601        let peer = UdpSocket::bind("127.0.0.1:0").unwrap();
602        let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
603        socket.connect(peer.local_addr().unwrap()).unwrap();
604        socket
605            .set_read_timeout(Some(Duration::from_millis(100)))
606            .unwrap();
607        (
608            Session {
609                socket,
610                id: 7,
611                crc_seed: 0x1122_3344,
612                crc_bytes: 2,
613                compression: true,
614                max_datagram: 512,
615                next_send: 0,
616                next_receive: 0,
617                ack_pending: false,
618                last_ack: Instant::now(),
619                reorder: HashMap::new(),
620                pending: VecDeque::new(),
621                fragment: None,
622                applications: VecDeque::new(),
623                last_receive: Instant::now(),
624                started: Instant::now(),
625                next_stats: Instant::now() + Duration::from_secs(10),
626                stats_request: None,
627                rtt: 0,
628                rtt_min: 0,
629                rtt_max: 0,
630                rtt_sum: 0,
631                rtt_count: 0,
632                sent_count: Cell::new(0),
633                received_count: 0,
634                closed: false,
635            },
636            peer,
637        )
638    }
639
640    fn packet(session: &Session, op: u16, seq: u16, body: &[u8]) -> Vec<u8> {
641        let mut data = seq.to_be_bytes().to_vec();
642        data.extend_from_slice(body);
643        session.datagram(op, &data)
644    }
645
646    #[test]
647    fn reordered_fragments_cross_sequence_wrap_once() {
648        let (mut session, _peer) = session();
649        session.next_receive = 65534;
650        let mut first = 6u32.to_be_bytes().to_vec();
651        first.extend_from_slice(&[4, 16]);
652        for (seq, data) in [(0, &b"!"[..]), (65534, &first), (65535, &b"hey"[..])] {
653            let frame = packet(&session, 13, seq, data);
654            session
655                .process(&frame[..frame.len() - 2], false, 0)
656                .unwrap();
657        }
658        assert_eq!(session.next_receive, 1);
659        let chat = session.applications.pop_front().unwrap();
660        assert_eq!((chat.opcode, chat.body), (0x1004, b"hey!".to_vec()));
661        let duplicate = packet(&session, 13, 0, b"!");
662        session
663            .process(&duplicate[..duplicate.len() - 2], false, 0)
664            .unwrap();
665        assert!(session.applications.is_empty());
666        assert!(session.reorder.is_empty());
667    }
668
669    #[test]
670    fn damaged_datagram_is_discarded_then_retransmission_delivered() {
671        let (mut session, peer) = session();
672        let frame = packet(&session, 9, 0, b"\x04\x10hello");
673        let mut damaged = frame.clone();
674        damaged[5] ^= 0x80;
675        peer.send_to(&damaged, session.socket.local_addr().unwrap())
676            .unwrap();
677        assert!(session.receive().unwrap().is_none());
678        peer.send_to(&frame, session.socket.local_addr().unwrap())
679            .unwrap();
680        assert_eq!(session.receive().unwrap().unwrap().body, b"hello");
681    }
682
683    #[test]
684    fn outgoing_fragment_sizes_and_cumulative_ack() {
685        let (mut session, _peer) = session();
686        let body: Vec<u8> = (0..=u8::MAX).cycle().take(2056).collect();
687        session.send(0x5072, &body).unwrap();
688        assert_eq!(session.pending.len(), 5);
689        assert!(session.pending.iter().all(|p| p.packet.len() <= 512));
690        let frames: Vec<_> = session.pending.iter().map(|p| p.packet.clone()).collect();
691        for frame in frames {
692            session
693                .process(&frame[..frame.len() - 2], false, 0)
694                .unwrap();
695        }
696        assert_eq!(session.applications.pop_front().unwrap().body, body);
697        let ack = session.datagram(0x15, &4u16.to_be_bytes());
698        session.process(&ack[..ack.len() - 2], false, 0).unwrap();
699        assert!(session.pending.is_empty());
700    }
701
702    #[test]
703    fn raw_position_packet_uses_marker_between_opcode_bytes() {
704        let (mut session, peer) = session();
705        let position = [0; 36];
706        session.send_unreliable(0x14cb, &position).unwrap();
707        let mut bytes = [0; 512];
708        let n = peer.recv(&mut bytes).unwrap();
709        assert_eq!(&bytes[..2], &[0xcb, 0x5a]);
710        assert!(n < 41);
711        peer.send_to(&bytes[..n], session.socket.local_addr().unwrap())
712            .unwrap();
713        let packet = session.receive().unwrap().unwrap();
714        assert_eq!(packet.opcode, 0x14cb);
715        assert_eq!(packet.body, position);
716    }
717
718    #[test]
719    fn reliable_burst_gets_one_cumulative_ack() {
720        let (mut session, peer) = session();
721        peer.set_read_timeout(Some(Duration::from_millis(100)))
722            .unwrap();
723        for sequence in 0..200 {
724            let frame = packet(&session, 9, sequence, b"\x04\x10hello");
725            session
726                .process(&frame[..frame.len() - 2], false, 0)
727                .unwrap();
728        }
729        let mut wire = [0; 512];
730        assert!(
731            peer.recv(&mut wire).is_err(),
732            "burst must not ACK each packet"
733        );
734        session.last_ack = Instant::now()
735            .checked_sub(Duration::from_millis(100))
736            .unwrap();
737        assert!(session.receive().unwrap().is_some());
738        let n = peer.recv(&mut wire).unwrap();
739        assert_eq!(&wire[..n], session.datagram(0x15, &199u16.to_be_bytes()));
740        assert!(!session.ack_pending);
741    }
742}