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
#[cfg(not(feature = "tokio"))]
use async_io::Async;
use static_assertions::assert_impl_all;
#[cfg(not(feature = "tokio"))]
use std::net::TcpStream;
#[cfg(all(unix, not(feature = "tokio")))]
use std::os::unix::net::UnixStream;
use std::{
collections::{HashMap, HashSet, VecDeque},
convert::TryInto,
sync::Arc,
};
#[cfg(feature = "tokio")]
use tokio::net::TcpStream;
#[cfg(all(unix, feature = "tokio"))]
use tokio::net::UnixStream;
#[cfg(windows)]
use uds_windows::UnixStream;
use zvariant::ObjectPath;
use crate::{
address::{self, Address},
async_lock::RwLock,
names::{InterfaceName, WellKnownName},
raw::Socket,
AuthMechanism, Authenticated, Connection, Error, Guid, Interface, Result,
};
const DEFAULT_MAX_QUEUED: usize = 64;
#[derive(Debug)]
enum Target {
UnixStream(UnixStream),
TcpStream(TcpStream),
Address(Address),
Socket(Box<dyn Socket>),
}
type Interfaces<'a> =
HashMap<ObjectPath<'a>, HashMap<InterfaceName<'static>, Arc<RwLock<dyn Interface>>>>;
#[derive(derivative::Derivative)]
#[derivative(Debug)]
pub struct ConnectionBuilder<'a> {
target: Target,
max_queued: Option<usize>,
guid: Option<&'a Guid>,
p2p: bool,
internal_executor: bool,
#[derivative(Debug = "ignore")]
interfaces: Interfaces<'a>,
names: HashSet<WellKnownName<'a>>,
auth_mechanisms: Option<VecDeque<AuthMechanism>>,
}
assert_impl_all!(ConnectionBuilder<'_>: Send, Sync, Unpin);
impl<'a> ConnectionBuilder<'a> {
pub fn session() -> Result<Self> {
Ok(Self::new(Target::Address(Address::session()?)))
}
pub fn system() -> Result<Self> {
Ok(Self::new(Target::Address(Address::system()?)))
}
pub fn address<A>(address: A) -> Result<Self>
where
A: TryInto<Address>,
A::Error: Into<Error>,
{
Ok(Self::new(Target::Address(
address.try_into().map_err(Into::into)?,
)))
}
#[must_use]
pub fn unix_stream(stream: UnixStream) -> Self {
Self::new(Target::UnixStream(stream))
}
#[must_use]
pub fn tcp_stream(stream: TcpStream) -> Self {
Self::new(Target::TcpStream(stream))
}
#[must_use]
pub fn socket<S: Socket + 'static>(socket: S) -> Self {
Self::new(Target::Socket(Box::new(socket)))
}
#[must_use]
pub fn auth_mechanisms(mut self, auth_mechanisms: &[AuthMechanism]) -> Self {
self.auth_mechanisms = Some(VecDeque::from(auth_mechanisms.to_vec()));
self
}
#[must_use]
pub fn p2p(mut self) -> Self {
self.p2p = true;
self
}
#[must_use]
pub fn server(mut self, guid: &'a Guid) -> Self {
self.guid = Some(guid);
self
}
#[must_use]
pub fn max_queued(mut self, max: usize) -> Self {
self.max_queued = Some(max);
self
}
#[must_use]
pub fn internal_executor(mut self, enabled: bool) -> Self {
self.internal_executor = enabled;
self
}
pub fn serve_at<P, I>(mut self, path: P, iface: I) -> Result<Self>
where
I: Interface,
P: TryInto<ObjectPath<'a>>,
P::Error: Into<Error>,
{
let path = path.try_into().map_err(Into::into)?;
let entry = self.interfaces.entry(path).or_default();
entry.insert(I::name(), Arc::new(RwLock::new(iface)));
Ok(self)
}
pub fn name<W>(mut self, well_known_name: W) -> Result<Self>
where
W: TryInto<WellKnownName<'a>>,
W::Error: Into<Error>,
{
let well_known_name = well_known_name.try_into().map_err(Into::into)?;
self.names.insert(well_known_name);
Ok(self)
}
pub async fn build(self) -> Result<Connection> {
let stream = match self.target {
#[cfg(all(not(feature = "tokio")))]
Target::UnixStream(stream) => Box::new(Async::new(stream)?) as Box<dyn Socket>,
#[cfg(all(unix, feature = "tokio"))]
Target::UnixStream(stream) => Box::new(stream) as Box<dyn Socket>,
#[cfg(all(not(unix), feature = "tokio"))]
Target::UnixStream(_) => return Err(Error::Unsupported),
#[cfg(not(feature = "tokio"))]
Target::TcpStream(stream) => Box::new(Async::new(stream)?) as Box<dyn Socket>,
#[cfg(feature = "tokio")]
Target::TcpStream(stream) => Box::new(stream) as Box<dyn Socket>,
Target::Address(address) => match address.connect().await? {
#[cfg(any(unix, not(feature = "tokio")))]
address::Stream::Unix(stream) => Box::new(stream) as Box<dyn Socket>,
address::Stream::Tcp(stream) => Box::new(stream) as Box<dyn Socket>,
},
Target::Socket(stream) => stream,
};
let auth = match self.guid {
None => {
Authenticated::client(stream, self.auth_mechanisms).await?
}
Some(guid) => {
if !self.p2p {
return Err(Error::Unsupported);
}
#[cfg(unix)]
let client_uid = stream.uid()?;
#[cfg(windows)]
let client_sid = stream.peer_sid();
Authenticated::server(
stream,
guid.clone(),
#[cfg(unix)]
client_uid,
#[cfg(windows)]
client_sid,
self.auth_mechanisms,
)
.await?
}
};
let mut conn = Connection::new(auth, !self.p2p, self.internal_executor).await?;
conn.set_max_queued(self.max_queued.unwrap_or(DEFAULT_MAX_QUEUED));
if !self.interfaces.is_empty() {
let object_server = conn.sync_object_server(false);
for (path, interfaces) in self.interfaces {
for (name, iface) in interfaces {
let future = object_server.at_ready(path.to_owned(), name, || iface);
let added = conn.run_future_at_init(future).await?;
assert!(added);
}
}
conn.start_object_server();
}
for name in self.names {
let future = conn.request_name(name);
conn.run_future_at_init(future).await?;
}
Ok(conn)
}
fn new(target: Target) -> Self {
Self {
target,
p2p: false,
max_queued: None,
guid: None,
internal_executor: true,
interfaces: HashMap::new(),
names: HashSet::new(),
auth_mechanisms: None,
}
}
}