aboutsummaryrefslogtreecommitdiff
path: root/sip/examples/server.rs
blob: 859c35eeeabc89439ec404a876066f5271ddf11c (plain)
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
use anyhow::Result;
use log::{info, warn};
use sip::{
    encoding::{
        headermap::HeaderMap,
        headers::{Contact, From, To, UserAgent, Via},
        method::Method,
        response::Response,
        status::Status,
    },
    transaction::TransactionUser,
    transport::tcp::TcpTransport,
};
use std::net::SocketAddr;
use tokio::{
    net::{TcpListener, TcpStream},
    spawn,
};

#[tokio::main]
async fn main() -> Result<()> {
    env_logger::init_from_env("LOG");
    let listener = TcpListener::bind("0.0.0.0:5060").await?;
    info!("tcp listener bound to {}", listener.local_addr().unwrap());

    loop {
        let (stream, addr) = listener.accept().await?;
        info!("connect {addr}");

        spawn(async move {
            if let Err(e) = handle_client(stream, addr).await {
                warn!("client error: {e}")
            }
            info!("disconnect {addr}")
        });
    }
}

async fn handle_client(stream: TcpStream, addr: SocketAddr) -> Result<()> {
    let transport = TcpTransport::new(stream).await?;
    let tu = TransactionUser::new(transport);
    loop {
        let req = tu.process_incoming().await?;

        if req.method == Method::Register {
            let from: From = req.headers.get_res()?;
            let to: To = req.headers.get_res()?;
            let via: Via = req.headers.get_res()?;
            let contact: Contact = req.headers.get_res()?;
            info!(
                "({addr}) Registered {}",
                contact.uri.localpart.as_ref().unwrap()
            );

            tu.respond(
                &req,
                Response {
                    status: Status::Ok,
                    headers: HeaderMap::new()
                        .add(contact)
                        .add(via)
                        .add(to)
                        .add(from)
                        .add(UserAgent("siptest v0.1.0".to_string())),
                    body: String::new(),
                },
            )
            .await?;
        }
        if req.method == Method::Invite {}
    }
}