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
use crate::Error;
use crate::PortFinder;
use crate::ScanningWithFallbackPortFinder;

use ::lazy_static::lazy_static;
use ::std::collections::HashSet;
use ::std::net::IpAddr;
use ::std::net::SocketAddr;
use ::std::net::TcpListener;
use ::std::sync::Mutex;
use std::sync::MutexGuard;

const MIN_PORT: u16 = 8_000;
const MAX_PORT: u16 = 15_999;

lazy_static! {
    static ref GLOBAL_PORT_FINDER: Mutex<ReservedPortFinder<MIN_PORT, MAX_PORT>> =
        Mutex::new(ReservedPortFinder::new());
}

pub(crate) fn borrow_global_port_finder(
) -> Result<MutexGuard<'static, ReservedPortFinder<MIN_PORT, MAX_PORT>>, Error> {
    let port_finder = GLOBAL_PORT_FINDER
        .lock()
        .map_err(|_| Error::InternalLockError)?;

    Ok(port_finder)
}

pub struct ReservedPortFinder<const MIN: u16, const MAX: u16> {
    finder: ScanningWithFallbackPortFinder<MIN, MAX>,
    ports_in_use: HashSet<u16>,
}

impl<const MIN: u16, const MAX: u16> ReservedPortFinder<MIN, MAX> {
    pub fn new() -> Self {
        Self {
            finder: ScanningWithFallbackPortFinder::new(),
            ports_in_use: HashSet::new(),
        }
    }

    /// Sets a port to be _permanently_ reserved.
    ///
    /// Reservations only affect this port scanner.
    pub fn reserve_port(&mut self, port: u16) {
        self.ports_in_use.insert(port);
    }

    #[must_use]
    pub fn reserve_random_tcp(&mut self, ip: IpAddr) -> Option<(TcpListener, SocketAddr)> {
        // As long as the port finder can keep finding ports,
        // we keep spinning, and checking if the port is in use.
        //
        // When a free port is found, we return it.
        while let Some((tcp_listener, socket_addr)) = self.finder.find_port_for_ip(ip) {
            let port = socket_addr.port();
            if self.ports_in_use.contains(&port) {
                continue;
            }

            self.ports_in_use.insert(port);
            return Some((tcp_listener, socket_addr));
        }

        None
    }

    #[must_use]
    pub fn reserve_random_port(&mut self) -> Option<u16> {
        // As long as the port finder can keep finding ports,
        // we keep spinning, and checking if the port is in use.
        //
        // When a free port is found, we return it.
        while let Some(port) = self.finder.find_port() {
            if self.ports_in_use.contains(&port) {
                continue;
            }

            self.ports_in_use.insert(port);
            return Some(port);
        }

        None
    }

    pub fn free_port(&mut self, port: u16) {
        self.ports_in_use.remove(&port);
    }
}