Skip to main content

android_auto/
lib.rs

1//! This crate provides android auto functionality for devices wishing to comunicate using the android auto protocol.
2
3#![deny(missing_docs)]
4#![deny(clippy::missing_docs_in_private_items)]
5
6use std::{
7    collections::HashSet,
8    io::{Cursor, Read, Write},
9    sync::Arc,
10};
11
12mod cert;
13
14use ::protobuf::Message;
15use Wifi::ChannelDescriptor;
16#[cfg(feature = "wireless")]
17use bluetooth_rust::{
18    BluetoothRfcommConnectableTrait, BluetoothRfcommProfileTrait, BluetoothStream,
19};
20use futures::StreamExt;
21use rustls::pki_types::{CertificateDer, pem::PemObject};
22use tokio::{
23    io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
24    sync::RwLockReadGuard,
25};
26
27mod avinput;
28use avinput::*;
29mod bluetooth;
30use bluetooth::*;
31mod common;
32use common::*;
33mod control;
34use control::*;
35mod input;
36use input::*;
37mod mediaaudio;
38use mediaaudio::*;
39mod mediastatus;
40use mediastatus::*;
41mod navigation;
42use navigation::*;
43mod sensor;
44use sensor::*;
45mod speechaudio;
46use speechaudio::*;
47mod sysaudio;
48use sysaudio::*;
49mod video;
50use video::*;
51
52#[cfg(feature = "usb")]
53mod usb;
54
55pub use protobuf;
56
57/// Errors that can occur when trying to receive frames
58#[derive(Debug)]
59pub enum FrameReceiptError {
60    /// A timeout occurred when trying to receive the frame header
61    TimeoutHeader,
62    /// The connection was disconnected
63    Disconnected,
64    /// An unexpected error receiving the frame channel id
65    UnexpectedDuringFrameChannel(std::io::Error),
66    /// An unexpected error receiving the frame header
67    UnexpectedDuringFrameHeader(std::io::Error),
68    /// An unexpected error receiving the frame length
69    UnexpectedDuringFrameLength(std::io::Error),
70    /// An unexpected error receiving the frame contents
71    UnexpectedDuringFrameContents(std::io::Error),
72    /// An error occurred calling read_tls with the received frame payload
73    TlsReadError(std::io::Error),
74    /// An error occurred processing tls data received
75    TlsProcessingError(rustls::Error),
76}
77
78/// An error that can occur when transmitting a frame
79#[derive(Debug)]
80pub enum FrameTransmissionError {
81    /// A timeout occurred while transmitting
82    Timeout,
83    /// The connection was disconnected
84    Disconnected,
85    /// An unexpected error
86    Unexpected(std::io::Error),
87}
88
89/// A sequence error in frames received
90#[derive(Debug)]
91pub enum FrameSequenceError {
92    /// Video data was received with the video channel not being open
93    VideoChannelNotOpen,
94}
95
96/// Errors that can occur when either sending or receiving frames
97#[derive(Debug)]
98pub enum FrameIoError {
99    /// An error receiving a frame
100    Rx(FrameReceiptError),
101    /// An error sending a frame
102    Tx(FrameTransmissionError),
103    /// A shutdown was requested
104    ShutdownRequested,
105    /// The client has an incompatible version
106    IncompatibleVersion(u16, u16),
107    /// An error occurred during the ssl handshake
108    SslHandshake(SslHandshakeError),
109    /// A logical error due to frames not being received in the expected order
110    Sequence(FrameSequenceError),
111    /// An error occurred opening the audio input channel
112    AudioInputOpenError,
113    /// An error occurred closing the audio input channel
114    AudioInputCloseError,
115}
116
117/// Errors that can occur during the handshake process
118#[derive(Debug)]
119pub enum SslHandshakeError {
120    /// A timeout occurred
121    Timeout,
122    /// The connection was disconnected
123    Disconnected,
124    /// An unexpected error
125    Unexpected(std::io::Error),
126}
127
128/// Errors that can occur during communication with a client
129#[derive(Debug)]
130pub enum ClientError {
131    /// The root certificate for the ssl communications was invalid
132    InvalidRootCert,
133    /// The client certificate was invalid
134    InvalidClientCertificate,
135    /// The client private key was invalid
136    InvalidClientPrivateKey,
137    /// A communication error
138    IoError(FrameIoError),
139}
140
141impl From<FrameTransmissionError> for FrameIoError {
142    fn from(value: FrameTransmissionError) -> Self {
143        Self::Tx(value)
144    }
145}
146
147impl From<SslHandshakeError> for FrameIoError {
148    fn from(value: SslHandshakeError) -> Self {
149        FrameIoError::SslHandshake(value)
150    }
151}
152
153impl From<FrameSequenceError> for FrameIoError {
154    fn from(value: FrameSequenceError) -> Self {
155        FrameIoError::Sequence(value)
156    }
157}
158
159impl From<FrameIoError> for ClientError {
160    fn from(value: FrameIoError) -> Self {
161        ClientError::IoError(value)
162    }
163}
164
165/// The list of channel handlers for the current android auto instance
166static CHANNEL_HANDLERS: tokio::sync::RwLock<Vec<ChannelHandler>> =
167    tokio::sync::RwLock::const_new(Vec::new());
168
169/// The base trait for crate users to implement
170#[async_trait::async_trait]
171pub trait AndroidAutoMainTrait:
172    AndroidAutoSensorTrait
173    + AndroidAutoAudioOutputTrait
174    + AndroidAutoInputChannelTrait
175    + AndroidAutoAudioInputTrait
176    + AndroidAutoVideoChannelTrait
177    + Send
178    + Sync
179{
180    /// Implement this to indicate that bluetooth hardware is possible, return None if bluetooth hardware is not present
181    #[inline(always)]
182    fn supports_bluetooth(&self) -> Option<&dyn AndroidAutoBluetoothTrait> {
183        None
184    }
185
186    #[cfg(feature = "wireless")]
187    /// Implement this to support wireless android auto communications
188    #[inline(always)]
189    fn supports_wireless(&self) -> Option<Arc<dyn AndroidAutoWirelessTrait>> {
190        None
191    }
192
193    /// Implement this to support wired android auto communications
194    #[inline(always)]
195    fn supports_wired(&self) -> Option<Arc<dyn AndroidAutoWiredTrait>> {
196        None
197    }
198
199    /// Implement this to support navigation
200    fn supports_navigation(&self) -> Option<&dyn AndroidAutoNavigationTrait> {
201        None
202    }
203
204    /// The android auto device just connected
205    async fn connect(&self);
206
207    /// The android auto device disconnected
208    async fn disconnect(&self);
209
210    /// Retrieve the receiver so that the user can send messages to the android auto compatible device or crate
211    async fn get_receiver(&self)
212    -> Option<tokio::sync::mpsc::Receiver<SendableAndroidAutoMessage>>;
213}
214
215/// this trait is implemented by users that support wired (usb) android auto
216#[async_trait::async_trait]
217pub trait AndroidAutoWiredTrait: AndroidAutoMainTrait {}
218
219/// this trait is implemented by users that support bluetooth and wifi (both are required for wireless android auto)
220#[cfg(feature = "wireless")]
221#[async_trait::async_trait]
222pub trait AndroidAutoWirelessTrait: AndroidAutoMainTrait {
223    /// The function to setup the android auto profile
224    async fn setup_bluetooth_profile(
225        &self,
226        suggestions: &bluetooth_rust::BluetoothRfcommProfileSettings,
227    ) -> Result<bluetooth_rust::BluetoothRfcommProfile, String>;
228
229    /// Returns wifi details
230    fn get_wifi_details(&self) -> NetworkInformation;
231}
232
233/// This trait is implemented by users that support navigation indicators
234#[async_trait::async_trait]
235pub trait AndroidAutoSensorTrait {
236    /// Returns the types of sensors supported
237    fn get_supported_sensors(&self) -> &SensorInformation;
238    /// Start the indicated sensor
239    async fn start_sensor(&self, stype: Wifi::sensor_type::Enum) -> Result<(), ()>;
240}
241
242/// This trait is implemented by users that support navigation indicators
243#[async_trait::async_trait]
244pub trait AndroidAutoNavigationTrait: AndroidAutoMainTrait {
245    /// A turn indication update
246    async fn turn_indication(&self, m: Wifi::NavigationTurnEvent);
247    /// A distance indication update
248    async fn distance_indication(&self, m: Wifi::NavigationDistanceEvent);
249    /// A status update
250    async fn nagivation_status(&self, m: Wifi::NavigationStatus);
251}
252
253/// This trait is implemented by users wishing to display a video stream from an android auto (phone probably).
254#[async_trait::async_trait]
255pub trait AndroidAutoVideoChannelTrait {
256    /// Parse a chunk of h264 video data
257    async fn receive_video(&self, data: Vec<u8>, timestamp: Option<u64>);
258    /// Setup the video device to receive h264 video, if anything is required. Return Ok(()) if setup was good, Err(()) if it was not good
259    async fn setup_video(&self) -> Result<(), ()>;
260    /// Tear down the video receiver, may be called without the setup having been called
261    async fn teardown_video(&self);
262    /// Wait for the video to be in focus
263    async fn wait_for_focus(&self);
264    /// Set the focus of the video stream to be as requested
265    async fn set_focus(&self, focus: bool);
266    /// Retrieve the video configuration for the channel
267    fn retrieve_video_configuration(&self) -> &VideoConfiguration;
268}
269
270/// The types of audio channels that can exist
271#[derive(Debug, serde::Serialize, serde::Deserialize)]
272pub enum AudioChannelType {
273    /// Media audio
274    Media,
275    /// System audio
276    System,
277    /// Speech audio
278    Speech,
279}
280
281/// This trait is implemented by users that have audio output capabilities
282#[async_trait::async_trait]
283pub trait AndroidAutoAudioOutputTrait {
284    /// Opens the specified channel
285    async fn open_output_channel(&self, t: AudioChannelType) -> Result<(), ()>;
286    /// Closes the specified channel
287    async fn close_output_channel(&self, t: AudioChannelType) -> Result<(), ()>;
288    /// Receive a chunk of audio data for the specified channel
289    async fn receive_output_audio(&self, t: AudioChannelType, data: Vec<u8>);
290    /// The specified audio channel will start
291    async fn start_output_audio(&self, t: AudioChannelType);
292    /// The specified audio channel will stop
293    async fn stop_output_audio(&self, t: AudioChannelType);
294}
295
296/// This trait is implemented by users that have audio input capabilities
297#[async_trait::async_trait]
298pub trait AndroidAutoAudioInputTrait {
299    /// Opens the channel
300    async fn open_input_channel(&self) -> Result<(), ()>;
301    /// Closes the channel
302    async fn close_input_channel(&self) -> Result<(), ()>;
303    /// The audio channel will start
304    async fn start_input_audio(&self);
305    /// The audio channel will stop
306    async fn stop_input_audio(&self);
307    /// The ack for the audio data
308    async fn audio_input_ack(&self, chan: u8, ack: AVMediaAckIndication);
309}
310
311/// The configuration for an input channel
312#[derive(Clone)]
313pub struct InputConfiguration {
314    /// The supported keycodes
315    pub keycodes: Vec<u32>,
316    /// The touchscreen width and height
317    pub touchscreen: Option<(u16, u16)>,
318}
319
320/// This trait is implemented by users that have inputs for their head unit
321#[async_trait::async_trait]
322pub trait AndroidAutoInputChannelTrait {
323    /// A binding request for the specified keycode, generally the same code reported in `AndroidAutoConfig::keycodes_supported`
324    async fn binding_request(&self, code: u32) -> Result<(), ()>;
325    /// Retrieve the input configuration
326    fn retrieve_input_configuration(&self) -> &InputConfiguration;
327}
328
329/// A trait that is implemented for users that somehow support bluetooth for their hardware
330#[async_trait::async_trait]
331pub trait AndroidAutoBluetoothTrait: AndroidAutoMainTrait {
332    /// Do something
333    async fn do_stuff(&self);
334    /// Get the configuration
335    fn get_config(&self) -> &BluetoothInformation;
336}
337
338/// This is the bluetooth server for initiating wireless android auto on compatible devices.
339pub struct AndroidAutoServer {}
340
341#[allow(missing_docs)]
342#[allow(clippy::missing_docs_in_private_items)]
343mod protobufmod {
344    include!(concat!(env!("OUT_DIR"), "/protobuf/mod.rs"));
345}
346pub use protobufmod::*;
347
348/// The android auto version supported
349const VERSION: (u16, u16) = (1, 1);
350
351/// The types of messages that can be sent over the android auto link
352pub enum AndroidAutoMessage {
353    /// An input message
354    Input(Wifi::InputEventIndication),
355    /// An audio packet message, optional timestamp (microseconds since UNIX_EPOCH) and data
356    Audio(Option<u64>, Vec<u8>),
357    /// A sensor event message
358    Sensor(Wifi::SensorEventIndication),
359    /// An other message
360    Other,
361}
362
363/// The type of channel being sent in a sendable message
364#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
365pub enum SendableChannelType {
366    /// The input channel
367    Input,
368    /// The audio input channel
369    AudioInput,
370    /// The sensor channel
371    Sensor,
372    /// Other channel type
373    Other,
374}
375
376/// The sendable form of an `AndroidAutoMessage`
377#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
378pub struct SendableAndroidAutoMessage {
379    /// The channel id to send the message to
380    channel: SendableChannelType,
381    /// The message body to send
382    data: Vec<u8>,
383}
384
385impl SendableAndroidAutoMessage {
386    /// Convert Self into an `AndroidAutoFrame``
387    async fn into_frame(self) -> AndroidAutoFrame {
388        let mut chan = None;
389        let chans = CHANNEL_HANDLERS.read().await;
390        for (i, c) in chans.iter().enumerate() {
391            match self.channel {
392                SendableChannelType::Sensor => {
393                    if let ChannelHandler::Sensor(_) = c {
394                        chan = Some(i as u8);
395                        break;
396                    }
397                }
398                SendableChannelType::AudioInput => {
399                    if let ChannelHandler::AvInput(_) = c {
400                        chan = Some(i as u8);
401                        break;
402                    }
403                }
404                SendableChannelType::Input => {
405                    if let ChannelHandler::Input(_) = c {
406                        chan = Some(i as u8);
407                        break;
408                    }
409                }
410                SendableChannelType::Other => {
411                    todo!();
412                }
413            }
414        }
415        AndroidAutoFrame {
416            header: FrameHeader {
417                channel_id: chan.unwrap(),
418                frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
419            },
420            data: self.data,
421        }
422    }
423}
424
425/// A message sent from an app user to this crate
426#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
427pub enum AndroidAutoChannelMessageFromApp {
428    /// A message that needs to be forwarded to the android auto device
429    MessageToPhone(SendableAndroidAutoMessage),
430}
431
432impl AndroidAutoMessage {
433    /// Convert the message to something that can be sent, if possible
434    pub fn sendable(self) -> SendableAndroidAutoMessage {
435        match self {
436            Self::Sensor(m) => {
437                let mut data = m.write_to_bytes().unwrap();
438                let t = Wifi::sensor_channel_message::Enum::SENSOR_EVENT_INDICATION as u16;
439                let t = t.to_be_bytes();
440                let mut m = Vec::new();
441                m.push(t[0]);
442                m.push(t[1]);
443                m.append(&mut data);
444                SendableAndroidAutoMessage {
445                    channel: SendableChannelType::Sensor,
446                    data: m,
447                }
448            }
449            Self::Input(m) => {
450                let mut data = m.write_to_bytes().unwrap();
451                let t = Wifi::input_channel_message::Enum::INPUT_EVENT_INDICATION as u16;
452                let t = t.to_be_bytes();
453                let mut m = Vec::new();
454                m.push(t[0]);
455                m.push(t[1]);
456                m.append(&mut data);
457                SendableAndroidAutoMessage {
458                    channel: SendableChannelType::Input,
459                    data: m,
460                }
461            }
462            Self::Audio(_timestamp, mut data) => {
463                let t = Wifi::avchannel_message::Enum::AV_MEDIA_WITH_TIMESTAMP_INDICATION as u16;
464                let t = t.to_be_bytes();
465                let mut m = Vec::new();
466                m.push(t[0]);
467                m.push(t[1]);
468                m.append(&mut data);
469                SendableAndroidAutoMessage {
470                    channel: SendableChannelType::AudioInput,
471                    data: m,
472                }
473            }
474            Self::Other => todo!(),
475        }
476    }
477}
478
479/// A message sent or received in the android auto protocol
480#[cfg(feature = "wireless")]
481struct AndroidAutoRawBluetoothMessage {
482    /// The message type
483    t: u16,
484    /// The message contained in the message
485    message: Vec<u8>,
486}
487
488/// The sensor information supported by the user for android auto
489#[derive(Clone)]
490pub struct SensorInformation {
491    /// The sensor types supported
492    pub sensors: HashSet<Wifi::sensor_type::Enum>,
493}
494
495/// The wireless network information to relay to the compatible android auto device
496#[derive(Clone, Debug)]
497pub struct NetworkInformation {
498    /// The ssid of the wireless network
499    pub ssid: String,
500    /// The password for the wireless network
501    pub psk: String,
502    /// Unsure, probably the mac address of the android auto host
503    pub mac_addr: String,
504    /// The ip address of the android auto host
505    pub ip: String,
506    /// The port that the android auto host should listen on
507    pub port: u16,
508    /// The security mode for the wireless network
509    pub security_mode: Bluetooth::SecurityMode,
510    /// The access point type of the wireless network
511    pub ap_type: Bluetooth::AccessPointType,
512}
513
514/// Information about the head unit that will be providing android auto services for compatible devices
515#[derive(Clone)]
516pub struct HeadUnitInfo {
517    /// The name of the head unit
518    pub name: String,
519    /// The model of the vehicle
520    pub car_model: String,
521    /// The year of the vehicle
522    pub car_year: String,
523    /// The serial number of the vehicle
524    pub car_serial: String,
525    /// True when the vehicle is a left hand drive, false when a right hand drive
526    pub left_hand: bool,
527    /// The manufacturer of the head unit
528    pub head_manufacturer: String,
529    /// The model of the head unit
530    pub head_model: String,
531    /// The software build for the head unit
532    pub sw_build: String,
533    /// The software version for the head unit
534    pub sw_version: String,
535    /// Does the head unit support native media during vr
536    pub native_media: bool,
537    /// Should the clock be hidden?
538    pub hide_clock: Option<bool>,
539}
540
541/// The required bluetooth information
542#[derive(Clone)]
543pub struct BluetoothInformation {
544    /// The mac address of the bluetooth adapter
545    pub address: String,
546}
547
548/// The configuration data for the video stream of android auto
549#[derive(Clone)]
550pub struct VideoConfiguration {
551    /// Defines the desired resolution for the video stream
552    pub resolution: Wifi::video_resolution::Enum,
553    /// The fps for the video stream
554    pub fps: Wifi::video_fps::Enum,
555    /// The dots per inch of the display
556    pub dpi: u16,
557}
558
559/// Provides basic configuration elements for setting up an android auto head unit
560#[derive(Clone)]
561pub struct AndroidAutoConfiguration {
562    /// The head unit information
563    pub unit: HeadUnitInfo,
564    /// The android auto client certificate and private key in pem format (only if a custom one is desired)
565    pub custom_certificate: Option<(Vec<u8>, Vec<u8>)>,
566}
567
568/// The channel identifier for channels in the android auto protocol
569type ChannelId = u8;
570
571/// Specifies the type of frame header, whether the data of a packet is contained in a single frame, or if it was too large and broken up into multiple frames for transmission.
572#[derive(Debug, PartialEq)]
573#[repr(u8)]
574pub enum FrameHeaderType {
575    /// This frame is neither the first or the last of a multi-frame packet
576    Middle = 0,
577    /// This is the first frame of a multi-frame packet
578    First = 1,
579    /// This is the last frame of a multi-frame packet
580    Last = 2,
581    /// The packet is contained in a single frame
582    Single = 3,
583}
584
585impl From<u8> for FrameHeaderType {
586    fn from(value: u8) -> Self {
587        match value & 3 {
588            0 => FrameHeaderType::Middle,
589            1 => FrameHeaderType::First,
590            2 => FrameHeaderType::Last,
591            _ => FrameHeaderType::Single,
592        }
593    }
594}
595
596impl From<FrameHeaderType> for u8 {
597    fn from(value: FrameHeaderType) -> Self {
598        value as u8
599    }
600}
601
602#[allow(missing_docs)]
603/// The frame header module, because bitfield new does not make documentation yet.
604mod frame_header {
605    bitfield::bitfield! {
606        #[derive(Copy, Clone)]
607        pub struct FrameHeaderContents(u8);
608        impl Debug;
609        impl new;
610        u8;
611        /// True indicates the frame is encrypted
612        pub get_encryption, set_encryption: 3;
613        /// The frame header type
614        pub from into super::FrameHeaderType, get_frame_type, set_frame_type: 1, 0;
615        /// True when frame is for control, false when specific
616        pub get_control, set_control: 2;
617    }
618}
619use frame_header::FrameHeaderContents;
620
621#[cfg(feature = "wireless")]
622use crate::Bluetooth::Status;
623use crate::protobufmod::Wifi::AVMediaAckIndication;
624
625/// Represents the header of a frame sent to the android auto client
626#[derive(Copy, Clone, Debug)]
627struct FrameHeader {
628    /// The channelid that this frame is intended for
629    channel_id: ChannelId,
630    /// The contents of the frame header
631    frame: FrameHeaderContents,
632}
633
634impl FrameHeader {
635    /// Add self to the given buffer to build part of a complete frame
636    pub fn add_to(&self, buf: &mut Vec<u8>) {
637        buf.push(self.channel_id);
638        buf.push(self.frame.0);
639    }
640}
641
642/// Responsible for receiving frame headers in the the android auto protocol.
643struct FrameHeaderReceiver {
644    /// The channel id received for a frame header, if one has been received.
645    channel_id: Option<ChannelId>,
646}
647
648impl FrameHeaderReceiver {
649    /// Construct a new self
650    pub fn new() -> Self {
651        Self { channel_id: None }
652    }
653
654    /// Read a frame header from the compatible android auto device
655    /// Returns Ok(Some(p)) when a full frame header is actually received.
656    pub async fn read<T: AsyncRead + Unpin>(
657        &mut self,
658        stream: &mut T,
659    ) -> Result<Option<FrameHeader>, FrameReceiptError> {
660        if self.channel_id.is_none() {
661            let mut b = [0u8];
662            stream
663                .read_exact(&mut b)
664                .await
665                .map_err(|e| match e.kind() {
666                    std::io::ErrorKind::TimedOut => FrameReceiptError::TimeoutHeader,
667                    std::io::ErrorKind::UnexpectedEof => FrameReceiptError::Disconnected,
668                    _ => FrameReceiptError::UnexpectedDuringFrameChannel(e),
669                })?;
670            self.channel_id = ChannelId::try_from(b[0]).ok();
671        }
672        if let Some(channel_id) = &self.channel_id {
673            let mut b = [0u8];
674            stream
675                .read_exact(&mut b)
676                .await
677                .map_err(|e| match e.kind() {
678                    std::io::ErrorKind::TimedOut => FrameReceiptError::TimeoutHeader,
679                    std::io::ErrorKind::UnexpectedEof => FrameReceiptError::Disconnected,
680                    _ => FrameReceiptError::UnexpectedDuringFrameHeader(e),
681                })?;
682            let mut a = FrameHeaderContents::new(false, FrameHeaderType::Single, false);
683            a.0 = b[0];
684            let fh = FrameHeader {
685                channel_id: *channel_id,
686                frame: a,
687            };
688            return Ok(Some(fh));
689        }
690        Ok(None)
691    }
692}
693
694/// A frame of data for comunication in the android auto. When receiving frames, multi-frames are combined into a single frame.
695#[derive(Debug)]
696struct AndroidAutoFrame {
697    /// The header of the frame
698    header: FrameHeader,
699    /// The data actually relayed in the frame
700    data: Vec<u8>,
701}
702
703impl AndroidAutoFrame {
704    /// The largest payload for a single frame
705    const MAX_FRAME_DATA_SIZE: usize = 0x4000;
706    #[allow(dead_code)]
707    /// Currently unused function for building a set of frames for a large packet
708    fn build_multi_frame(f: FrameHeader, d: Vec<u8>) -> Vec<Self> {
709        let mut m = Vec::new();
710        if d.len() < Self::MAX_FRAME_DATA_SIZE {
711            let fr = AndroidAutoFrame { header: f, data: d };
712            m.push(fr);
713        } else {
714            let packets = d.chunks(Self::MAX_FRAME_DATA_SIZE);
715            let max = packets.len();
716            for (i, p) in packets.enumerate() {
717                let first = i == 0;
718                let last = i == (max - 1);
719                let mut h = f;
720                if first {
721                    h.frame.set_frame_type(FrameHeaderType::First);
722                } else if last {
723                    h.frame.set_frame_type(FrameHeaderType::Last);
724                } else {
725                    h.frame.set_frame_type(FrameHeaderType::Middle);
726                }
727                let fr = AndroidAutoFrame {
728                    header: h,
729                    data: p.to_vec(),
730                };
731                m.push(fr);
732            }
733        }
734        m
735    }
736
737    /// Build a vec with the frame that is ready to send out over the connection to the compatible android auto device.
738    /// If necessary, the data will be encrypted.
739    async fn build_vec(&self, stream: Option<&mut rustls::client::ClientConnection>) -> Vec<u8> {
740        let mut buf = Vec::new();
741        self.header.add_to(&mut buf);
742        if self.header.frame.get_encryption() {
743            if let Some(stream) = stream {
744                let mut data = Vec::new();
745                stream.writer().write_all(&self.data).unwrap();
746                stream.write_tls(&mut data).unwrap();
747                let mut p = (data.len() as u16).to_be_bytes().to_vec();
748                buf.append(&mut p);
749                buf.append(&mut data);
750            } else {
751                panic!("No ssl object when encryption was required");
752            }
753        } else {
754            let mut data = self.data.clone();
755            let mut p = (data.len() as u16).to_be_bytes().to_vec();
756            buf.append(&mut p);
757            buf.append(&mut data);
758        }
759        buf
760    }
761}
762
763/// Responsible for receiving a full frame from the compatible android auto device
764struct AndroidAutoFrameReceiver {
765    /// The length of the frame to receive, if it is known yet
766    len: Option<u16>,
767    /// The data received so far for a multi-frame packet
768    rx_sofar: Vec<Vec<u8>>,
769}
770
771impl AndroidAutoFrameReceiver {
772    /// Construct a new frame receiver
773    fn new() -> Self {
774        Self {
775            len: None,
776            rx_sofar: Vec::new(),
777        }
778    }
779
780    /// Read the contents of a frame using the details specified in the header that has already been read.
781    async fn read<T: tokio::io::AsyncRead + Unpin>(
782        &mut self,
783        header: &FrameHeader,
784        stream: &mut T,
785        ssl_stream: &mut rustls::client::ClientConnection,
786    ) -> Result<Option<AndroidAutoFrame>, FrameReceiptError> {
787        if self.len.is_none() {
788            if header.frame.get_frame_type() == FrameHeaderType::First {
789                let mut p = [0u8; 6];
790                stream
791                    .read_exact(&mut p)
792                    .await
793                    .map_err(|e| match e.kind() {
794                        std::io::ErrorKind::TimedOut => FrameReceiptError::TimeoutHeader,
795                        std::io::ErrorKind::UnexpectedEof => FrameReceiptError::Disconnected,
796                        _ => FrameReceiptError::UnexpectedDuringFrameLength(e),
797                    })?;
798                let len = u16::from_be_bytes([p[0], p[1]]);
799                self.len.replace(len);
800            } else {
801                let mut p = [0u8; 2];
802                stream
803                    .read_exact(&mut p)
804                    .await
805                    .map_err(|e| match e.kind() {
806                        std::io::ErrorKind::TimedOut => FrameReceiptError::TimeoutHeader,
807                        std::io::ErrorKind::UnexpectedEof => FrameReceiptError::Disconnected,
808                        _ => FrameReceiptError::UnexpectedDuringFrameLength(e),
809                    })?;
810                let len = u16::from_be_bytes(p);
811                self.len.replace(len);
812            }
813        }
814
815        let decrypt = |ssl_stream: &mut rustls::client::ClientConnection,
816                       _len: u16,
817                       data_frame: Vec<u8>|
818         -> Result<Vec<u8>, FrameReceiptError> {
819            let mut plain_data = vec![0u8; data_frame.len()];
820            let mut cursor = Cursor::new(&data_frame);
821            let mut index = 0;
822            loop {
823                let asdf = ssl_stream
824                    .read_tls(&mut cursor)
825                    .map_err(|e| FrameReceiptError::TlsReadError(e))?;
826                let _ = ssl_stream
827                    .process_new_packets()
828                    .map_err(|e| FrameReceiptError::TlsProcessingError(e))?;
829                if asdf == 0 {
830                    break;
831                }
832                if let Ok(l) = ssl_stream.reader().read(&mut plain_data[index..]) {
833                    index += l;
834                }
835            }
836            Ok(plain_data[0..index].to_vec())
837        };
838
839        if let Some(len) = self.len.take() {
840            let mut data_frame = vec![0u8; len as usize];
841            stream
842                .read_exact(&mut data_frame)
843                .await
844                .map_err(|e| match e.kind() {
845                    std::io::ErrorKind::TimedOut => FrameReceiptError::TimeoutHeader,
846                    std::io::ErrorKind::UnexpectedEof => FrameReceiptError::Disconnected,
847                    _ => FrameReceiptError::UnexpectedDuringFrameContents(e),
848                })?;
849            let data = if header.frame.get_frame_type() == FrameHeaderType::Single {
850                let data_plain = if header.frame.get_encryption() {
851                    decrypt(ssl_stream, len, data_frame)?
852                } else {
853                    data_frame
854                };
855                let d = data_plain.clone();
856                Some(vec![d])
857            } else {
858                let data_plain = if header.frame.get_encryption() {
859                    decrypt(ssl_stream, len, data_frame)?
860                } else {
861                    data_frame
862                };
863                self.rx_sofar.push(data_plain);
864                if header.frame.get_frame_type() == FrameHeaderType::Last {
865                    let d = self.rx_sofar.clone();
866                    self.rx_sofar.clear();
867                    Some(d)
868                } else {
869                    None
870                }
871            };
872            if let Some(data) = data {
873                let data: Vec<u8> = data.into_iter().flatten().collect();
874                let f = AndroidAutoFrame {
875                    header: *header,
876                    data,
877                };
878                let f = Some(f);
879                return Ok(f);
880            }
881        }
882        Ok(None)
883    }
884}
885
886#[cfg(feature = "wireless")]
887/// A message sent or received over the android auto bluetooth connection. Used for setting up wireless android auto.
888enum AndroidAutoBluetoothMessage {
889    /// A request for socket information
890    SocketInfoRequest(Bluetooth::SocketInfoRequest),
891    /// A message relaying network information to the other party
892    NetworkInfoMessage(Bluetooth::NetworkInfo),
893}
894
895#[cfg(feature = "wireless")]
896impl AndroidAutoBluetoothMessage {
897    /// Build an `AndroidAutoMessage` from self
898    fn as_message(&self) -> AndroidAutoRawBluetoothMessage {
899        use protobuf::Message;
900        match self {
901            AndroidAutoBluetoothMessage::SocketInfoRequest(m) => AndroidAutoRawBluetoothMessage {
902                t: Bluetooth::MessageId::BLUETOOTH_SOCKET_INFO_REQUEST as u16,
903                message: m.write_to_bytes().unwrap(),
904            },
905            AndroidAutoBluetoothMessage::NetworkInfoMessage(m) => AndroidAutoRawBluetoothMessage {
906                t: Bluetooth::MessageId::BLUETOOTH_NETWORK_INFO_MESSAGE as u16,
907                message: m.write_to_bytes().unwrap(),
908            },
909        }
910    }
911}
912
913#[cfg(feature = "wireless")]
914impl From<AndroidAutoRawBluetoothMessage> for Vec<u8> {
915    fn from(value: AndroidAutoRawBluetoothMessage) -> Self {
916        let mut buf = Vec::new();
917        let b = value.message.len() as u16;
918        let a = b.to_be_bytes();
919        buf.push(a[0]);
920        buf.push(a[1]);
921        let a = value.t.to_be_bytes();
922        buf.push(a[0]);
923        buf.push(a[1]);
924        for b in value.message {
925            buf.push(b);
926        }
927        buf
928    }
929}
930
931/// The trait that all channel handlers must implement for android auto channels.
932#[enum_dispatch::enum_dispatch]
933trait ChannelHandlerTrait {
934    /// Process data received that is specific to this channel. Return an error for any packets that were not handled that should cause communication to stop.
935    async fn receive_data<
936        T: AndroidAutoMainTrait + ?Sized,
937        U: tokio::io::AsyncRead + Unpin,
938        V: tokio::io::AsyncWrite + Unpin,
939    >(
940        &self,
941        msg: AndroidAutoFrame,
942        stream: &StreamMux<U, V>,
943        _config: &AndroidAutoConfiguration,
944        _main: &T,
945    ) -> Result<(), FrameIoError>;
946
947    /// Construct the channeldescriptor with the channel handler so it can be conveyed to the compatible android auto device
948    fn build_channel<T: AndroidAutoMainTrait + ?Sized>(
949        &self,
950        config: &AndroidAutoConfiguration,
951        chanid: ChannelId,
952        main: &T,
953    ) -> Option<ChannelDescriptor>;
954
955    /// Set the list of all channels for the current channel. Only used for the control channel. This is because the control channel must be created first.
956    fn set_channels(&self, _chans: Vec<ChannelDescriptor>) {}
957}
958
959/// A message sent for an av channel
960#[derive(Debug)]
961enum AvChannelMessage {
962    /// A message to start setup of the av channel
963    SetupRequest(ChannelId, Wifi::AVChannelSetupRequest),
964    /// A message that responds to a setup request
965    SetupResponse(ChannelId, Wifi::AVChannelSetupResponse),
966    /// Message requesting the focus of the video channel to be set
967    VideoFocusRequest(ChannelId, Wifi::VideoFocusRequest),
968    /// Message requesting to open the channel
969    AvChannelOpen(ChannelId, Wifi::AVInputOpenRequest),
970    /// Message indication the focus status of the video stream on the head unit
971    VideoIndicationResponse(ChannelId, Wifi::VideoFocusIndication),
972    /// The stream is about to start
973    StartIndication(ChannelId, Wifi::AVChannelStartIndication),
974    /// The stream is about to stop
975    StopIndication(ChannelId, Wifi::AVChannelStopIndication),
976    /// A media indication message, optionally containing a timestamp
977    MediaIndication(ChannelId, Option<u64>, Vec<u8>),
978    /// An acknowledgement of receiving a media indication message
979    MediaIndicationAck(ChannelId, Wifi::AVMediaAckIndication),
980}
981
982impl From<AvChannelMessage> for AndroidAutoFrame {
983    fn from(value: AvChannelMessage) -> Self {
984        match value {
985            AvChannelMessage::AvChannelOpen(_, _) => unimplemented!(),
986            AvChannelMessage::MediaIndicationAck(chan, m) => {
987                let mut data = m.write_to_bytes().unwrap();
988                let t = Wifi::avchannel_message::Enum::AV_MEDIA_ACK_INDICATION as u16;
989                let t = t.to_be_bytes();
990                let mut m = Vec::new();
991                m.push(t[0]);
992                m.push(t[1]);
993                m.append(&mut data);
994                AndroidAutoFrame {
995                    header: FrameHeader {
996                        channel_id: chan,
997                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
998                    },
999                    data: m,
1000                }
1001            }
1002            AvChannelMessage::SetupRequest(_, _) => unimplemented!(),
1003            AvChannelMessage::SetupResponse(chan, m) => {
1004                let mut data = m.write_to_bytes().unwrap();
1005                let t = Wifi::avchannel_message::Enum::SETUP_RESPONSE as u16;
1006                let t = t.to_be_bytes();
1007                let mut m = Vec::new();
1008                m.push(t[0]);
1009                m.push(t[1]);
1010                m.append(&mut data);
1011                AndroidAutoFrame {
1012                    header: FrameHeader {
1013                        channel_id: chan,
1014                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
1015                    },
1016                    data: m,
1017                }
1018            }
1019            AvChannelMessage::MediaIndication(chan, timestamp, mut data) => {
1020                let (t, mut data) = if let Some(ts) = timestamp {
1021                    let mut m = Vec::new();
1022                    let mut tsb = ts.to_be_bytes().to_vec();
1023                    m.append(&mut tsb);
1024                    m.append(&mut data);
1025                    (
1026                        Wifi::avchannel_message::Enum::AV_MEDIA_WITH_TIMESTAMP_INDICATION as u16,
1027                        m,
1028                    )
1029                } else {
1030                    let mut m = Vec::new();
1031                    m.append(&mut data);
1032                    (Wifi::avchannel_message::Enum::AV_MEDIA_INDICATION as u16, m)
1033                };
1034                let t = t.to_be_bytes();
1035                let mut m = Vec::new();
1036                m.push(t[0]);
1037                m.push(t[1]);
1038                m.append(&mut data);
1039                AndroidAutoFrame {
1040                    header: FrameHeader {
1041                        channel_id: chan,
1042                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
1043                    },
1044                    data: m,
1045                }
1046            }
1047            AvChannelMessage::VideoFocusRequest(_chan, _m) => unimplemented!(),
1048            AvChannelMessage::VideoIndicationResponse(chan, m) => {
1049                let mut data = m.write_to_bytes().unwrap();
1050                let t = Wifi::avchannel_message::Enum::VIDEO_FOCUS_INDICATION as u16;
1051                let t = t.to_be_bytes();
1052                let mut m = Vec::new();
1053                m.push(t[0]);
1054                m.push(t[1]);
1055                m.append(&mut data);
1056                AndroidAutoFrame {
1057                    header: FrameHeader {
1058                        channel_id: chan,
1059                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
1060                    },
1061                    data: m,
1062                }
1063            }
1064            AvChannelMessage::StartIndication(_, _) => unimplemented!(),
1065            AvChannelMessage::StopIndication(_, _) => unimplemented!(),
1066        }
1067    }
1068}
1069
1070impl TryFrom<&AndroidAutoFrame> for AvChannelMessage {
1071    type Error = String;
1072    fn try_from(value: &AndroidAutoFrame) -> Result<Self, Self::Error> {
1073        use protobuf::Enum;
1074        let mut ty = [0u8; 2];
1075        ty.copy_from_slice(&value.data[0..2]);
1076        let ty = u16::from_be_bytes(ty);
1077        if let Some(sys) = Wifi::avchannel_message::Enum::from_i32(ty as i32) {
1078            match sys {
1079                Wifi::avchannel_message::Enum::AV_MEDIA_WITH_TIMESTAMP_INDICATION => {
1080                    let mut b = [0u8; 8];
1081                    b.copy_from_slice(&value.data[2..10]);
1082                    let ts: u64 = u64::from_be_bytes(b);
1083                    Ok(Self::MediaIndication(
1084                        value.header.channel_id,
1085                        Some(ts),
1086                        value.data[10..].to_vec(),
1087                    ))
1088                }
1089                Wifi::avchannel_message::Enum::AV_MEDIA_INDICATION => Ok(Self::MediaIndication(
1090                    value.header.channel_id,
1091                    None,
1092                    value.data[2..].to_vec(),
1093                )),
1094                Wifi::avchannel_message::Enum::SETUP_REQUEST => {
1095                    let m = Wifi::AVChannelSetupRequest::parse_from_bytes(&value.data[2..]);
1096                    match m {
1097                        Ok(m) => Ok(Self::SetupRequest(value.header.channel_id, m)),
1098                        Err(e) => Err(format!("Invalid channel setup request: {}", e)),
1099                    }
1100                }
1101                Wifi::avchannel_message::Enum::START_INDICATION => {
1102                    let m = Wifi::AVChannelStartIndication::parse_from_bytes(&value.data[2..]);
1103                    match m {
1104                        Ok(m) => Ok(Self::StartIndication(value.header.channel_id, m)),
1105                        Err(e) => Err(format!("Invalid channel start request: {}", e)),
1106                    }
1107                }
1108                Wifi::avchannel_message::Enum::STOP_INDICATION => {
1109                    let m = Wifi::AVChannelStopIndication::parse_from_bytes(&value.data[2..]);
1110                    match m {
1111                        Ok(m) => Ok(Self::StopIndication(value.header.channel_id, m)),
1112                        Err(e) => Err(format!("Invalid channel stop request: {}", e)),
1113                    }
1114                }
1115                Wifi::avchannel_message::Enum::SETUP_RESPONSE => unimplemented!(),
1116                Wifi::avchannel_message::Enum::AV_MEDIA_ACK_INDICATION => {
1117                    let m = Wifi::AVMediaAckIndication::parse_from_bytes(&value.data[2..]);
1118                    match m {
1119                        Ok(m) => Ok(Self::MediaIndicationAck(value.header.channel_id, m)),
1120                        Err(e) => Err(format!("Invalid channel stop request: {}", e)),
1121                    }
1122                }
1123                Wifi::avchannel_message::Enum::AV_INPUT_OPEN_REQUEST => {
1124                    let m = Wifi::AVInputOpenRequest::parse_from_bytes(&value.data[2..]);
1125                    match m {
1126                        Ok(m) => Ok(Self::AvChannelOpen(value.header.channel_id, m)),
1127                        Err(e) => Err(format!("Invalid request: {}", e)),
1128                    }
1129                }
1130                Wifi::avchannel_message::Enum::AV_INPUT_OPEN_RESPONSE => todo!(),
1131                Wifi::avchannel_message::Enum::VIDEO_FOCUS_REQUEST => {
1132                    let m = Wifi::VideoFocusRequest::parse_from_bytes(&value.data[2..]);
1133                    match m {
1134                        Ok(m) => Ok(Self::VideoFocusRequest(value.header.channel_id, m)),
1135                        Err(e) => Err(format!("Invalid request: {}", e)),
1136                    }
1137                }
1138                Wifi::avchannel_message::Enum::VIDEO_FOCUS_INDICATION => unimplemented!(),
1139            }
1140        } else {
1141            Err(format!("Not converted message: {:x?}", value.data))
1142        }
1143    }
1144}
1145
1146/// An object that allows multiple tasks to send or receive frames
1147struct StreamMux<T: AsyncRead + Unpin, U: AsyncWrite + Unpin> {
1148    /// The reader for receiving frames from the android auto device
1149    reader: Arc<tokio::sync::Mutex<T>>,
1150    /// The writer for sending frames to the android auto device
1151    writer: Arc<tokio::sync::Mutex<U>>,
1152    /// The object used for tls communication
1153    ssl_client: Arc<tokio::sync::Mutex<rustls::client::ClientConnection>>,
1154}
1155
1156impl<T: AsyncRead + Unpin, U: AsyncWrite + Unpin> Clone for StreamMux<T, U> {
1157    fn clone(&self) -> Self {
1158        Self {
1159            reader: self.reader.clone(),
1160            writer: self.writer.clone(),
1161            ssl_client: self.ssl_client.clone(),
1162        }
1163    }
1164}
1165
1166impl<T: AsyncRead + Unpin, U: AsyncWrite + Unpin> StreamMux<T, U> {
1167    /// Construct a new self
1168    pub fn new(sr: T, ss: U, ssl_client: rustls::client::ClientConnection) -> Self {
1169        Self {
1170            reader: Arc::new(tokio::sync::Mutex::new(sr)),
1171            writer: Arc::new(tokio::sync::Mutex::new(ss)),
1172            ssl_client: Arc::new(tokio::sync::Mutex::new(ssl_client)),
1173        }
1174    }
1175
1176    /// Is the stream currently in handshake process?
1177    pub async fn is_handshaking(&self) -> bool {
1178        let ssl_stream = self.ssl_client.lock().await;
1179        ssl_stream.is_handshaking()
1180    }
1181
1182    /// Start the ssl handshake process
1183    pub async fn start_handshake(&self) -> Result<(), SslHandshakeError> {
1184        let mut w = self.writer.lock().await;
1185        let mut ssl_stream = self.ssl_client.lock().await;
1186        let mut s = Vec::new();
1187        if ssl_stream.wants_write() {
1188            let l = ssl_stream.write_tls(&mut s);
1189            if l.is_ok() {
1190                let f: AndroidAutoFrame = AndroidAutoControlMessage::SslHandshake(s).into();
1191                let d2: Vec<u8> = f.build_vec(Some(&mut *ssl_stream)).await;
1192                w.write_all(&d2).await.map_err(|e| match e.kind() {
1193                    std::io::ErrorKind::TimedOut => SslHandshakeError::Timeout,
1194                    std::io::ErrorKind::UnexpectedEof => SslHandshakeError::Disconnected,
1195                    _ => SslHandshakeError::Unexpected(e),
1196                })?;
1197                let _ = w.flush().await;
1198            }
1199        }
1200        Ok(())
1201    }
1202
1203    /// Continue the handshake process
1204    pub async fn do_handshake(&self, data: Vec<u8>) -> Result<(), SslHandshakeError> {
1205        let mut w = self.writer.lock().await;
1206        let mut ssl_stream = self.ssl_client.lock().await;
1207        if ssl_stream.wants_read() {
1208            let mut dc = std::io::Cursor::new(data);
1209            let _ = ssl_stream.read_tls(&mut dc);
1210            let _ = ssl_stream.process_new_packets();
1211        }
1212        if ssl_stream.wants_write() {
1213            let mut s = Vec::new();
1214            let l = ssl_stream.write_tls(&mut s);
1215            if l.is_ok() {
1216                let f: AndroidAutoFrame = AndroidAutoControlMessage::SslHandshake(s).into();
1217                let d2: Vec<u8> = f.build_vec(Some(&mut *ssl_stream)).await;
1218                w.write_all(&d2).await.map_err(|e| match e.kind() {
1219                    std::io::ErrorKind::TimedOut => SslHandshakeError::Timeout,
1220                    std::io::ErrorKind::UnexpectedEof => SslHandshakeError::Disconnected,
1221                    _ => SslHandshakeError::Unexpected(e),
1222                })?;
1223                let _ = w.flush().await;
1224            }
1225        }
1226        Ok(())
1227    }
1228
1229    /// Read a frame from the stream
1230    pub async fn read_frame(
1231        &self,
1232        fr2: &mut AndroidAutoFrameReceiver,
1233    ) -> Result<AndroidAutoFrame, FrameReceiptError> {
1234        let mut s = self.reader.lock().await;
1235        loop {
1236            let mut fr = FrameHeaderReceiver::new();
1237            let f = fr.read(&mut *s).await?;
1238            let f2 = if let Some(f) = f {
1239                let mut ssl_stream = self.ssl_client.lock().await;
1240                fr2.read(&f, &mut *s, &mut ssl_stream).await?
1241            } else {
1242                None
1243            };
1244            if let Some(f) = f2 {
1245                return Ok(f);
1246            }
1247        }
1248    }
1249
1250    /// Write a frame to the stream, encrypting if necessary
1251    pub async fn write_frame(&self, f: AndroidAutoFrame) -> Result<(), FrameTransmissionError> {
1252        let mut s = self.writer.lock().await;
1253        let mut ssl_stream = self.ssl_client.lock().await;
1254        let d2: Vec<u8> = f.build_vec(Some(&mut *ssl_stream)).await;
1255        let a = s.write_all(&d2).await.map_err(|e| match e.kind() {
1256            std::io::ErrorKind::TimedOut => FrameTransmissionError::Timeout,
1257            std::io::ErrorKind::UnexpectedEof => FrameTransmissionError::Disconnected,
1258            _ => FrameTransmissionError::Unexpected(e),
1259        });
1260        let _ = s.flush().await;
1261        a
1262    }
1263
1264    /// Write a frame to the stream, encrypting if necessary
1265    pub async fn write_sendable(
1266        &self,
1267        f: SendableAndroidAutoMessage,
1268    ) -> Result<(), FrameTransmissionError> {
1269        let mut s = self.writer.lock().await;
1270        let mut ssl_stream = self.ssl_client.lock().await;
1271        let d2: Vec<u8> = f.into_frame().await.build_vec(Some(&mut *ssl_stream)).await;
1272        let a = s.write_all(&d2).await.map_err(|e| match e.kind() {
1273            std::io::ErrorKind::TimedOut => FrameTransmissionError::Timeout,
1274            std::io::ErrorKind::UnexpectedEof => FrameTransmissionError::Disconnected,
1275            _ => FrameTransmissionError::Unexpected(e),
1276        });
1277        let _ = s.flush().await;
1278        a
1279    }
1280}
1281
1282/// The server verifier for android auto head units. This verifies the certificate in the android auto compatible device (probably a phone)
1283#[derive(Debug)]
1284struct AndroidAutoServerVerifier {
1285    /// The object providing most of the functionality for server verification
1286    base: Arc<rustls::client::WebPkiServerVerifier>,
1287}
1288
1289impl AndroidAutoServerVerifier {
1290    /// Build a new server verifier using the given root certificate store
1291    fn new(roots: Arc<rustls::RootCertStore>) -> Self {
1292        Self {
1293            base: rustls::client::WebPkiServerVerifier::builder(roots)
1294                .build()
1295                .unwrap(),
1296        }
1297    }
1298}
1299
1300impl rustls::client::danger::ServerCertVerifier for AndroidAutoServerVerifier {
1301    fn verify_server_cert(
1302        &self,
1303        _end_entity: &rustls::pki_types::CertificateDer<'_>,
1304        _intermediates: &[rustls::pki_types::CertificateDer<'_>],
1305        _server_name: &rustls::pki_types::ServerName<'_>,
1306        _ocsp_response: &[u8],
1307        _now: rustls::pki_types::UnixTime,
1308    ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
1309        Ok(rustls::client::danger::ServerCertVerified::assertion())
1310    }
1311
1312    fn verify_tls12_signature(
1313        &self,
1314        message: &[u8],
1315        cert: &rustls::pki_types::CertificateDer<'_>,
1316        dss: &rustls::DigitallySignedStruct,
1317    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1318        self.base.verify_tls12_signature(message, cert, dss)
1319    }
1320
1321    fn verify_tls13_signature(
1322        &self,
1323        message: &[u8],
1324        cert: &rustls::pki_types::CertificateDer<'_>,
1325        dss: &rustls::DigitallySignedStruct,
1326    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1327        self.base.verify_tls13_signature(message, cert, dss)
1328    }
1329
1330    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
1331        self.base.supported_verify_schemes()
1332    }
1333}
1334
1335/// The channel handler type that covers all possible channel handlers
1336#[enum_dispatch::enum_dispatch(ChannelHandlerTrait)]
1337enum ChannelHandler {
1338    Control(ControlChannelHandler),
1339    Bluetooth(BluetoothChannelHandler),
1340    AvInput(AvInputChannelHandler),
1341    SystemAudio(SystemAudioChannelHandler),
1342    SpeechAudio(SpeechAudioChannelHandler),
1343    Sensor(SensorChannelHandler),
1344    Video(VideoChannelHandler),
1345    Navigation(NavigationChannelHandler),
1346    MediaStatus(MediaStatusChannelHandler),
1347    Input(InputChannelHandler),
1348    MediaAudio(MediaAudioChannelHandler),
1349}
1350
1351/// This is a wrapper around a join handle, it aborts the handle when it is dropped.
1352struct DroppingJoinHandle<T> {
1353    /// The handle for the struct
1354    handle: tokio::task::JoinHandle<T>,
1355}
1356
1357impl<T> Drop for DroppingJoinHandle<T> {
1358    fn drop(&mut self) {
1359        self.handle.abort();
1360    }
1361}
1362
1363#[cfg(feature = "wireless")]
1364/// The handler function for a single bluetooth connection
1365async fn handle_bluetooth_client(
1366    stream: &mut BluetoothStream,
1367    network2: &NetworkInformation,
1368) -> Result<(), String> {
1369    let mut s = Bluetooth::SocketInfoRequest::new();
1370    s.set_ip_address(network2.ip.clone());
1371    s.set_port(network2.port as u32);
1372    log::info!("Got a bluetooth client");
1373    let m1 = AndroidAutoBluetoothMessage::SocketInfoRequest(s);
1374    let m: AndroidAutoRawBluetoothMessage = m1.as_message();
1375    let mdata: Vec<u8> = m.into();
1376    stream.write_all(&mdata).await.map_err(|e| e.to_string())?;
1377    loop {
1378        let mut ty = [0u8; 2];
1379        let mut len = [0u8; 2];
1380        stream
1381            .read_exact(&mut len)
1382            .await
1383            .map_err(|e| e.to_string())?;
1384        stream
1385            .read_exact(&mut ty)
1386            .await
1387            .map_err(|e| e.to_string())?;
1388        let len = u16::from_be_bytes(len);
1389        let ty = u16::from_be_bytes(ty);
1390        let mut message = vec![0; len as usize];
1391        stream
1392            .read_exact(&mut message)
1393            .await
1394            .map_err(|e| e.to_string())?;
1395        use protobuf::Enum;
1396        match Bluetooth::MessageId::from_i32(ty as i32) {
1397            Some(m) => match m {
1398                Bluetooth::MessageId::BLUETOOTH_SOCKET_INFO_REQUEST => {
1399                    log::error!("Got a socket info request {:x?}", message);
1400                    break;
1401                }
1402                Bluetooth::MessageId::BLUETOOTH_NETWORK_INFO_REQUEST => {
1403                    let mut response = Bluetooth::NetworkInfo::new();
1404                    log::debug!("Network info for bluetooth response: {:?}", network2);
1405                    response.set_ssid(network2.ssid.clone());
1406                    response.set_psk(network2.psk.clone());
1407                    response.set_mac_addr(network2.mac_addr.clone());
1408                    response.set_security_mode(network2.security_mode);
1409                    response.set_ap_type(network2.ap_type);
1410                    let response = AndroidAutoBluetoothMessage::NetworkInfoMessage(response);
1411                    let m: AndroidAutoRawBluetoothMessage = response.as_message();
1412                    let mdata: Vec<u8> = m.into();
1413                    let _ = stream.write_all(&mdata).await;
1414                }
1415                Bluetooth::MessageId::BLUETOOTH_SOCKET_INFO_RESPONSE => {
1416                    let message = Bluetooth::SocketInfoResponse::parse_from_bytes(&message);
1417                    log::info!("Message is now {:?}", message);
1418                    if let Ok(m) = message {
1419                        if m.status() == Status::STATUS_SUCCESS {
1420                            break;
1421                        }
1422                    }
1423                }
1424                _ => {}
1425            },
1426            _ => {
1427                log::error!("Unknown bluetooth packet {} {:x?}", ty, message);
1428            }
1429        }
1430        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1431    }
1432    log::info!("Ending bluetooth comms");
1433    Ok(())
1434}
1435
1436#[cfg(feature = "wireless")]
1437/// Runs the bluetooth service that allows wireless android auto connections to start up
1438async fn bluetooth_service(
1439    mut profile: bluetooth_rust::BluetoothRfcommProfile,
1440    wireless: Arc<dyn AndroidAutoWirelessTrait>,
1441) -> Result<(), String> {
1442    log::info!("Starting bluetooth service");
1443    loop {
1444        if let Ok(c) = profile.connectable().await {
1445            let network2 = wireless.get_wifi_details();
1446            let mut stream = c.accept().await?;
1447            let e = handle_bluetooth_client(&mut stream, &network2).await;
1448            log::info!("Bluetooth client disconnected: {:?}", e);
1449        }
1450    }
1451}
1452
1453#[cfg(feature = "wireless")]
1454/// Runs the wifi service for android auto
1455async fn wifi_service<T: AndroidAutoWirelessTrait + Send + ?Sized>(
1456    config: AndroidAutoConfiguration,
1457    wireless: Arc<T>,
1458) -> Result<(), String> {
1459    let network = wireless.get_wifi_details();
1460
1461    log::info!(
1462        "Starting android auto wireless service on port {}",
1463        network.port
1464    );
1465    if let Ok(a) = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", network.port)).await {
1466        log::info!("Starting wifi listener");
1467        if let Ok((stream, _addr)) = a.accept().await {
1468            let config2 = config.clone();
1469            let _ = stream.set_nodelay(true);
1470            wireless.connect().await;
1471            if let Err(e) = handle_client_tcp(stream, config2, wireless.as_ref()).await {
1472                log::error!("Disconnect from client: {:?}", e);
1473            }
1474            wireless.disconnect().await;
1475        }
1476        log::info!("Stopping wifi listener");
1477        Ok(())
1478    } else {
1479        Err(format!("Failed to listen on port {} tcp", network.port))
1480    }
1481}
1482
1483/// Handle a single android auto device for a head unit
1484async fn handle_client_generic<
1485    T: AndroidAutoMainTrait + ?Sized,
1486    R: AsyncRead + Send + Unpin + 'static,
1487    W: AsyncWrite + Send + Unpin + 'static,
1488>(
1489    reader: R,
1490    writer: W,
1491    config: AndroidAutoConfiguration,
1492    main: &T,
1493) -> Result<(), ClientError> {
1494    log::info!("Got android auto client");
1495    let mut root_store =
1496        rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
1497    let aautocertder = {
1498        let mut br = std::io::Cursor::new(cert::AAUTO_CERT.to_string().as_bytes().to_vec());
1499        let aautocertpem = rustls::pki_types::pem::from_buf(&mut br)
1500            .map_err(|_| ClientError::InvalidRootCert)?
1501            .ok_or(ClientError::InvalidRootCert)?;
1502        CertificateDer::from_pem(aautocertpem.0, aautocertpem.1)
1503            .ok_or(ClientError::InvalidRootCert)?
1504    };
1505
1506    let client_cert_data_pem = if let Some(custom) = &config.custom_certificate {
1507        custom
1508    } else {
1509        &(
1510            cert::CERTIFICATE.to_string().as_bytes().to_vec(),
1511            cert::PRIVATE_KEY.to_string().as_bytes().to_vec(),
1512        )
1513    };
1514
1515    let cert = {
1516        let mut br = std::io::Cursor::new(&client_cert_data_pem.0);
1517        let aautocertpem = rustls::pki_types::pem::from_buf(&mut br)
1518            .map_err(|_| ClientError::InvalidClientCertificate)?
1519            .ok_or(ClientError::InvalidClientCertificate)?;
1520        CertificateDer::from_pem(aautocertpem.0, aautocertpem.1)
1521            .ok_or(ClientError::InvalidClientCertificate)?
1522    };
1523    let key = {
1524        let mut br = std::io::Cursor::new(&client_cert_data_pem.1);
1525        let aautocertpem = rustls::pki_types::pem::from_buf(&mut br)
1526            .map_err(|_| ClientError::InvalidClientPrivateKey)?
1527            .ok_or(ClientError::InvalidClientPrivateKey)?;
1528        rustls::pki_types::PrivateKeyDer::from_pem(aautocertpem.0, aautocertpem.1)
1529            .ok_or(ClientError::InvalidClientPrivateKey)?
1530    };
1531    let cert = vec![cert];
1532    root_store
1533        .add(aautocertder)
1534        .map_err(|_| ClientError::InvalidRootCert)?;
1535    let root_store = Arc::new(root_store);
1536    let mut ssl_client_config = rustls::ClientConfig::builder()
1537        .with_root_certificates(root_store.clone())
1538        .with_client_auth_cert(cert, key)
1539        .unwrap();
1540    let sver = Arc::new(AndroidAutoServerVerifier::new(root_store));
1541    ssl_client_config.dangerous().set_certificate_verifier(sver);
1542    let sslconfig = Arc::new(ssl_client_config);
1543    let server = "idontknow.com".try_into().unwrap();
1544    let ssl_client =
1545        rustls::ClientConnection::new(sslconfig, server).expect("Failed to build ssl client");
1546    let sm = StreamMux::new(reader, writer, ssl_client);
1547    let message_recv = main.get_receiver().await;
1548    let sm2 = sm.clone();
1549    let kill = tokio::sync::oneshot::channel::<()>();
1550    let _task2 = if let Some(mut msgr) = message_recv {
1551        let jh: tokio::task::JoinHandle<Result<(), FrameTransmissionError>> =
1552            tokio::task::spawn(async move {
1553                while let Some(m) = msgr.recv().await {
1554                    if let Err(e) = sm2.write_sendable(m).await {
1555                        log::error!("Error passing message: {:?}", e);
1556                        let _ = kill.0.send(());
1557                        return Err(e);
1558                    }
1559                }
1560                Ok(())
1561            });
1562        Some(DroppingJoinHandle { handle: jh })
1563    } else {
1564        None
1565    };
1566    log::info!("Sending channel handlers");
1567    {
1568        let mut channel_handlers: Vec<ChannelHandler> = Vec::new();
1569        channel_handlers.push(ControlChannelHandler::new().into());
1570        channel_handlers.push(InputChannelHandler {}.into());
1571        channel_handlers.push(SensorChannelHandler {}.into());
1572        channel_handlers.push(VideoChannelHandler::new().into());
1573        channel_handlers.push(MediaAudioChannelHandler {}.into());
1574        channel_handlers.push(SpeechAudioChannelHandler {}.into());
1575        channel_handlers.push(SystemAudioChannelHandler {}.into());
1576        channel_handlers.push(AvInputChannelHandler {}.into());
1577        if main.supports_bluetooth().is_some() {
1578            channel_handlers.push(BluetoothChannelHandler {}.into());
1579        }
1580        if main.supports_navigation().is_some() {
1581            channel_handlers.push(NavigationChannelHandler {}.into());
1582        }
1583        channel_handlers.push(MediaStatusChannelHandler {}.into());
1584
1585        let mut chans = Vec::new();
1586        for (index, handler) in channel_handlers.iter().enumerate() {
1587            let chan: ChannelId = index as u8;
1588            if let Some(chan) = handler.build_channel(&config, chan, main) {
1589                chans.push(chan);
1590            }
1591        }
1592        channel_handlers.get_mut(0).unwrap().set_channels(chans);
1593        {
1594            let mut ch = CHANNEL_HANDLERS.write().await;
1595            ch.clear();
1596            log::error!(
1597                "Adding {} channels to CHANNEL_HANDLERS",
1598                channel_handlers.len()
1599            );
1600            ch.append(&mut channel_handlers);
1601        }
1602    }
1603    log::info!("Sending version request");
1604    sm.write_frame(AndroidAutoControlMessage::VersionRequest.into())
1605        .await
1606        .map_err(|e| {
1607            let e2: FrameIoError = e.into();
1608            e2
1609        })?;
1610    let mut fr2 = AndroidAutoFrameReceiver::new();
1611    let channel_handlers = CHANNEL_HANDLERS.read().await;
1612    log::debug!("Waiting on first packet from android auto client");
1613
1614    tokio::select! {
1615        a = do_android_auto_loop(fr2, channel_handlers, sm, config, main) => {
1616
1617        }
1618        _ = kill.1 => {
1619
1620        }
1621    }
1622    Ok(())
1623}
1624
1625async fn do_android_auto_loop<
1626    T: AndroidAutoMainTrait + ?Sized,
1627    R: AsyncRead + Send + Unpin + 'static,
1628    W: AsyncWrite + Send + Unpin + 'static,
1629>(
1630    mut fr2: AndroidAutoFrameReceiver,
1631    channel_handlers: RwLockReadGuard<'_, Vec<ChannelHandler>>,
1632    sm: StreamMux<R, W>,
1633    config: AndroidAutoConfiguration,
1634    main: &T,
1635) -> Result<(), ClientError> {
1636    loop {
1637        if let Ok(f) = sm.read_frame(&mut fr2).await {
1638            if let Some(handler) = channel_handlers.get(f.header.channel_id as usize) {
1639                handler.receive_data(f, &sm, &config, main).await?;
1640            } else {
1641                panic!("Unknown channel id: {:?}", f.header.channel_id);
1642            }
1643        }
1644    }
1645}
1646
1647#[cfg(feature = "wireless")]
1648/// Handle a single android auto device for a head unit
1649async fn handle_client_tcp<T: AndroidAutoMainTrait + ?Sized>(
1650    stream: tokio::net::TcpStream,
1651    config: AndroidAutoConfiguration,
1652    main: &T,
1653) -> Result<(), ClientError> {
1654    let stream = stream.into_split();
1655    handle_client_generic(stream.0, stream.1, config, main).await
1656}
1657
1658#[cfg(feature = "usb")]
1659/// Handle a single android auto device for a head unit
1660async fn handle_client_usb<T: AndroidAutoMainTrait + ?Sized>(
1661    stream: usb::AndroidAutoUsb,
1662    config: AndroidAutoConfiguration,
1663    main: &T,
1664) -> Result<(), ClientError> {
1665    let stream = stream.into_split();
1666    handle_client_generic(stream.0, stream.1, config, main).await
1667}
1668
1669#[cfg(feature = "usb")]
1670/// Watch for a usb disconnect message from nusb
1671async fn watch_for_disconnect(device_address: nusb::DeviceInfo) {
1672    let mut watcher = nusb::watch_devices().unwrap();
1673    while let Some(event) = watcher.next().await {
1674        match event {
1675            nusb::hotplug::HotplugEvent::Disconnected(info) => {
1676                let devs = nusb::list_devices().await;
1677                if let Ok(mut devs) = devs {
1678                    if devs
1679                        .find(|a| {
1680                            a.busnum() == device_address.busnum()
1681                                && a.device_address() == device_address.device_address()
1682                        })
1683                        .is_none()
1684                    {
1685                        log::info!("Android Auto USB device disconnected");
1686                        break;
1687                    }
1688                } else {
1689                    break;
1690                }
1691            }
1692            _ => {}
1693        }
1694    }
1695}
1696
1697#[cfg(feature = "usb")]
1698/// Run a single usb device for android auto
1699async fn do_usb_iteration<T: AndroidAutoMainTrait + Send + 'static>(
1700    d: nusb::DeviceInfo,
1701    config: &AndroidAutoConfiguration,
1702    main: &T,
1703) -> Result<(), ()> {
1704    match d.open().await {
1705        Ok(d) => {
1706            let aoa = usb::get_aoa_protocol(&d).await;
1707            log::info!("AOA is {:?}", aoa);
1708            usb::identify_accessory(&d).await;
1709            usb::accessory_start(&d).await;
1710        }
1711        Err(e) => {
1712            log::error!("Failed to open android device {e}");
1713            return Err(());
1714        }
1715    }
1716    match tokio::time::timeout(
1717        std::time::Duration::from_millis(2000),
1718        usb::wait_for_accessory(),
1719    )
1720    .await
1721    {
1722        Ok(Ok(newdev)) => {
1723            let _ = newdev.reset().await;
1724        }
1725        Ok(Err(e)) => {
1726            log::error!("Failed to get accessory {e}");
1727            return Err(());
1728        }
1729        Err(_e) => {
1730            log::error!("Timeout get accessory");
1731            return Err(());
1732        }
1733    }
1734    match tokio::time::timeout(
1735        std::time::Duration::from_millis(2000),
1736        usb::wait_for_accessory(),
1737    )
1738    .await
1739    {
1740        Ok(Ok(newdev)) => {
1741            log::info!("AOA DEV IS {:?}", newdev);
1742            let aoa = usb::claim_aoa_interface(&newdev).await;
1743            let aauto = usb::AndroidAutoUsb::new(aoa);
1744            if let Some(aauto) = aauto {
1745                log::info!("got aoa interface?");
1746                tokio::select! {
1747                    a = handle_client_usb(aauto, config.clone(), main) => {
1748                        log::info!("handled usb client: {:?}", a);
1749                    }
1750                    _ = watch_for_disconnect(d) => {
1751                        log::info!("USB DISCONNECTED");
1752                    }
1753                }
1754                main.disconnect().await;
1755                Ok(())
1756            } else {
1757                Err(())
1758            }
1759        }
1760        Ok(Err(e)) => {
1761            log::error!("Failed to get accessory 2 {e}");
1762            Err(())
1763        }
1764        Err(_e) => {
1765            log::error!("Timeout get accessory 2");
1766            return Err(());
1767        }
1768    }
1769}
1770
1771impl AndroidAutoServer {
1772    /// Runs the android auto server
1773    pub async fn run<T: AndroidAutoMainTrait + Send + 'static>(
1774        self,
1775        config: AndroidAutoConfiguration,
1776        js: &mut tokio::task::JoinSet<Result<(), String>>,
1777        main: T,
1778    ) -> Result<(), String> {
1779        log::info!("Running android auto server");
1780        #[cfg(feature = "usb")]
1781        {
1782            if main.supports_wired().is_some() {
1783                if let Ok(mut watcher) = nusb::watch_devices() {
1784                    js.spawn(async move {
1785                        use futures::StreamExt;
1786                        log::info!("Looking for usb devices");
1787                        if let Ok(devs) = nusb::list_devices().await {
1788                            let mut start_device = None;
1789                            for dev in devs {
1790                                if usb::is_android_device(&dev) {
1791                                    start_device = Some(dev);
1792                                }
1793                            }
1794                            let d = if let Some(d) = start_device {
1795                                log::info!("Startup device {:?}", d);
1796                                d
1797                            } else {
1798                                let device = loop {
1799                                    if let Some(dev) = watcher.next().await {
1800                                        use nusb::hotplug::HotplugEvent;
1801                                        if let HotplugEvent::Connected(di) = dev {
1802                                            if usb::is_android_device(&di) {
1803                                                log::info!("Hotplug device {:?}", di);
1804                                                tokio::time::sleep(
1805                                                    std::time::Duration::from_millis(500),
1806                                                )
1807                                                .await;
1808                                                break di;
1809                                            }
1810                                        }
1811                                    }
1812                                };
1813                                device
1814                            };
1815                            let _ = do_usb_iteration(d, &config, &main).await;
1816                        }
1817                        Ok(())
1818                    });
1819                }
1820            }
1821        }
1822        #[cfg(feature = "wireless")]
1823        if let Some(wireless) = main.supports_wireless() {
1824            let psettings = bluetooth_rust::BluetoothRfcommProfileSettings {
1825                uuid: bluetooth_rust::BluetoothUuid::AndroidAuto
1826                    .as_str()
1827                    .to_string(),
1828                name: Some("Android Auto Bluetooth Service".to_string()),
1829                service_uuid: Some(
1830                    bluetooth_rust::BluetoothUuid::AndroidAuto
1831                        .as_str()
1832                        .to_string(),
1833                ),
1834                channel: Some(22),
1835                psm: None,
1836                authenticate: Some(true),
1837                authorize: Some(true),
1838                auto_connect: Some(true),
1839                sdp_record: None,
1840                sdp_version: None,
1841                sdp_features: None,
1842            };
1843
1844            let profile = wireless.setup_bluetooth_profile(&psettings).await?;
1845            log::info!("Setup bluetooth profile is ok?");
1846            let wireless2 = wireless.clone();
1847            let kill = tokio::sync::oneshot::channel::<()>();
1848            js.spawn(async move {
1849                tokio::select! {
1850                    e = bluetooth_service(profile, wireless2) => {
1851                        log::error!("Android auto bluetooth service stopped: {:?}", e);
1852                        e
1853                    }
1854                    _ = kill.1 => {
1855                        Ok(())
1856                    }
1857                }
1858            });
1859            let e = wifi_service(config, wireless.clone()).await;
1860            let _ = kill.0.send(());
1861            log::error!("Android auto wireless service stopped: {:?}", e);
1862        }
1863        Ok(())
1864    }
1865
1866    /// Construct a new self
1867    pub async fn new() -> Self {
1868        Self {}
1869    }
1870}
1871
1872/// Perform any setup required on startup of the library
1873pub fn setup() {
1874    let cp = rustls::crypto::ring::default_provider();
1875    cp.install_default().expect("Failed to set ssl provider");
1876}