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
use std::net::SocketAddr;

use message_encoding::MessageEncoding;
use playit_agent_proto::control_feed::ControlFeed;
use playit_agent_proto::control_messages::{AgentRegistered, ControlRequest, ControlResponse, Ping, Pong};
use playit_agent_proto::rpc::ControlRpcMessage;

use crate::tunnel::setup::{ConnectedControl, SetupError};
use crate::utils::now_milli;

use super::setup::{AuthenticationProvider, PacketIO};

pub struct AuthenticatedControl<A: AuthenticationProvider, IO: PacketIO> {
    pub(crate) auth: A,
    pub(crate) conn: ConnectedControl<IO>,
    pub(crate) last_pong: Pong,
    pub(crate) registered: AgentRegistered,
    pub(crate) buffer: Vec<u8>,
    pub(crate) current_ping: Option<u32>,

    pub(crate) force_expired: bool,
}

impl<A: AuthenticationProvider, IO: PacketIO> AuthenticatedControl<A, IO> {
    pub async fn send_keep_alive(&mut self, request_id: u64) -> Result<(), ControlError> {
        self.send(ControlRpcMessage {
            request_id,
            content: ControlRequest::AgentKeepAlive(self.registered.id.clone()),
        }).await
    }

    pub async fn send_setup_udp_channel(&mut self, request_id: u64) -> Result<(), ControlError> {
        self.send(ControlRpcMessage {
            request_id,
            content: ControlRequest::SetupUdpChannel(self.registered.id.clone()),
        }).await
    }

    pub async fn send_ping(&mut self, request_id: u64, now: u64) -> Result<(), ControlError> {
        self.send(ControlRpcMessage {
            request_id,
            content: ControlRequest::Ping(Ping { now, current_ping: self.current_ping, session_id: Some(self.registered.id.clone()) }),
        }).await
    }

    pub fn get_expire_at(&self) -> u64 {
        self.registered.expires_at
    }

    pub fn is_expired(&self) -> bool {
        self.force_expired || self.last_pong.session_expire_at.is_none() || self.flow_changed()
    }

    pub fn set_expired(&mut self) {
        self.force_expired = true;
    }

    fn flow_changed(&self) -> bool {
        self.conn.pong.client_addr != self.last_pong.client_addr
    }

    async fn send(&mut self, req: ControlRpcMessage<ControlRequest>) -> Result<(), ControlError> {
        self.buffer.clear();
        req.write_to(&mut self.buffer)?;
        self.conn.udp.send_to(&self.buffer, self.conn.control_addr).await?;
        Ok(())
    }

    pub async fn authenticate(&mut self) -> Result<(), SetupError> {
        let conn = ConnectedControl {
            control_addr: self.conn.control_addr,
            udp: self.conn.udp.clone(),
            pong: self.last_pong.clone(),
        };

        tracing::info!(
            last_pong = ?self.last_pong,
            "authenticate control"
        );

        let res = conn.authenticate(self.auth.clone()).await?;

        *self = res;

        Ok(())
    }

    pub fn into_requires_auth(self) -> ConnectedControl<IO> {
        ConnectedControl {
            control_addr: self.conn.control_addr,
            udp: self.conn.udp,
            pong: self.last_pong,
        }
    }

    pub async fn recv_feed_msg(&mut self) -> Result<ControlFeed, ControlError> {
        self.buffer.resize(1024, 0);

        let (bytes, remote) = self.conn.udp.recv_from(&mut self.buffer).await?;
        if remote != self.conn.control_addr {
            return Err(ControlError::InvalidRemote { expected: self.conn.control_addr, got: remote });
        }

        let mut reader = &self.buffer[..bytes];
        let feed = ControlFeed::read_from(&mut reader).map_err(|e| ControlError::FailedToReadControlFeed(e))?;

        if let ControlFeed::Response(res) = &feed {
            match &res.content {
                ControlResponse::AgentRegistered(registered) => {
                    tracing::info!(details = ?registered, "agent registered");
                    self.registered = registered.clone();
                }
                ControlResponse::Pong(pong) => {
                    self.current_ping = Some((now_milli() - pong.request_now) as u32);
                    self.last_pong = pong.clone();

                    if let Some(expires_at) = pong.session_expire_at {
                        self.registered.expires_at = expires_at;
                    }
                }
                _ => {}
            }
        }

        Ok(feed)
    }
}

#[derive(Debug)]
pub enum ControlError {
    IoError(std::io::Error),
    InvalidRemote { expected: SocketAddr, got: SocketAddr },
    FailedToReadControlFeed(std::io::Error),
}

impl From<std::io::Error> for ControlError {
    fn from(e: std::io::Error) -> Self {
        ControlError::IoError(e)
    }
}