Skip to main content

rust_raknet/
lib.rs

1//! An asynchronous implementation of the RakNet transport protocol in Rust.
2//!
3//! RakNet provides reliable and ordered delivery modes over UDP and is used by
4//! Minecraft Bedrock Edition. This library implements the connection handshake,
5//! packet reliability, fragmentation, and listener/client APIs.
6//!
7//! The library requires the Tokio 1.x asynchronous runtime.
8//!
9//! # Features
10//!
11//! - Asynchronous client and server APIs
12//! - Five RakNet reliability modes
13//! - Selective retransmission and fast acknowledgements
14//! - IPv4 and IPv6 socket addresses
15//!
16//! # Getting started
17//!
18//! ```toml
19//! [dependencies]
20//! rust-raknet = "1.0.0"
21//! ```
22//!
23//! # Reliability modes
24//!
25//! - Unreliable
26//! - Unreliable sequenced
27//! - Reliable
28//! - Reliable ordered
29//! - Reliable sequenced
30//!
31//! This project is not affiliated with Jenkins Software LLC or RakNet.
32//! See the [RakNet protocol reference](http://www.jenkinssoftware.com/raknet/manual/index.html).
33
34mod arq;
35mod datatype;
36pub mod error;
37mod fragment;
38mod log;
39mod packet;
40mod sequence;
41mod server;
42mod socket;
43mod udp;
44mod utils;
45
46pub use crate::arq::Reliability;
47pub use crate::log::enable_raknet_log;
48pub use crate::server::*;
49pub use crate::socket::*;
50pub use bytes::Bytes;
51
52#[test]
53fn test_raknet_error_implements_std_error() {
54    fn assert_error<T: std::error::Error>() {}
55    assert_error::<error::RaknetError>();
56    assert_eq!(
57        error::RaknetError::NotListen.to_string(),
58        "the RakNet listener is not listening"
59    );
60}
61
62#[tokio::test]
63async fn test_listener_updates_motd_after_listen() {
64    let mut listener = RaknetListener::bind(&"127.0.0.1:0".parse().unwrap())
65        .await
66        .unwrap();
67    let local_addr = listener.local_addr().unwrap();
68    listener.listen().await;
69
70    let motd = "MCPE;Updated MOTD;486;1.20.0;0;20;123;World;Survival;1;19132;";
71    listener.set_full_motd(motd.to_owned()).await.unwrap();
72
73    let (_, received_motd) = tokio::time::timeout(
74        std::time::Duration::from_secs(3),
75        RaknetSocket::ping(&local_addr),
76    )
77    .await
78    .expect("server did not answer the unconnected ping")
79    .unwrap();
80    assert_eq!(received_motd, motd);
81
82    listener.close().await.unwrap();
83}
84
85#[tokio::test]
86async fn test_listener_accepts_more_than_one_queue_of_connections() {
87    const CONNECTIONS: usize = 12;
88
89    let mut listener = RaknetListener::bind(&"127.0.0.1:0".parse().unwrap())
90        .await
91        .unwrap();
92    let local_addr = listener.local_addr().unwrap();
93    listener.listen().await;
94
95    let accept_task = tokio::spawn(async move {
96        let mut accepted = Vec::with_capacity(CONNECTIONS);
97        for _ in 0..CONNECTIONS {
98            accepted.push(
99                tokio::time::timeout(std::time::Duration::from_secs(5), listener.accept())
100                    .await
101                    .expect("listener stopped accepting connections")
102                    .unwrap(),
103            );
104        }
105        (accepted, listener)
106    });
107
108    let mut clients = Vec::with_capacity(CONNECTIONS);
109    for _ in 0..CONNECTIONS {
110        clients.push(
111            tokio::time::timeout(
112                std::time::Duration::from_secs(5),
113                RaknetSocket::connect(&local_addr),
114            )
115            .await
116            .expect("client connection timed out")
117            .unwrap(),
118        );
119    }
120
121    let (accepted, mut listener) =
122        tokio::time::timeout(std::time::Duration::from_secs(5), accept_task)
123            .await
124            .expect("listener accept loop timed out")
125            .unwrap();
126    assert_eq!(accepted.len(), CONNECTIONS);
127
128    for socket in clients {
129        socket.close().await.unwrap();
130    }
131    for socket in accepted {
132        socket.close().await.unwrap();
133    }
134    listener.close().await.unwrap();
135}
136
137#[tokio::test]
138async fn test_connect() {
139    let mut server = RaknetListener::bind(&"127.0.0.1:0".parse().unwrap())
140        .await
141        .unwrap();
142    let local_addr = server.local_addr().unwrap();
143    server.listen().await;
144
145    let notify = std::sync::Arc::new(tokio::sync::Notify::new());
146    let notify2 = notify.clone();
147
148    tokio::spawn(async move {
149        let client1 = server.accept().await.unwrap();
150        assert!(client1.local_addr().unwrap() == local_addr);
151        client1
152            .send(&[0xfe, 2, 3], Reliability::Reliable)
153            .await
154            .unwrap();
155        notify2.notified().await;
156    });
157    let client2 = RaknetSocket::connect(&local_addr).await.unwrap();
158    assert!(client2.peer_addr().unwrap() == local_addr);
159    let buf = client2.recv().await.unwrap();
160    assert!(buf == vec![0xfe, 2, 3]);
161
162    notify.notify_one();
163}
164
165#[tokio::test]
166async fn test_send_recv_fragment_data() {
167    let mut server = RaknetListener::bind(&"127.0.0.1:0".parse().unwrap())
168        .await
169        .unwrap();
170    let local_addr = server.local_addr().unwrap();
171    server.listen().await;
172
173    let notify = std::sync::Arc::new(tokio::sync::Notify::new());
174    let notify2 = notify.clone();
175
176    tokio::spawn(async move {
177        let client1 = server.accept().await.unwrap();
178        assert!(client1.local_addr().unwrap() == local_addr);
179
180        let mut a = vec![3u8; 1000];
181        let mut b = vec![2u8; 1000];
182        let mut c = vec![0xfe; 1000];
183        b.append(&mut a);
184        c.append(&mut b);
185
186        client1
187            .send(&c, Reliability::ReliableOrdered)
188            .await
189            .unwrap();
190
191        notify2.notified().await;
192    });
193    let client2 = RaknetSocket::connect(&local_addr).await.unwrap();
194    assert!(client2.peer_addr().unwrap() == local_addr);
195    let buf = client2.recv().await.unwrap();
196    assert!(buf.len() == 3000);
197    assert!(buf[0..1000] == vec![0xfe; 1000]);
198    assert!(buf[1000..2000] == vec![2u8; 1000]);
199    assert!(buf[2000..3000] == vec![3u8; 1000]);
200
201    notify.notify_one();
202}
203
204#[tokio::test]
205async fn test_send_recv_more_reliability_type_packet() {
206    let mut server = RaknetListener::bind(&"127.0.0.1:0".parse().unwrap())
207        .await
208        .unwrap();
209    let local_addr = server.local_addr().unwrap();
210    server.listen().await;
211
212    let notify = std::sync::Arc::new(tokio::sync::Notify::new());
213    let notify2 = notify.clone();
214
215    tokio::spawn(async move {
216        let client1 = server.accept().await.unwrap();
217        assert!(client1.local_addr().unwrap() == local_addr);
218
219        client1
220            .send(&[0xfe, 1, 2, 3], Reliability::Unreliable)
221            .await
222            .unwrap();
223        let data = client1.recv().await.unwrap();
224        assert!(data == [0xfe, 4, 5, 6].to_vec());
225
226        client1
227            .send(&[0xfe, 7, 8, 9], Reliability::UnreliableSequenced)
228            .await
229            .unwrap();
230        let data = client1.recv().await.unwrap();
231        assert!(data == [0xfe, 10, 11, 12].to_vec());
232
233        client1
234            .send(&[0xfe, 13, 14, 15], Reliability::Reliable)
235            .await
236            .unwrap();
237        let data = client1.recv().await.unwrap();
238        assert!(data == [0xfe, 16, 17, 18].to_vec());
239
240        let mut a = vec![3u8; 1000];
241        let mut b = vec![2u8; 1000];
242        let mut c = vec![0xfe; 1000];
243        b.append(&mut a);
244        c.append(&mut b);
245
246        client1
247            .send(&c, Reliability::ReliableOrdered)
248            .await
249            .unwrap();
250
251        let buf = client1.recv().await.unwrap();
252        assert!(buf.len() == 3000);
253        assert!(buf[0..1000] == vec![0xfe; 1000]);
254        assert!(buf[1000..2000] == vec![2u8; 1000]);
255        assert!(buf[2000..3000] == vec![3u8; 1000]);
256
257        client1
258            .send(&[0xfe, 19, 20, 21], Reliability::ReliableSequenced)
259            .await
260            .unwrap();
261        let data = client1.recv().await.unwrap();
262        assert!(data == [0xfe, 22, 23, 24].to_vec());
263
264        notify2.notified().await;
265    });
266    let client2 = RaknetSocket::connect(&local_addr).await.unwrap();
267    assert!(client2.peer_addr().unwrap() == local_addr);
268
269    let buf = client2.recv().await.unwrap();
270    assert!(buf == [0xfe, 1, 2, 3]);
271
272    client2
273        .send(&[0xfe, 4, 5, 6], Reliability::Unreliable)
274        .await
275        .unwrap();
276
277    let buf = client2.recv().await.unwrap();
278    assert!(buf == [0xfe, 7, 8, 9]);
279
280    client2
281        .send(&[0xfe, 10, 11, 12], Reliability::UnreliableSequenced)
282        .await
283        .unwrap();
284
285    let buf = client2.recv().await.unwrap();
286    assert!(buf == [0xfe, 13, 14, 15]);
287
288    client2
289        .send(&[0xfe, 16, 17, 18], Reliability::Reliable)
290        .await
291        .unwrap();
292
293    let buf = client2.recv().await.unwrap();
294    assert!(buf.len() == 3000);
295    assert!(buf[0..1000] == vec![0xfe; 1000]);
296    assert!(buf[1000..2000] == vec![2u8; 1000]);
297    assert!(buf[2000..3000] == vec![3u8; 1000]);
298
299    let mut a = vec![3u8; 1000];
300    let mut b = vec![2u8; 1000];
301    let mut c = vec![0xfe; 1000];
302    b.append(&mut a);
303    c.append(&mut b);
304
305    client2
306        .send(&c, Reliability::ReliableOrdered)
307        .await
308        .unwrap();
309
310    let buf = client2.recv().await.unwrap();
311    assert!(buf == [0xfe, 19, 20, 21]);
312
313    client2
314        .send(&[0xfe, 22, 23, 24], Reliability::ReliableSequenced)
315        .await
316        .unwrap();
317
318    notify.notify_one();
319}
320
321#[tokio::test]
322async fn test_loss_packet1() {
323    let notify = std::sync::Arc::new(tokio::sync::Notify::new());
324    let notify2 = notify.clone();
325    let mut server = RaknetListener::bind(&"127.0.0.1:0".parse().unwrap())
326        .await
327        .unwrap();
328    let local_addr = server.local_addr().unwrap();
329    server.listen().await;
330    tokio::spawn(async move {
331        let mut client1 = server.accept().await.unwrap();
332        // Simulate 20% packet loss.
333        client1.set_loss_rate(2);
334
335        for i in 0..10 {
336            let mut flag = vec![0xfe_u8];
337            let mut data = vec![i as u8; 2000];
338            flag.append(&mut data);
339            client1
340                .send(&flag, Reliability::ReliableOrdered)
341                .await
342                .unwrap();
343
344            let data = client1.recv().await.unwrap();
345            assert!(data == flag);
346        }
347
348        notify2.notified().await;
349    });
350    let mut client2 = RaknetSocket::connect(&local_addr).await.unwrap();
351    // Simulate 20% packet loss.
352    client2.set_loss_rate(2);
353
354    for i in 0..10 {
355        let mut flag = vec![0xfe_u8];
356        let mut data = vec![i as u8; 2000];
357        flag.append(&mut data);
358        client2
359            .send(&flag, Reliability::ReliableOrdered)
360            .await
361            .unwrap();
362
363        let data = client2.recv().await.unwrap();
364        assert!(data == flag);
365    }
366    notify.notify_one();
367}
368
369#[tokio::test]
370async fn test_loss_packet2() {
371    let notify = std::sync::Arc::new(tokio::sync::Notify::new());
372    let notify2 = notify.clone();
373    let mut server = RaknetListener::bind(&"127.0.0.1:0".parse().unwrap())
374        .await
375        .unwrap();
376    let local_addr = server.local_addr().unwrap();
377    server.listen().await;
378    tokio::spawn(async move {
379        let mut client1 = server.accept().await.unwrap();
380        // Simulate 20% packet loss.
381        client1.set_loss_rate(2);
382
383        for i in 0..10 {
384            let mut flag = vec![0xfe_u8];
385            let mut data = vec![i as u8; 2000];
386            flag.append(&mut data);
387            client1
388                .send(&flag, Reliability::ReliableOrdered)
389                .await
390                .unwrap();
391        }
392
393        for i in 0..10 {
394            let mut flag = vec![0xfe_u8];
395            let mut data = vec![i as u8; 2000];
396            flag.append(&mut data);
397            let data = client1.recv().await.unwrap();
398            assert!(data == flag);
399        }
400        notify2.notified().await;
401    });
402    let mut client2 = RaknetSocket::connect(&local_addr).await.unwrap();
403    // Simulate 20% packet loss.
404    client2.set_loss_rate(2);
405
406    for i in 0..10 {
407        let mut flag = vec![0xfe_u8];
408        let mut data = vec![i as u8; 2000];
409        flag.append(&mut data);
410        client2
411            .send(&flag, Reliability::ReliableOrdered)
412            .await
413            .unwrap();
414    }
415
416    for i in 0..10 {
417        let mut flag = vec![0xfe_u8];
418        let mut data = vec![i as u8; 2000];
419        flag.append(&mut data);
420        let data = client2.recv().await.unwrap();
421        assert!(data == flag);
422    }
423    notify.notify_one();
424}
425
426#[tokio::test]
427async fn test_loss_packet_with_sequenced() {
428    let notify = std::sync::Arc::new(tokio::sync::Notify::new());
429    let notify2 = notify.clone();
430    let mut server = RaknetListener::bind(&"127.0.0.1:0".parse().unwrap())
431        .await
432        .unwrap();
433    let local_addr = server.local_addr().unwrap();
434    server.listen().await;
435    tokio::spawn(async move {
436        let mut client1 = server.accept().await.unwrap();
437        // Simulate 20% packet loss.
438        client1.set_loss_rate(2);
439
440        for i in 0..100 {
441            let mut flag = vec![0xfe_u8];
442            let mut data = vec![i as u8; 20];
443            flag.append(&mut data);
444            client1
445                .send(&flag, Reliability::ReliableSequenced)
446                .await
447                .unwrap();
448        }
449
450        let mut last = 0;
451        for i in 0..50 {
452            let mut flag = vec![0xfe_u8];
453            let mut data = vec![i as u8; 20];
454            flag.append(&mut data);
455            let data = client1.recv().await.unwrap();
456            assert!(data[1] >= last);
457            last = data[1];
458        }
459        notify2.notified().await;
460    });
461    let mut client2 = RaknetSocket::connect(&local_addr).await.unwrap();
462    // Simulate 20% packet loss.
463    client2.set_loss_rate(2);
464
465    for i in 0..100 {
466        let mut flag = vec![0xfe_u8];
467        let mut data = vec![i as u8; 20];
468        flag.append(&mut data);
469        client2
470            .send(&flag, Reliability::ReliableSequenced)
471            .await
472            .unwrap();
473    }
474
475    let mut last = 0;
476    for i in 0..50 {
477        let mut flag = vec![0xfe_u8];
478        let mut data = vec![i as u8; 20];
479        flag.append(&mut data);
480        let data = client2.recv().await.unwrap();
481        assert!(data[1] >= last);
482        last = data[1];
483    }
484    notify.notify_one();
485}
486
487#[tokio::test]
488async fn test_raknet_server_close() {
489    for _ in 0..10 {
490        let mut server = RaknetListener::bind(&"127.0.0.1:19132".parse().unwrap())
491            .await
492            .unwrap();
493        server.listen().await;
494        let client = RaknetSocket::connect(&"127.0.0.1:19132".parse().unwrap())
495            .await
496            .unwrap();
497        let mut a = vec![3u8; 1000];
498        let mut b = vec![2u8; 1000];
499        let mut c = vec![0xfe; 1000];
500        b.append(&mut a);
501        c.append(&mut b);
502        client.send(&c, Reliability::ReliableOrdered).await.unwrap();
503
504        let client2 = server.accept().await.unwrap();
505        let buf = client2.recv().await.unwrap();
506        assert!(buf.len() == 3000);
507        assert!(buf[0..1000] == vec![0xfe; 1000]);
508        assert!(buf[1000..2000] == vec![2u8; 1000]);
509        assert!(buf[2000..3000] == vec![3u8; 1000]);
510
511        server.close().await.unwrap();
512        client.close().await.unwrap();
513    }
514
515    let mut server1 = RaknetListener::bind(&"127.0.0.1:19132".parse().unwrap())
516        .await
517        .unwrap();
518    server1.listen().await;
519    server1.close().await.unwrap();
520    let mut server2 = RaknetListener::bind(&"127.0.0.1:19132".parse().unwrap())
521        .await
522        .unwrap();
523    server2.listen().await;
524}
525
526#[tokio::test]
527async fn test_send_recv_full_packet() {
528    let mut server = RaknetListener::bind(&"127.0.0.1:0".parse().unwrap())
529        .await
530        .unwrap();
531    let remote_addr = format!("127.0.0.1:{}", server.local_addr().unwrap().port());
532    tokio::spawn(async move {
533        server.listen().await;
534        let client = server.accept().await.unwrap();
535
536        // Complete delivery requires ordered reliability; sequenced mode may
537        // discard superseded messages during retransmission.
538        for _ in 0..50 {
539            client
540                .send(&vec![0xfe; 1000], Reliability::ReliableOrdered)
541                .await
542                .unwrap();
543        }
544        client.flush().await.unwrap();
545
546        client.close().await.unwrap();
547        server.close().await.unwrap();
548    });
549
550    let client = RaknetSocket::connect(&remote_addr.parse().unwrap())
551        .await
552        .unwrap();
553
554    for _ in 0..50 {
555        let buf = client.recv().await.unwrap();
556        assert!(buf == [0xfe; 1000]);
557    }
558}
559
560#[tokio::test]
561async fn test_send_recv_with_flush() {
562    let mut server = RaknetListener::bind(&"127.0.0.1:0".parse().unwrap())
563        .await
564        .unwrap();
565    let remote_addr = format!("127.0.0.1:{}", server.local_addr().unwrap().port());
566    let s1 = std::sync::Arc::new(tokio::sync::Semaphore::new(1));
567    let s2 = s1.clone();
568    tokio::spawn(async move {
569        server.listen().await;
570        let client = server.accept().await.unwrap();
571
572        for _ in 0..50 {
573            #[allow(unused_must_use)]
574            {
575                s1.acquire().await.unwrap();
576            }
577            client
578                .send(&vec![0xfe; 1000], Reliability::ReliableSequenced)
579                .await
580                .unwrap();
581            client.flush().await.unwrap();
582        }
583
584        client.close().await.unwrap();
585        for _ in 0..5 {
586            client
587                .send(&vec![0xfe; 1000], Reliability::ReliableSequenced)
588                .await
589                .unwrap();
590            match match client.flush().await {
591                Ok(_) => panic!("incorrect return"),
592                Err(e) => e,
593            } {
594                error::RaknetError::ConnectionClosed => {}
595                _ => panic!("incorrect return"),
596            };
597        }
598        server.close().await.unwrap();
599    });
600
601    let client = RaknetSocket::connect(&remote_addr.parse().unwrap())
602        .await
603        .unwrap();
604
605    for _ in 0..50 {
606        let buf = client.recv().await.unwrap();
607        assert!(buf == [0xfe; 1000]);
608        s2.add_permits(1);
609    }
610}
611
612/*
613#[tokio::test]
614async fn chore2(){
615
616    enbale_raknet_log(true);
617    let mut listener = RaknetListener::bind("0.0.0.0:19199".parse().unwrap()).await.unwrap();
618    listener.listen().await;
619    loop{
620        let mut client1 = listener.accept().await.unwrap();
621        let mut client2 = RaknetSocket::connect(&"192.168.199.127:19132".parse().unwrap()).await.unwrap();
622        tokio::spawn(async move {
623            println!("build connection");
624            loop{
625                tokio::select!{
626                    a = client1.recv() => {
627                        let a = match a{
628                            Ok(p) => p,
629                            Err(_) => {
630                                client2.close().await.unwrap();
631                                break;
632                            },
633                        };
634                        match client2.send(&a, Reliability::ReliableOrdered).await{
635                            Ok(p) => p,
636                            Err(_) => {
637                                client1.close().await.unwrap();
638                                break;
639                            },
640                        };
641                    },
642                    b = client2.recv() => {
643                        let b = match b{
644                            Ok(p) => p,
645                            Err(_) => {
646                                client1.close().await.unwrap();
647                                break;
648                            },
649                        };
650                        match client1.send(&b, Reliability::ReliableOrdered).await{
651                            Ok(p) => p,
652                            Err(_) => {
653                                client2.close().await.unwrap();
654                                break;
655                            },
656                        };
657                    }
658                }
659            }
660            println!("close connection");
661        });
662    }
663
664
665}
666*/