buttplug 2.1.5

Buttplug Intimate Hardware Control Library
Documentation
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use crate::{
  connector::{
    transport::{
      ButtplugConnectorTransport,
      ButtplugConnectorTransportSpecificError,
      ButtplugTransportIncomingMessage,
    },
    ButtplugConnectorError,
    ButtplugConnectorResultFuture,
  },
  core::messages::serializer::ButtplugSerializedMessage,
  util::async_manager,
};
#[cfg(feature = "async-std-runtime")]
use async_std::net::TcpListener;
use async_tls::TlsAcceptor;
use futures::{
  future::{select_all, BoxFuture},
  AsyncRead,
  AsyncWrite,
  FutureExt,
  SinkExt,
  StreamExt,
};
use rustls::{
  internal::pemfile::{certs, pkcs8_private_keys, rsa_private_keys},
  NoClientAuth,
  ServerConfig,
};
use std::{fs::File, io::BufReader, sync::Arc};
use tokio::sync::{
  mpsc::{Receiver, Sender},
  Mutex,
  Notify,
};

#[derive(Default, Clone, Debug)]
pub struct ButtplugWebsocketServerTransportOptions {
  /// If true, listens all on available interfaces. Otherwise, only listens on 127.0.0.1.
  pub ws_listen_on_all_interfaces: bool,
  /// Insecure port for listening for websocket connections.
  pub ws_insecure_port: Option<u16>,
  /// Secure port for listen for websocket connections. Requires cert and key
  /// file options to be passed in also. For secure connections to localhost
  /// (i.e. from browsers that require secure localhost context to native
  /// buttplug-rs), certs should work for 127.0.0.1. Certs signed to "localhost"
  /// may work, but many Buttplug apps default to 127.0.0.1.
  pub ws_secure_port: Option<u16>,
  /// Certificate file for secure connections.
  pub ws_cert_file: Option<String>,
  /// Private key file for secure connections. Key must be > 1024 bit, and in
  /// either RSA or PKCS8 format.
  pub ws_priv_file: Option<String>,
}

async fn run_connection_loop<S>(
  ws_stream: async_tungstenite::WebSocketStream<S>,
  mut request_receiver: Receiver<ButtplugSerializedMessage>,
  response_sender: Sender<ButtplugTransportIncomingMessage>,
  disconnect_notifier: Arc<Notify>,
) where
  S: AsyncRead + AsyncWrite + Unpin,
{
  info!("Starting websocket server connection event loop.");

  let (mut websocket_server_sender, mut websocket_server_receiver) = ws_stream.split();

  loop {
    select! {
      _ = disconnect_notifier.notified().fuse() => {
        info!("Websocket server connector requested disconnect.");
        if websocket_server_sender.close().await.is_err() {
          error!("Cannot close, assuming connection already closed");
          return;
        }
      },
      serialized_msg = request_receiver.recv().fuse() => {
        if let Some(serialized_msg) = serialized_msg {
          match serialized_msg {
            ButtplugSerializedMessage::Text(text_msg) => {
              if websocket_server_sender
                .send(async_tungstenite::tungstenite::Message::Text(text_msg))
                .await
                .is_err() {
                error!("Cannot send text value to server, considering connection closed.");
                return;
              }
            }
            ButtplugSerializedMessage::Binary(binary_msg) => {
              if websocket_server_sender
                .send(async_tungstenite::tungstenite::Message::Binary(binary_msg))
                .await
                .is_err() {
                error!("Cannot send binary value to server, considering connection closed.");
                return;
              }
            }
          }
        } else {
          info!("Websocket server connector owner dropped, disconnecting websocket connection.");
          if websocket_server_sender.close().await.is_err() {
            error!("Cannot close, assuming connection already closed");
            return;
          }
        }
      }
      websocket_server_msg = websocket_server_receiver.next().fuse() => match websocket_server_msg {
        Some(ws_data) => {
          match ws_data {
            Ok(msg) => {
              match msg {
                async_tungstenite::tungstenite::Message::Text(text_msg) => {
                  debug!("Got text: {}", text_msg);
                  if response_sender.send(ButtplugTransportIncomingMessage::Message(ButtplugSerializedMessage::Text(text_msg))).await.is_err() {
                    error!("Connector that owns transport no longer available, exiting.");
                    break;
                  }
                }
                async_tungstenite::tungstenite::Message::Close(_) => {
                  let _ = response_sender.send(ButtplugTransportIncomingMessage::Close("Websocket server closed".to_owned())).await;
                  break;
                }
                async_tungstenite::tungstenite::Message::Ping(_) => {
                  // noop
                  continue;
                }
                async_tungstenite::tungstenite::Message::Pong(_) => {
                  // noop
                  continue;
                }
                async_tungstenite::tungstenite::Message::Binary(_) => {
                  error!("Don't know how to handle binary message types!");
                }
              }
            },
            Err(err) => {
              error!("Error from websocket server, assuming disconnection: {:?}", err);
              let _ = response_sender.send(ButtplugTransportIncomingMessage::Close("Websocket server closed".to_owned())).await;
              break;
            }
          }
        },
        None => {
          error!("Websocket channel closed, breaking");
          return;
        }
      }
    }
  }
}

/// Websocket connector for ButtplugClients, using [async_tungstenite]
pub struct ButtplugWebsocketServerTransport {
  options: ButtplugWebsocketServerTransportOptions,
  disconnect_notifier: Arc<Notify>,
}

impl ButtplugWebsocketServerTransport {
  pub fn new(options: ButtplugWebsocketServerTransportOptions) -> Self {
    Self {
      options,
      disconnect_notifier: Arc::new(Notify::new()),
    }
  }
}

impl ButtplugConnectorTransport for ButtplugWebsocketServerTransport {
  fn connect(
    &self,
    outgoing_receiver: Receiver<ButtplugSerializedMessage>,
    incoming_sender: Sender<ButtplugTransportIncomingMessage>,
  ) -> BoxFuture<'static, Result<(), ButtplugConnectorError>> {
    let disconnect_notifier = self.disconnect_notifier.clone();
    let mut tasks: Vec<BoxFuture<'static, Result<(), ButtplugConnectorError>>> = vec![];

    let base_addr = if self.options.ws_listen_on_all_interfaces {
      "0.0.0.0"
    } else {
      "127.0.0.1"
    };

    let request_receiver = Arc::new(Mutex::new(Some(outgoing_receiver)));

    if let Some(ws_insecure_port) = self.options.ws_insecure_port {
      let addr = format!("{}:{}", base_addr, ws_insecure_port);

      debug!("Websocket Insecure: Trying to listen on {}", addr);
      let request_receiver_clone = request_receiver.clone();
      let response_sender_clone = incoming_sender.clone();
      let disconnect_notifier_clone = disconnect_notifier.clone();

      let fut = async move {
        // Create the event loop and TCP listener we'll accept connections on.
        let try_socket = TcpListener::bind(&addr).await;
        debug!("Websocket Insecure: Socket bound.");
        let listener = try_socket.expect("Failed to bind");
        debug!("Websocket Insecure: Listening on: {}", addr);

        if let Ok((stream, _)) = listener.accept().await {
          info!("Websocket Insecure: Got connection");
          let ws_stream = async_tungstenite::accept_async(stream)
            .await
            .map_err(|err| {
              error!("Websocket server accept error: {:?}", err);
              ButtplugConnectorError::TransportSpecificError(
                ButtplugConnectorTransportSpecificError::SecureServerError(format!(
                  "Error occurred during the websocket handshake: {:?}",
                  err
                )),
              )
            })?;

          async_manager::spawn(async move {
            run_connection_loop(
              ws_stream,
              (*request_receiver_clone.lock().await).take().unwrap(),
              response_sender_clone,
              disconnect_notifier_clone,
            )
            .await;
          })
          .unwrap();
          Ok(())
        } else {
          Err(ButtplugConnectorError::ConnectorGenericError(
            "Could not run accept for insecure port".to_owned(),
          ))
        }
      };
      tasks.push(Box::pin(fut));
    }

    if let Some(ws_secure_port) = self.options.ws_secure_port {
      let options = self.options.clone();
      let request_receiver_clone = request_receiver;
      let response_sender_clone = incoming_sender;
      let disconnect_notifier_clone = disconnect_notifier;

      let fut = async move {
        if options.ws_cert_file.is_none() {
          return Err(ButtplugConnectorError::TransportSpecificError(
            ButtplugConnectorTransportSpecificError::SecureServerError(
              "No cert file provided".to_owned(),
            ),
          ));
        }

        info!("Loading cert file {:?}", options.ws_cert_file);
        let cert_file = File::open(options.ws_cert_file.unwrap()).map_err(|_| {
          ButtplugConnectorError::TransportSpecificError(
            ButtplugConnectorTransportSpecificError::SecureServerError(
              "Specified cert file does not exist or cannot be opened".to_owned(),
            ),
          )
        })?;
        let certs = certs(&mut BufReader::new(cert_file)).map_err(|_| {
          ButtplugConnectorError::TransportSpecificError(
            ButtplugConnectorTransportSpecificError::SecureServerError(
              "Specified cert file cannot load correctly".to_owned(),
            ),
          )
        })?;
        info!("Loaded certificate file");

        if options.ws_priv_file.is_none() {
          return Err(ButtplugConnectorError::TransportSpecificError(
            ButtplugConnectorTransportSpecificError::SecureServerError(
              "No private key file provided".to_owned(),
            ),
          ));
        }

        info!("Loading RSA private key file {:?}", options.ws_priv_file);
        let rsa_key_file = File::open(options.ws_priv_file.clone().unwrap()).map_err(|_| {
          ButtplugConnectorError::TransportSpecificError(
            ButtplugConnectorTransportSpecificError::SecureServerError(
              "Specified private key file does not exist or cannot be opened".to_owned(),
            ),
          )
        })?;

        let mut rsa_key_buf = BufReader::new(rsa_key_file);
        let mut keys = rsa_private_keys(&mut rsa_key_buf).map_err(|e| {
          error!("Cannot load RSA keys: {:?}", e);
          ButtplugConnectorError::TransportSpecificError(
            ButtplugConnectorTransportSpecificError::SecureServerError(
              "Specified private key file cannot load correctly".to_owned(),
            ),
          )
        })?;

        if keys.is_empty() {
          let pkcs8_key_file = File::open(options.ws_priv_file.unwrap()).map_err(|_| {
            ButtplugConnectorError::TransportSpecificError(
              ButtplugConnectorTransportSpecificError::SecureServerError(
                "Specified private key file does not exist or cannot be opened".to_owned(),
              ),
            )
          })?;

          let mut pkcs8_key_buf = BufReader::new(pkcs8_key_file);
          keys = pkcs8_private_keys(&mut pkcs8_key_buf).map_err(|e| {
            error!("Cannot load PKCS8 keys: {:?}", e);
            ButtplugConnectorError::TransportSpecificError(
              ButtplugConnectorTransportSpecificError::SecureServerError(
                "Specified private key file cannot load correctly".to_owned(),
              ),
            )
          })?;
          if keys.is_empty() {
            error!("No keys were loaded, cannot start secure server.");
            return Err(ButtplugConnectorError::TransportSpecificError(
              ButtplugConnectorTransportSpecificError::SecureServerError(
                "Could not load private keys from file".to_owned(),
              ),
            ));
          }
        }
        info!("Loaded private key file");

        // we don't use client authentication
        let mut config = ServerConfig::new(NoClientAuth::new());
        config
          // set this server to use one cert together with the loaded private key
          .set_single_cert(certs, keys.remove(0))
          .map_err(|e| {
            error!("Secure cert config cannot set up: {:?}", e);
            ButtplugConnectorError::TransportSpecificError(
              ButtplugConnectorTransportSpecificError::SecureServerError(
                "Cannot set up cert with provided cert/key pair due to TLS Error".to_owned(),
              ),
            )
          })?;
        let acceptor = TlsAcceptor::from(Arc::new(config));
        let addr = format!("{}:{}", base_addr, ws_secure_port);

        debug!("Websocket Secure: Trying to listen on {}", addr);
        // Create the event loop and TCP listener we'll accept connections on.
        let try_socket = TcpListener::bind(&addr).await;
        debug!("Websocket Secure: Socket bound.");
        let listener = try_socket.expect("Failed to bind");
        debug!("Websocket Secure: Listening on: {}", addr);

        if let Ok((stream, _)) = listener.accept().await {
          let handshake = acceptor.accept(stream);
          // The handshake is a future we can await to get an encrypted
          // stream back.
          let tls_stream = handshake.await.map_err(|e| {
            error!("Secure cert config cannot run handshake: {:?}", e);
            ButtplugConnectorError::TransportSpecificError(
              ButtplugConnectorTransportSpecificError::SecureServerError(format!("{:?}", e)),
            )
          })?;
          info!("Websocket Secure: Got connection");
          let ws_stream = async_tungstenite::accept_async(tls_stream)
            .await
            .map_err(|err| {
              error!("Websocket server accept error: {:?}", err);
              ButtplugConnectorError::TransportSpecificError(
                ButtplugConnectorTransportSpecificError::SecureServerError(format!(
                  "Error occurred during the websocket handshake: {:?}",
                  err
                )),
              )
            })?;
          async_manager::spawn(async move {
            run_connection_loop(
              ws_stream,
              (*request_receiver_clone.lock().await).take().unwrap(),
              response_sender_clone,
              disconnect_notifier_clone,
            )
            .await;
          })
          .unwrap();
          Ok(())
        } else {
          Err(ButtplugConnectorError::ConnectorGenericError(
            "Could not run accept for insecure port".to_owned(),
          ))
        }
      };
      tasks.push(Box::pin(fut));
    }

    Box::pin(async move {
      // Use select_all on the tasks, returning the first one to resolves.
      // Dropping the rest of them means we
      if tasks.is_empty() {
        Err(ButtplugConnectorError::ConnectorGenericError(
          "No ports specified for listening in websocket server connector.".to_owned(),
        ))
      } else if let Err(connector_err) = select_all(tasks).await.0 {
        Err(connector_err)
      } else {
        Ok(())
      }
    })
  }

  fn disconnect(self) -> ButtplugConnectorResultFuture {
    let disconnect_notifier = self.disconnect_notifier;
    Box::pin(async move {
      disconnect_notifier.notify_waiters();
      Ok(())
    })
  }
}