turn_server_proto/
api.rs

1// Copyright (C) 2025 Matthew Waters <matthew@centricular.com>
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! API for TURN servers.
10
11use std::{
12    net::SocketAddr,
13    time::{Duration, Instant},
14};
15
16use stun_proto::agent::Transmit;
17use turn_types::stun::TransportType;
18
19/// API for TURN servers.
20pub trait TurnServerApi: Send + std::fmt::Debug {
21    /// Add a user credentials that would be accepted by this [`TurnServerApi`].
22    fn add_user(&mut self, username: String, password: String);
23    /// The address that the [`TurnServerApi`] is listening on for incoming client connections.
24    fn listen_address(&self) -> SocketAddr;
25    /// Set the amount of time that a Nonce (used for authentication) will expire and a new Nonce
26    /// will need to be acquired by a client.
27    fn set_nonce_expiry_duration(&mut self, expiry_duration: Duration);
28    /// Provide received data to the [`TurnServerApi`].
29    ///
30    /// Any returned Transmit should be forwarded to the appropriate socket.
31    fn recv<T: AsRef<[u8]>>(
32        &mut self,
33        transmit: Transmit<T>,
34        now: Instant,
35    ) -> Option<Transmit<Vec<u8>>>;
36    /// Poll the [`TurnServerApi`] in order to make further progress.
37    ///
38    /// The returned value indicates what the caller should do.
39    fn poll(&mut self, now: Instant) -> TurnServerPollRet;
40    /// Poll for a new Transmit to send over a socket.
41    fn poll_transmit(&mut self, now: Instant) -> Option<Transmit<Vec<u8>>>;
42    /// Notify the [`TurnServerApi`] that a UDP socket has been allocated (or an error) in response to
43    /// [TurnServerPollRet::AllocateSocketUdp].
44    fn allocated_udp_socket(
45        &mut self,
46        transport: TransportType,
47        local_addr: SocketAddr,
48        remote_addr: SocketAddr,
49        socket_addr: Result<SocketAddr, ()>,
50        now: Instant,
51    );
52}
53
54/// Return value for [poll](TurnServerApi::poll).
55#[derive(Debug)]
56pub enum TurnServerPollRet {
57    /// Wait until the specified time before calling poll() again.
58    WaitUntil(Instant),
59    /// Allocate a UDP socket for a client specified by the client's network 5-tuple.
60    AllocateSocketUdp {
61        /// The transport of the client asking for an allocation.
62        transport: TransportType,
63        /// The TURN server address of the client asking for an allocation.
64        local_addr: SocketAddr,
65        /// The client local address of the client asking for an allocation.
66        remote_addr: SocketAddr,
67    },
68}