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
use {Interface, NatError, NatMsg, NatState, NatTimer};
use config::{HOLE_PUNCH_TIMEOUT_SEC, HOLE_PUNCH_WAIT_FOR_OTHER, RENDEZVOUS_TIMEOUT_SEC};
use mio::{Poll, Token};
use mio::channel::Sender;
use mio::net::UdpSocket;
use mio::tcp::TcpStream;
use mio::timer::Timeout;
use sodium::crypto::box_;
use std::any::Any;
use std::cell::RefCell;
use std::fmt::{self, Debug, Formatter};
use std::mem;
use std::net::SocketAddr;
use std::rc::{Rc, Weak};
use std::time::Duration;
use tcp::TcpHolePunchMediator;
use udp::UdpHolePunchMediator;

/// Callback to receive the result of rendezvous
pub type GetInfo = Box<FnMut(&mut Interface, &Poll, ::Res<(Handle, RendezvousInfo)>)>;
/// Callback to receive the result of hole punching
pub type HolePunchFinsih = Box<FnMut(&mut Interface, &Poll, ::Res<HolePunchInfo>) + Send + 'static>;

/// A rendezvous packet.
///
/// This is supposed to be exchanged out of band between the peers to allow them to hole-punch to
/// each other.
#[derive(Debug, Serialize, Deserialize)]
pub struct RendezvousInfo {
    /// UDP addresses in order
    pub udp: Vec<SocketAddr>,
    /// TCP addresses in order
    pub tcp: Option<SocketAddr>,
    /// Encrypting Asymmetric PublicKey. Peer will use our public key to encrypt and their secret
    /// key to authenticate the message. We will use our secret key to decrypt and peer public key
    /// to validate authenticity of the message.
    pub enc_pk: [u8; box_::PUBLICKEYBYTES],
}

impl RendezvousInfo {
    fn with_key(enc_pk: &box_::PublicKey) -> Self {
        RendezvousInfo {
            udp: vec![],
            tcp: None,
            enc_pk: enc_pk.0,
        }
    }
}

impl Default for RendezvousInfo {
    fn default() -> Self {
        RendezvousInfo {
            udp: vec![],
            tcp: None,
            enc_pk: [0; box_::PUBLICKEYBYTES],
        }
    }
}

/// A successful result of hole punch will be bundled in this structure
#[derive(Debug)]
pub struct HolePunchInfo {
    /// TCP socket that successfully managed to hole punch
    pub tcp: Option<(TcpStream, Token)>,
    /// UDP socket that successfully managed to hole punch
    pub udp: Option<(UdpSocket, SocketAddr, Token)>,
    /// Encrypting Asymmetric PublicKey. Peer will use our public key to encrypt and their secret
    /// key to authenticate the message. We will use our secret key to decrypt and peer public key
    /// to validate authenticity of the message.
    pub enc_pk: box_::PublicKey,
}

impl HolePunchInfo {
    fn with_key(enc_pk: box_::PublicKey) -> Self {
        HolePunchInfo {
            tcp: None,
            udp: None,
            enc_pk: enc_pk,
        }
    }
}

impl Default for HolePunchInfo {
    fn default() -> Self {
        HolePunchInfo {
            tcp: None,
            udp: None,
            enc_pk: box_::PublicKey([0; box_::PUBLICKEYBYTES]),
        }
    }
}

const TIMER_ID: u8 = 0;

enum State {
    None,
    Rendezvous {
        info: RendezvousInfo,
        timeout: Timeout,
        f: GetInfo,
    },
    ReadyToHolePunch,
    HolePunching {
        info: HolePunchInfo,
        timeout: Timeout,
        f: HolePunchFinsih,
    },
}

impl Debug for State {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            State::None => write!(f, "State::None"),
            State::Rendezvous { .. } => write!(f, "State::Rendezvous"),
            State::ReadyToHolePunch => write!(f, "State::ReadyToHolePunch"),
            State::HolePunching { .. } => write!(f, "State::HolePunching"),
        }
    }
}

/// The main hole punch mediator engine.
///
/// This is responsible for managing all the hole punching details. It has child states to mediate
/// UDP and TCP rendezvous as well as UDP and TCP hole punching. The result will be published to
/// the user via accepted callbacks.
pub struct HolePunchMediator {
    token: Token,
    state: State,
    udp_child: Option<Rc<RefCell<UdpHolePunchMediator>>>,
    tcp_child: Option<Rc<RefCell<TcpHolePunchMediator>>>,
    self_weak: Weak<RefCell<HolePunchMediator>>,
}

impl HolePunchMediator {
    /// Start the mediator engine. This will prepare it for the rendezvous. Once rendezvous
    /// information is obtained via the given callback, the user is expected to exchange it out of
    /// band with the peer and begin hole punching by giving the peer's rendezvous information.
    pub fn start(ifc: &mut Interface, poll: &Poll, f: GetInfo) -> ::Res<()> {
        let token = ifc.new_token();
        let dur = ifc.config()
            .rendezvous_timeout_sec
            .unwrap_or(RENDEZVOUS_TIMEOUT_SEC);
        let timeout = ifc.set_timeout(Duration::from_secs(dur), NatTimer::new(token, TIMER_ID))?;

        let mediator = Rc::new(RefCell::new(HolePunchMediator {
                                                token: token,
                                                state: State::None,
                                                udp_child: None,
                                                tcp_child: None,
                                                self_weak: Weak::new(),
                                            }));
        let weak = Rc::downgrade(&mediator);
        let weak_cloned = weak.clone();
        mediator.borrow_mut().self_weak = weak.clone();

        let handler = move |ifc: &mut Interface, poll: &Poll, res| if let Some(mediator) =
            weak.upgrade() {
            mediator
                .borrow_mut()
                .handle_udp_rendezvous(ifc, poll, res);
        };

        let udp_child = match UdpHolePunchMediator::start(ifc, poll, Box::new(handler)) {
            Ok(child) => Some(child),
            Err(e) => {
                debug!("Udp Hole Punch Mediator failed to initialise: {:?}", e);
                None
            }
        };

        let handler = move |ifc: &mut Interface, poll: &Poll, res| if let Some(mediator) =
            weak_cloned.upgrade() {
            mediator
                .borrow_mut()
                .handle_tcp_rendezvous(ifc, poll, res);
        };

        let tcp_child = match TcpHolePunchMediator::start(ifc, poll, Box::new(handler)) {
            Ok(child) => Some(child),
            Err(e) => {
                debug!("Tcp Hole Punch Mediator failed to initialise: {:?}", e);
                None
            }
        };

        if udp_child.is_none() && tcp_child.is_none() {
            Err(NatError::RendezvousFailed)
        } else {
            {
                let mut m = mediator.borrow_mut();
                m.state = State::Rendezvous {
                    info: RendezvousInfo::with_key(ifc.enc_pk()),
                    timeout: timeout,
                    f: f,
                };
                m.udp_child = udp_child;
                m.tcp_child = tcp_child;
            }

            if let Err((nat_state, e)) = ifc.insert_state(token, mediator) {
                // TODO Handle properly
                error!("To be handled properly: {}", e);
                nat_state.borrow_mut().terminate(ifc, poll);
                return Err(NatError::HolePunchMediatorFailedToStart);
            }

            Ok(())
        }
    }

    fn handle_udp_rendezvous(&mut self,
                             ifc: &mut Interface,
                             poll: &Poll,
                             res: ::Res<Vec<SocketAddr>>) {
        if let State::Rendezvous { ref mut info, .. } = self.state {
            if let Ok(ext_addrs) = res {
                // We assume that udp_child does not return an empty list here - rather it
                // should error out on such case (i.e. call us with an error)
                info.udp = ext_addrs;
            } else {
                self.udp_child = None;
            }
        }

        self.handle_rendezvous_impl(ifc, poll);
    }

    fn handle_tcp_rendezvous(&mut self, ifc: &mut Interface, poll: &Poll, res: ::Res<SocketAddr>) {
        if let State::Rendezvous { ref mut info, .. } = self.state {
            if let Ok(ext_addr) = res {
                info.tcp = Some(ext_addr);
            } else {
                self.tcp_child = None;
            }
        }

        self.handle_rendezvous_impl(ifc, poll);
    }

    fn handle_rendezvous_impl(&mut self, ifc: &mut Interface, poll: &Poll) {
        let r = match self.state {
            State::Rendezvous {
                ref mut info,
                ref mut f,
                ref timeout,
            } => {
                if (self.udp_child.is_none() || !info.udp.is_empty()) &&
                   (self.tcp_child.is_none() || info.tcp.is_some()) {
                    if self.udp_child.is_none() && self.tcp_child.is_none() {
                        f(ifc, poll, Err(NatError::RendezvousFailed));
                        Err(NatError::RendezvousFailed)
                    } else {
                        let _ = ifc.cancel_timeout(timeout);
                        let info = mem::replace(info, Default::default());
                        let handle = Handle {
                            token: self.token,
                            tx: ifc.sender().clone(),
                        };
                        f(ifc, poll, Ok((handle, info)));
                        Ok(true)
                    }
                } else {
                    Ok(false)
                }
            }
            ref x => {
                warn!("Logic Error in state book-keeping - Pls report this as a bug. Expected \
                       state: State::Rendezvous ;; Found: {:?}",
                      x);
                Err(NatError::InvalidState)
            }
        };

        match r {
            Ok(true) => self.state = State::ReadyToHolePunch,
            Ok(false) => (),
            Err(e @ NatError::RendezvousFailed) => {
                // This is reached only if children is empty. So no chance of borrow violation for
                // children in terminate()
                debug!("Terminating due to: {:?}", e);
                self.terminate(ifc, poll);
            }
            // Don't call terminate as that can lead to child being borrowed twice
            Err(e) => debug!("Ignoring error in handle hole-punch: {:?}", e),
        }
    }

    fn punch_hole(&mut self,
                  ifc: &mut Interface,
                  poll: &Poll,
                  peer: RendezvousInfo,
                  mut f: HolePunchFinsih) {
        match self.state {
            State::ReadyToHolePunch => (),
            ref x => {
                debug!("Improper state for this operation: {:?}", x);
                return f(ifc, poll, Err(NatError::HolePunchFailed));
            }
        };

        let dur = ifc.config()
            .hole_punch_timeout_sec
            .unwrap_or(HOLE_PUNCH_TIMEOUT_SEC);
        let timeout = match ifc.set_timeout(Duration::from_secs(dur),
                                            NatTimer::new(self.token, TIMER_ID)) {
            Ok(t) => t,
            Err(e) => {
                debug!("Terminating punch hole due to error in timer: {:?}", e);
                return self.terminate(ifc, poll);
            }
        };

        let peer_enc_pk = box_::PublicKey(peer.enc_pk);

        if let Some(udp_child) = self.udp_child.as_ref().cloned() {
            let weak = self.self_weak.clone();
            let handler = move |ifc: &mut Interface, poll: &Poll, res| if let Some(mediator) =
                weak.upgrade() {
                mediator
                    .borrow_mut()
                    .handle_udp_hole_punch(ifc, poll, res);
            };
            if let Err(e) = udp_child
                   .borrow_mut()
                   .punch_hole(ifc, poll, peer.udp, &peer_enc_pk, Box::new(handler)) {
                debug!("Udp punch hole failed to start: {:?}", e);
                self.udp_child = None;
            }
        }

        if let Some(tcp_child) = self.tcp_child.as_ref().cloned() {
            let weak = self.self_weak.clone();
            let handler = move |ifc: &mut Interface, poll: &Poll, res| if let Some(mediator) =
                weak.upgrade() {
                mediator
                    .borrow_mut()
                    .handle_tcp_hole_punch(ifc, poll, res);
            };
            if let Some(tcp_peer) = peer.tcp {
                if let Err(e) =
                    tcp_child
                        .borrow_mut()
                        .punch_hole(ifc, poll, tcp_peer, &peer_enc_pk, Box::new(handler)) {
                    debug!("Tcp punch hole failed to start: {:?}", e);
                    self.tcp_child = None;
                }
            } else {
                tcp_child.borrow_mut().terminate(ifc, poll);
                self.tcp_child = None;
            }
        }

        if self.udp_child.is_none() && self.tcp_child.is_none() {
            debug!("Failure: Not even one valid child even managed to start hole punching");
            self.terminate(ifc, poll);
            return f(ifc, poll, Err(NatError::HolePunchFailed));
        }

        self.state = State::HolePunching {
            info: HolePunchInfo::with_key(peer_enc_pk),
            timeout: timeout,
            f: f,
        };
    }

    fn handle_udp_hole_punch(&mut self,
                             ifc: &mut Interface,
                             poll: &Poll,
                             res: ::Res<(UdpSocket, SocketAddr, Token)>) {
        if let State::HolePunching { ref mut info, .. } = self.state {
            self.udp_child = None;
            if let Ok(sock) = res {
                trace!("UDP has successfully hole punched");
                info.udp = Some(sock);
            }
        }

        self.handle_hole_punch_impl(ifc, poll);
    }

    fn handle_tcp_hole_punch(&mut self,
                             ifc: &mut Interface,
                             poll: &Poll,
                             res: ::Res<(TcpStream, Token)>) {
        if let State::HolePunching { ref mut info, .. } = self.state {
            self.tcp_child = None;
            if let Ok(sock) = res {
                trace!("TCP has successfully hole punched");
                info.tcp = Some(sock);
            }
        }

        self.handle_hole_punch_impl(ifc, poll);
    }

    fn handle_hole_punch_impl(&mut self, ifc: &mut Interface, poll: &Poll) {
        let r = match self.state {
            State::HolePunching {
                ref mut info,
                ref mut f,
                ..
            } => {
                if self.tcp_child.is_none() && self.udp_child.is_none() {
                    if info.tcp.is_none() && info.udp.is_none() {
                        f(ifc, poll, Err(NatError::HolePunchFailed));
                        Err(NatError::HolePunchFailed)
                    } else {
                        let info = mem::replace(info, Default::default());
                        f(ifc, poll, Ok(info));
                        Ok(true)
                    }
                } else if info.tcp.is_none() && info.udp.is_none() {
                    // None has succeeded yet so continue waiting
                    Ok(false)
                } else {
                    // At-least one has succeeded
                    let wait = ifc.config()
                        .hole_punch_wait_for_other
                        .unwrap_or(HOLE_PUNCH_WAIT_FOR_OTHER);
                    if wait {
                        Ok(false)
                    } else {
                        let info = mem::replace(info, Default::default());
                        f(ifc, poll, Ok(info));
                        Ok(true)
                    }
                }
            }
            ref x => {
                warn!("Logic Error in state book-keeping - Pls report this as a bug. Expected \
                       state: State::HolePunching ;; Found: {:?}",
                      x);
                Err(NatError::InvalidState)
            }
        };

        match r {
            Ok(true) => self.terminate(ifc, poll),
            Ok(false) => (),
            Err(e @ NatError::HolePunchFailed) => {
                // This is reached only if children is empty. So no chance of borrow violation for
                // children in terminate()
                debug!("Terminating due to: {:?}", e);
                self.terminate(ifc, poll);
            }
            // Don't call terminate as that can lead to child being borrowed twice
            Err(e) => debug!("Ignoring error in handle hole-punch: {:?}", e),
        }
    }
}

impl NatState for HolePunchMediator {
    fn timeout(&mut self, ifc: &mut Interface, poll: &Poll, timer_id: u8) {
        if timer_id != TIMER_ID {
            debug!("Invalid Timer ID: {}", timer_id);
        }

        let terminate = match self.state {
            State::Rendezvous { .. } => {
                if let Some(udp_child) = self.udp_child.as_ref().cloned() {
                    match udp_child.borrow_mut().rendezvous_timeout(ifc, poll) {
                        // It has already gone to the next state, ignore it
                        Err(NatError::InvalidState) => (),
                        r @ Ok(_) | r @ Err(_) => self.handle_udp_rendezvous(ifc, poll, r),
                    }
                }
                if let Some(tcp_child) = self.tcp_child.as_ref().cloned() {
                    match tcp_child.borrow_mut().rendezvous_timeout(ifc, poll) {
                        // It has already gone to the next state, ignore it
                        NatError::InvalidState => (),
                        e => self.handle_tcp_rendezvous(ifc, poll, Err(e)),
                    }
                }

                false
            }
            State::HolePunching {
                ref mut info,
                ref mut f,
                ..
            } => {
                if info.tcp.is_none() && info.udp.is_none() {
                    f(ifc, poll, Err(NatError::HolePunchFailed));
                } else {
                    let info = mem::replace(info, Default::default());
                    f(ifc, poll, Ok(info));
                }

                true
            }
            ref x => {
                warn!("Logic error, report bug: terminating due to invalid state for a timeout: \
                       {:?}",
                      x);
                true
            }
        };

        if terminate {
            self.terminate(ifc, poll);
        }
    }

    fn terminate(&mut self, ifc: &mut Interface, poll: &Poll) {
        let _ = ifc.remove_state(self.token);
        match self.state {
            State::Rendezvous { ref timeout, .. } => {
                let _ = ifc.cancel_timeout(timeout);
            }
            State::HolePunching {
                ref mut info,
                ref timeout,
                ..
            } => {
                let _ = ifc.cancel_timeout(timeout);

                if let Some((ref tcp, _)) = info.tcp {
                    let _ = poll.deregister(tcp);
                }
                if let Some((ref udp, ..)) = info.udp {
                    let _ = poll.deregister(udp);
                }
            }
            _ => (),
        }
        if let Some(udp_child) = self.udp_child.take() {
            udp_child.borrow_mut().terminate(ifc, poll);
        }
        if let Some(tcp_child) = self.tcp_child.take() {
            tcp_child.borrow_mut().terminate(ifc, poll);
        }
    }

    fn as_any(&mut self) -> &mut Any {
        self
    }
}

/// Handle to the [`HolePunchMediator`].
///
/// Using this handle, the user can provide peer rendezvous information to begin hole punching. The
/// handle is flexible enough to invoke hole punching either from another thread or from the event
/// loop thread. The choice is up to the user.
///
/// Dropping this handle will clean up all the internal states associated with this handle and the
/// entire [`HolePunchMediator`] for this handle will terminate gracefully.
///
/// [`HolePunchMediator`]: ../p2p/hole_punch/struct.HolePunchMediator.html
pub struct Handle {
    token: Token,
    tx: Sender<NatMsg>,
}

impl Handle {
    /// Fire hole punch request from a non-event loop thread.
    pub fn fire_hole_punch(self, peer: RendezvousInfo, f: HolePunchFinsih) {
        let token = self.token;
        if let Err(e) = self.tx
               .send(NatMsg::new(move |ifc, poll| {
                                     Handle::start_hole_punch(ifc, poll, token, peer, f)
                                 })) {
            debug!("Could not fire hole punch request: {:?}", e);
        } else {
            mem::forget(self);
        }
    }

    /// Request hole punch from within the event loop thread.
    pub fn start_hole_punch(ifc: &mut Interface,
                            poll: &Poll,
                            hole_punch_mediator: Token,
                            peer: RendezvousInfo,
                            mut f: HolePunchFinsih) {
        if let Some(nat_state) = ifc.state(hole_punch_mediator) {
            let mut state = nat_state.borrow_mut();
            let mediator = match state.as_any().downcast_mut::<HolePunchMediator>() {
                Some(m) => m,
                None => {
                    debug!("Token has some other state mapped, not HolePunchMediator");
                    return f(ifc, poll, Err(NatError::InvalidState));
                }
            };
            mediator.punch_hole(ifc, poll, peer, f);

        }
    }

    /// Obtain the token associated with the HolePunchMediator to which this is a handle.
    pub fn mediator_token(self) -> Token {
        let token = self.token;
        mem::forget(self);
        token
    }
}

impl Drop for Handle {
    fn drop(&mut self) {
        let token = self.token;
        let _ = self.tx
            .send(NatMsg::new(move |ifc, poll| if let Some(nat_state) = ifc.state(token) {
                                  nat_state.borrow_mut().terminate(ifc, poll);
                              }));
    }
}