~liz/yooper

ref: c4cb255c05ac772c178b9defe9328bdf787dfd80 yooper/yooper/src/discovery.rs -rw-r--r-- 4.7 KiB
c4cb255cEllie Frost License some stuff 2 years ago
                                                                                
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use std::collections::HashMap;
use std::net::{Ipv4Addr, SocketAddr};

use futures::sink::SinkExt;
use mac_address::{get_mac_address, MacAddressError};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::{
    net::UdpSocket,
    select,
    stream::StreamExt,
    time::{self, Duration},
};
use tokio_util::udp::UdpFramed;
use uuid::{self, Uuid};

use crate::{
    ssdp::message::{Codec, MSearch, Message, SearchTarget},
    Error,
};

const VERSION: &str = env!("CARGO_PKG_VERSION");

const SSDP_ADDRESS: Ipv4Addr = Ipv4Addr::new(239, 255, 255, 250);
const SSDP_PORT: u16 = 1900;

/// Discover services on your network
pub struct Discovery {
    uuid: Uuid,
    user_agent: String,
    socket: UdpFramed<Codec>,
}

/// A Device that's responded to a search
pub struct Device {
    /// version information for the server that responded to the search
    pub server: String,
    /// The address the device responded from
    pub address: SocketAddr,
    /// A list of discovered services
    pub services: Vec<Service>,
}

/// A Service represents a running service on a device
pub struct Service {
    /// Unique Service Name identifies a unique instance of a device or service.
    pub service_name: String,
    /// the search target you would use to describe this service
    pub target: SearchTarget,
}

impl Discovery {
    /// Create a new Discovery struct, including creating a new socket
    pub async fn new() -> Result<Self, Error> {
        let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, SSDP_PORT)).await?;
        socket.join_multicast_v4(SSDP_ADDRESS, Ipv4Addr::UNSPECIFIED)?;
        socket.set_multicast_ttl_v4(4)?;

        Self::from_socket(socket)
    }

    /// Create a new Discovery struct based on an existing Tokio socket
    pub fn from_socket(socket: UdpSocket) -> Result<Self, Error> {
        Ok(Self {
            socket: UdpFramed::new(socket, Codec::new()),
            uuid: get_uuid()?,
            user_agent: user_agent(),
        })
    }

    /// Send out an MSearch packet to discover services
    pub async fn start_search(&mut self, secs: u8) -> Result<(), Error> {
        // TODO: secs should be between 1 and 5
        let msg = Message::MSearch(MSearch {
            max_wait: Some(secs),
            target: SearchTarget::All,
            user_agent: Some(self.user_agent.clone()),
            host: format!("{}:{}", SSDP_ADDRESS, SSDP_PORT),

            friendly_name: Some("yooper".into()),
            uuid: Some(self.uuid.to_string()),

            ..Default::default()
        });

        self.socket
            .send((msg, (SSDP_ADDRESS, SSDP_PORT).into()))
            .await?;

        Ok(())
    }

    /// Find all SSDP services on the network.
    /// Will block for n secs then return a list of discovered devices
    /// secs should be between 1 and 5 to comply with
    pub async fn find(&mut self, secs: u8) -> Result<Vec<Device>, Error> {
        let mut map: HashMap<SocketAddr, Device> = HashMap::new();
        self.start_search(secs).await?;

        let mut delay = time::delay_for(Duration::from_secs(secs.into()));

        loop {
            select! {
                msg = self.socket.next() => {
                    match msg {
                        Some(Err(e)) => eprintln!("Error receiving: {:?}", e),
                        Some(Ok((Message::SearchResponse(sr), address))) => {
                            let device = map.entry(address).or_insert(Device {
                                address,
                                server: sr.server,
                                services: Vec::new(),

                            });
                            device.services.push(Service{
                                target: sr.target,
                                service_name: sr.unique_service_name
                            })
                        }
                        _ => (),
                    }
                }
                _ = &mut delay => {
                    break
                }
            };
        }

        Ok(map.into_iter().map(|(_k, v)| v).collect())
    }
}

fn user_agent() -> String {
    let info = os_info::get();

    format!(
        "{}/{}.1 upnp/2.0 yooper/{}",
        info.os_type(),
        info.version(),
        VERSION
    )
}

fn get_uuid() -> Result<Uuid, Error> {
    let mac = get_mac_address()?.ok_or(MacAddressError::InternalError)?;
    let ctx = uuid::v1::Context::new(0);

    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");
    let ts = uuid::v1::Timestamp::from_unix(
        &ctx,
        since_the_epoch.as_secs(),
        since_the_epoch.subsec_nanos(),
    );

    Ok(uuid::Uuid::new_v1(ts, &mac.bytes())?)
}