File: IOLoop.pm

package info (click to toggle)
libmojolicious-perl 0.999926-1%2Bsqueeze2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,672 kB
  • ctags: 949
  • sloc: perl: 17,391; makefile: 4
file content (1739 lines) | stat: -rw-r--r-- 39,805 bytes parent folder | download
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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
# Copyright (C) 2008-2010, Sebastian Riedel.

package Mojo::IOLoop;

use strict;
use warnings;

use base 'Mojo::Base';

use Carp 'croak';
use Errno qw/EAGAIN EWOULDBLOCK/;
use File::Spec;
use IO::File;
use IO::Poll qw/POLLERR POLLHUP POLLIN POLLOUT/;
use IO::Socket;
use Mojo::ByteStream;
use Socket qw/IPPROTO_TCP TCP_NODELAY/;
use Time::HiRes 'time';

use constant CHUNK_SIZE => $ENV{MOJO_CHUNK_SIZE} || 8192;

# Epoll support requires IO::Epoll
use constant EPOLL => ($ENV{MOJO_POLL} || $ENV{MOJO_KQUEUE})
  ? 0
  : eval 'use IO::Epoll 0.02 (); 1';
use constant EPOLL_POLLERR => EPOLL ? IO::Epoll::POLLERR() : 0;
use constant EPOLL_POLLHUP => EPOLL ? IO::Epoll::POLLHUP() : 0;
use constant EPOLL_POLLIN  => EPOLL ? IO::Epoll::POLLIN()  : 0;
use constant EPOLL_POLLOUT => EPOLL ? IO::Epoll::POLLOUT() : 0;

# IPv6 support requires IO::Socket::INET6
use constant IPV6 => $ENV{MOJO_NO_IPV6}
  ? 0
  : eval 'use IO::Socket::INET6 2.64 (); 1';

# KQueue support requires IO::KQueue
use constant KQUEUE => ($ENV{MOJO_POLL} || $ENV{MOJO_EPOLL})
  ? 0
  : eval 'use IO::KQueue 0.34 (); 1';
use constant KQUEUE_ADD    => KQUEUE ? IO::KQueue::EV_ADD()       : 0;
use constant KQUEUE_DELETE => KQUEUE ? IO::KQueue::EV_DELETE()    : 0;
use constant KQUEUE_EOF    => KQUEUE ? IO::KQueue::EV_EOF()       : 0;
use constant KQUEUE_READ   => KQUEUE ? IO::KQueue::EVFILT_READ()  : 0;
use constant KQUEUE_WRITE  => KQUEUE ? IO::KQueue::EVFILT_WRITE() : 0;

# TLS support requires IO::Socket::SSL
use constant TLS => $ENV{MOJO_NO_TLS}
  ? 0
  : eval 'use IO::Socket::SSL 1.33 (); 1';
use constant TLS_READ  => TLS ? IO::Socket::SSL::SSL_WANT_READ()  : 0;
use constant TLS_WRITE => TLS ? IO::Socket::SSL::SSL_WANT_WRITE() : 0;

# Default TLS cert (20.03.2010)
# (openssl req -new -x509 -keyout cakey.pem -out cacert.pem -nodes -days 7300)
use constant CERT => <<EOF;
-----BEGIN CERTIFICATE-----
MIIDbzCCAtigAwIBAgIJAM+kFv1MwalmMA0GCSqGSIb3DQEBBQUAMIGCMQswCQYD
VQQGEwJERTEWMBQGA1UECBMNTmllZGVyc2FjaHNlbjESMBAGA1UEBxMJSGFtYmVy
Z2VuMRQwEgYDVQQKEwtNb2pvbGljaW91czESMBAGA1UEAxMJbG9jYWxob3N0MR0w
GwYJKoZIhvcNAQkBFg5rcmFpaEBjcGFuLm9yZzAeFw0xMDAzMjAwMDQ1MDFaFw0z
MDAzMTUwMDQ1MDFaMIGCMQswCQYDVQQGEwJERTEWMBQGA1UECBMNTmllZGVyc2Fj
aHNlbjESMBAGA1UEBxMJSGFtYmVyZ2VuMRQwEgYDVQQKEwtNb2pvbGljaW91czES
MBAGA1UEAxMJbG9jYWxob3N0MR0wGwYJKoZIhvcNAQkBFg5rcmFpaEBjcGFuLm9y
ZzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAzu9mOiyUJB2NBuf1lZxViNM2
VISqRAoaXXGOBa6RgUoVfA/n81RQlgvVA0qCSQHC534DdYRk3CdyJR9UGPuxF8k4
CckOaHWgcJJsd8H0/q73PjbA5ItIpGTTJNh8WVpFDjHTJmQ5ihwddap4/offJxZD
dPrMFtw1ZHBRug5tHUECAwEAAaOB6jCB5zAdBgNVHQ4EFgQUo+Re5wuuzVFqH/zV
cxRGXL0j5K4wgbcGA1UdIwSBrzCBrIAUo+Re5wuuzVFqH/zVcxRGXL0j5K6hgYik
gYUwgYIxCzAJBgNVBAYTAkRFMRYwFAYDVQQIEw1OaWVkZXJzYWNoc2VuMRIwEAYD
VQQHEwlIYW1iZXJnZW4xFDASBgNVBAoTC01vam9saWNpb3VzMRIwEAYDVQQDEwls
b2NhbGhvc3QxHTAbBgkqhkiG9w0BCQEWDmtyYWloQGNwYW4ub3JnggkAz6QW/UzB
qWYwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQCZZcOeAobctD9wtPtO
40CKHpiGYEM3rh7VvBhjTcVnX6XlLvffIg3uTrVRhzmlEQCZz3O5TsBzfMAVnjYz
llhwgRF6Xn8ict9L8yKDoGSbw0Q7HaCb8/kOe0uKhcSDUd3PjJU0ZWgc20zcGFA9
R65bABoJ2vU1rlQFmjs0RT4UcQ==
-----END CERTIFICATE-----
EOF

# Default TLS key (20.03.2010)
# (openssl req -new -x509 -keyout cakey.pem -out cacert.pem -nodes -days 7300)
use constant KEY => <<EOF;
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDO72Y6LJQkHY0G5/WVnFWI0zZUhKpEChpdcY4FrpGBShV8D+fz
VFCWC9UDSoJJAcLnfgN1hGTcJ3IlH1QY+7EXyTgJyQ5odaBwkmx3wfT+rvc+NsDk
i0ikZNMk2HxZWkUOMdMmZDmKHB11qnj+h98nFkN0+swW3DVkcFG6Dm0dQQIDAQAB
AoGAeLmd8C51tqQu1GqbEc+E7zAZsDE9jDhArWdELfhsFvt7kUdOUN1Nrlv0x9i+
LY2Dgb44kmTM2suAgjvGulSMOYBGosZcM0w3ES76nmeAVJ1NBFhbZTCJqo9svoD/
NKdctRflUuvFSWimoui+vj9D5p/4lvAMdBHUWj5FlQsYiOECQQD/FRXtsDetptFu
Vp8Kw+6bZ5+efcjVfciTp7fQKI2xZ2n1QyloaV4zYXgDC2y3fMYuRigCGrX9XeFX
oGHGMyYFAkEAz635I8f4WQa/wvyl/SR5agtDVnkJqMHMgOuykytiF8NFbDSkJv+b
1VfyrWcfK/PVsSGBI67LCMDoP+PZBVOjDQJBAIInoCjH4aEZnYNPb5duojFpjmiw
helpZQ7yZTgxeRssSUR8IITGPuq4sSPckHyPjg/OfFuWhYXigTjU/Q7EyoECQERT
Dykna9wWLVZ/+jgLHOq3Y+L6FSRxBc/QO0LRvgblVlygAPVXmLQaqBtGVuoF4WLS
DANqSR/LH12Nn2NyPa0CQBbzoHgx2i3RncWoq1EeIg2mSMevEcjA6sxgYmsyyzlv
AnqxHi90n/p912ynLg2SjBq+03GaECeGzC/QqKK2gtA=
-----END RSA PRIVATE KEY-----
EOF

__PACKAGE__->attr([qw/idle_cb tick_cb/]);
__PACKAGE__->attr([qw/accept_timeout connect_timeout/] => 5);
__PACKAGE__->attr(
    [qw/lock_cb unlock_cb/] => sub {
        sub {1}
    }
);
__PACKAGE__->attr(max_connections => 1000);
__PACKAGE__->attr(timeout         => '0.25');

# Singleton
our $LOOP;

sub DESTROY {
    my $self = shift;

    # Cleanup temporary cert file
    if (my $cert = $self->{_cert}) { unlink $cert if -w $cert }

    # Cleanup temporary key file
    if (my $key = $self->{_key}) { unlink $key if -w $key }
}

sub new {
    my $self = shift->SUPER::new(@_);

    # Ignore PIPE signal
    $SIG{PIPE} = 'IGNORE';

    return $self;
}

sub connect {
    my $self = shift;

    # Arguments
    my $args = ref $_[0] ? $_[0] : {@_};

    # Options
    my %options = (
        Blocking => 0,
        PeerAddr => $args->{address},
        PeerPort => $args->{port} || ($args->{tls} ? 443 : 80),
        Proto    => 'tcp',
        Type     => SOCK_STREAM
    );

    # New connection
    my $class = IPV6 ? 'IO::Socket::INET6' : 'IO::Socket::INET';
    my $socket = $class->new(%options) or return;
    my $id = "$socket";

    # Add connection
    my $c = $self->{_cs}->{$id} = {
        buffer     => Mojo::ByteStream->new,
        connect_cb => $args->{connect_cb} || $args->{cb},
        connecting => 1,
        socket     => $socket
    };

    # Non blocking
    $socket->blocking(0);

    # Disable Nagle's algorithm
    setsockopt $socket, IPPROTO_TCP, TCP_NODELAY, 1;

    # Timeout
    $c->{connect_timer} =
      $self->timer($self->connect_timeout =>
          sub { shift->_error($id, 'Connect timeout.') });

    # File descriptor
    my $fd = fileno $socket;
    $self->{_fds}->{$fd} = $id;

    # Register callbacks
    for my $name (qw/error_cb hup_cb read_cb write_cb/) {
        my $cb = $args->{$name};
        $self->$name($id => $cb) if $cb;
    }

    # Add socket to poll
    $self->writing($id);

    # Start TLS
    if ($args->{tls}) { return unless $id = $self->start_tls($id => $args) }

    return $id;
}

sub connection_timeout {
    my ($self, $id, $timeout) = @_;

    # Connection
    return unless my $c = $self->{_cs}->{$id};

    # Timeout
    $c->{timeout} = $timeout and return $self if $timeout;

    return $c->{timeout};
}

sub drop {
    my ($self, $id) = @_;

    # Connection
    if (my $c = $self->{_cs}->{$id}) {

        # Protected connection
        my $protected = $c->{protected} || 0;

        # Finish connection once buffer is empty
        if (my $buffer = $c->{buffer}) { $protected = 1 if $buffer->size }

        # Delay connection drop
        if ($protected) {
            $c->{finish} = 1;
            return $self;
        }
    }

    # Drop
    return $self->_drop_immediately($id);
}

sub error_cb { shift->_add_event('error', @_) }

sub generate_port {
    my $self = shift;

    # Ports
    my $port = 1 . int(rand 10) . int(rand 10) . int(rand 10) . int(rand 10);
    while ($port++ < 30000) {

        # Try port
        return $port
          if IO::Socket::INET->new(
            Listen    => 5,
            LocalAddr => '127.0.0.1',
            LocalPort => $port,
            Proto     => 'tcp'
          );
    }

    # Nothing
    return;
}

sub hup_cb { shift->_add_event('hup', @_) }

sub is_running { shift->{_running} }

# Fat Tony is a cancer on this fair city!
# He is the cancer and I am the… uh… what cures cancer?
sub listen {
    my $self = shift;

    # Arguments
    my $args = ref $_[0] ? $_[0] : {@_};

    # TLS check
    croak "IO::Socket::SSL 1.33 required for TLS support"
      if $args->{tls} && !TLS;

    # Options
    my %options = (
        Blocking => 0,
        Listen   => $args->{queue_size} || SOMAXCONN,
        Type     => SOCK_STREAM
    );

    # Listen on UNIX domain socket
    my $socket;
    if (my $file = $args->{file}) {

        # Path
        $options{Local} = $file;

        # Create socket
        $socket = IO::Socket::UNIX->new(%options)
          or croak "Can't create listen socket: $!";
    }

    # Listen on port
    else {

        # Socket options
        $options{LocalAddr} = $args->{address} || (IPV6 ? '::' : '0.0.0.0');
        $options{LocalPort} = $args->{port}    || 3000;
        $options{Proto}     = 'tcp';
        $options{ReuseAddr} = 1;

        # Create socket
        my $class = IPV6 ? 'IO::Socket::INET6' : 'IO::Socket::INET';
        $socket = $class->new(%options)
          or croak "Can't create listen socket: $!";
    }
    my $id = "$socket";

    # Add listen socket
    my $c = $self->{_listen}->{$id} = {
        accept_cb => $args->{accept_cb} || $args->{cb},
        error_cb => $args->{error_cb},
        file => $args->{file} ? 1 : 0,
        hup_cb   => $args->{hup_cb},
        read_cb  => $args->{read_cb},
        socket   => $socket,
        write_cb => $args->{write_cb}
    };

    # TLS options
    $c->{tls} = {
        SSL_startHandshake => 0,
        SSL_cert_file      => $args->{tls_cert} || $self->_prepare_cert,
        SSL_key_file       => $args->{tls_key} || $self->_prepare_key
      }
      if $args->{tls};

    # File descriptor
    my $fd = fileno $socket;
    $self->{_fds}->{$fd} = $id;

    return $id;
}

sub local_info {
    my ($self, $id) = @_;

    # Connection
    return {} unless my $c = $self->{_cs}->{$id};

    # Socket
    return {} unless my $socket = $c->{socket};

    # UNIX domain socket info
    return {path => $socket->hostpath} if $socket->can('hostpath');

    # Info
    return {address => $socket->sockhost, port => $socket->sockport};
}

sub not_writing {
    my ($self, $id) = @_;

    # Connection
    return unless my $c = $self->{_cs}->{$id};

    # Activity
    $self->_activity($id);

    # Chunk still in buffer or protected
    my $protected = $c->{protected} || 0;
    if (my $buffer = $c->{buffer}) { $protected = 1 if $buffer->size }
    return $c->{read_only} = 1 if $protected;

    # Socket
    return unless my $socket = $c->{socket};

    # Writing
    my $writing = $c->{writing};

    # KQueue
    my $loop = $self->{_loop} ||= $self->_build_loop;
    if (KQUEUE) {
        my $fd = fileno $socket;

        # Writing
        $loop->EV_SET($fd, KQUEUE_READ, KQUEUE_ADD) unless defined $writing;
        $loop->EV_SET($fd, KQUEUE_WRITE, KQUEUE_DELETE) if $writing;
    }

    # Poll and epoll
    else {

        # Not writing anymore
        if ($writing) {
            $loop->remove($socket);
            $writing = undef;
        }

        # Reading
        my $mask = EPOLL ? EPOLL_POLLIN : POLLIN;
        $loop->mask($socket, $mask) unless defined $writing;
    }

    # Not writing anymore
    $c->{writing} = 0;
}

sub one_tick {
    my ($self, $timeout) = @_;

    # Timeout
    $timeout = $self->timeout unless defined $timeout;

    # Listening
    my $loop = $self->{_loop} ||= $self->_build_loop;
    if (!$self->{_listening} && $self->_should_listen) {

        # Add listen sockets
        my $listen = $self->{_listen} || {};
        for my $lid (keys %$listen) {
            my $socket = $listen->{$lid}->{socket};
            my $fd     = fileno $socket;

            # KQueue
            $loop->EV_SET($fd, KQUEUE_READ, KQUEUE_ADD) if KQUEUE;

            # Epoll
            $loop->mask($socket, EPOLL_POLLIN) if EPOLL;

            # Poll
            $loop->mask($socket, POLLIN) unless KQUEUE || EPOLL;
        }

        # Listening
        $self->{_listening} = 1;
    }

    # Prepare
    $self->_prepare;

    # Events
    my (@error, @hup, @read, @write);

    # KQueue
    if (KQUEUE) {

        # Catch interrupted system call errors
        my @ret;
        eval { @ret = $loop->kevent(1000 * $timeout) };
        die "KQueue error: $@" if $@;

        # Events
        for my $kev (@ret) {
            my ($fd, $filter, $flags, $fflags) = @$kev;

            # Id
            my $id = $self->{_fds}->{$fd};
            next unless $id;

            # Error
            if ($flags == KQUEUE_EOF) {
                if   ($fflags) { push @error, $id }
                else           { push @hup,   $id }
            }

            # Read
            push @read, $id if $filter == KQUEUE_READ;

            # Write
            push @write, $id if $filter == KQUEUE_WRITE;
        }
    }

    # Epoll
    elsif (EPOLL) {
        $loop->poll($timeout);

        # Read
        push @read, $_ for $loop->handles(EPOLL_POLLIN);

        # Write
        push @write, $_ for $loop->handles(EPOLL_POLLOUT);

        # Error
        push @error, $_ for $loop->handles(EPOLL_POLLERR);

        # HUP
        push @hup, $_ for $loop->handles(EPOLL_POLLHUP);
    }

    # Poll
    else {
        $loop->poll($timeout);

        # Read
        push @read, $_ for $loop->handles(POLLIN);

        # Write
        push @write, $_ for $loop->handles(POLLOUT);

        # Error
        push @error, $_ for $loop->handles(POLLERR);

        # HUP
        push @hup, $_ for $loop->handles(POLLHUP);
    }

    # Read
    $self->_read($_) for @read;

    # Write
    $self->_write($_) for @write;

    # Error
    $self->_error($_) for @error;

    # HUP
    $self->_hup($_) for @hup;

    # Timers
    my $timers = $self->_timer;

    # Tick callback
    if (my $cb = $self->tick_cb) {
        $self->_run_callback('tick', $cb);
    }

    # Idle callback
    if (my $cb = $self->idle_cb) {
        $self->_run_callback('idle', $cb)
          unless @read || @write || @error || @hup || $timers;
    }
}

sub read_cb { shift->_add_event('read', @_) }

sub remote_info {
    my ($self, $id) = @_;

    # Connection
    return {} unless my $c = $self->{_cs}->{$id};

    # Socket
    return {} unless my $socket = $c->{socket};

    # UNIX domain socket info
    return {path => $socket->peerpath} if $socket->can('peerpath');

    # Info
    return {address => $socket->peerhost, port => $socket->peerport};
}

sub singleton { $LOOP ||= shift->new(@_) }

sub start {
    my $self = shift;

    # Already running
    return if $self->{_running};

    # Running
    $self->{_running} = 1;

    # Loop
    $self->{_loop} ||= $self->_build_loop;

    # Mainloop
    $self->one_tick while $self->{_running};

    return $self;
}

sub start_tls {
    my $self = shift;
    my $id   = shift;

    # Shortcut
    $self->drop($id) and return unless TLS;

    # Arguments
    my $args = ref $_[0] ? $_[0] : {@_};

    # Options
    my %options =
      (SSL_startHandshake => 0, Timeout => $self->connect_timeout);
    if ($args->{tls_ca_file}) {
        $options{SSL_ca_file}         = $args->{tls_ca_file};
        $options{SSL_verify_mode}     = 0x01;
        $options{SSL_verify_callback} = $args->{tls_verify_cb};
    }

    # Connection
    $self->drop($id) and return unless my $c = $self->{_cs}->{$id};

    # Socket
    $self->drop($id) and return unless my $socket = $c->{socket};
    my $fd = fileno $socket;

    # Start
    $self->drop($id) and return
      unless my $new = IO::Socket::SSL->start_SSL($socket, %options);

    # Update file descriptor
    delete $self->{_fds}->{$fd};
    $fd = fileno $new;
    $self->{_fds}->{$fd} = "$new";

    # Upgrade
    $c->{socket}         = $new;
    $self->{_cs}->{$new} = delete $self->{_cs}->{$id};
    $c->{tls_connect}    = 1;

    return "$new";
}

sub stop { delete shift->{_running} }

sub timer {
    my ($self, $after, $cb) = @_;

    # Timer
    my $timer = {after => $after, cb => $cb, started => time};

    # Add timer
    my $id = "$timer";
    $self->{_ts}->{$id} = $timer;

    return $id;
}

sub write_cb { shift->_add_event('write', @_) }

sub writing {
    my ($self, $id) = @_;

    # Activity
    $self->_activity($id);

    # Connection
    my $c = $self->{_cs}->{$id};

    # Writing again
    delete $c->{read_only};

    # Socket
    return unless my $socket = $c->{socket};

    # Writing
    my $writing = $c->{writing};

    # KQueue
    my $loop = $self->{_loop} ||= $self->_build_loop;
    if (KQUEUE) {
        my $fd = fileno $socket;

        # Writing
        $loop->EV_SET($fd, KQUEUE_READ,  KQUEUE_ADD) unless defined $writing;
        $loop->EV_SET($fd, KQUEUE_WRITE, KQUEUE_ADD) unless $writing;
    }

    # Poll and epoll
    else {

        # Not writing anymore
        unless ($writing) {
            $loop->remove($socket);

            # Writing
            my $mask =
              EPOLL ? EPOLL_POLLIN | EPOLL_POLLOUT : POLLIN | POLLOUT;
            $loop->mask($socket, $mask);
        }
    }

    # Writing
    $c->{writing} = 1;
}

sub _accept {
    my ($self, $listen) = @_;

    # Accept
    my $socket = $listen->accept or return;

    # Unlock callback
    $self->unlock_cb->();

    # Listen
    my $l = $self->{_listen}->{$listen};

    # TLS handshake
    my $tls = $l->{tls};
    $socket = IO::Socket::SSL->start_SSL($socket, %$tls) if $tls;

    # Add connection
    my $id = "$socket";
    my $c = $self->{_cs}->{$id} = {
        accepting => 1,
        buffer    => Mojo::ByteStream->new,
        socket    => $socket
    };
    $c->{tls_accept} = 1 if $tls;

    # Timeout
    $c->{accept_timer} =
      $self->timer($self->accept_timeout, =>
          sub { shift->_error($id, 'Accept timeout.') });

    # Disable Nagle's algorithm
    setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1) unless $l->{file};

    # File descriptor
    my $fd = fileno $socket;
    $self->{_fds}->{$fd} = $id;

    # Register callbacks
    for my $name (qw/error_cb hup_cb read_cb write_cb/) {
        my $cb = $l->{$name};
        $self->$name($id => $cb) if $cb;
    }

    # Accept callback
    my $cb = $l->{accept_cb};
    $self->_run_event('accept', $cb, $id) if $cb;

    # Remove listen sockets
    $listen = $self->{_listen} || {};
    my $loop = $self->{_loop};
    for my $lid (keys %$listen) {
        my $socket = $listen->{$lid}->{socket};

        # Remove listen socket from kqueue
        if (KQUEUE) {
            $loop->EV_SET(fileno $socket, KQUEUE_READ, KQUEUE_DELETE);
        }

        # Remove listen socket from poll or epoll
        else { $loop->remove($socket) }
    }

    # Not listening anymore
    delete $self->{_listening};
}

sub _activity {
    my ($self, $id) = @_;

    # Connection
    return unless my $c = $self->{_cs}->{$id};

    # Activity
    return $c->{active} = time;
}

sub _add_event {
    my ($self, $event, $id, $cb) = @_;

    # Connection
    return unless my $c = $self->{_cs}->{$id};

    # Add event callback
    $c->{$event} = $cb if $cb;

    return $self;
}

# Initialize as late as possible because kqueues don't survive a fork
sub _build_loop {

    # "kqueue"
    return IO::KQueue->new if KQUEUE;

    # "epoll"
    return IO::Epoll->new if EPOLL;

    # "poll"
    return IO::Poll->new;
}

sub _drop_immediately {
    my ($self, $id) = @_;

    # Drop timer
    if ($self->{_ts}->{$id}) {

        # Drop
        delete $self->{_ts}->{$id};
        return $self;
    }

    # Delete connection
    my $c = delete $self->{_cs}->{$id};

    # Drop listen socket
    if (!$c && ($c = delete $self->{_listen}->{$id})) {

        # Not listening
        return $self unless $self->{_listening};

        # Not listening anymore
        delete $self->{_listening};
    }

    # Drop socket
    if (my $socket = $c->{socket}) {

        # Remove file descriptor
        return unless my $fd = fileno $socket;
        delete $self->{_fds}->{$fd};

        # Remove socket from kqueue
        if (my $loop = $self->{_loop}) {
            if (KQUEUE) {

                # Writing
                my $writing = $c->{writing};
                $loop->EV_SET($fd, KQUEUE_READ, KQUEUE_DELETE)
                  if defined $writing;
                $loop->EV_SET($fd, KQUEUE_WRITE, KQUEUE_DELETE) if $writing;
            }

            # Remove socket from poll or epoll
            else { $loop->remove($socket) }
        }

        # Close socket
        close $socket;
    }

    return $self;
}

sub _error {
    my ($self, $id, $error) = @_;

    # Get error callback
    my $event = $self->{_cs}->{$id}->{error};

    # Cleanup
    $self->_drop_immediately($id);

    # No event
    warn "Unhandled event error: $error" and return unless $event;

    # Error callback
    $self->_run_event('error', $event, $id, $error);
}

sub _hup {
    my ($self, $id) = @_;

    # Get hup callback
    my $event = $self->{_cs}->{$id}->{hup};

    # Cleanup
    $self->_drop_immediately($id);

    # No event
    return unless $event;

    # HUP callback
    $self->_run_event('hup', $event, $id);
}

sub _prepare {
    my $self = shift;

    # Prepare
    while (my ($id, $c) = each %{$self->{_cs}}) {

        # Accepting
        $self->_prepare_accept($id) if $c->{accepting};

        # Connecting
        $self->_prepare_connect($id) if $c->{connecting};

        # Connection needs to be finished
        if ($c->{finish}) {

            # Buffer empty
            unless ($c->{buffer} && !$c->{buffer}->size) {
                $self->_drop_immediately($id);
                next;
            }
        }

        # Read only
        $self->not_writing($id) if delete $c->{read_only};

        # Timeout
        my $timeout = $c->{timeout} || 15;

        # Last active
        my $time = $c->{active} || $self->_activity($id);

        # HUP
        $self->_hup($id) if (time - $time) >= $timeout;
    }

    # Nothing to do
    my $running = 0;

    # Connections
    my $listen = $self->{_listen} || {};
    if (keys %{$self->{_cs}}) { $running = 1 }

    # Timers
    elsif (keys %{$self->{_ts}}) { $running = 1 }

    # Listening
    elsif ($self->{_listening}) { $running = 1 }

    # Listen sockets
    elsif ($self->max_connections > 0 && keys %$listen) { $running = 1 }

    # Stopped
    delete $self->{_running} unless $running;
}

sub _prepare_accept {
    my ($self, $id) = @_;

    # Connection
    my $c = $self->{_cs}->{$id};

    # Connected
    return unless $c->{socket}->connected;

    # Accepted
    delete $c->{accepting};

    # Remove timeout
    $self->_drop_immediately(delete $c->{accept_timer});

    # Non blocking
    $c->{socket}->blocking(0);

    # Add socket to poll
    $self->not_writing($id);
}

sub _prepare_cert {
    my $self = shift;

    # Shortcut
    my $cert = $self->{_cert};
    return $cert if $cert && -r $cert;

    # Create temporary TLS cert file
    $cert = File::Spec->catfile($ENV{MOJO_TMPDIR} || File::Spec->tmpdir,
        'mojocert.pem');
    my $file = IO::File->new;
    $file->open("> $cert")
      or croak qq/Can't create temporary TLS cert file "$cert"/;
    print $file CERT;

    return $self->{_cert} = $cert;
}

sub _prepare_connect {
    my ($self, $id) = @_;

    # Connection
    my $c = $self->{_cs}->{$id};

    # Not yet connected
    return unless $c->{socket}->connected;

    # Connected
    delete $c->{connecting};

    # Remove timeout
    $self->_drop_immediately(delete $c->{connect_timer});

    # Connect callback
    my $cb = $c->{connect_cb};
    $self->_run_event('connect', $cb, $id) if $cb;
}

sub _prepare_key {
    my $self = shift;

    # Shortcut
    my $key = $self->{_key};
    return $key if $key && -r $key;

    # Create temporary TLS key file
    $key = File::Spec->catfile($ENV{MOJO_TMPDIR} || File::Spec->tmpdir,
        'mojokey.pem');
    my $file = IO::File->new;
    $file->open("> $key")
      or croak qq/Can't create temporary TLS key file "$key"/;
    print $file KEY;

    return $self->{_key} = $key;
}

sub _read {
    my ($self, $id) = @_;

    # Listen socket (new connection)
    my $found;
    my $listen = $self->{_listen} || {};
    for my $lid (keys %$listen) {
        my $socket = $listen->{$lid}->{socket};
        if ($id eq $socket) {
            $found = $socket;
            last;
        }
    }

    # Accept new connection
    return $self->_accept($found) if $found;

    # Connection
    my $c = $self->{_cs}->{$id};

    # TLS accept
    return $self->_tls_accept($id) if $c->{tls_accept};

    # TLS connect
    return $self->_tls_connect($id) if $c->{tls_connect};

    # Socket
    return unless defined(my $socket = $c->{socket});

    # Read chunk
    my $read = $socket->sysread(my $buffer, CHUNK_SIZE, 0);

    # Error
    unless (defined $read) {

        # Retry
        return if $! == EAGAIN || $! == EWOULDBLOCK;

        # Read error
        return $self->_error($id, $!);
    }

    # EOF
    return $self->_hup($id) if $read == 0;

    # Callback
    my $event = $c->{read};
    $self->_run_event('read', $event, $id, $buffer) if $event;

    # Active
    $self->_activity($id);
}

# Failed callbacks should not kill everything
sub _run_callback {
    my $self  = shift;
    my $event = shift;
    my $cb    = shift;

    # Invoke callback
    my $value = eval { $self->$cb(@_) };

    # Callback error
    warn qq/Callback "$event" failed: $@/ if $@;

    return $value;
}

# Failed events should not kill everything
sub _run_event {
    my $self  = shift;
    my $event = shift;
    my $cb    = shift;
    my $id    = shift;

    # Invoke callback
    my $value = eval { $self->$cb($id, @_) };

    # Event error
    if ($@) {
        my $message = qq/Event "$event" failed for connection "$id": $@/;
        $event eq 'error'
          ? ($self->_drop_immediately($id) and warn $message)
          : $self->_error($id, $message);
    }

    return $value;
}

sub _should_listen {
    my $self = shift;

    # Listen sockets
    my $listen = $self->{_listen} || {};
    return unless keys %$listen;

    # Connections
    my $cs = $self->{_cs};
    return unless keys %$cs < $self->max_connections;

    # Lock
    return unless $self->lock_cb->(!keys %$cs);

    return 1;
}

sub _timer {
    my $self = shift;

    # Timers
    return unless my $ts = $self->{_ts};

    # Check
    my $count = 0;
    for my $id (keys %$ts) {
        my $t = $ts->{$id};

        # Timer
        my $after = $t->{after} || 0;
        if ($after <= time - $t->{started}) {

            # Callback
            if (my $cb = $t->{cb}) {
                $self->_run_callback('timer', $cb);
                $count++;
            }

            # Drop
            $self->_drop_immediately($id);
        }
    }

    return $count;
}

sub _tls_accept {
    my ($self, $id) = @_;

    # Connection
    my $c = $self->{_cs}->{$id};

    # Connected
    if ($c->{socket}->accept_SSL) {
        delete $c->{tls_accept};
        $self->writing($id);
        return;
    }

    # Error
    my $error = $IO::Socket::SSL::SSL_ERROR;

    # Reading
    if ($error == TLS_READ) { $self->not_writing($id) }

    # Writing
    elsif ($error == TLS_WRITE) { $self->writing($id) }

    # Real error
    else { $self->_error($id, $error) }
}

sub _tls_connect {
    my ($self, $id) = @_;

    # Connection
    my $c = $self->{_cs}->{$id};

    # Connected
    if ($c->{socket}->connect_SSL) {
        delete $c->{tls_connect};
        $self->writing($id);
        return;
    }

    # Error
    my $error = $IO::Socket::SSL::SSL_ERROR;

    # Reading
    if ($error == TLS_READ) { $self->not_writing($id) }

    # Writing
    elsif ($error == TLS_WRITE) { $self->writing($id) }

    # Real error
    else { $self->_error($id, $error) }
}

sub _write {
    my ($self, $id) = @_;

    # Connection
    my $c = $self->{_cs}->{$id};

    # TLS accept
    return $self->_tls_accept($id) if $c->{tls_accept};

    # TLS connect
    return $self->_tls_connect($id) if $c->{tls_connect};

    # Connect has just completed
    return if $c->{connecting};

    # Buffer
    my $buffer = $c->{buffer};

    # Try to fill the buffer before writing
    my $more = !$c->{read_only} && !$c->{finish} ? 1 : 0;
    my $event = $c->{write};
    if ($more && $event && $buffer->size < CHUNK_SIZE) {

        # Write callback
        $c->{protected} = 1;
        my $chunk = $self->_run_event('write', $event, $id);
        delete $c->{protected};

        # Add to buffer
        $buffer->add_chunk($chunk);
    }

    # Socket
    return unless my $socket = $c->{socket};
    return unless $socket->connected;

    # Try to write whole buffer
    my $chunk = $buffer->to_string;

    # Write
    my $written = $socket->syswrite($chunk, length $chunk);

    # Error
    unless (defined $written) {

        # Retry
        return if $! == EAGAIN || $! == EWOULDBLOCK;

        # Write error
        return $self->_error($id, $!);
    }

    # Remove written chunk from buffer
    $buffer->remove($written);

    # Activity
    $self->_activity($id) if $written;
}

1;
__END__

=head1 NAME

Mojo::IOLoop - Minimalistic Reactor For TCP Clients And Servers

=head1 SYNOPSIS

    use Mojo::IOLoop;

    # Create loop
    my $loop = Mojo::IOLoop->new;

    # Listen on port 3000
    $loop->listen(
        port => 3000,
        accept_cb => sub {
            my ($self, $id) = @_;

            # Start read only when accepting a new connection
            $self->not_writing($id);
        },
        read_cb => sub {
            my ($self, $id, $chunk) = @_;

            # Process input
            print $chunk;

            # Got some data, time to write
            $self->writing($id);
        },
        write_cb => sub {
            my ($self, $id) = @_;

            # Back to reading only
            $self->not_writing($id);

            # The loop will take care of buffering for us
            return 'HTTP/1.1 200 OK';
        }
    );

    # Connect to port 3000 with TLS activated
    my $id = $loop->connect(
        address => 'localhost',
        port => 3000,
        tls => 1,
        write_cb => sub {
            my ($self, $id) = @_;

            # Back to reading only
            $self->not_writing($id);

            # The loop will take care of buffering for us
            return "GET / HTTP/1.1\r\n\r\n";
        },
        read_cb => sub {
            my ($self, $id, $chunk) = @_;

            # Process input
            print $chunk;

            # Time to write more
            $self->writing($id);
        }
    );

    # Loop starts writing
    $loop->writing($id);

    # Add a timer
    $loop->timer(5 => sub {
        my $self = shift;
        $self->drop($id);
    });

    # Start and stop loop
    $loop->start;
    $loop->stop;

=head1 DESCRIPTION

L<Mojo::IOLoop> is a very minimalistic reactor that has been reduced to the
absolute minimal feature set required to build solid and scalable TCP clients
and servers.

Optional modules L<IO::KQueue>, L<IO::Epoll>, L<IO::Socket::INET6> and
L<IO::Socket::SSL> are supported transparently and used if installed.

=head1 ATTRIBUTES

L<Mojo::IOLoop> implements the following attributes.

=head2 C<accept_timeout>

    my $timeout = $loop->accept_timeout;
    $loop       = $loop->accept_timeout(5);

Maximum time in seconds a connection can take to be accepted before being
dropped, defaults to C<5>.

=head2 C<connect_timeout>

    my $timeout = $loop->connect_timeout;
    $loop       = $loop->connect_timeout(5);

Maximum time in seconds a conenction can take to be connected before being
dropped, defaults to C<5>.

=head2 C<idle_cb>

    my $cb = $loop->idle_cb;
    $loop  = $loop->idle_cb(sub {...});

Callback to be invoked on every reactor tick if no events occurred.
Note that this attribute is EXPERIMENTAL and might change without warning!

=head2 C<lock_cb>

    my $cb = $loop->lock_cb;
    $loop  = $loop->lock_cb(sub {...});

A locking callback that decides if this loop is allowed to listen for new
incoming connections, used to sync multiple server processes.
The callback should return true or false.
Note that exceptions in this callback are not captured.

    $loop->lock_cb(sub {
        my ($loop, $blocking) = @_;

        # Got the lock, listen for new connections
        return 1;
    });

=head2 C<max_connections>

    my $max = $loop->max_connections;
    $loop   = $loop->max_connections(1000);

The maximum number of connections this loop is allowed to handle before
stopping to accept new incoming connections, defaults to C<1000>.
Setting the value to C<0> will make this loop stop accepting new connections
and allow it to shutdown gracefully without interrupting existing
connections.

=head2 C<tick_cb>

    my $cb = $loop->tick_cb;
    $loop  = $loop->tick_cb(sub {...});

Callback to be invoked on every reactor tick, this for example allows you to
run multiple reactors next to each other.

    my $loop2 = Mojo::IOLoop->new(timeout => 0);
    Mojo::IOLoop->singleton->tick_cb(sub { $loop2->one_tick });

Note that the loop timeout can be changed dynamically at any time to adjust
responsiveness.

=head2 C<timeout>

    my $timeout = $loop->timeout;
    $loop       = $loop->timeout(5);

Maximum time in seconds our loop waits for new events to happen, defaults to
C<0.25>.
Note that a value of C<0> would make the loop non blocking.

=head2 C<unlock_cb>

    my $cb = $loop->unlock_cb;
    $loop  = $loop->unlock_cb(sub {...});

A callback to free the listen lock, called after accepting a new connection
and used to sync multiple server processes.
Note that exceptions in this callback are not captured.

=head1 METHODS

L<Mojo::IOLoop> inherits all methods from L<Mojo::Base> and implements the
following new ones.

=head2 C<new>

    my $loop = Mojo::IOLoop->new;

Construct a new L<Mojo::IOLoop> object.
Multiple of these will block each other, so use C<singleton> instead if
possible.

=head2 C<connect>

    my $id = $loop->connect(
        address => '127.0.0.1',
        port    => 3000
    );
    my $id = $loop->connect({
        address => '[::1]',
        port    => 443,
        tls     => 1
    });

Open a TCP connection to a remote host, IPv6 will be used automatically if
available.
Note that IPv6 support depends on L<IO::Socket::INET6> and TLS support on
L<IO::Socket::SSL>.

These options are currently available.

=over 4

=item C<address>

Address or host name of the peer to connect to.

=item C<connect_cb>

Callback to be invoked once the connection is established.

=item C<error_cb>

Callback to be invoked if an error event happens on the connection.

=item C<hup_cb>

Callback to be invoked if the connection gets closed.

=item C<port>

Port to connect to.

=item C<read_cb>

Callback to be invoked if new data arrives on the connection.

=item C<tls>

Enable TLS.

=item C<tls_ca_file>

CA file to use for TLS.

=item C<tls_verify_cb>

Callback to invoke for TLS verification.

=item C<write_cb>

Callback to be invoked if new data can be written to the connection.
The callback should return a chunk of data which will be buffered inside the
loop to guarantee safe writing.

=back

=head2 C<connection_timeout>

    my $timeout = $loop->connection_timeout($id);
    $loop       = $loop->connection_timeout($id => 45);

Maximum amount of time in seconds a connection can be inactive before being
dropped.

=head2 C<drop>

    $loop = $loop->drop($id);

Drop a connection, listen socket or timer.
Connections will be dropped gracefully by allowing them to finish writing all
data in it's write buffer.

=head2 C<error_cb>

    $loop = $loop->error_cb($id => sub {...});

Callback to be invoked if an error event happens on the connection.

=head2 C<generate_port>

    my $port = $loop->generate_port;

Find a free TCP port, this is a utility function primarily used for tests.

=head2 C<hup_cb>

    $loop = $loop->hup_cb($id => sub {...});

Callback to be invoked if the connection gets closed.

=head2 C<is_running>

    my $running = $loop->is_running;

Check if loop is running.

    exit unless Mojo::IOLoop->singleton->is_running;

=head2 C<listen>

    my $id = $loop->listen(port => 3000);
    my $id = $loop->listen({port => 3000});
    my $id = $loop->listen(file => '/foo/myapp.sock');
    my $id = $loop->listen(
        port     => 443,
        tls      => 1,
        tls_cert => '/foo/server.cert',
        tls_key  => '/foo/server.key'
    );

Create a new listen socket, IPv6 will be used automatically if available.
Note that IPv6 support depends on L<IO::Socket::INET6> and TLS support on
L<IO::Socket::SSL>.

These options are currently available.

=over 4

=item C<address>

Local address to listen on, defaults to all.

=item C<accept_cb>

Callback to invoke for each accepted connection.

=item C<error_cb>

Callback to be invoked if an error event happens on the connection.

=item C<file>

A unix domain socket to listen on.

=item C<hup_cb>

Callback to be invoked if the connection gets closed.

=item C<port>

Port to listen on.

=item C<queue_size>

Maximum queue size, defaults to C<SOMAXCONN>.

=item C<read_cb>

Callback to be invoked if new data arrives on the connection.

=item C<tls>

Enable TLS.

=item C<tls_cert>

Path to the TLS cert file.

=item C<tls_key>

Path to the TLS key file.

=item C<write_cb>

Callback to be invoked if new data can be written to the connection.
The callback should return a chunk of data which will be buffered inside the
loop to guarantee safe writing.

=back

=head2 C<local_info>

    my $info = $loop->local_info($id);

Get local information about a connection.

    my $address = $info->{address};

These values are to be expected in the returned hash reference.

=over 4

=item C<address>

The local address.

=item C<port>

The local port.

=back

=head2 C<not_writing>

    $loop->not_writing($id);

Activate read only mode for a connection.
Note that connections have no mode after they are created.

=head2 C<one_tick>

    $loop->one_tick;
    $loop->one_tick('0.25');
    $loop->one_tick(0);

Run reactor for exactly one tick.

=head2 C<read_cb>

    $loop = $loop->read_cb($id => sub {...});

Callback to be invoked if new data arrives on the connection.

    $loop->read_cb($id => sub {
        my ($loop, $id, $chunk) = @_;

        # Process chunk
    });

=head2 C<remote_info>

    my $info = $loop->remote_info($id);

Get remote information about a connection.

    my $address = $info->{address};

These values are to be expected in the returned hash reference.

=over 4

=item C<address>

The remote address.

=item C<port>

The remote port.

=back

=head2 C<singleton>

    my $loop = Mojo::IOLoop->singleton;

The global loop object, used to access a single shared loop instance from
everywhere inside the process.

=head2 C<start>

    $loop->start;

Start the loop, this will block until the loop is finished or return
immediately if the loop is already running.

=head2 C<start_tls>

    my $id = $loop->start_tls($id);
    my $id = $loop->start_tls($id => {tls_ca_file => '/etc/tls/cacerts.pem'});

Start new TLS connection inside old connection.
Note that TLS support depends on L<IO::Socket::SSL>.

These options are currently available.

=over 4

=item C<tls_ca_file>

CA file to use for TLS.

=item C<tls_verify_cb>

Callback to invoke for TLS verification.

=back

=head2 C<stop>

    $loop->stop;

Stop the loop immediately, this will not interrupt any existing connections
and the loop can be restarted by running C<start> again.

=head2 C<timer>

    my $id = $loop->timer(5 => sub {...});
    my $id = $loop->timer(0.25 => sub {...});

Create a new timer, invoking the callback afer a given amount of seconds.

=head2 C<write_cb>

    $loop = $loop->write_cb($id => sub {...});

Callback to be invoked if new data can be written to the connection.
The callback should return a chunk of data which will be buffered inside the
loop to guarantee safe writing.

    $loop->write_cb($id => sub {
        my ($loop, $id) = @_;
        return 'Data to be buffered by the loop!';
    });

=head2 C<writing>

    $loop->writing($id);

Activate read/write mode for a connection.
Note that connections have no mode after they are created.

=head1 SEE ALSO

L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>.

=cut