1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//! Network front-end driver

use {
    alloc::{collections::BTreeMap, vec, vec::Vec},
    core::{fmt::Write, str},
    log::{info, warn},
    phy::Device,
    smoltcp::{
        iface::{InterfaceBuilder, NeighborCache, Routes},
        socket::{TcpSocket, TcpSocketBuffer},
        time::Instant,
        wire::{IpCidr, Ipv4Address},
    },
    xen::time::get_system_time,
};

mod phy;
mod ring;

pub async fn server() {
    let phy = Device::new().await;
    let mac = phy.mac();

    let neighbor_cache = NeighborCache::new(BTreeMap::new());

    let ip_addrs = [IpCidr::new(Ipv4Address::new(192, 168, 1, 2).into(), 0)];
    let mut routes_storage = [None; 1];
    let routes = Routes::new(&mut routes_storage[..]);

    let mut iface = InterfaceBuilder::new(phy, Vec::new())
        .hardware_addr(mac.into())
        .neighbor_cache(neighbor_cache)
        .ip_addrs(ip_addrs)
        .routes(routes)
        .finalize();

    let mut rx_buffer = vec![0; 2048];
    let mut tx_buffer = vec![0; 2048];
    let socket = TcpSocket::new(
        TcpSocketBuffer::new(&mut rx_buffer[..]),
        TcpSocketBuffer::new(&mut tx_buffer[..]),
    );

    let tcp_handle = iface.add_socket(socket);

    info!("starting TCP server");

    loop {
        match iface.poll(Instant::from_micros((get_system_time() >> 10) as i64)) {
            Ok(_) => {}
            Err(e) => {
                warn!("poll error: {}", e);
            }
        }

        let socket = iface.get_socket::<TcpSocket>(tcp_handle);
        if !socket.is_open() {
            socket.listen(80).unwrap();
        }

        if socket.can_recv() {
            let mut recv_buf = vec![0; 2048];
            let len = socket.recv_slice(&mut recv_buf).unwrap();

            info!("tcp:80 received: {:?}", unsafe {
                str::from_utf8_unchecked(&recv_buf[..len])
            });

            writeln!(socket, "SERVER:\t hello! you sent {:?}", unsafe {
                str::from_utf8_unchecked(&recv_buf[..len])
            })
            .unwrap();
            writeln!(socket, "SERVER:\t goodbye 👋").unwrap();

            info!("tcp:80 close");
            socket.close();
        }
    }
}