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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
use std::borrow::Borrow;
use std::io::{Error as IoError, ErrorKind};
use std::net::{SocketAddr, ToSocketAddrs};
use std::time::Duration;
use std::usize;

use mio;
use mio::tcp::{TcpListener, TcpStream};
use mio::{Poll, PollOpt, Ready, Token};
use mio_extras;

use url::Url;

#[cfg(feature = "native_tls")]
use native_tls::Error as SslError;

use super::Settings;
use communication::{Command, Sender, Signal};
use connection::Connection;
use factory::Factory;
use slab::Slab;
use result::{Error, Kind, Result};


const QUEUE: Token = Token(usize::MAX - 3);
const TIMER: Token = Token(usize::MAX - 4);
pub const ALL: Token = Token(usize::MAX - 5);
const SYSTEM: Token = Token(usize::MAX - 6);

type Conn<F> = Connection<<F as Factory>::Handler>;

const MAX_EVENTS: usize = 1024;
const MESSAGES_PER_TICK: usize = 256;
const TIMER_TICK_MILLIS: u64 = 100;
const TIMER_WHEEL_SIZE: usize = 1024;
const TIMER_CAPACITY: usize = 65_536;

#[cfg(not(windows))]
const CONNECTION_REFUSED: i32 = 111;
#[cfg(windows)]
const CONNECTION_REFUSED: i32 = 61;

fn url_to_addrs(url: &Url) -> Result<Vec<SocketAddr>> {
    let host = url.host_str();
    if host.is_none() || (url.scheme() != "ws" && url.scheme() != "wss") {
        return Err(Error::new(
            Kind::Internal,
            format!("Not a valid websocket url: {}", url),
        ));
    }
    let host = host.unwrap();

    let port = url.port_or_known_default().unwrap_or(80);
    let mut addrs = (&host[..], port)
        .to_socket_addrs()?
        .collect::<Vec<SocketAddr>>();
    addrs.dedup();
    Ok(addrs)
}

enum State {
    Active,
    Inactive,
}

impl State {
    fn is_active(&self) -> bool {
        match *self {
            State::Active => true,
            State::Inactive => false,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Timeout {
    connection: Token,
    event: Token,
}

pub struct Handler<F>
where
    F: Factory,
{
    listener: Option<TcpListener>,
    connections: Slab<Conn<F>>,
    factory: F,
    settings: Settings,
    state: State,
    queue_tx: mio::channel::SyncSender<Command>,
    queue_rx: mio::channel::Receiver<Command>,
    timer: mio_extras::timer::Timer<Timeout>,
    next_connection_id: u32,
}

impl<F> Handler<F>
where
    F: Factory,
{
    pub fn new(factory: F, settings: Settings) -> Handler<F> {
        let (tx, rx) = mio::channel::sync_channel(settings.max_connections * settings.queue_size);
        let timer = mio_extras::timer::Builder::default()
            .tick_duration(Duration::from_millis(TIMER_TICK_MILLIS))
            .num_slots(TIMER_WHEEL_SIZE)
            .capacity(TIMER_CAPACITY)
            .build();
        Handler {
            listener: None,
            connections: Slab::with_capacity(settings.max_connections),
            factory,
            settings,
            state: State::Inactive,
            queue_tx: tx,
            queue_rx: rx,
            timer,
            next_connection_id: 0,
        }
    }

    pub fn sender(&self) -> Sender {
        Sender::new(ALL, self.queue_tx.clone(), 0)
    }

    pub fn listen(&mut self, poll: &mut Poll, addr: &SocketAddr) -> Result<&mut Handler<F>> {
        debug_assert!(
            self.listener.is_none(),
            "Attempted to listen for connections from two addresses on the same websocket."
        );

        let tcp = TcpListener::bind(addr)?;
        // TODO: consider net2 in order to set reuse_addr
        poll.register(&tcp, ALL, Ready::readable(), PollOpt::level())?;
        self.listener = Some(tcp);
        Ok(self)
    }

    pub fn local_addr(&self) -> ::std::io::Result<SocketAddr> {
        if let Some(ref listener) = self.listener {
            listener.local_addr()
        } else {
            Err(IoError::new(ErrorKind::NotFound, "Not a listening socket"))
        }
    }

    #[cfg(any(feature = "ssl", feature = "nativetls"))]
    pub fn connect(&mut self, poll: &mut Poll, url: Url) -> Result<()> {
        let settings = self.settings;

        let (tok, addresses) = {
            let (tok, entry, connection_id, handler) =
                if self.connections.len() < settings.max_connections {
                    let entry = self.connections.vacant_entry();
                    let tok = Token(entry.key());
                    let connection_id = self.next_connection_id;
                    self.next_connection_id = self.next_connection_id.wrapping_add(1);
                    (
                        tok,
                        entry,
                        connection_id,
                        self.factory.client_connected(Sender::new(
                            tok,
                            self.queue_tx.clone(),
                            connection_id,
                        )),
                    )
                } else {
                    return Err(Error::new(
                        Kind::Capacity,
                        "Unable to add another connection to the event loop.",
                    ));
                };

            let mut addresses = match url_to_addrs(&url) {
                Ok(addresses) => addresses,
                Err(err) => {
                    self.factory.connection_lost(handler);
                    return Err(err);
                }
            };

            loop {
                if let Some(addr) = addresses.pop() {
                    if let Ok(sock) = TcpStream::connect(&addr) {
                        if settings.tcp_nodelay {
                            sock.set_nodelay(true)?
                        }
                        addresses.push(addr); // Replace the first addr in case ssl fails and we fallback
                        entry.insert(Connection::new(tok, sock, handler, settings, connection_id));
                        break;
                    }
                } else {
                    self.factory.connection_lost(handler);
                    return Err(Error::new(
                        Kind::Internal,
                        format!("Unable to obtain any socket address for {}", url),
                    ));
                }
            }

            (tok, addresses)
        };

        let will_encrypt = url.scheme() == "wss";

        if let Err(error) = self.connections[tok.into()].as_client(url, addresses) {
            let handler = self.connections.remove(tok.into()).consume();
            self.factory.connection_lost(handler);
            return Err(error);
        }

        if will_encrypt {
            while let Err(ssl_error) = self.connections[tok.into()].encrypt() {
                match ssl_error.kind {
                    #[cfg(feature = "ssl")]
                    Kind::Ssl(ref inner_ssl_error) => {
                        if let Some(io_error) = inner_ssl_error.io_error() {
                            if let Some(errno) = io_error.raw_os_error() {
                                if errno == CONNECTION_REFUSED {
                                    if let Err(reset_error) = self.connections[tok.into()].reset() {
                                        trace!(
                                            "Encountered error while trying to reset connection: {:?}",
                                            reset_error
                                        );
                                    } else {
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                    #[cfg(feature = "nativetls")]
                    Kind::Ssl(_) => {
                        if let Err(reset_error) = self.connections[tok.into()].reset() {
                            trace!(
                                "Encountered error while trying to reset connection: {:?}",
                                reset_error
                            );
                        } else {
                            continue;
                        }
                    }
                    _ => (),
                }
                self.connections[tok.into()].error(ssl_error);
                // Allow socket to be registered anyway to await hangup
                break;
            }
        }

        poll.register(
            self.connections[tok.into()].socket(),
            self.connections[tok.into()].token(),
            self.connections[tok.into()].events(),
            PollOpt::edge() | PollOpt::oneshot(),
        ).map_err(Error::from)
            .or_else(|err| {
                error!(
                    "Encountered error while trying to build WebSocket connection: {}",
                    err
                );
                let handler = self.connections.remove(tok.into()).consume();
                self.factory.connection_lost(handler);
                Err(err)
            })
    }

    #[cfg(not(any(feature = "ssl", feature = "nativetls")))]
    pub fn connect(&mut self, poll: &mut Poll, url: Url) -> Result<()> {
        let settings = self.settings;

        let (tok, addresses) = {
            let (tok, entry, connection_id, handler) =
                if self.connections.len() < settings.max_connections {
                    let entry = self.connections.vacant_entry();
                    let tok = Token(entry.key());
                    let connection_id = self.next_connection_id;
                    self.next_connection_id = self.next_connection_id.wrapping_add(1);
                    (
                        tok,
                        entry,
                        connection_id,
                        self.factory.client_connected(Sender::new(
                            tok,
                            self.queue_tx.clone(),
                            connection_id,
                        )),
                    )
                } else {
                    return Err(Error::new(
                        Kind::Capacity,
                        "Unable to add another connection to the event loop.",
                    ));
                };

            let mut addresses = match url_to_addrs(&url) {
                Ok(addresses) => addresses,
                Err(err) => {
                    self.factory.connection_lost(handler);
                    return Err(err);
                }
            };

            loop {
                if let Some(addr) = addresses.pop() {
                    if let Ok(sock) = TcpStream::connect(&addr) {
                        if settings.tcp_nodelay {
                            sock.set_nodelay(true)?
                        }
                        entry.insert(Connection::new(tok, sock, handler, settings, connection_id));
                        break;
                    }
                } else {
                    self.factory.connection_lost(handler);
                    return Err(Error::new(
                        Kind::Internal,
                        format!("Unable to obtain any socket address for {}", url),
                    ));
                }
            }

            (tok, addresses)
        };

        if url.scheme() == "wss" {
            let error = Error::new(
                Kind::Protocol,
                "The ssl feature is not enabled. Please enable it to use wss urls.",
            );
            let handler = self.connections.remove(tok.into()).consume();
            self.factory.connection_lost(handler);
            return Err(error);
        }

        if let Err(error) = self.connections[tok.into()].as_client(url, addresses) {
            let handler = self.connections.remove(tok.into()).consume();
            self.factory.connection_lost(handler);
            return Err(error);
        }

        poll.register(
            self.connections[tok.into()].socket(),
            self.connections[tok.into()].token(),
            self.connections[tok.into()].events(),
            PollOpt::edge() | PollOpt::oneshot(),
        ).map_err(Error::from)
            .or_else(|err| {
                error!(
                    "Encountered error while trying to build WebSocket connection: {}",
                    err
                );
                let handler = self.connections.remove(tok.into()).consume();
                self.factory.connection_lost(handler);
                Err(err)
            })
    }

    #[cfg(any(feature = "ssl", feature = "nativetls"))]
    pub fn accept(&mut self, poll: &mut Poll, sock: TcpStream) -> Result<()> {
        let factory = &mut self.factory;
        let settings = self.settings;

        if settings.tcp_nodelay {
            sock.set_nodelay(true)?
        }

        let tok = {
            if self.connections.len() < settings.max_connections {
                let entry = self.connections.vacant_entry();
                let tok = Token(entry.key());
                let connection_id = self.next_connection_id;
                self.next_connection_id = self.next_connection_id.wrapping_add(1);
                let handler = factory.server_connected(Sender::new(
                    tok,
                    self.queue_tx.clone(),
                    connection_id,
                ));
                entry.insert(Connection::new(tok, sock, handler, settings, connection_id));
                tok
            } else {
                return Err(Error::new(
                    Kind::Capacity,
                    "Unable to add another connection to the event loop.",
                ));
            }
        };

        let conn = &mut self.connections[tok.into()];

        conn.as_server()?;
        if settings.encrypt_server {
            conn.encrypt()?
        }

        poll.register(
            conn.socket(),
            conn.token(),
            conn.events(),
            PollOpt::edge() | PollOpt::oneshot(),
        ).map_err(Error::from)
            .or_else(|err| {
                error!(
                    "Encountered error while trying to build WebSocket connection: {}",
                    err
                );
                conn.error(err);
                if settings.panic_on_new_connection {
                    panic!("Encountered error while trying to build WebSocket connection.");
                }
                Ok(())
            })
    }

    #[cfg(not(any(feature = "ssl", feature = "nativetls")))]
    pub fn accept(&mut self, poll: &mut Poll, sock: TcpStream) -> Result<()> {
        let factory = &mut self.factory;
        let settings = self.settings;

        if settings.tcp_nodelay {
            sock.set_nodelay(true)?
        }

        let tok = {
            if self.connections.len() < settings.max_connections {
                let entry = self.connections.vacant_entry();
                let tok = Token(entry.key());
                let connection_id = self.next_connection_id;
                self.next_connection_id = self.next_connection_id.wrapping_add(1);
                let handler = factory.server_connected(Sender::new(
                    tok,
                    self.queue_tx.clone(),
                    connection_id,
                ));
                entry.insert(Connection::new(tok, sock, handler, settings, connection_id));
                tok
            } else {
                return Err(Error::new(
                    Kind::Capacity,
                    "Unable to add another connection to the event loop.",
                ));
            }
        };

        let conn = &mut self.connections[tok.into()];

        conn.as_server()?;
        if settings.encrypt_server {
            return Err(Error::new(
                Kind::Protocol,
                "The ssl feature is not enabled. Please enable it to use wss urls.",
            ));
        }

        poll.register(
            conn.socket(),
            conn.token(),
            conn.events(),
            PollOpt::edge() | PollOpt::oneshot(),
        ).map_err(Error::from)
            .or_else(|err| {
                error!(
                    "Encountered error while trying to build WebSocket connection: {}",
                    err
                );
                conn.error(err);
                if settings.panic_on_new_connection {
                    panic!("Encountered error while trying to build WebSocket connection.");
                }
                Ok(())
            })
    }

    pub fn run(&mut self, poll: &mut Poll) -> Result<()> {
        trace!("Running event loop");
        poll.register(
            &self.queue_rx,
            QUEUE,
            Ready::readable(),
            PollOpt::edge() | PollOpt::oneshot(),
        )?;
        poll.register(&self.timer, TIMER, Ready::readable(), PollOpt::edge())?;

        self.state = State::Active;
        let result = self.event_loop(poll);
        self.state = State::Inactive;

        result
            .and(poll.deregister(&self.timer).map_err(Error::from))
            .and(poll.deregister(&self.queue_rx).map_err(Error::from))
    }

    #[inline]
    fn event_loop(&mut self, poll: &mut Poll) -> Result<()> {
        let mut events = mio::Events::with_capacity(MAX_EVENTS);
        while self.state.is_active() {
            trace!("Waiting for event");
            let nevents = match poll.poll(&mut events, None) {
                Ok(nevents) => nevents,
                Err(err) => {
                    if err.kind() == ErrorKind::Interrupted {
                        if self.settings.shutdown_on_interrupt {
                            error!("Websocket shutting down for interrupt.");
                            self.state = State::Inactive;
                        } else {
                            error!("Websocket received interrupt.");
                        }
                        0
                    } else {
                        return Err(Error::from(err));
                    }
                }
            };
            trace!("Processing {} events", nevents);

            for i in 0..nevents {
                let evt = events.get(i).unwrap();
                self.handle_event(poll, evt.token(), evt.kind());
            }

            self.check_count();
        }
        Ok(())
    }

    #[inline]
    fn schedule(&self, poll: &mut Poll, conn: &Conn<F>) -> Result<()> {
        trace!(
            "Scheduling connection to {} as {:?}",
            conn.socket()
                .peer_addr()
                .map(|addr| addr.to_string())
                .unwrap_or_else(|_| "UNKNOWN".into()),
            conn.events()
        );
        poll.reregister(
            conn.socket(),
            conn.token(),
            conn.events(),
            PollOpt::edge() | PollOpt::oneshot(),
        )?;
        Ok(())
    }

    fn shutdown(&mut self) {
        debug!("Received shutdown signal. WebSocket is attempting to shut down.");
        for (_, conn) in self.connections.iter_mut() {
            conn.shutdown();
        }
        self.factory.on_shutdown();
        self.state = State::Inactive;
        if self.settings.panic_on_shutdown {
            panic!("Panicking on shutdown as per setting.")
        }
    }

    #[inline]
    fn check_active(&mut self, poll: &mut Poll, active: bool, token: Token) {
        // NOTE: Closing state only applies after a ws connection was successfully
        // established. It's possible that we may go inactive while in a connecting
        // state if the handshake fails.
        if !active {
            if let Ok(addr) = self.connections[token.into()].socket().peer_addr() {
                debug!("WebSocket connection to {} disconnected.", addr);
            } else {
                trace!("WebSocket connection to token={:?} disconnected.", token);
            }
            let handler = self.connections.remove(token.into()).consume();
            self.factory.connection_lost(handler);
        } else {
            self.schedule(poll, &self.connections[token.into()])
                .or_else(|err| {
                    // This will be an io error, so disconnect will already be called
                    self.connections[token.into()].error(err);
                    let handler = self.connections.remove(token.into()).consume();
                    self.factory.connection_lost(handler);
                    Ok::<(), Error>(())
                })
                .unwrap()
        }
    }

    #[inline]
    fn is_client(&self) -> bool {
        self.listener.is_none()
    }

    #[inline]
    fn check_count(&mut self) {
        trace!("Active connections {:?}", self.connections.len());
        if self.connections.is_empty() {
            if !self.state.is_active() {
                debug!("Shutting down websocket server.");
            } else if self.is_client() {
                debug!("Shutting down websocket client.");
                self.factory.on_shutdown();
                self.state = State::Inactive;
            }
        }
    }

    fn handle_event(&mut self, poll: &mut Poll, token: Token, events: Ready) {
        match token {
            SYSTEM => {
                debug_assert!(false, "System token used for io event. This is a bug!");
                error!("System token used for io event. This is a bug!");
            }
            ALL => {
                if events.is_readable() {
                    match self.listener
                        .as_ref()
                        .expect("No listener provided for server websocket connections")
                        .accept()
                    {
                        Ok((sock, addr)) => {
                            info!("Accepted a new tcp connection from {}.", addr);
                            if let Err(err) = self.accept(poll, sock) {
                                error!("Unable to build WebSocket connection {:?}", err);
                                if self.settings.panic_on_new_connection {
                                    panic!("Unable to build WebSocket connection {:?}", err);
                                }
                            }
                        }
                        Err(err) => error!(
                            "Encountered an error {:?} while accepting tcp connection.",
                            err
                        ),
                    }
                }
            }
            TIMER => while let Some(t) = self.timer.poll() {
                self.handle_timeout(poll, t);
            },
            QUEUE => {
                for _ in 0..MESSAGES_PER_TICK {
                    match self.queue_rx.try_recv() {
                        Ok(cmd) => self.handle_queue(poll, cmd),
                        _ => break,
                    }
                }
                let _ = poll.reregister(
                    &self.queue_rx,
                    QUEUE,
                    Ready::readable(),
                    PollOpt::edge() | PollOpt::oneshot(),
                );
            }
            _ => {
                let active = {
                    let conn_events = self.connections[token.into()].events();

                    if (events & conn_events).is_readable() {
                        if let Err(err) = self.connections[token.into()].read() {
                            trace!("Encountered error while reading: {}", err);
                            if let Kind::Io(ref err) = err.kind {
                                if let Some(errno) = err.raw_os_error() {
                                    if errno == CONNECTION_REFUSED {
                                        match self.connections[token.into()].reset() {
                                            Ok(_) => {
                                                poll.register(
                                                    self.connections[token.into()].socket(),
                                                    self.connections[token.into()].token(),
                                                    self.connections[token.into()].events(),
                                                    PollOpt::edge() | PollOpt::oneshot(),
                                                ).or_else(|err| {
                                                        self.connections[token.into()]
                                                            .error(Error::from(err));
                                                        let handler = self.connections
                                                            .remove(token.into())
                                                            .consume();
                                                        self.factory.connection_lost(handler);
                                                        Ok::<(), Error>(())
                                                    })
                                                    .unwrap();
                                                return;
                                            }
                                            Err(err) => {
                                                trace!("Encountered error while trying to reset connection: {:?}", err);
                                            }
                                        }
                                    }
                                }
                            }
                            // This will trigger disconnect if the connection is open
                            self.connections[token.into()].error(err)
                        }
                    }

                    let conn_events = self.connections[token.into()].events();

                    if (events & conn_events).is_writable() {
                        if let Err(err) = self.connections[token.into()].write() {
                            trace!("Encountered error while writing: {}", err);
                            if let Kind::Io(ref err) = err.kind {
                                if let Some(errno) = err.raw_os_error() {
                                    if errno == CONNECTION_REFUSED {
                                        match self.connections[token.into()].reset() {
                                            Ok(_) => {
                                                poll.register(
                                                    self.connections[token.into()].socket(),
                                                    self.connections[token.into()].token(),
                                                    self.connections[token.into()].events(),
                                                    PollOpt::edge() | PollOpt::oneshot(),
                                                ).or_else(|err| {
                                                        self.connections[token.into()]
                                                            .error(Error::from(err));
                                                        let handler = self.connections
                                                            .remove(token.into())
                                                            .consume();
                                                        self.factory.connection_lost(handler);
                                                        Ok::<(), Error>(())
                                                    })
                                                    .unwrap();
                                                return;
                                            }
                                            Err(err) => {
                                                trace!("Encountered error while trying to reset connection: {:?}", err);
                                            }
                                        }
                                    }
                                }
                            }
                            // This will trigger disconnect if the connection is open
                            self.connections[token.into()].error(err)
                        }
                    }

                    // connection events may have changed
                    self.connections[token.into()].events().is_readable()
                        || self.connections[token.into()].events().is_writable()
                };

                self.check_active(poll, active, token)
            }
        }
    }

    fn handle_queue(&mut self, poll: &mut Poll, cmd: Command) {
        match cmd.token() {
            SYSTEM => {
                // Scaffolding for system events such as internal timeouts
            }
            ALL => {
                let mut dead = Vec::with_capacity(self.connections.len());

                match cmd.into_signal() {
                    Signal::Message(msg) => {
                        trace!("Broadcasting message: {:?}", msg);
                        for (_, conn) in self.connections.iter_mut() {
                            if let Err(err) = conn.send_message(msg.clone()) {
                                dead.push((conn.token(), err))
                            }
                        }
                    }
                    Signal::Close(code, reason) => {
                        trace!("Broadcasting close: {:?} - {}", code, reason);
                        for (_, conn) in self.connections.iter_mut() {
                            if let Err(err) = conn.send_close(code, reason.borrow()) {
                                dead.push((conn.token(), err))
                            }
                        }
                    }
                    Signal::Ping(data) => {
                        trace!("Broadcasting ping");
                        for (_, conn) in self.connections.iter_mut() {
                            if let Err(err) = conn.send_ping(data.clone()) {
                                dead.push((conn.token(), err))
                            }
                        }
                    }
                    Signal::Pong(data) => {
                        trace!("Broadcasting pong");
                        for (_, conn) in self.connections.iter_mut() {
                            if let Err(err) = conn.send_pong(data.clone()) {
                                dead.push((conn.token(), err))
                            }
                        }
                    }
                    Signal::Connect(url) => {
                        if let Err(err) = self.connect(poll, url.clone()) {
                            if self.settings.panic_on_new_connection {
                                panic!("Unable to establish connection to {}: {:?}", url, err);
                            }
                            error!("Unable to establish connection to {}: {:?}", url, err);
                        }
                        return;
                    }
                    Signal::Shutdown => self.shutdown(),
                    Signal::Timeout {
                        delay,
                        token: event,
                    } => {
                        let timeout = self.timer.set_timeout(
                            Duration::from_millis(delay),
                            Timeout {
                                connection: ALL,
                                event,
                            },
                        );
                        for (_, conn) in self.connections.iter_mut() {
                            if let Err(err) = conn.new_timeout(event, timeout.clone()) {
                                conn.error(err);
                            }
                        }
                        return;
                    }
                    Signal::Cancel(timeout) => {
                        self.timer.cancel_timeout(&timeout);
                        return;
                    }
                }

                for (_, conn) in self.connections.iter() {
                    if let Err(err) = self.schedule(poll, conn) {
                        dead.push((conn.token(), err))
                    }
                }
                for (token, err) in dead {
                    // note the same connection may be called twice
                    self.connections[token.into()].error(err)
                }
            }
            token => {
                let connection_id = cmd.connection_id();
                match cmd.into_signal() {
                    Signal::Message(msg) => {
                        if let Some(conn) = self.connections.get_mut(token.into()) {
                            if conn.connection_id() == connection_id {
                                if let Err(err) = conn.send_message(msg) {
                                    conn.error(err)
                                }
                            } else {
                                trace!("Connection disconnected while a message was waiting in the queue.")
                            }
                        } else {
                            trace!(
                                "Connection disconnected while a message was waiting in the queue."
                            )
                        }
                    }
                    Signal::Close(code, reason) => {
                        if let Some(conn) = self.connections.get_mut(token.into()) {
                            if conn.connection_id() == connection_id {
                                if let Err(err) = conn.send_close(code, reason) {
                                    conn.error(err)
                                }
                            } else {
                                trace!("Connection disconnected while close signal was waiting in the queue.")
                            }
                        } else {
                            trace!("Connection disconnected while close signal was waiting in the queue.")
                        }
                    }
                    Signal::Ping(data) => {
                        if let Some(conn) = self.connections.get_mut(token.into()) {
                            if conn.connection_id() == connection_id {
                                if let Err(err) = conn.send_ping(data) {
                                    conn.error(err)
                                }
                            } else {
                                trace!("Connection disconnected while ping signal was waiting in the queue.")
                            }
                        } else {
                            trace!("Connection disconnected while ping signal was waiting in the queue.")
                        }
                    }
                    Signal::Pong(data) => {
                        if let Some(conn) = self.connections.get_mut(token.into()) {
                            if conn.connection_id() == connection_id {
                                if let Err(err) = conn.send_pong(data) {
                                    conn.error(err)
                                }
                            } else {
                                trace!("Connection disconnected while pong signal was waiting in the queue.")
                            }
                        } else {
                            trace!("Connection disconnected while pong signal was waiting in the queue.")
                        }
                    }
                    Signal::Connect(url) => {
                        if let Err(err) = self.connect(poll, url.clone()) {
                            if let Some(conn) = self.connections.get_mut(token.into()) {
                                conn.error(err)
                            } else {
                                if self.settings.panic_on_new_connection {
                                    panic!("Unable to establish connection to {}: {:?}", url, err);
                                }
                                error!("Unable to establish connection to {}: {:?}", url, err);
                            }
                        }
                        return;
                    }
                    Signal::Shutdown => self.shutdown(),
                    Signal::Timeout {
                        delay,
                        token: event,
                    } => {
                        let timeout = self.timer.set_timeout(
                            Duration::from_millis(delay),
                            Timeout {
                                connection: token,
                                event,
                            },
                        );
                        if let Some(conn) = self.connections.get_mut(token.into()) {
                            if let Err(err) = conn.new_timeout(event, timeout) {
                                conn.error(err)
                            }
                        } else {
                            trace!("Connection disconnected while pong signal was waiting in the queue.")
                        }
                        return;
                    }
                    Signal::Cancel(timeout) => {
                        self.timer.cancel_timeout(&timeout);
                        return;
                    }
                }

                if self.connections.get(token.into()).is_some() {
                    if let Err(err) = self.schedule(poll, &self.connections[token.into()]) {
                        self.connections[token.into()].error(err)
                    }
                }
            }
        }
    }

    fn handle_timeout(&mut self, poll: &mut Poll, Timeout { connection, event }: Timeout) {
        let active = {
            if let Some(conn) = self.connections.get_mut(connection.into()) {
                if let Err(err) = conn.timeout_triggered(event) {
                    conn.error(err)
                }

                conn.events().is_readable() || conn.events().is_writable()
            } else {
                trace!("Connection disconnected while timeout was waiting.");
                return;
            }
        };
        self.check_active(poll, active, connection);
    }
}

mod test {
    #![allow(unused_imports, unused_variables, dead_code)]
    use std::str::FromStr;

    use url::Url;

    use super::url_to_addrs;
    use super::*;
    use result::{Error, Kind};

    #[test]
    fn test_url_to_addrs() {
        let ws_url = Url::from_str("ws://example.com?query=me").unwrap();
        let wss_url = Url::from_str("wss://example.com/suburl#fragment").unwrap();
        let bad_url = Url::from_str("http://howdy.bad.com").unwrap();
        let no_resolve = Url::from_str("ws://bad.elucitrans.com").unwrap();

        assert!(url_to_addrs(&ws_url).is_ok());
        assert!(url_to_addrs(&ws_url).unwrap().len() > 0);
        assert!(url_to_addrs(&wss_url).is_ok());
        assert!(url_to_addrs(&wss_url).unwrap().len() > 0);

        match url_to_addrs(&bad_url) {
            Ok(_) => panic!("url_to_addrs accepts http urls."),
            Err(Error {
                kind: Kind::Internal,
                details: _,
            }) => (), // pass
            err => panic!("{:?}", err),
        }

        match url_to_addrs(&no_resolve) {
            Ok(_) => panic!("url_to_addrs creates addresses for non-existent domains."),
            Err(Error {
                kind: Kind::Io(_),
                details: _,
            }) => (), // pass
            err => panic!("{:?}", err),
        }
    }

}