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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Copyright (C) 2020 Matthew Waters <matthew@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use async_std::net::{SocketAddr, UdpSocket};

use std::net::IpAddr;
use std::sync::{Arc, Mutex};

use futures::prelude::*;
use futures::StreamExt;

use get_if_addrs::get_if_addrs;

use crate::candidate::{Candidate, CandidateType, TransportType};
use crate::stun::agent::StunAgent;
use crate::stun::agent::StunError;
use crate::stun::attribute::*;
use crate::stun::message::*;
use crate::stun::socket::{StunChannel, UdpSocketChannel};

fn address_is_ignorable(ip: IpAddr) -> bool {
    // TODO: add is_benchmarking() and is_documentation() when they become stable
    if ip.is_loopback() || ip.is_unspecified() || ip.is_multicast() {
        return true;
    }
    match ip {
        IpAddr::V4(ipv4) => ipv4.is_broadcast() || ipv4.is_link_local(),
        IpAddr::V6(_ipv6) => false,
    }
}

pub fn iface_udp_sockets(
) -> Result<impl Stream<Item = Result<UdpSocketChannel, std::io::Error>>, StunError> {
    let mut ifaces = get_if_addrs()?;
    // We only care about non-loopback interfaces for now
    // TODO: remove 'Deprecated IPv4-compatible IPv6 addresses [RFC4291]'
    // TODO: remove 'IPv6 site-local unicast addresses [RFC3879]'
    // TODO: remove 'IPv4-mapped IPv6 addresses unless ipv6 only'
    // TODO: location tracking Ipv6 address mismatches
    ifaces.retain(|e| !address_is_ignorable(e.ip()));

    for _f in ifaces.iter().inspect(|iface| {
        info!("Found interface {} address {:?}", iface.name, iface.ip());
    }) {}

    Ok(
        futures::stream::iter(ifaces.into_iter()).then(|iface| async move {
            Ok(UdpSocketChannel::new(
                UdpSocket::bind(SocketAddr::new(iface.clone().ip(), 0)).await?,
            ))
        }),
    )
}

fn generate_bind_request() -> std::io::Result<Message> {
    let mut out = Message::new_request(BINDING);
    out.add_fingerprint()
        .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid message"))?;

    trace!("generated to {}", out);
    Ok(out)
}

#[derive(Debug)]
struct GatherCandidateAddress {
    ctype: CandidateType,
    local_preference: u8,
    transport: TransportType,
    address: SocketAddr,
    base: SocketAddr,
    related: Option<SocketAddr>,
}

async fn gather_stun_xor_address(
    local_preference: u8,
    agent: StunAgent,
    transport: TransportType,
    stun_server: SocketAddr,
) -> Result<GatherCandidateAddress, StunError> {
    let msg = generate_bind_request()?;

    agent
        .stun_request_transaction(&msg, stun_server)?
        .build()?
        .perform()
        .await
        .and_then(move |(response, from)| {
            if let Some(attr) = response.attribute::<XorMappedAddress>(XOR_MAPPED_ADDRESS) {
                debug!(
                    "got external address {:?}",
                    attr.addr(response.transaction_id())
                );
                return Ok(GatherCandidateAddress {
                    ctype: CandidateType::ServerReflexive,
                    local_preference,
                    transport,
                    address: attr.addr(response.transaction_id()),
                    base: from,
                    related: Some(stun_server),
                });
            }
            Err(StunError::Failed)
        })
}

fn udp_socket_host_gather_candidate(
    socket: Arc<UdpSocket>,
    local_preference: u8,
) -> Result<GatherCandidateAddress, StunError> {
    let local_addr = socket.local_addr().unwrap();
    Ok(GatherCandidateAddress {
        ctype: CandidateType::Host,
        local_preference,
        transport: TransportType::Udp,
        address: local_addr,
        base: local_addr,
        related: None,
    })
}

pub fn gather_component(
    component_id: usize,
    local_agents: Vec<StunAgent>,
    stun_servers: Vec<(TransportType, SocketAddr)>,
) -> impl Stream<Item = (Candidate, StunAgent)> {
    let futures = futures::stream::FuturesUnordered::new();

    for f in local_agents
        .iter()
        .enumerate()
        .filter_map(|(i, agent)| match &agent.inner.channel {
            StunChannel::UdpAny(schannel) => Some(futures::future::ready(
                udp_socket_host_gather_candidate(schannel.socket(), (i * 10) as u8)
                    .map(|ga| (ga, agent.clone())),
            )),
            _ => None,
        })
    {
        futures.push(f.boxed_local());
    }

    for (i, agent) in local_agents.iter().cloned().enumerate() {
        for stun_server in stun_servers.iter() {
            futures.push(
                {
                    let agent = agent.clone();
                    let stun_server = *stun_server;
                    async move {
                        gather_stun_xor_address(
                            (i * 10) as u8,
                            agent.clone(),
                            stun_server.0,
                            stun_server.1,
                        )
                        .await
                        .map(move |ga| (ga, agent))
                    }
                }
                .boxed_local(),
            )
        }
    }

    // TODO: add peer-reflexive and relayed (TURN) candidates

    let produced = Arc::new(Mutex::new(Vec::new()));
    futures.filter_map(move |ga| {
        let produced = produced.clone();
        async move {
            match ga {
                Ok((ga, channel)) => {
                    let priority = Candidate::calculate_priority(
                        ga.ctype,
                        ga.local_preference as u32,
                        component_id,
                    );
                    trace!("candidate {:?}, {:?}", ga, priority);
                    if address_is_ignorable(ga.address.ip()) {
                        return None;
                    }
                    if address_is_ignorable(ga.base.ip()) {
                        return None;
                    }
                    let mut produced = produced.lock().unwrap();
                    let mut builder = Candidate::builder(
                        component_id,
                        ga.ctype,
                        ga.transport,
                        &produced.len().to_string(),
                        ga.address,
                    )
                    .priority(priority)
                    .base_address(ga.base);
                    if let Some(related) = ga.related {
                        builder = builder.related_address(related);
                    }
                    let cand = builder.build();
                    for c in produced.iter() {
                        // ignore candidates that produce the same local/remote pair of
                        // addresses
                        if cand.redundant_with(c) {
                            trace!("redundant {:?}", cand);
                            return None;
                        }
                    }
                    debug!("producing {:?}", cand);
                    produced.push(cand.clone());
                    Some((cand, channel))
                }
                Err(e) => {
                    trace!("candidate retrieval error \'{:?}\'", e);
                    None
                }
            }
        }
    })
}