1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use std::env;
use std::net::{TcpStream,ToSocketAddrs};
use std::io;
use std::io::{Read,Write};
use std::ops::Deref;
use std::path::Path;
use std::str::FromStr;
use libc;
use unix_socket::UnixStream;
use rustc_serialize::hex::ToHex;
use dbus_serialize::types::Value;
use dbus_serialize::decoder::DBusDecoder;
use address;
use address::ServerAddress;
use message;
use message::{Message,HeaderField};
use demarshal::{demarshal,DemarshalError};
use marshal::Marshal;
trait StreamSocket : Read + Write { }
impl<T: Read + Write> StreamSocket for T {}
enum Socket {
Tcp(TcpStream),
Uds(UnixStream)
}
pub struct Connection {
sock: Socket,
next_serial: u32,
queue: Vec<Message>,
}
#[derive(Debug)]
pub enum Error {
Disconnected,
IOError(io::Error),
DemarshalError(DemarshalError),
AddressError(address::ServerAddressError),
BadData,
AuthFailed,
NoEnvironment,
}
impl From<io::Error> for Error {
fn from(x: io::Error) -> Self {
Error::IOError(x)
}
}
impl From<DemarshalError> for Error {
fn from(x: DemarshalError) -> Self {
Error::DemarshalError(x)
}
}
impl From<address::ServerAddressError> for Error {
fn from(x: address::ServerAddressError) -> Self {
Error::AddressError(x)
}
}
fn read_exactly(sock: &mut StreamSocket, buf: &mut Vec<u8>, len: usize) -> Result<(),Error> {
buf.truncate(0);
buf.reserve(len);
if try!(sock.take(len as u64).read_to_end(buf)) != len {
return Err(Error::Disconnected);
}
Ok(())
}
fn read_line(sock: &mut StreamSocket) -> Result<String,Error> {
let mut line = "".to_string();
let mut last = '\0';
loop {
let mut buf = vec![0];
match sock.read(&mut buf) {
Ok(x) if x > 0 => (),
_ => return Err(Error::Disconnected)
};
let chr = buf[0] as char;
line.push(chr);
if chr == '\n' && last == '\r' {
break;
}
last = chr;
}
Ok(line)
}
impl Connection {
fn get_sock(&mut self) -> &mut StreamSocket {
match self.sock {
Socket::Tcp(ref mut x) => x,
Socket::Uds(ref mut x) => x
}
}
fn send_nul_byte(&mut self) -> Result<(),Error> {
let sock = self.get_sock();
let buf = vec![0];
try!(sock.write_all(&buf));
Ok(())
}
fn auth_anonymous(&mut self) -> Result<(),Error> {
let sock = self.get_sock();
try!(sock.write_all(b"AUTH ANONYMOUS 6c69626462757320312e382e3132\r\n"));
let resp = try!(read_line(sock));
if !resp.starts_with("OK ") {
return Err(Error::AuthFailed);
}
try!(sock.write_all(b"BEGIN\r\n"));
Ok(())
}
fn auth_external(&mut self) -> Result<(),Error> {
let sock = self.get_sock();
let uid = unsafe {
libc::funcs::posix88::unistd::getuid()
};
let uid_str = uid.to_string();
let uid_hex = uid_str.into_bytes().to_hex();
let cmd = "AUTH EXTERNAL ".to_string() + &uid_hex + "\r\n";
try!(sock.write_all(&cmd.into_bytes()));
let resp = try!(read_line(sock));
if !resp.starts_with("OK ") {
return Err(Error::AuthFailed);
}
try!(sock.write_all(b"BEGIN\r\n"));
Ok(())
}
fn say_hello(&mut self) -> Result<(),Error> {
let mut msg = message::create_method_call("org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"Hello");
try!(self.call_sync(&mut msg));
Ok(())
}
fn connect_addr(addr: ServerAddress) -> Result<Connection,Error> {
match addr {
ServerAddress::Unix(unix) => Self::connect_uds(unix.path()),
ServerAddress::Tcp(tcp) => Self::connect_tcp(tcp),
}
}
pub fn connect(addr: &str) -> Result<Connection, Error> {
Self::connect_addr(try!(ServerAddress::from_str(addr)))
}
pub fn connect_system() -> Result<Connection, Error> {
let default = "unix:path=/var/run/dbus/system_bus_socket";
if let Ok(e) = env::var("DBUS_SYSTEM_BUS_ADDRESS") {
Self::connect(&e)
} else {
Self::connect(default)
}
}
pub fn connect_session() -> Result<Connection, Error> {
if let Ok(e) = env::var("DBUS_SESSION_BUS_ADDRESS") {
Self::connect(&e)
} else {
Err(Error::NoEnvironment)
}
}
pub fn connect_uds<P: AsRef<Path>>(addr: P) -> Result<Connection,Error> {
let sock = try!(UnixStream::connect(addr));
let mut conn = Connection {
sock: Socket::Uds(sock),
queue: Vec::new(),
next_serial: 1
};
try!(conn.send_nul_byte());
try!(conn.auth_external());
try!(conn.say_hello());
Ok(conn)
}
pub fn connect_tcp<T: ToSocketAddrs>(addr: T) -> Result<Connection,Error> {
let sock = try!(TcpStream::connect(addr));
let mut conn = Connection {
sock: Socket::Tcp(sock),
queue: Vec::new(),
next_serial: 1
};
try!(conn.send_nul_byte());
try!(conn.auth_anonymous());
try!(conn.say_hello());
Ok(conn)
}
pub fn send(&mut self, mbuf: &mut Message) -> Result<u32, Error> {
let this_serial = self.next_serial;
self.next_serial += 1;
mbuf.serial = this_serial;
let mut msg = Vec::new();
mbuf.dbus_encode(&mut msg);
let sock = self.get_sock();
try!(sock.write_all(&msg));
try!(sock.write_all(&mbuf.body));
Ok(this_serial)
}
pub fn call_sync(&mut self, mbuf: &mut Message) -> Result<Option<Vec<Value>>,Error> {
assert_eq!(mbuf.message_type, message::MESSAGE_TYPE_METHOD_CALL);
assert_eq!(mbuf.flags & message::FLAGS_NO_REPLY_EXPECTED, 0);
let serial = try!(self.send(mbuf));
let mut queue = Vec::new();
loop {
let mut msg = try!(self.read_msg());
match msg.headers.iter().position(|x| { x.0 == message::HEADER_FIELD_REPLY_SERIAL }) {
Some(idx) => {
let obj = {
let x = &msg.headers[idx].1;
x.object.deref().clone()
};
let reply_serial : u32 = DBusDecoder::decode(obj).unwrap();
if reply_serial == serial {
for _ in 0..queue.len() {
self.queue.push(queue.remove(0));
}
return Ok(try!(msg.get_body()))
};
}
_ => ()
};
queue.push(msg);
}
}
pub fn read_msg(&mut self) -> Result<Message,Error> {
match self.queue.get(0) {
Some(_) => return Ok(self.queue.remove(0)),
_ => ()
};
let mut buf = Vec::new();
let sock = self.get_sock();
try!(read_exactly(sock, &mut buf, 12));
let mut offset = 0;
let mut sig = "(yyyyuu)".to_string();
let header = match try!(demarshal(&mut buf, &mut offset, &mut sig)) {
Value::Struct(x) => x,
x => panic!("Demarshal didn't return what we asked for: {:?}", x)
};
let mut v = header.objects;
let mut msg : Message = Default::default();
let endian : u8 = DBusDecoder::decode(v.remove(0)).unwrap();
if endian == 'B' as u8 {
msg.big_endian = true;
}
msg.message_type = message::MessageType(DBusDecoder::decode(v.remove(0)).unwrap());
msg.flags = DBusDecoder::decode::<u8>(v.remove(0)).unwrap();
msg.version = DBusDecoder::decode::<u8>(v.remove(0)).unwrap();
let body_len = DBusDecoder::decode::<u32>(v.remove(0)).unwrap();
msg.serial = DBusDecoder::decode::<u32>(v.remove(0)).unwrap();
try!(read_exactly(sock, &mut buf, 4));
let mut buf_copy = buf.clone();
offset = 12;
sig = "u".to_string();
let data = demarshal(&mut buf, &mut offset, &mut sig).ok().unwrap();
let arr_len = DBusDecoder::decode::<u32>(data).unwrap() as usize;
buf_copy.reserve(arr_len);
if try!(sock.take(arr_len as u64).read_to_end(&mut buf_copy)) != arr_len {
return Err(Error::Disconnected);
};
offset = 12;
sig = "a(yv)".to_string();
let header_fields = match try!(demarshal(&mut buf_copy, &mut offset, &mut sig)) {
Value::Array(x) => x,
x => panic!("Demarshal didn't return what we asked for: {:?}", x)
};
msg.headers = Vec::new();
for i in header_fields.objects {
let mut st = match i {
Value::Struct(x) => x,
x => panic!("Demarshal didn't return what we asked for: {:?}", x)
};
let val = st.objects.remove(1);
let code = DBusDecoder::decode::<u8>(st.objects.remove(0)).unwrap();
let variant = match val {
Value::Variant(x) => x,
x => panic!("Demarshal didn't return what we asked for: {:?}", x)
};
msg.headers.push(HeaderField(code, variant));
}
let trailing_pad = 8 - (offset % 8);
if trailing_pad % 8 != 0 {
try!(read_exactly(sock, &mut buf, trailing_pad));
}
if body_len > 0 {
try!(read_exactly(sock, &mut msg.body, body_len as usize));
}
Ok(msg)
}
}
#[cfg(test)]
fn validate_connection(conn: &mut Connection) {
let mut msg = message::create_method_call("org.freedesktop.DBus", "/org/freedesktop/DBus",
"org.freedesktop.DBus", "ListNames");
let resp = conn.call_sync(&mut msg).unwrap();
println!("ListNames: {:?}", resp);
}
#[test]
fn test_connect_system() {
let mut conn = Connection::connect_system().unwrap();
validate_connection(&mut conn);
}
#[test]
fn test_connect_session() {
let mut conn = Connection::connect_session().unwrap();
validate_connection(&mut conn);
let mut msg = message::create_method_call("org.freedesktop.DBus", "/org/freedesktop/DBus",
"org.freedesktop.DBus", "RequestName");
msg = msg.add_arg(&"com.test.foobar")
.add_arg(&(0 as u32));
println!("{:?}", msg);
let mut resp = conn.call_sync(&mut msg).unwrap().unwrap();
println!("RequestName: {:?}", resp);
let value = resp.remove(0);
assert_eq!(value, Value::from(1 as u32));
}
#[test]
fn test_tcp() {
let mut conn = Connection::connect(&env::var("DBUS_TCP_BUS_ADDRESS").unwrap()).unwrap();
let mut msg = message::create_method_call("org.freedesktop.DBus", "/org/freedesktop/DBus",
"org.freedesktop.DBus", "ListNames");
conn.send(&mut msg).ok();
let msg = conn.read_msg().unwrap();
println!("{:?}", msg.body);
}