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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! The core rust-tox module.
//!
//! # Example (a simple echo bot)
//!
//! ```no_run
//! #![feature(globs)]
//! extern crate tox;
//! 
//! use tox::core::*;
//! 
//! fn main() {
//!     let tox = Tox::new(ToxOptions::new()).unwrap();
//!     let bootkey = box "951C88B7E75C867418ACDB5D273821372BB5BD652740BCDF623A4FA293E75D2F".parse().unwrap();
//!     tox.bootstrap_from_address("192.254.75.98".to_string(), 33445, bootkey).unwrap();
//! 
//!     println!("Bot key: {}", tox.get_address());
//! 
//!     for ev in tox.events().iter() {
//!         match ev {
//!             FriendRequest(fnum, _) => {
//!                 tox.add_friend_norequest(fnum).unwrap();
//!             },
//!             FriendMessage(fnum, msg) => {
//!                 tox.send_message(fnum, msg).unwrap();
//!             },
//!             _ => (),
//!         }
//!     }
//! }
//! ```

// TODO: Wrap unwrapped core functions

use std::{fmt, mem};
use std::str::{FromStr};
use rust_core::slice::{MutableIntSlice};
pub use self::Event::*;
use av;

mod backend;
pub mod ll;

pub const MAX_NAME_LENGTH:              uint = 128u;
pub const MAX_MESSAGE_LENGTH:           uint = 1368u;
pub const MAX_STATUSMESSAGE_LENGTH:     uint = 1007u;
pub const TOX_MAX_FRIENDREQUEST_LENGTH: uint = 1016u;
pub const ID_CLIENT_SIZE:               uint = 32u;
pub const ADDRESS_SIZE:                 uint = ID_CLIENT_SIZE + 6u;
pub const AVATAR_MAX_DATA_LENGTH:       uint = 16384u;
pub const HASH_LENGTH:                  uint = 32u;

#[deriving(Copy, Clone, Eq, PartialEq, Show)]
#[repr(u8)]
pub enum AvatarFormat {
    None = ll::TOX_AVATAR_FORMAT_NONE as u8,
    PNG = ll::TOX_AVATAR_FORMAT_PNG as u8,
}

#[deriving(Copy, Clone, Eq, PartialEq, Show)]
#[repr(u8)]
pub enum GroupchatType {
    Text = ll::TOX_GROUPCHAT_TYPE_TEXT as u8,
    Av = ll::TOX_GROUPCHAT_TYPE_AV as u8,
}

/// Tox events enum
#[deriving(Clone)]
pub enum Event {
    /// The first value is the client id, the second is the friend request message
    FriendRequest(Box<ClientId>, String),
    /// `(fnum, msg)` where `fnum` is the friend number and `msg` is the received message
    FriendMessage(i32, String),
    /// `(fnum, msg)` where `fnum` is the friend number and `msg` is the action message
    FriendAction(i32, String),
    /// `(fnum, name)` where `fnum` is the friend number and `name` is the new friend name
    NameChange(i32, String),
    /// `(fnum, status)` where `fnum` is the friend number and `status` is the status
    /// message
    StatusMessage(i32, String),
    /// `(fnum, usrst)` where `fnum` is the friend number and `usrst` is the friend status
    UserStatusVar(i32, UserStatus),
    /// `(fnum, is_typing)`. `true` value of is_typing means that friend is typing. `fnum`
    /// is the friend number
    TypingChange(i32, bool),
    // ?
    ReadReceipt(i32, u32),
    /// `(fnum, ConnectionStatus)`. `fnum` is the friend number
    ConnectionStatusVar(i32, ConnectionStatus),
    /// `(fnum, ty, data)` where `data` is special data what needs
    /// to be passed to Tox::join_group method, `fnum` is the friend number, and `ty` is
    /// the type of the group.
    GroupInvite(i32, GroupchatType, Vec<u8>),
    /// `(gnum, pnum, msg)` where `gnum` is the group number, `pnum` is the peer number
    /// and `msg` is the message
    GroupMessage(i32, i32, String),
    /// `(gnum, pnum, ChatChange)`
    GroupNamelistChange(i32, i32, ChatChange),
    /// `(fnum, fid, fisize, finame)`
    FileSendRequest(i32, u8, u64, Vec<u8>),
    /// `(fnum, TranserType, fid, ControlType, data)`
    FileControl(i32, TransferType, u8, ControlType, Vec<u8>),
    /// `(fnum, fid, data)`
    FileData(i32, u8, Vec<u8>),
    /// `(fnum, AvatarFormat, Hash)`
    AvatarInfo(i32, AvatarFormat, Hash),
    /// `(fnum, AvatarFormat, Hash, data)`
    AvatarData(i32, AvatarFormat, Hash, Vec<u8>),
}

/// A Tox address consist of `ClientId`, nospam and checksum
#[repr(C)]
#[deriving(PartialEq, Clone)]
pub struct Address {
    id: ClientId,
    nospam: [u8, ..4],
    // #[allow(dead_code)]
    checksum: [u8, ..2],
}

impl Address {
    pub fn client_id(&self) -> &ClientId {
        &self.id
    }
    fn checksum(&self) -> [u8, ..2] {
        let mut check = [0u8, 0u8];
        for (i, &x) in self.id.raw.iter().enumerate() {
            check[i % 2] ^= x;
        }
        for i in range(0u, 4) {
            check[(ID_CLIENT_SIZE + i) % 2] ^= self.nospam[i];
        }
        check
    }
}

impl fmt::Show for Address {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        try!(self.id.fmt(fmt));
        try!(write!(fmt, "{:02X}", self.nospam[0]));
        try!(write!(fmt, "{:02X}", self.nospam[1]));
        try!(write!(fmt, "{:02X}", self.nospam[2]));
        try!(write!(fmt, "{:02X}", self.nospam[3]));
        let check = self.checksum();
        try!(write!(fmt, "{:02X}", check[0]));
        try!(write!(fmt, "{:02X}", check[1]));
        Ok(())
    }
}

impl FromStr for Address {
    fn from_str(s: &str) -> Option<Address> {
        if s.len() != 2 * ADDRESS_SIZE {
            return None;
        }

        let mut id     = [0u8, ..32];
        let mut nospam = [0u8, ..4];
        let mut check  = [0u8, ..2];

        if parse_hex(s.slice(0, 2*ID_CLIENT_SIZE), id.as_mut_slice()).is_err() {
            return None;
        }
        if parse_hex(s.slice(2*ID_CLIENT_SIZE, 2*ID_CLIENT_SIZE+8),
                             nospam.as_mut_slice()).is_err() {
            return None;
        }
        if parse_hex(s.slice(2*ID_CLIENT_SIZE+8, 2*ADDRESS_SIZE),
                             check.as_mut_slice()).is_err() {
            return None;
        }

        let addr = Address { id: ClientId { raw: id }, nospam: nospam, checksum: check };
        if addr.checksum().as_slice() != check.as_slice() {
            return None;
        }
        Some(addr)
    }
}

fn parse_hex(s: &str, buf: &mut [u8]) -> Result<(),()> {
    if s.len() != 2*buf.len() {
        return Err(());
    }
    for i in range(0u, buf.len()) {
        for j in range(0u, 2) {
            buf[i] = (buf[i] << 4) + match s.as_bytes()[2*i + j] as char {
                c @ '0' ... '9' => (c as u8) - ('0' as u8),
                c @ 'a' ... 'f' => (c as u8) - ('a' as u8) + 10,
                c @ 'A' ... 'F' => (c as u8) - ('A' as u8) + 10,
                _              => return Err(()),
            }
        }
    }
    return Ok(());
}

/// `ClientId` is the main part of tox `Address`. Other two are nospam and checksum.
#[repr(C)]
#[deriving(PartialEq, Clone)]
#[allow(missing_copy_implementations)]
pub struct ClientId {
    pub raw: [u8, ..ID_CLIENT_SIZE],
}

impl fmt::Show for ClientId {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        for &n in self.raw.iter() {
            try!(write!(fmt, "{:02X}", n));
        }
        Ok(())
    }
}

impl FromStr for ClientId {
    fn from_str(s: &str) -> Option<ClientId> {
        if s.len() != 2 * ID_CLIENT_SIZE {
            return None;
        }

        let mut id = [0u8, ..ID_CLIENT_SIZE];

        if parse_hex(s, id.as_mut_slice()).is_err() {
            return None;
        }
        Some(ClientId { raw: id })
    }
}

/// Locally-calculated cryptographic hash of the avatar data
#[deriving(Clone, PartialEq, Eq)]
#[allow(missing_copy_implementations)]
pub struct Hash {
    pub hash: [u8, ..HASH_LENGTH]
}

impl Hash {
    pub fn new(data: &[u8]) -> Result<Hash, ()> {
        let mut hash: Hash = unsafe { mem::uninitialized() };
        let res = unsafe {
            ll::tox_hash(hash.hash.as_mut_ptr(), data.as_ptr(), data.len() as u32)
        };
        match res {
            0 => Ok(hash),
            _ => Err(()),
        }
    }
}

#[deriving(Copy, Clone, PartialEq, Eq)]
pub enum ConnectionStatus {
    Online,
    Offline,
}

#[repr(u32)]
#[deriving(Copy, Clone, PartialEq, Eq)]
pub enum UserStatus {
    None = ll::TOX_USERSTATUS_NONE,
    Away = ll::TOX_USERSTATUS_AWAY,
    Busy = ll::TOX_USERSTATUS_BUSY,
}

#[repr(u32)]
#[deriving(Copy, Clone, PartialEq, Eq)]
pub enum ChatChange {
    PeerAdd  = ll::TOX_CHAT_CHANGE_PEER_ADD,
    PeerDel  = ll::TOX_CHAT_CHANGE_PEER_DEL,
    PeerName = ll::TOX_CHAT_CHANGE_PEER_NAME,
}

#[repr(u32)]
#[deriving(Copy, Clone, PartialEq, Eq)]
pub enum ControlType {
    Accept       = ll::TOX_FILECONTROL_ACCEPT,
    Pause        = ll::TOX_FILECONTROL_PAUSE,
    Kill         = ll::TOX_FILECONTROL_KILL,
    Finished     = ll::TOX_FILECONTROL_FINISHED,
    ResumeBroken = ll::TOX_FILECONTROL_RESUME_BROKEN,
}

/// Faerr - Friend Add Error
#[repr(i32)]
#[deriving(Copy, Clone, PartialEq, Eq)]
pub enum Faerr {
    Toolong      = ll::TOX_FAERR_TOOLONG,
    Nomessage    = ll::TOX_FAERR_NOMESSAGE,
    Ownkey       = ll::TOX_FAERR_OWNKEY,
    Alreadysent  = ll::TOX_FAERR_ALREADYSENT,
    Unknown      = ll::TOX_FAERR_UNKNOWN,
    Badchecksum  = ll::TOX_FAERR_BADCHECKSUM,
    Setnewnospam = ll::TOX_FAERR_SETNEWNOSPAM,
    Nomem        = ll::TOX_FAERR_NOMEM,
}

#[deriving(Copy, Clone, PartialEq, Eq)]
pub enum TransferType {
    Receiving,
    Sending,
}


/// ToxOptions provides options that tox will be initalized with.
///
/// Usage:
/// ```
///     let txo = ToxOptions::new().ipv6().proxy("[proxy address]", port);
///     let tox = Tox::new(txo);
/// ```
#[deriving(Copy)]
pub struct ToxOptions {
    txo: ll::Tox_Options
}

#[repr(u8)]
#[deriving(Copy)]
pub enum ProxyType {
    None,
    Socks5,
    HTTP,
}

impl ToxOptions {
    /// Create a default ToxOptions struct
    pub fn new() -> ToxOptions {
        ToxOptions {
            txo: ll::Tox_Options {
                ipv6enabled: 0,
                udp_disabled: 0,
                proxy_type: 0,
                proxy_address: [0, ..256u],
                proxy_port: 0,
            }
        }
    }

    /// Enable IPv6
    pub fn ipv6(mut self) -> ToxOptions {
        self.txo.ipv6enabled = 1;
        self
    }

    /// Disable UDP
    pub fn no_udp(mut self) -> ToxOptions {
        self.txo.udp_disabled = 1;
        self
    }

    /// Use a proxy
    pub fn proxy(mut self, ty: ProxyType, addr: &str, port: u16) -> ToxOptions {
        if addr.len() >= 256 {
            panic!("proxy address is too long");
        }

        self.txo.proxy_address.as_mut_slice()
                              .as_unsigned_mut()
                              .clone_from_slice(addr.as_bytes());
        self.txo.proxy_type = ty as u8;
        self.txo.proxy_port = port;
        self
    }
}

/// The main tox struct. All the control goes here.
pub struct Tox {
    pub events: Receiver<Event>,
    control: SyncSender<backend::Control>,
}

macro_rules! forward {
    ($slf:expr, $name:expr, ($($pp:ident),+), ->) => {
        {
            let (snd, rcv) = channel();
            $slf.control.send($name($($pp),*, snd));
            rcv.recv()
        }
    };
    ($slf:expr, $name:expr, ->) => {
        {
            let (snd, rcv) = channel();
            $slf.control.send($name(snd));
            rcv.recv()
        }
    };
    ($slf:expr, $name:expr, ($($pp:ident),+)) => {
        {
            $slf.control.send($name($($pp),*));
        }
    };
    ($slf:expr, $name:expr) => {
            $slf.control.send($name);
    };

}

impl Tox {
    /// Get self address
    pub fn get_address(&self) -> Address {
        forward!(self, backend::Control::GetAddress, ->)
    }

    /// Add a friend and send friend request
    pub fn add_friend(&self, address: Box<Address>, msg: String) -> Result<i32, Faerr> {
        forward!(self, backend::Control::AddFriend, (address, msg), ->)
    }

    /// Add a friend without sending friend request. Beware, friend will appear online
    /// only if he added you too
    pub fn add_friend_norequest(&self, client_id: Box<ClientId>) -> Result<i32, ()> {
        forward!(self, backend::Control::AddFriendNorequest, (client_id), ->)
    }

    /// Get friend number associated with given ClientId
    pub fn get_friend_number(&self, client_id: Box<ClientId>) -> Result<i32, ()> {
        forward!(self, backend::Control::GetFriendNumber, (client_id), ->)
    }

    /// Get ClientId of the friend with given friend number
    pub fn get_client_id(&self, friendnumber: i32) -> Result<Box<ClientId>, ()> {
        forward!(self, backend::Control::GetClientId, (friendnumber), ->)
    }

    /// Remove the friend with given friend number
    pub fn del_friend(&self, friendnumber: i32) -> Result<(),()> {
        forward!(self, backend::Control::DelFriend, (friendnumber), ->)
    }

    /// Get the connection status of the friend
    pub fn get_friend_connection_status(
            &self,
            friendnumber: i32) -> Result<ConnectionStatus, ()> {
        forward!(self, backend::Control::GetFriendConnectionStatus, (friendnumber), ->)
    }

    /// Returns `true` if friend with given friend number exists. Otherwise, returns
    /// `false`
    pub fn friend_exists(&self, friendnumber: i32) -> bool {
        forward!(self, backend::Control::FriendExists, (friendnumber), ->)
    }

    /// Send a message to the friend
    pub fn send_message(&self, friendnumber: i32,
                        msg: String) -> Result<u32, ()> {
        forward!(self, backend::Control::SendMessage, (friendnumber, msg), ->)
    }

    /// Send an action message to the friend
    pub fn send_action(&self, friendnumber: i32, action: String) -> Result<u32, ()> {
        forward!(self, backend::Control::SendAction, (friendnumber, action), ->)
    }

    /// Set self nickname
    pub fn set_name(&self, name: String) -> Result<(),()> {
        forward!(self, backend::Control::SetName, (name), ->)
    }

    /// Returns the self nickname
    pub fn get_self_name(&self) -> Result<String, ()> {
        forward!(self, backend::Control::GetSelfName, ->)
    }

    /// Get the nickname of the friend
    pub fn get_name(&self, friendnumber: i32) -> Result<String, ()> {
        forward!(self, backend::Control::GetName, (friendnumber), ->)
    }

    /// Set self status message
    pub fn set_status_message(&self, status: String) -> Result<(),()> {
        forward!(self, backend::Control::SetStatusMessage, (status), ->)
    }

    /// Set self status (`None`, `Away` or `Busy`)
    pub fn set_user_status(&self, userstatus: UserStatus) -> Result<(), ()> {
        forward!(self, backend::Control::SetUserStatus, (userstatus), ->)
    }

    /// Get the status message of the friend
    pub fn get_status_message(&self, friendnumber: i32) -> Result<String, ()> {
        forward!(self, backend::Control::GetStatusMessage, (friendnumber), ->)
    }

    /// Get self status message
    pub fn get_self_status_message(&self) -> Result<String, ()> {
        forward!(self, backend::Control::GetSelfStatusMessage, ->)
    }

    /// Get status of the friend
    pub fn get_user_status(&self, friendnumber: i32) -> Result<UserStatus, ()> {
        forward!(self, backend::Control::GetUserStatus, (friendnumber), ->)
    }

    /// Get self status
    pub fn get_self_user_status(&self) -> Result<UserStatus, ()> {
        forward!(self, backend::Control::GetSelfUserStatus, ->)
    }

    /// Return timestamp of last time the friend was seen online, or 0 if never seen
    pub fn get_last_online(&self, friendnumber: i32) -> Result<u64, ()> {
        forward!(self, backend::Control::GetLastOnline, (friendnumber), ->)
    }

    /// Set typing status for the given friend.You are responsible for turning it on or
    /// off
    pub fn set_user_is_typing(&self, friendnumber: i32,
                              is_typing: bool) -> Result<(), ()> {
        forward!(self, backend::Control::SetUserIsTyping, (friendnumber, is_typing), ->)
    }

    /// Get typing status of the given friend
    pub fn get_is_typing(&self, friendnumber: i32) -> bool {
        forward!(self, backend::Control::GetIsTyping, (friendnumber), ->)
    }

    /// Returns the number of friends
    pub fn count_friendlist(&self) -> u32 {
        forward!(self, backend::Control::CountFriendlist, ->)
    }

    /// Returns the number of chats
    pub fn count_chatlist(&self) -> u32 {
        forward!(self, backend::Control::CountChatlist, ->)
    }

    /// Get the number of online friends
    pub fn get_num_online_friends(&self) -> u32 {
        forward!(self, backend::Control::GetNumOnlineFriends, ->)
    }

    /// Get the Vec of valid friend IDs
    pub fn get_friendlist(&self) -> Vec<i32> {
        forward!(self, backend::Control::GetFriendlist, ->)
    }

    /// Get self nospam
    pub fn get_nospam(&self) -> [u8, ..4] {
        forward!(self, backend::Control::GetNospam, ->)
    }

    /// Set self nospam
    pub fn set_nospam(&self, nospam: [u8, ..4]) {
        forward!(self, backend::Control::SetNospam, (nospam))
    }

    /// Create a new groupchat, returns groupchat number
    pub fn add_groupchat(&self) -> Result<i32, ()> {
        forward!(self, backend::Control::AddGroupchat, ->)
    }

    /// Leave the groupchat
    pub fn del_groupchat(&self, groupnumber: i32) -> Result<(),()> {
        forward!(self, backend::Control::DelGroupchat, (groupnumber), ->)
    }

    /// Returns the name of peer with given peer number in the groupchat
    pub fn group_peername(&self, groupnumber: i32,
                          peernumber: i32) -> Result<String, ()> {
        forward!(self, backend::Control::GroupPeername, (groupnumber, peernumber), ->)
    }

    /// Invite the friend to the groupchat
    pub fn invite_friend(&self, friendnumber: i32, groupnumber: i32) -> Result<(), ()> {
        forward!(self, backend::Control::InviteFriend, (friendnumber, groupnumber), ->)
    }

    /// Join a groupchat using `data` obtained by `GroupInvite` event
    pub fn join_groupchat(&self, friendnumber: i32, data: Vec<u8>) -> Result<i32, ()> {
        forward!(self, backend::Control::JoinGroupchat, (friendnumber, data), ->)
    }

    /// Send a message to the groupchat
    pub fn group_message_send(&self, groupnumber: i32,
                              message: String) -> Result<(), ()> {
        forward!(self, backend::Control::GroupMessageSend, (groupnumber, message), ->)
    }

    /// Send an action message to the groupchat
    pub fn group_action_send(&self, groupnumber: i32, action: String) -> Result<(), ()> {
        forward!(self, backend::Control::GroupActionSend, (groupnumber, action), ->)
    }

    /// Returns number of peers in the groupchat
    pub fn group_number_peers(&self, groupnumber: i32) -> Result<i32, ()> {
        forward!(self, backend::Control::GroupNumberPeers, (groupnumber), ->)
    }

    /// Returns list of all peer names in the groupchat
    pub fn group_get_names(&self,
                           groupnumber: i32) -> Result<Vec<Option<String>>, ()> {
        forward!(self, backend::Control::GroupGetNames, (groupnumber), ->)
    }

    /// Returns the Vec of all valid group IDs
    pub fn get_chatlist(&self) -> Vec<i32> {
        forward!(self, backend::Control::GetChatlist, ->)
    }

    pub fn set_avatar(&self, format: AvatarFormat, data: Vec<u8>) -> Result<(), ()> {
        forward!(self, backend::Control::SetAvatar, (format, data), ->)
    }

    pub fn unset_avatar(&self) {
        forward!(self, backend::Control::UnsetAvatar)
    }

    pub fn get_self_avatar(&self) -> Result<(AvatarFormat, Vec<u8>, Hash), ()> {
        forward!(self, backend::Control::GetSelfAvatar, ->)
    }

    pub fn request_avatar_info(&self, friendnumber: i32) -> Result<(), ()> {
        forward!(self, backend::Control::RequestAvatarInfo, (friendnumber), ->)
    }

    pub fn send_avatar_info(&self, friendnumber: i32) -> Result<(), ()> {
        forward!(self, backend::Control::SendAvatarInfo, (friendnumber), ->)
    }

    pub fn request_avatar_data(&self, friendnumber: i32) -> Result<(), ()> {
        forward!(self, backend::Control::RequestAvatarData, (friendnumber), ->)
    }

    pub fn new_file_sender(&self, friendnumber: i32, filesize: u64,
                           filename: Path) -> Result<i32, ()> {
        forward!(self, backend::Control::NewFileSender,
                 (friendnumber, filesize, filename), ->)
    }

    pub fn file_send_control(&self, friendnumber: i32, send_receive: TransferType,
                             filenumber: u8, message_id: u8,
                             data: Vec<u8>) -> Result<(), ()> {
        forward!(self, backend::Control::FileSendControl,
                 (friendnumber, send_receive, filenumber, message_id, data), ->)
    }

    pub fn file_send_data(&self, friendnumber: i32, filenumber: u8,
                          data: Vec<u8>) -> Result<(), ()> {
        forward!(self, backend::Control::FileSendData,
                 (friendnumber, filenumber, data), ->)
    }

    pub fn file_data_size(&self, friendnumber: i32) -> Result<i32, ()> {
        forward!(self, backend::Control::FileDataSize, (friendnumber), ->)
    }

    pub fn file_data_remaining(&self, friendnumber: i32, filenumber: u8,
                               send_receive: TransferType) -> Result<u64, ()> {
        forward!(self, backend::Control::FileDataRemaining,
                 (friendnumber, filenumber, send_receive), ->)
    }

    /// Bootstrap from the given (address, port, ClientId)
    pub fn bootstrap_from_address(&self, address: String, port: u16,
                                  public_key: Box<ClientId>) -> Result<(), ()> {
        forward!(self, backend::Control::BootstrapFromAddress,
                 (address, port, public_key), ->)
    }

    /// Returns `true` if connected to DHT. Otherwise, returns `false`
    pub fn is_connected(&self) -> bool {
        forward!(self, backend::Control::Isconnected, ->)
    }

    /// Create a new tox instance
    pub fn new(mut opts: ToxOptions) -> Option<Tox> {
        let (ctrl, events) = match backend::Backend::new(&mut opts.txo) {
            Some(x) => x,
            None => return None,
        };
        Some(Tox {
            events: events,
            control: ctrl,
        })
    }

    /// Returns a tox data that should be saved in the tox file
    pub fn save(&self) -> Vec<u8> {
        forward!(self, backend::Control::Save, ->)
    }

    /// Load instance data from Vec
    pub fn load(&self, data: Vec<u8>) -> Result<(), ()> {
        forward!(self, backend::Control::Load, (data), ->)
    }

    /// Return an events receiver
    pub fn events(&self) -> &Receiver<Event> {
        &self.events
    }

    pub unsafe fn raw(&self) -> *mut ll::Tox {
        forward!(self, backend::Control::Raw, ->)
    }

    pub fn av(&self, max_calls: i32) -> Option<av::Av> {
        forward!(self, backend::Control::Av, (max_calls), ->)
    }
}