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
//! `kdeconnect-proto` is a pure Rust modular implementation of the
//! [KDE Connect protocol](https://kdeconnect.kde.org).
//!
//! It implements the transport layer as well as full serializing/deserializing of all
//! packet types according to
//! [the specification](https://invent.kde.org/network/kdeconnect-meta/blob/master/protocol.md).
//! It's up to the user of this library to decide what to do when a packet of a specific type is
//! received.
//!
//! It's written using an abstraction over all IO usage, hence it supports a wide range of
//! hardware. A backend using [tokio](https://tokio.rs) is provided by default as well as a
//! backend for embedded devices using [Embassy](https://embassy.dev) in the
//! `kdeconnect-embassy` crate.
//!
//! The entrypoint of the API is the [`Device`](`device::Device`) structure which represents the
//! host device KDE Connect client.
//!
//! This crate has the `embedded` feature which enables the use of a crypto implementation for
//! embedded devices, used in TLS connections. You should enable it if you develop for embedded
//! devices, don't use the default features of this crate, or use `kdeconnect-embassy`.
//!
//! ### Getting started
//!
//! Add to your `Cargo.toml` file `kdeconnect-proto`, `uuid` (with the feature `v4`), `tokio`
//! (with the feature `rt-multi-thread`) and `rcgen`
//! (optional, read the documentation of [`DeviceConfig`](`config::DeviceConfig`) for
//! more information).
//!
//! ```no_run
//! use std::{fs, collections::HashMap, path::{Path, PathBuf}, sync::Arc};
//! use kdeconnect_proto::{
//! config::DeviceConfig,
//! device::{Device, DeviceType, Link},
//! trust::TrustHandler,
//! io::TokioIoImpl,
//! packet::{NetworkPacket, NetworkPacketBody, NetworkPacketType},
//! plugin::Plugin,
//! };
//! use rcgen::{CertificateParams, DistinguishedName, DnType, IsCa, KeyPair};
//!
//! // 1. Generate a self-signed certificate and a private key using rcgen
//!
//! pub fn gen_certificate() {
//! let device_id = uuid::Uuid::new_v4().to_string().replace('-', "");
//! let mut params = CertificateParams::default();
//! params.is_ca = IsCa::ExplicitNoCa;
//!
//! let mut dn = DistinguishedName::new();
//! dn.push(DnType::CommonName, device_id);
//! dn.push(DnType::OrganizationName, "KDE");
//! dn.push(DnType::OrganizationalUnitName, "KDE Connect");
//! params.distinguished_name = dn;
//!
//! let key_pair = KeyPair::generate().unwrap();
//! let cert = params.self_signed(&key_pair).unwrap();
//!
//! fs::write("private_key.pem", key_pair.serialize_pem()).unwrap();
//! fs::write("cert.pem", cert.pem()).unwrap();
//! }
//!
//! // 2. Manage device trust by making a structure implementing the TrustHandler trait
//!
//! struct TrustHandlerImpl {
//! path: PathBuf,
//! trusted_devices: HashMap<String, Vec<u8>>,
//! }
//!
//! impl TrustHandlerImpl {
//! pub fn new<P: AsRef<Path>>(path: P) -> Self {
//! let path = path.as_ref();
//!
//! let trusted_devices = if path.exists() {
//! HashMap::from_iter(fs::read_dir(path).unwrap().filter_map(Result::ok).map(|f| {
//! let device_id = f.path().file_stem().unwrap().to_string_lossy().to_string();
//! let cert = fs::read(f.path()).expect("failed to read certificate");
//! (device_id, cert)
//! }))
//! } else {
//! fs::create_dir_all(path).expect("failed to create directory for trusted devices");
//! HashMap::new()
//! };
//!
//! Self {
//! path: path.to_path_buf(),
//! trusted_devices,
//! }
//! }
//! }
//!
//! #[kdeconnect_proto::async_trait]
//! impl TrustHandler for TrustHandlerImpl {
//! async fn trust_device(&mut self, device_id: String, cert: Vec<u8>) {
//! fs::write(self.path.join(device_id.clone() + ".pem"), &cert).unwrap();
//! self.trusted_devices.insert(device_id, cert);
//! }
//!
//! async fn untrust_device(&mut self, device_id: &str) {
//! fs::remove_file(self.path.join(device_id.to_string() + ".pem")).unwrap();
//! self.trusted_devices.remove(device_id);
//! }
//!
//! async fn get_certificate(&mut self, device_id: &str) -> Option<&[u8]> {
//! self.trusted_devices.get(device_id).map(|v| &**v)
//! }
//! }
//!
//! // 3. Make as many plugins as you need by making structures implementing the Plugin trait
//!
//! struct PingPlugin;
//!
//! #[kdeconnect_proto::async_trait]
//! impl Plugin for PingPlugin {
//! fn supported_incoming_packets(&self) -> Vec<NetworkPacketType> {
//! vec![NetworkPacketType::Ping]
//! }
//!
//! fn supported_outgoing_packets(&self) -> Vec<NetworkPacketType> {
//! vec![NetworkPacketType::Ping]
//! }
//!
//! async fn on_packet_received(
//! &self,
//! packet: &NetworkPacket,
//! link: &Link,
//! ) -> kdeconnect_proto::error::Result<()> {
//! match &packet.body {
//! NetworkPacketBody::Ping(packet) => {
//! let device_name = link
//! .info
//! .device_name
//! .as_ref()
//! .unwrap_or(&link.info.device_id);
//! let msg = if let Some(msg) = &packet.message {
//! format!(" \"{msg}\"")
//! } else {
//! String::new()
//! };
//! println!("PING{msg} from {device_name}!",);
//! }
//! _ => unreachable!(),
//! }
//! Ok(())
//! }
//!
//! async fn on_start(&self, link: &Link) -> kdeconnect_proto::error::Result<()> {
//! link.send(NetworkPacket::ping("Connected")).await;
//! Ok(())
//! }
//! }
//!
//! #[tokio::main]
//! async fn main() {
//! if !Path::new("cert.pem").exists() {
//! gen_certificate();
//! }
//!
//! // 4. Make a device configuration for the host using the DeviceConfig structure
//!
//! let config = DeviceConfig {
//! name: String::from("kdeconnect client"),
//! device_type: DeviceType::Desktop,
//! cert: fs::read("cert.pem").expect("failed to read certificate"),
//! private_key: fs::read("private_key.pem").expect("failed to read private key"),
//! };
//!
//! // 5. Start discovering other devices by calling Device::start or Device::start_arced
//!
//! let device = Device::new(
//! config,
//! vec![Box::new(PingPlugin)],
//! TrustHandlerImpl::new("trusted_devices"),
//! TokioIoImpl,
//! );
//! let device = Arc::new(device);
//! {
//! let device = Arc::clone(&device);
//! std::thread::spawn(move || {
//! device.start_arced();
//! });
//! }
//!
//! // 6. When another device connects, pair with it immediately by calling Device::pair_with
//!
//! println!("Started discovering devices");
//! loop {
//! let link_id = device.wait_for_connection().await;
//! println!("Device {link_id} found");
//! device.pair_with(&link_id).await;
//! }
//! }
//! ```
extern crate alloc;
pub use async_trait;