spread 0.0.1

A Rust client library for the Spread toolkit
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
#![crate_name = "spread"]
#![crate_type = "lib"]

#![feature(phase)]
#[deny(non_camel_case_types)]

extern crate encoding;
#[phase(plugin, link)] extern crate log;

use encoding::{Encoding, EncoderTrap, DecoderTrap};
use encoding::all::ISO_8859_1;
use std::io::{ConnectionFailed, ConnectionRefused, IoError, IoResult, OtherIoError};
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::TcpStream;
use std::result::Result;
use util::{bytes_to_int, flip_endianness, int_to_bytes, same_endianness};

mod test;
mod util;

pub static DEFAULT_SPREAD_PORT: i16 = 4803;

static MAX_PRIVATE_NAME_LENGTH: uint = 10;
static DEFAULT_AUTH_NAME: &'static str  = "NULL";
static MAX_AUTH_NAME_LENGTH: uint = 30;
static MAX_AUTH_METHOD_COUNT: uint = 3;
static MAX_GROUP_NAME_LENGTH: uint = 32;

// Control message types.
// NOTE: The only currently-implemented service type for messaging is "reliable".
enum ControlServiceType {
    JoinMessage     = 0x00010000,
    LeaveMessage    = 0x00020000,
    KillMessage     = 0x00040000,
    ReliableMessage = 0x00000002
}

static SPREAD_MAJOR_VERSION: u8 = 4;
static SPREAD_MINOR_VERSION: u8 = 4;
static SPREAD_PATCH_VERSION: u8 = 0;

// Error codes, as per http://www.spread.org/docs/spread_docs_4/docs/error_codes.html
pub enum SpreadError {
    AcceptSession = 1,
    IllegalSpread = -1,
    CouldNotConnection = -2,
    RejectQuota = -3,
    RejectNOName = -4,
    RejectIllegalName = -5,
    RejectNotUnique = -6,
    RejectVersion = -7,
    ConnectionClosed = -8,
    RejectAuth = -9,
    IllegalSession = -11,
    IllegalService = -12,
    IllegalMessage = -13,
    IllegalGroup = -14,
    BufferTooShort = -15,
    GroupsTooShort = -16,
    MessageTooLong = -17,
    NetErrorOnSession = -18
}

impl Copy for SpreadError {}

/// A message to be sent or received by a Spread client to/from a group.
pub struct SpreadMessage {
    service_type: u32,
    pub groups: Vec<String>,
    pub sender: String,
    pub data: Vec<u8>,
}

/// Representation of a client connection to a Spread daemon.
pub struct SpreadClient {
    stream: TcpStream,
    pub private_name: String,
    pub groups: Vec<String>,
    receive_membership_messages: bool
}

// Construct a byte vector representation of a connect message for the given
// connection arguments.
fn encode_connect_message(
    private_name: &str,
    receive_membership_messages: bool
) -> Result<Vec<u8>, String> {
    let mut vec: Vec<u8> = Vec::new();

    // Set Spread version.
    vec.push(SPREAD_MAJOR_VERSION);
    vec.push(SPREAD_MINOR_VERSION);
    vec.push(SPREAD_PATCH_VERSION);

    // Apply masks for group membership (and priority, which is unimplemented).
    let mask = if receive_membership_messages {
        0x10
    } else {
        0
    };
    vec.push(mask);

    let private_name_buf = try!(ISO_8859_1.encode(private_name, EncoderTrap::Strict).map_err(
        |_| format!("Failed to encode private name: {}", private_name)
    ));

    vec.push(private_name.char_len() as u8);
    vec.push_all(private_name_buf.as_slice());
    Ok(vec)
}

/// Establishes a named connection to a Spread daemon running at a given
/// `SocketAddr`.
///
/// *Arguments:*
///
/// - `addr`: The address at which the Spread daemon is running.
/// - `private_name`: A name to use privately to refer to the connection.
/// - `receive_membership_messages`: If true, membership messages will be
///   received by the resultant client.
pub fn connect(
    addr: SocketAddr,
    private_name: &str,
    receive_membership_messages: bool
) -> IoResult<SpreadClient> {
    // Truncate (if necessary) and write `private_name`.
    let truncated_private_name = match private_name {
        too_long if too_long.char_len() > MAX_PRIVATE_NAME_LENGTH =>
            too_long.slice_to(MAX_PRIVATE_NAME_LENGTH),
        just_fine => just_fine
    };

    // Send the initial connect message.
    let connect_message = try!(encode_connect_message(
        truncated_private_name,
        receive_membership_messages
    ).map_err(|error_msg| IoError {
        kind: ConnectionFailed,
        desc: "",
        detail: Some(error_msg)
    }));

    let mut stream = try!(TcpStream::connect(addr));
    debug!("Sending connect message to {}", addr);
    try!(stream.write(connect_message.as_slice()));

    // Read the authentication methods.
    let authname_len = try!(stream.read_byte()) as i32;
    if authname_len == -1 {
        return Err(IoError {
            kind: ConnectionFailed,
            desc: "Connection closed during connect attempt to read auth name length",
            detail: None
        });
    } else if authname_len >= 128 {
        return Err(IoError {
            kind: ConnectionRefused,
            desc: "Connection attempt rejected",
            detail: Some(format!("{}", (0xffffff00 | authname_len as u32) as i32))
        });
    }

    // Ignore the list.
    // TODO: Support IP-based auth?
    let authname_vec = try!(stream.read_exact(authname_len as uint));
    let authname = try!(ISO_8859_1.decode(
        authname_vec.as_slice(), DecoderTrap::Strict
    ).map_err(|error| IoError {
        kind: OtherIoError,
        desc: "Failed to decode received authname",
        detail: Some(String::from_str(error.as_slice()))
    }));
    debug!("Received authentication method choice(s): {}", authname);

    // Send auth method choice.
    let mut authname_vec: Vec<u8> = match ISO_8859_1.encode(DEFAULT_AUTH_NAME, EncoderTrap::Strict) {
        Ok(vec) => vec,
        Err(error) => return Err(IoError {
            kind: ConnectionFailed,
            desc: "Failed to encode authname",
            detail: Some(format!("{}", error))
        })
    };

    for _ in range(authname_len as uint, (MAX_AUTH_NAME_LENGTH * MAX_AUTH_METHOD_COUNT + 1)) {
        authname_vec.push(0);
    }

    debug!("Sending authentication method choice of {}", DEFAULT_AUTH_NAME);
    try!(stream.write(authname_vec.as_slice()));

    // Check for an accept message.
    let accepted: u8 = try!(stream.read_byte());
    if accepted != SpreadError::AcceptSession as u8 {
        return Err(IoError {
            kind: ConnectionFailed,
            desc: "Connection attempt rejected",
            detail: Some(format!("{}", (0xffffff00 | accepted as u32) as i32))
        });
    }

    debug!("Received session acceptance message from daemon");

    // Read the version of Spread that the server is running.
    let (major, minor, patch) =
        (try!(stream.read_byte()) as i32,
         try!(stream.read_byte()) as i32,
         try!(stream.read_byte()) as i32);

    debug!(
        "Received version message: daemon running Spread version {}.{}.{}",
        major, minor, patch
    );

    if major == -1 || minor == -1 || patch == -1 {
        return Err(IoError {
            kind: ConnectionFailed,
            desc: "Invalid version returned from server",
            detail: Some(format!("{}.{}.{}", major, minor, patch))
        });
    }

    let version_sum = (major*10000) + (minor*100) + patch;
    if version_sum < 30100 {
        return Err(IoError {
            kind: ConnectionFailed,
            desc: "Server is running old, unsupported version of Spread",
            detail: Some(format!("{}.{}.{}", major, minor, patch))
        });
    }

    // Read the private group name.
    let group_name_len = try!(stream.read_byte()) as i32;
    if group_name_len == -1 {
        return Err(IoError {
            kind: ConnectionFailed,
            desc: "Connection closed during connect attempt to read group name length",
            detail: None
        });
    }
    let group_name_buf = try!(stream.read_exact(group_name_len as uint));
    let private_group_name = match String::from_utf8(group_name_buf) {
        Ok(group_name) => group_name,
        Err(error) => return Err(IoError {
            kind: ConnectionFailed,
            desc: "Server sent invalid group name",
            detail: Some(format!("{}", error))
        })
    };

    debug!("Received private name assignment from daemon: {}", private_group_name);
    debug!("Client connected to daemon at {}", addr);

    Ok(SpreadClient {
        stream: stream,
        private_name: private_group_name,
        groups: Vec::new(),
        receive_membership_messages: receive_membership_messages
    })
}

impl SpreadClient {
    // Encode a service message for dispatch to a Spread daemon.
    fn encode_message(
        service_type: u32,
        private_name: &str,
        groups: &[&str],
        data: &[u8]
    ) -> Result<Vec<u8>, String> {
        let mut vec: Vec<u8> = Vec::new();
        vec.push_all(int_to_bytes(service_type).as_slice());

        let private_name_buf = try!(ISO_8859_1.encode(private_name, EncoderTrap::Strict).map_err(
            |_| format!("Failed to encode private name: {}", private_name)
        ));
        vec.push_all(private_name_buf.as_slice());
        for _ in range(private_name.len(), (MAX_GROUP_NAME_LENGTH)) {
            vec.push(0);
        }

        vec.push_all(int_to_bytes(groups.len() as u32).as_slice());
        vec.push_all(int_to_bytes(0).as_slice());
        vec.push_all(int_to_bytes(data.len() as u32).as_slice());

        // Encode and push each group name, converting any encoding errors
        // to error message strings.
        for group in groups.iter() {
            let group_buf = try!(ISO_8859_1.encode(*group, EncoderTrap::Strict).map_err(
                |_| format!("Failed to encode group name: {}", group)
            ));
            vec.push_all(group_buf.as_slice());
            for _ in range(group.len(), (MAX_GROUP_NAME_LENGTH)) {
                vec.push(0);
            }
        }

        vec.push_all(data);
        Ok(vec)
    }

    /// Disconnects the client from the Spread daemon.
    // TODO: Prevent further usage of client?
    pub fn disconnect(&mut self) -> IoResult<()> {
        let name_slice = self.private_name.as_slice();
        let kill_message = try!(SpreadClient::encode_message(
            ControlServiceType::KillMessage as u32,
            name_slice,
            [name_slice].as_slice(),
            [].as_slice()
        ).map_err(|error_msg| IoError {
            kind: OtherIoError,
            desc: "Disconnection failed",
            detail: Some(error_msg)
        }));

        debug!("Disconnecting from daemon at {}", try!(self.stream.peer_name()));
        self.stream.write(kill_message.as_slice())
    }

    /// Join a named Spread group.
    ///
    /// All messages sent to the group will be received by the client until it
    /// has left the group.
    pub fn join(&mut self, group_name: &str) -> IoResult<()> {
        let join_message = try!(SpreadClient::encode_message(
            ControlServiceType::JoinMessage as u32,
            self.private_name.as_slice(),
            [group_name].as_slice(),
            [].as_slice()
        ).map_err(|error_msg| IoError {
            kind: OtherIoError,
            desc: "Group join failed",
            detail: Some(error_msg)
        }));

        debug!("Client \"{}\" joining group \"{}\"", self.private_name, group_name);
        try!(self.stream.write(join_message.as_slice()));
        self.groups.push(group_name.to_string());
        Ok(())
    }

    /// Leave a named Spread group.
    pub fn leave(&mut self, group_name: &str) -> IoResult<()> {
        let leave_message = try!(SpreadClient::encode_message(
            ControlServiceType::LeaveMessage as u32,
            self.private_name.as_slice(),
            [group_name].as_slice(),
            [].as_slice()
        ).map_err(|error_msg| IoError {
            kind: OtherIoError,
            desc: "Group leave failed",
            detail: Some(error_msg)
        }));

        debug!("Client \"{}\" leaving group \"{}\"", self.private_name, group_name);
        try!(self.stream.write(leave_message.as_slice()));
        self.groups.push(group_name.to_string());
        Ok(())
    }

    /// Send a message to a set of named groups.
    pub fn multicast(
        &mut self,
        groups: &[&str],
        data: &[u8]
    ) -> IoResult<()> {
        let message = try!(SpreadClient::encode_message(
            ControlServiceType::ReliableMessage as u32,
            self.private_name.as_slice(),
            groups,
            data
        ).map_err(|error_msg| IoError {
            kind: OtherIoError,
            desc: "Multicast failed",
            detail: Some(error_msg)
        }));

        debug!("Client \"{}\" multicasting {} bytes to group(s) {}",
               self.private_name, data.len(), groups);
        self.stream.write(message.as_slice())
    }

    /// Receive the next available message. If there are no messages available,
    /// the call will block until either a message is received or a timeout
    /// expires.
    pub fn receive(&mut self) -> IoResult<SpreadMessage> {
        // Header format (sizes in bytes):
        //   svc_type:   4
        //   sender:    32
        //   num_groups: 4
        //   hint:       4
        //   data_len:   4
        let header_vec = try!(self.stream.read_exact(MAX_GROUP_NAME_LENGTH + 16));
        let is_correct_endianness = same_endianness(bytes_to_int(header_vec.slice(0, 4)));

        let svc_type = match (is_correct_endianness, bytes_to_int(header_vec.slice(0, 4))) {
            (true, correct) => correct,
            (false, incorrect) => flip_endianness(incorrect)
        };

        let sender = try!(
            ISO_8859_1.decode(
                header_vec.slice(4, 36), DecoderTrap::Strict
            ).map_err(|error| IoError {
                kind: OtherIoError,
                desc: "Failed to decode sender name",
                detail: Some(String::from_str(error.as_slice()))
            })
        );

        let num_groups = match (is_correct_endianness, bytes_to_int(header_vec.slice(36, 40))) {
            (true, correct) => correct,
            (false, incorrect) => flip_endianness(incorrect)
        };
        let data_len = match (is_correct_endianness, bytes_to_int(header_vec.slice(44, 48))) {
            (true, correct) => correct,
            (false, incorrect) => flip_endianness(incorrect)
        };

        // Groups format (sizes in bytes):
        //   groups: num_groups
        let groups_vec =
            try!(self.stream.read_exact(MAX_GROUP_NAME_LENGTH * num_groups as uint));
        let mut groups = Vec::new();

        for n in range(0, num_groups) {
            let i: uint = n as uint * MAX_GROUP_NAME_LENGTH;
            let group = try!(
                ISO_8859_1.decode(groups_vec.slice(i, i + MAX_GROUP_NAME_LENGTH), DecoderTrap::Strict)
                    .map_err(|error| IoError {
                        kind: OtherIoError,
                        desc: "Failed to decode group name",
                        detail: Some(String::from_str(error.as_slice()))
                    }));
            groups.push(group);
        }

        // Data format (sizes in bytes):
        //   data: data_len
        let data_vec = try!(self.stream.read_exact(data_len as uint));

        debug!("Received {} bytes from \"{}\" sent to group(s) {}",
               data_len, sender, groups);

        Ok(SpreadMessage {
            service_type: svc_type as u32,
            groups: groups,
            sender: sender,
            data: data_vec
        })
    }
}