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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::sync::Arc;
use std::time::Duration;

use tokio::net::UdpSocket;

use playit_agent_proto::control_feed::ControlFeed;
use playit_agent_proto::control_messages::{ControlRequest, ControlResponse, Ping, Pong};
use playit_agent_proto::encoding::MessageEncoding;
use playit_agent_proto::raw_slice::RawSlice;
use playit_agent_proto::rpc::ControlRpcMessage;

use crate::api::api::{AgentVersion, ApiError, ApiErrorNoFail, ApiResponseError, Platform, PlayitAgentVersion, ReqProtoRegister};
use crate::api::http_client::HttpClientError;
use crate::api::PlayitApi;
use crate::tunnel::control::AuthenticatedControl;
use crate::utils::error_helper::ErrorHelper;
use crate::utils::now_milli;

pub struct SetupFindSuitableChannel {
    options: Vec<SocketAddr>,
}

impl SetupFindSuitableChannel {
    pub fn new(options: Vec<SocketAddr>) -> Self {
        SetupFindSuitableChannel { options }
    }

    pub async fn setup(self) -> Result<ConnectedControl, SetupError> {
        let mut buffer: Vec<u8> = Vec::new();

        for addr in self.options {
            tracing::info!(?addr, "trying to establish tunnel connection");

            let is_ip6 = addr.is_ipv6();
            let socket = match UdpSocket::bind(match addr {
                SocketAddr::V4(_) => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)),
                SocketAddr::V6(_) => SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0)),
            }).await {
                Ok(v) => v,
                Err(error) => {
                    tracing::error!(?error, is_ip6 = addr.is_ipv6(), "failed to bind to UdpSocket");
                    continue;
                }
            };

            let attempts = if is_ip6 { 1 } else { 3 };
            for _ in 0..attempts {
                buffer.clear();

                ControlRpcMessage {
                    request_id: 1,
                    content: ControlRequest::Ping(Ping {
                        now: now_milli(),
                        current_ping: None,
                        session_id: None,
                    }),
                }.write_to(&mut buffer)?;

                if let Err(error) = socket.send_to(&buffer, addr).await {
                    tracing::error!(?error, ?addr, "failed to send initial ping");
                    break;
                }

                buffer.resize(2048, 0);

                let waits = if is_ip6 { 3 } else { 5 };
                for i in 0..waits {
                    let res = tokio::time::timeout(
                        Duration::from_millis(500),
                        socket.recv_from(&mut buffer),
                    ).await;

                    match res {
                        Ok(Ok((bytes, peer))) => {
                            if peer != addr {
                                tracing::error!(?peer, ?addr, "got message from different source");
                                continue;
                            }

                            let mut reader = &buffer[..bytes];
                            match ControlFeed::read_from(&mut reader) {
                                Ok(ControlFeed::Response(msg)) => {
                                    if msg.request_id != 1 {
                                        tracing::error!(?msg, "got response with unexpected request_id");
                                        continue;
                                    }

                                    match msg.content {
                                        ControlResponse::Pong(pong) => {
                                            tracing::info!(?pong, "got initial pong from tunnel server");

                                            return Ok(ConnectedControl {
                                                control_addr: addr,
                                                udp: Arc::new(socket),
                                                pong,
                                            });
                                        }
                                        other => {
                                            tracing::error!(?other, "expected pong got other response");
                                        }
                                    }
                                }
                                Ok(other) => {
                                    tracing::error!(?other, "unexpected control feed");
                                }
                                Err(error) => {
                                    tracing::error!(?error, test = ?(), "failed to parse response data");
                                }
                            }
                        }
                        Ok(Err(error)) => {
                            tracing::error!(?error, "failed to receive UDP packet");
                        }
                        Err(_) => {
                            tracing::warn!(%addr, "waited {}ms for pong", (i + 1) * 500);
                        }
                    }
                }

                tracing::error!("timeout waiting for pong");
            }

            tracing::error!("failed to ping tunnel server");
        }

        Err(SetupError::FailedToConnect)
    }
}

fn get_platform() -> Platform {
    #[cfg(target_os = "window")]
    return Platform::Windows;

    #[cfg(target_os = "linux")]
    return Platform::Linux;

    #[cfg(target_os = "freebsd")]
    return Platform::Freebsd;

    #[cfg(target_os = "macos")]
    return Platform::Macos;

    #[cfg(target_os = "android")]
    return Platform::Android;

    #[cfg(target_os = "ios")]
    return Platform::Ios;

    #[allow(unreachable_code)]
    Platform::Unknown
}

#[derive(Debug)]
pub struct ConnectedControl {
    pub(crate) control_addr: SocketAddr,
    pub(crate) udp: Arc<UdpSocket>,
    pub(crate) pong: Pong,
}

impl ConnectedControl {
    pub async fn authenticate(self, api_url: String, secret_key: String) -> Result<AuthenticatedControl, SetupError> {
        let api = PlayitApi::create(api_url, Some(secret_key.clone()));

        let res = api.proto_register(ReqProtoRegister {
            agent_version: PlayitAgentVersion {
                version: AgentVersion {
                    platform: get_platform(),
                    version: env!("CARGO_PKG_VERSION").to_string(),
                },
                official: true,
                details_website: None,
            },
            client_addr: self.pong.client_addr,
            tunnel_addr: self.pong.tunnel_addr,
        }).await.with_error(|error| tracing::error!(?error, "failed to sign and register"))?;

        let bytes = match hex::decode(&res.key) {
            Ok(data) => data,
            Err(_) => return Err(SetupError::FailedToDecodeSignedAgentRegisterHex),
        };

        let mut buffer = Vec::new();

        for _ in 0..5 {
            buffer.clear();

            ControlRpcMessage {
                request_id: 10,
                content: RawSlice(&bytes),
            }.write_to(&mut buffer)?;

            self.udp.send_to(&buffer, self.control_addr).await?;

            for _ in 0..5 {
                buffer.resize(1024, 0);
                match tokio::time::timeout(Duration::from_millis(500), self.udp.recv_from(&mut buffer)).await {
                    Ok(Ok((bytes, remote))) => {
                        if remote != self.control_addr {
                            tracing::warn!("got response not from tunnel server");
                            continue;
                        }

                        let mut reader = &buffer[..bytes];
                        match ControlFeed::read_from(&mut reader) {
                            Ok(ControlFeed::Response(response)) => {
                                if response.request_id != 10 {
                                    tracing::error!(?response, "got response for different request");
                                    continue;
                                }

                                return match response.content {
                                    ControlResponse::RequestQueued => {
                                        tracing::info!("register queued, waiting 1s");
                                        tokio::time::sleep(Duration::from_secs(1)).await;
                                        break;
                                    }
                                    ControlResponse::AgentRegistered(registered) => {
                                        let pong = self.pong.clone();

                                        Ok(AuthenticatedControl {
                                            secret_key,
                                            api_client: api,
                                            conn: self,
                                            last_pong: pong,
                                            registered,
                                            buffer,
                                            current_ping: None,
                                            force_expired: false,
                                        })
                                    }
                                    ControlResponse::InvalidSignature => Err(SetupError::RegisterInvalidSignature),
                                    ControlResponse::Unauthorized => Err(SetupError::RegisterUnauthorized),
                                    other => {
                                        tracing::error!(?other, "expected AgentRegistered but got something else");
                                        continue;
                                    }
                                };
                            }
                            Ok(other) => {
                                tracing::error!(?other, "got unexpected response from register request");
                                continue;
                            }
                            Err(error) => {
                                tracing::error!(?error, "failed to read response from tunnel");
                                continue;
                            }
                        }
                    }
                    Ok(Err(error)) => {
                        tracing::error!(?error, "got error reading from socket");
                        break;
                    }
                    Err(_) => {
                        tracing::error!("timeout waiting for register response");
                        break;
                    }
                }
            }
        }

        Err(SetupError::FailedToConnect)
    }
}

#[derive(Debug)]
pub enum SetupError {
    IoError(std::io::Error),
    FailedToConnect,
    ApiFail(String),
    ApiError(ApiResponseError),
    RequestError(HttpClientError),
    FailedToDecodeSignedAgentRegisterHex,
    NoResponseFromAuthenticate,
    RegisterInvalidSignature,
    RegisterUnauthorized,
}

impl<F: serde::Serialize> From<ApiError<F, HttpClientError>> for SetupError {
    fn from(value: ApiError<F, HttpClientError>) -> Self {
        match value {
            ApiError::ApiError(api) => SetupError::ApiError(api),
            ApiError::ClientError(error) => SetupError::RequestError(error),
            ApiError::Fail(fail) => SetupError::ApiFail(serde_json::to_string(&fail).unwrap())
        }
    }
}

impl From<ApiErrorNoFail<HttpClientError>> for SetupError {
    fn from(value: ApiErrorNoFail<HttpClientError>) -> Self {
        match value {
            ApiErrorNoFail::ApiError(api) => SetupError::ApiError(api),
            ApiErrorNoFail::ClientError(error) => SetupError::RequestError(error),
        }
    }
}

impl Display for SetupError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl Error for SetupError {}

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