1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4mod callback;
5pub mod device_info;
6pub use callback::CallbackListener;
7pub use smgw::management::{
8 FIXTURE_RECIPIENT, ProfileWindow, ReadOutcome, parse_recipient, peer_fingerprint,
9};
10use smgw::management::{TlsEndpoint, load_endpoint, read_provisioned_pem, request_profile_outcome};
11pub use smgw::taf15::Record;
12use smgw::wakeup::{WakeUpPrefix, valid_recipient};
13use smgw_sec::{openssl::BrainpoolP256SigningKey, transport::check_loopback};
14use std::sync::Arc;
15use std::{
16 io,
17 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
18 path::Path,
19 time::Duration,
20};
21use tokio::io::AsyncReadExt;
22use tokio::{
23 net::{TcpListener, UdpSocket},
24 time::timeout,
25};
26
27pub struct CommissionedGateway {
29 recipient: [u8; 9],
30 endpoint: Arc<TlsEndpoint>,
31 signer: BrainpoolP256SigningKey,
32}
33
34impl CommissionedGateway {
35 pub fn load(bundle: &Path, recipient: [u8; 9]) -> io::Result<Self> {
37 if !valid_recipient(&recipient) {
38 return Err(io::Error::new(
39 io::ErrorKind::InvalidInput,
40 "invalid gateway recipient",
41 ));
42 }
43 Ok(Self {
44 recipient,
45 endpoint: Arc::new(load_endpoint(bundle)?),
46 signer: BrainpoolP256SigningKey::from_pem(&read_provisioned_pem(
47 bundle.join("wakeup.key.pem"),
48 )?)?,
49 })
50 }
51
52 pub fn recipient(&self) -> [u8; 9] {
54 self.recipient
55 }
56
57 pub fn peer_fingerprint(&self) -> [u8; 32] {
59 self.endpoint.peer_fingerprint()
60 }
61
62 fn packet(&self, timestamp: i64) -> io::Result<[u8; 108]> {
63 let prefix = WakeUpPrefix::new(self.recipient, timestamp)
64 .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
65 let (r, s) = self.signer.sign(prefix.as_bytes())?;
66 Ok(prefix.with_p256_signature(&r, &s))
67 }
68
69 pub async fn read_shared(
71 &self,
72 listener: &CallbackListener,
73 wakeup: SocketAddr,
74 timestamp: i64,
75 window: ProfileWindow,
76 ) -> io::Result<ReadOutcome> {
77 let packet = self.packet(timestamp)?;
78 let id = smgw::management::callback_id(&packet);
79 let (_registration, rx) = listener.arm(id, self.endpoint.clone())?;
80 budget(async {
81 send(&packet, wakeup).await?;
82 let mut tls = rx
83 .await
84 .map_err(|_| io::Error::other("callback listener closed"))?;
85 request_profile_outcome(&mut tls, window).await
86 })
87 .await
88 }
89
90 pub async fn bind(
93 &self,
94 listen: SocketAddr,
95 wakeup: SocketAddr,
96 ) -> io::Result<ReadExchange<'_>> {
97 check_loopback(listen)?;
98 check_loopback(wakeup)?;
99 if wakeup.port() == 0 {
100 return Err(io::Error::new(
101 io::ErrorKind::InvalidInput,
102 "expected a bound gateway wake-up port",
103 ));
104 }
105 let listener = TcpListener::bind(listen).await?;
106 Ok(ReadExchange {
107 gateway: self,
108 listener,
109 wakeup,
110 })
111 }
112}
113
114pub struct ReadExchange<'a> {
116 gateway: &'a CommissionedGateway,
117 listener: TcpListener,
118 wakeup: SocketAddr,
119}
120
121impl ReadExchange<'_> {
122 pub fn local_addr(&self) -> io::Result<SocketAddr> {
124 self.listener.local_addr()
125 }
126
127 pub async fn read(
131 self,
132 timestamp: i64,
133 window: ProfileWindow,
134 mut on_rejected: impl FnMut(&io::Error),
135 ) -> io::Result<ReadOutcome> {
136 let packet = self.gateway.packet(timestamp)?;
137 let id = smgw::management::callback_id(&packet);
138 budget(async {
139 send(&packet, self.wakeup).await?;
140 loop {
141 let (mut tcp, _) = self.listener.accept().await?;
142 let authenticate = async {
143 let mut hint = [0; 32];
144 tcp.read_exact(&mut hint).await?;
145 if hint != id {
146 return Err(io::Error::other("unrecognized callback attempt"));
147 }
148 callback::authenticate(&self.gateway.endpoint, tcp, id).await
149 };
150 match timeout(Duration::from_secs(2), authenticate)
151 .await
152 .map_err(io::Error::from)
153 .and_then(|r| r)
154 {
155 Ok(mut tls) => return request_profile_outcome(&mut tls, window).await,
156 Err(error) => on_rejected(&error),
157 }
158 }
159 })
160 .await
161 }
162}
163
164async fn send(packet: &[u8], wakeup: SocketAddr) -> io::Result<()> {
165 check_loopback(wakeup)?;
166 let source = if wakeup.is_ipv4() {
167 IpAddr::V4(Ipv4Addr::LOCALHOST)
168 } else {
169 IpAddr::V6(Ipv6Addr::LOCALHOST)
170 };
171 UdpSocket::bind(SocketAddr::new(source, 0))
172 .await?
173 .send_to(packet, wakeup)
174 .await?;
175 Ok(())
176}
177async fn budget<T>(operation: impl Future<Output = io::Result<T>>) -> io::Result<T> {
178 timeout(Duration::from_secs(12), operation)
179 .await
180 .map_err(|_| {
181 io::Error::new(
182 io::ErrorKind::TimedOut,
183 "management read timed out waiting for the commissioned gateway",
184 )
185 })?
186}