summaryrefslogtreecommitdiff
path: root/ext/socket/ipsocket.c
blob: 8ef0034b7d012fbb563a6d7e235f4834d33bea66 (plain)
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
/************************************************

  ipsocket.c -

  created at: Thu Mar 31 12:21:29 JST 1994

  Copyright (C) 1993-2007 Yukihiro Matsumoto

************************************************/

#include "rubysocket.h"
#include <stdio.h>

struct inetsock_arg
{
    VALUE self;
    VALUE io;

    struct {
        VALUE host, serv;
        struct rb_addrinfo *res;
    } remote, local;
    int type;
    VALUE resolv_timeout;
    VALUE connect_timeout;
};

static VALUE
inetsock_cleanup(VALUE v)
{
    struct inetsock_arg *arg = (void *)v;
    if (arg->remote.res) {
        rb_freeaddrinfo(arg->remote.res);
        arg->remote.res = 0;
    }
    if (arg->local.res) {
        rb_freeaddrinfo(arg->local.res);
        arg->local.res = 0;
    }
    if (arg->io != Qnil) {
        rb_io_close(arg->io);
        arg->io = Qnil;
    }
    return Qnil;
}

static VALUE
init_inetsock_internal(VALUE v)
{
    struct inetsock_arg *arg = (void *)v;
    int error = 0;
    int type = arg->type;
    struct addrinfo *res, *lres;
    int status = 0, local = 0;
    int family = AF_UNSPEC;
    const char *syscall = 0;
    VALUE connect_timeout = arg->connect_timeout;

    arg->remote.res = rsock_addrinfo(arg->remote.host, arg->remote.serv,
                                     family, SOCK_STREAM,
                                     (type == INET_SERVER) ? AI_PASSIVE : 0);


    /*
     * Maybe also accept a local address
     */

    if (type != INET_SERVER && (!NIL_P(arg->local.host) || !NIL_P(arg->local.serv))) {
        arg->local.res = rsock_addrinfo(arg->local.host, arg->local.serv,
                                        family, SOCK_STREAM, 0);
    }

    VALUE io = Qnil;

    for (res = arg->remote.res->ai; res; res = res->ai_next) {
#if !defined(INET6) && defined(AF_INET6)
        if (res->ai_family == AF_INET6)
            continue;
#endif
        lres = NULL;
        if (arg->local.res) {
            for (lres = arg->local.res->ai; lres; lres = lres->ai_next) {
                if (lres->ai_family == res->ai_family)
                    break;
            }
            if (!lres) {
                if (res->ai_next || status < 0)
                    continue;
                /* Use a different family local address if no choice, this
                 * will cause EAFNOSUPPORT. */
                lres = arg->local.res->ai;
            }
        }
        status = rsock_socket(res->ai_family,res->ai_socktype,res->ai_protocol);
        syscall = "socket(2)";
        if (status < 0) {
            error = errno;
            continue;
        }

        int fd = status;
        io = arg->io = rsock_init_sock(arg->self, fd);

        if (type == INET_SERVER) {
#if !defined(_WIN32) && !defined(__CYGWIN__)
            status = 1;
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
                       (char*)&status, (socklen_t)sizeof(status));
#endif
            status = bind(fd, res->ai_addr, res->ai_addrlen);
            syscall = "bind(2)";
        }
        else {
            if (lres) {
#if !defined(_WIN32) && !defined(__CYGWIN__)
                status = 1;
                setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
                           (char*)&status, (socklen_t)sizeof(status));
#endif
                status = bind(fd, lres->ai_addr, lres->ai_addrlen);
                local = status;
                syscall = "bind(2)";
            }

            if (status >= 0) {
                status = rsock_connect(io, res->ai_addr, res->ai_addrlen, (type == INET_SOCKS), connect_timeout);
                syscall = "connect(2)";
            }
        }

        if (status < 0) {
            error = errno;
            arg->io = Qnil;
            rb_io_close(io);
            io = Qnil;
            continue;
        } else {
            break;
        }
    }

    if (status < 0) {
        VALUE host, port;

        if (local < 0) {
            host = arg->local.host;
            port = arg->local.serv;
        } else {
            host = arg->remote.host;
            port = arg->remote.serv;
        }

        rsock_syserr_fail_host_port(error, syscall, host, port);
    }

    // Don't close the socket in `inetsock_cleanup` if we are returning it:
    arg->io = Qnil;

    if (type == INET_SERVER && io != Qnil) {
        status = listen(rb_io_descriptor(io), SOMAXCONN);
        if (status < 0) {
            error = errno;
            rb_io_close(io);
            rb_syserr_fail(error, "listen(2)");
        }
    }

    /* create new instance */
    return io;
}

#if FAST_FALLBACK_INIT_INETSOCK_IMPL == 0

VALUE
rsock_init_inetsock(VALUE self, VALUE remote_host, VALUE remote_serv, VALUE local_host, VALUE local_serv, int type, VALUE resolv_timeout, VALUE connect_timeout, VALUE _fast_fallback, VALUE _test_mode_settings)
{
    struct inetsock_arg arg;
    arg.self = self;
    arg.io = Qnil;
    arg.remote.host = remote_host;
    arg.remote.serv = remote_serv;
    arg.remote.res = 0;
    arg.local.host = local_host;
    arg.local.serv = local_serv;
    arg.local.res = 0;
    arg.type = type;
    arg.resolv_timeout = resolv_timeout;
    arg.connect_timeout = connect_timeout;
    return rb_ensure(init_inetsock_internal, (VALUE)&arg,
                     inetsock_cleanup, (VALUE)&arg);
}

#elif FAST_FALLBACK_INIT_INETSOCK_IMPL == 1

#define IPV6_ENTRY_POS 0
#define IPV4_ENTRY_POS 1
#define RESOLUTION_ERROR 0
#define SYSCALL_ERROR 1

static int
is_specified_ip_address(const char *hostname)
{
    if (!hostname) return false;

    struct in_addr ipv4addr;
    struct in6_addr ipv6addr;

    return (inet_pton(AF_INET6, hostname, &ipv6addr) == 1 ||
            inet_pton(AF_INET, hostname, &ipv4addr) == 1);
}

struct fast_fallback_inetsock_arg
{
    VALUE self;
    VALUE io;

    struct {
        VALUE host, serv;
        struct rb_addrinfo *res;
    } remote, local;
    int type;
    VALUE resolv_timeout;
    VALUE connect_timeout;

    const char *hostp, *portp;
    int *families;
    int family_size;
    int additional_flags;
    rb_nativethread_lock_t *lock;
    struct fast_fallback_getaddrinfo_entry *getaddrinfo_entries[2];
    struct fast_fallback_getaddrinfo_shared *getaddrinfo_shared;
    int connection_attempt_fds_size;
    int *connection_attempt_fds;
    VALUE test_mode_settings;
};

static struct fast_fallback_getaddrinfo_shared *
allocate_fast_fallback_getaddrinfo_shared(void)
{
    struct fast_fallback_getaddrinfo_shared *shared;

    shared = (struct fast_fallback_getaddrinfo_shared *)calloc(
        1,
        sizeof(struct fast_fallback_getaddrinfo_shared)
    );

    return shared;
}

static struct fast_fallback_getaddrinfo_entry *
allocate_fast_fallback_getaddrinfo_entry(void)
{
    struct fast_fallback_getaddrinfo_entry *entry;

    entry = (struct fast_fallback_getaddrinfo_entry *)calloc(
        1,
        sizeof(struct fast_fallback_getaddrinfo_entry)
    );

    return entry;
}

static void
allocate_fast_fallback_getaddrinfo_hints(struct addrinfo *hints, int family, int remote_addrinfo_hints, int additional_flags)
{
    MEMZERO(hints, struct addrinfo, 1);
    hints->ai_family = family;
    hints->ai_socktype = SOCK_STREAM;
    hints->ai_protocol = IPPROTO_TCP;
    hints->ai_flags = remote_addrinfo_hints;
    hints->ai_flags |= additional_flags;
}

static int*
allocate_connection_attempt_fds(int additional_capacity)
{
    int *fds = (int *)malloc(additional_capacity * sizeof(int));
    if (!fds) rb_syserr_fail(errno, "malloc(3)");
    for (int i = 0; i < additional_capacity; i++) fds[i] = -1;
    return fds;
}

static int
reallocate_connection_attempt_fds(int *fds, int current_capacity, int additional_capacity)
{
    int new_capacity = current_capacity + additional_capacity;

    if (realloc(fds, new_capacity * sizeof(int)) == NULL) {
        rb_syserr_fail(errno, "realloc(3)");
    }

    for (int i = current_capacity; i < new_capacity; i++) fds[i] = -1;
    return new_capacity;
}

struct wait_fast_fallback_arg
{
    int status, nfds;
    fd_set *readfds, *writefds;
    struct timeval *delay;
    int *cancelled;
};

static void *
wait_fast_fallback(void *ptr)
{
    struct wait_fast_fallback_arg *arg = (struct wait_fast_fallback_arg *)ptr;
    int status;
    status = select(arg->nfds, arg->readfds, arg->writefds, NULL, arg->delay);
    arg->status = status;
    if (errno == EINTR) *arg->cancelled = true;
    return 0;
}

static void
cancel_fast_fallback(void *ptr)
{
    if (!ptr) return;

    struct fast_fallback_getaddrinfo_shared *arg = (struct fast_fallback_getaddrinfo_shared *)ptr;

    rb_nativethread_lock_lock(arg->lock);
    {
        arg->cancelled = true;
        char notification = SELECT_CANCELLED;
        if ((write(arg->notify, &notification, 1)) < 0) {
            rb_syserr_fail(errno, "write(2)");
        }
    }
    rb_nativethread_lock_unlock(arg->lock);
}

struct hostname_resolution_result
{
    struct addrinfo *ai;
    int finished;
    int has_error;
};

struct hostname_resolution_store
{
    struct hostname_resolution_result v6;
    struct hostname_resolution_result v4;
    int is_all_finised;
};

static int
any_addrinfos(struct hostname_resolution_store *resolution_store)
{
    return resolution_store->v6.ai || resolution_store->v4.ai;
}

static struct timespec
current_clocktime_ts(void)
{
    struct timespec ts;
    if ((clock_gettime(CLOCK_MONOTONIC, &ts)) < 0) {
        rb_syserr_fail(errno, "clock_gettime(2)");
    }
    return ts;
}

static void
set_timeout_tv(struct timeval *tv, long ms, struct timespec from)
{
    long sec = ms / 1000;
    long nsec = (ms % 1000) * 1000000;
    long result_sec = from.tv_sec + sec;
    long result_nsec = from.tv_nsec + nsec;

    result_sec += result_nsec / 1000000000;
    result_nsec = result_nsec % 1000000000;

    tv->tv_sec = result_sec;
    tv->tv_usec = (int)(result_nsec / 1000);
}

static struct timeval
add_ts_to_tv(struct timeval tv, struct timespec ts)
{
    long ts_usec = ts.tv_nsec / 1000;
    tv.tv_sec += ts.tv_sec;
    tv.tv_usec += ts_usec;

    if (tv.tv_usec >= 1000000) {
        tv.tv_sec += tv.tv_usec / 1000000;
        tv.tv_usec = tv.tv_usec % 1000000;
    }

    return tv;
}

static VALUE
tv_to_seconds(struct timeval *timeout) {
    if (timeout == NULL) return Qnil;

    double seconds = (double)timeout->tv_sec + (double)timeout->tv_usec / 1000000.0;

    return DBL2NUM(seconds);
}

static int
is_infinity(struct timeval tv)
{
    // { -1, -1 } as infinity
    return tv.tv_sec == -1 || tv.tv_usec == -1;
}

static int
is_timeout_tv(struct timeval *timeout_tv, struct timespec now) {
    if (!timeout_tv) return false;
    if (timeout_tv->tv_sec == -1 && timeout_tv->tv_usec == -1) return false;

    struct timespec ts;
    ts.tv_sec = timeout_tv->tv_sec;
    ts.tv_nsec = timeout_tv->tv_usec * 1000;

    if (now.tv_sec > ts.tv_sec) return true;
    if (now.tv_sec == ts.tv_sec && now.tv_nsec >= ts.tv_nsec) return true;
    return false;
}

static struct timeval *
select_expires_at(
    struct hostname_resolution_store *resolution_store,
    struct timeval *resolution_delay,
    struct timeval *connection_attempt_delay,
    struct timeval *user_specified_resolv_timeout_at,
    struct timeval *user_specified_connect_timeout_at
) {
    if (any_addrinfos(resolution_store)) {
        return resolution_delay ? resolution_delay : connection_attempt_delay;
    }

    struct timeval *timeout = NULL;

    if (user_specified_resolv_timeout_at) {
        if (is_infinity(*user_specified_resolv_timeout_at)) return NULL;
        timeout = user_specified_resolv_timeout_at;
    }

    if (user_specified_connect_timeout_at) {
        if (is_infinity(*user_specified_connect_timeout_at)) return NULL;
        if (!timeout || timercmp(user_specified_connect_timeout_at, timeout, >)) {
            return user_specified_connect_timeout_at;
        }
    }

    return timeout;
}

static struct timeval
tv_to_timeout(struct timeval *ends_at, struct timespec now)
{
    struct timeval delay;
    struct timespec expires_at;
    expires_at.tv_sec = ends_at->tv_sec;
    expires_at.tv_nsec = ends_at->tv_usec * 1000;

    struct timespec diff;
    diff.tv_sec = expires_at.tv_sec - now.tv_sec;

    if (expires_at.tv_nsec >= now.tv_nsec) {
        diff.tv_nsec = expires_at.tv_nsec - now.tv_nsec;
    } else {
        diff.tv_sec -= 1;
        diff.tv_nsec = (1000000000 + expires_at.tv_nsec) - now.tv_nsec;
    }

    delay.tv_sec = diff.tv_sec;
    delay.tv_usec = (int)diff.tv_nsec / 1000;

    return delay;
}

static struct addrinfo *
pick_addrinfo(struct hostname_resolution_store *resolution_store, int last_family)
{
    int priority_on_v6[2] = { AF_INET6, AF_INET };
    int priority_on_v4[2] = { AF_INET, AF_INET6 };
    int *precedences = last_family == AF_INET6 ? priority_on_v4 : priority_on_v6;
    struct addrinfo *selected_ai = NULL;

    for (int i = 0; i < 2; i++) {
        if (precedences[i] == AF_INET6) {
            selected_ai = resolution_store->v6.ai;
            if (selected_ai) {
                resolution_store->v6.ai = selected_ai->ai_next;
                break;
            }
        } else {
            selected_ai = resolution_store->v4.ai;
            if (selected_ai) {
                resolution_store->v4.ai = selected_ai->ai_next;
                break;
            }
        }
    }
    return selected_ai;
}

static void
socket_nonblock_set(int fd)
{
    int flags = fcntl(fd, F_GETFL);

    if (flags < 0) rb_syserr_fail(errno, "fcntl(2)");
    if ((flags & O_NONBLOCK) != 0) return;

    flags |= O_NONBLOCK;

    if (fcntl(fd, F_SETFL, flags) < 0) rb_syserr_fail(errno, "fcntl(2)");
    return;
}

static int
in_progress_fds(int fds_size)
{
    return fds_size > 0;
}

static void
remove_connection_attempt_fd(int *fds, int *fds_size, int removing_fd) {
    int i, j;

    for (i = 0; i < *fds_size; i++) {
        if (fds[i] != removing_fd) continue;

        for (j = i; j < *fds_size - 1; j++) {
            fds[j] = fds[j + 1];
        }

        (*fds_size)--;
        fds[*fds_size] = -1;
        break;
    }
}

struct fast_fallback_error
{
    int type;
    int ecode;
};

static VALUE
init_fast_fallback_inetsock_internal(VALUE v)
{
    struct fast_fallback_inetsock_arg *arg = (void *)v;
    VALUE io = arg->io;
    VALUE resolv_timeout = arg->resolv_timeout;
    VALUE connect_timeout = arg->connect_timeout;
    VALUE test_mode_settings = arg->test_mode_settings;
    struct addrinfo *remote_ai = NULL, *local_ai = NULL;
    int connected_fd = -1, status = 0, local_status = 0;
    int remote_addrinfo_hints = 0;
    struct fast_fallback_error last_error = { 0, 0 };
    const char *syscall = 0;
    VALUE host, serv;

    #ifdef HAVE_CONST_AI_ADDRCONFIG
    remote_addrinfo_hints |= AI_ADDRCONFIG;
    #endif

    pthread_t threads[arg->family_size];
    char resolved_type[2];
    ssize_t resolved_type_size;
    int hostname_resolution_waiter = 0, hostname_resolution_notifier = 0;
    int pipefd[2];
    fd_set readfds, writefds;

    struct wait_fast_fallback_arg wait_arg;
    struct timeval *ends_at = NULL;
    struct timeval delay = (struct timeval){ -1, -1 };
    wait_arg.writefds = NULL;
    wait_arg.status = 0;

    struct hostname_resolution_store resolution_store;
    resolution_store.is_all_finised = false;
    resolution_store.v6.ai = NULL;
    resolution_store.v6.finished = false;
    resolution_store.v6.has_error = false;
    resolution_store.v4.ai = NULL;
    resolution_store.v4.finished = false;
    resolution_store.v4.has_error = false;

    int last_family = 0;

    int additional_capacity = 10;
    int current_capacity = additional_capacity;
    arg->connection_attempt_fds = allocate_connection_attempt_fds(additional_capacity);
    arg->connection_attempt_fds_size = 0;

    struct timeval resolution_delay_storage;
    struct timeval *resolution_delay_expires_at = NULL;
    struct timeval connection_attempt_delay_strage;
    struct timeval *connection_attempt_delay_expires_at = NULL;
    struct timeval user_specified_resolv_timeout_storage;
    struct timeval *user_specified_resolv_timeout_at = NULL;
    struct timeval user_specified_connect_timeout_storage;
    struct timeval *user_specified_connect_timeout_at = NULL;
    struct timespec now = current_clocktime_ts();

    /* start of hostname resolution */
    if (arg->family_size == 1) {
        int family = arg->families[0];
        arg->remote.res = rsock_addrinfo(
            arg->remote.host,
            arg->remote.serv,
            family,
            SOCK_STREAM,
            0
        );

        if (family == AF_INET6) {
            resolution_store.v6.ai = arg->remote.res->ai;
            resolution_store.v6.finished = true;
            resolution_store.v4.finished = true;
        } else if (family == AF_INET) {
            resolution_store.v4.ai = arg->remote.res->ai;
            resolution_store.v4.finished = true;
            resolution_store.v6.finished = true;
        }
        resolution_store.is_all_finised = true;
        wait_arg.readfds = NULL;
    } else {
        if (pipe(pipefd) != 0) rb_syserr_fail(errno, "pipe(2)");
        hostname_resolution_waiter = pipefd[0];
        int waiter_flags = fcntl(hostname_resolution_waiter, F_GETFL, 0);
        if (waiter_flags < 0) rb_syserr_fail(errno, "fcntl(2)");
        if ((fcntl(hostname_resolution_waiter, F_SETFL, waiter_flags | O_NONBLOCK)) < 0) {
            rb_syserr_fail(errno, "fcntl(2)");
        }

        hostname_resolution_notifier = pipefd[1];
        wait_arg.readfds = &readfds;

        arg->getaddrinfo_shared = allocate_fast_fallback_getaddrinfo_shared();
        if (!arg->getaddrinfo_shared) rb_syserr_fail(errno, "calloc(3)");

        arg->getaddrinfo_shared->lock = calloc(1, sizeof(rb_nativethread_lock_t));
        if (!arg->getaddrinfo_shared->lock) rb_syserr_fail(errno, "calloc(3)");
        rb_nativethread_lock_initialize(arg->getaddrinfo_shared->lock);

        arg->getaddrinfo_shared->node = arg->hostp ? strdup(arg->hostp) : NULL;
        arg->getaddrinfo_shared->service = strdup(arg->portp);
        arg->getaddrinfo_shared->refcount = arg->family_size + 1;
        arg->getaddrinfo_shared->notify = hostname_resolution_notifier;
        arg->getaddrinfo_shared->wait = hostname_resolution_waiter;
        arg->getaddrinfo_shared->connection_attempt_fds = arg->connection_attempt_fds;
        arg->getaddrinfo_shared->connection_attempt_fds_size = arg->connection_attempt_fds_size;
        arg->getaddrinfo_shared->cancelled = false;
        wait_arg.cancelled = false;

        for (int i = 0; i < arg->family_size; i++) {
            arg->getaddrinfo_entries[i] = allocate_fast_fallback_getaddrinfo_entry();
            if (!(arg->getaddrinfo_entries[i])) rb_syserr_fail(errno, "calloc(3)");
            arg->getaddrinfo_entries[i]->shared = arg->getaddrinfo_shared;

            struct addrinfo getaddrinfo_hints[arg->family_size];

            allocate_fast_fallback_getaddrinfo_hints(
                &getaddrinfo_hints[i],
                arg->families[i],
                remote_addrinfo_hints,
                arg->additional_flags
            );

            arg->getaddrinfo_entries[i]->hints = getaddrinfo_hints[i];
            arg->getaddrinfo_entries[i]->ai = NULL;
            arg->getaddrinfo_entries[i]->family = arg->families[i];
            arg->getaddrinfo_entries[i]->refcount = 2;
            arg->getaddrinfo_entries[i]->has_syserr = false;
            arg->getaddrinfo_entries[i]->test_sleep_ms = 0;
            arg->getaddrinfo_entries[i]->test_ecode = 0;

            /* for testing HEv2 */
            if (!NIL_P(test_mode_settings) && RB_TYPE_P(test_mode_settings, T_HASH)) {
                const char *family_sym = arg->families[i] == AF_INET6 ? "ipv6" : "ipv4";

                VALUE test_delay_setting = rb_hash_aref(test_mode_settings, ID2SYM(rb_intern("delay")));
                if (!NIL_P(test_delay_setting)) {
                    VALUE rb_test_delay_ms = rb_hash_aref(test_delay_setting, ID2SYM(rb_intern(family_sym)));
                    long test_delay_ms = NIL_P(rb_test_delay_ms) ? 0 : rb_test_delay_ms;
                    arg->getaddrinfo_entries[i]->test_sleep_ms = test_delay_ms;
                }

                VALUE test_error_setting = rb_hash_aref(test_mode_settings, ID2SYM(rb_intern("error")));
                if (!NIL_P(test_error_setting)) {
                    VALUE rb_test_ecode = rb_hash_aref(test_error_setting, ID2SYM(rb_intern(family_sym)));
                    if (!NIL_P(rb_test_ecode)) {
                        arg->getaddrinfo_entries[i]->test_ecode = NUM2INT(rb_test_ecode);
                    }
                }
            }

            if (raddrinfo_pthread_create(&threads[i], do_fast_fallback_getaddrinfo, arg->getaddrinfo_entries[i]) != 0) {
                rsock_raise_resolution_error("getaddrinfo(3)", EAI_AGAIN);
            }
            pthread_detach(threads[i]);
        }

        if (NIL_P(resolv_timeout)) {
            user_specified_resolv_timeout_storage = (struct timeval){ -1, -1 };
        } else {
            struct timeval resolv_timeout_tv = rb_time_interval(resolv_timeout);
            user_specified_resolv_timeout_storage = add_ts_to_tv(resolv_timeout_tv, now);
        }
        user_specified_resolv_timeout_at = &user_specified_resolv_timeout_storage;
    }

    while (true) {
        /* start of connection */
        if (any_addrinfos(&resolution_store) &&
            !resolution_delay_expires_at &&
            !connection_attempt_delay_expires_at) {
            while ((remote_ai = pick_addrinfo(&resolution_store, last_family))) {
                int fd = -1;

                #if !defined(INET6) && defined(AF_INET6)
                if (remote_ai->ai_family == AF_INET6) {
                    if (any_addrinfos(&resolution_store)) continue;
                    if (!in_progress_fds(arg->connection_attempt_fds_size)) break;
                    if (resolution_store.is_all_finised) break;

                    if (local_status < 0) {
                        host = arg->local.host;
                        serv = arg->local.serv;
                    } else {
                        host = arg->remote.host;
                        serv = arg->remote.serv;
                    }
                    if (last_error.type == RESOLUTION_ERROR) {
                        rsock_raise_resolution_error(syscall, last_error.ecode);
                    } else {
                        rsock_syserr_fail_host_port(last_error.ecode, syscall, host, serv);
                    }
                }
                #endif

                local_ai = NULL;

                if (arg->local.res) {
                    for (local_ai = arg->local.res->ai; local_ai; local_ai = local_ai->ai_next) {
                        if (local_ai->ai_family == remote_ai->ai_family) break;
                    }
                    if (!local_ai) {
                        if (any_addrinfos(&resolution_store)) continue;
                        if (in_progress_fds(arg->connection_attempt_fds_size)) break;
                        if (!resolution_store.is_all_finised) break;

                        /* Use a different family local address if no choice, this
                         * will cause EAFNOSUPPORT. */
                        rsock_syserr_fail_host_port(EAFNOSUPPORT, syscall, arg->local.host, arg->local.serv);
                    }
                }

                status = rsock_socket(remote_ai->ai_family, remote_ai->ai_socktype, remote_ai->ai_protocol);
                syscall = "socket(2)";

                if (status < 0) {
                    last_error.type = SYSCALL_ERROR;
                    last_error.ecode = errno;

                    if (any_addrinfos(&resolution_store)) continue;
                    if (in_progress_fds(arg->connection_attempt_fds_size)) break;
                    if (!resolution_store.is_all_finised) break;

                    if (local_status < 0) {
                        host = arg->local.host;
                        serv = arg->local.serv;
                    } else {
                        host = arg->remote.host;
                        serv = arg->remote.serv;
                    }
                    if (last_error.type == RESOLUTION_ERROR) {
                        rsock_raise_resolution_error(syscall, last_error.ecode);
                    } else {
                        rsock_syserr_fail_host_port(last_error.ecode, syscall, host, serv);
                    }
                }

                fd = status;

                if (local_ai) {
                    #if !defined(_WIN32) && !defined(__CYGWIN__)
                    status = 1;
                    if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&status, (socklen_t)sizeof(status))) < 0) {
                        rb_syserr_fail(errno, "setsockopt(2)");
                    }
                    #endif
                    status = bind(fd, local_ai->ai_addr, local_ai->ai_addrlen);
                    local_status = status;
                    syscall = "bind(2)";

                    if (status < 0) {
                        last_error.type = SYSCALL_ERROR;
                        last_error.ecode = errno;
                        close(fd);

                        if (any_addrinfos(&resolution_store)) continue;
                        if (in_progress_fds(arg->connection_attempt_fds_size)) break;
                        if (!resolution_store.is_all_finised) break;

                        if (local_status < 0) {
                            host = arg->local.host;
                            serv = arg->local.serv;
                        } else {
                            host = arg->remote.host;
                            serv = arg->remote.serv;
                        }
                        if (last_error.type == RESOLUTION_ERROR) {
                            rsock_raise_resolution_error(syscall, last_error.ecode);
                        } else {
                            rsock_syserr_fail_host_port(last_error.ecode, syscall, host, serv);
                        }
                    }
                }

                syscall = "connect(2)";

                if (any_addrinfos(&resolution_store) ||
                    in_progress_fds(arg->connection_attempt_fds_size) ||
                    !resolution_store.is_all_finised) {
                    socket_nonblock_set(fd);
                    status = connect(fd, remote_ai->ai_addr, remote_ai->ai_addrlen);
                    last_family = remote_ai->ai_family;
                } else {
                    if (!NIL_P(connect_timeout)) {
                        user_specified_connect_timeout_storage = rb_time_interval(connect_timeout);
                        user_specified_connect_timeout_at = &user_specified_connect_timeout_storage;
                    }

                    VALUE timeout =
                        (user_specified_connect_timeout_at && is_infinity(*user_specified_connect_timeout_at)) ?
                        Qnil : tv_to_seconds(user_specified_connect_timeout_at);
                    io = arg->io = rsock_init_sock(arg->self, fd);
                    status = rsock_connect(io, remote_ai->ai_addr, remote_ai->ai_addrlen, 0, timeout);
                }

                if (status == 0) {
                    connected_fd = fd;
                    break;
                }

                if (errno == EINPROGRESS) {
                    if (current_capacity == arg->connection_attempt_fds_size) {
                        current_capacity = reallocate_connection_attempt_fds(
                            arg->connection_attempt_fds,
                            current_capacity,
                            additional_capacity
                        );
                    }
                    arg->connection_attempt_fds[arg->connection_attempt_fds_size] = fd;
                    (arg->connection_attempt_fds_size)++;
                    wait_arg.writefds = &writefds;

                    set_timeout_tv(&connection_attempt_delay_strage, 250, now);
                    connection_attempt_delay_expires_at = &connection_attempt_delay_strage;

                    if (!any_addrinfos(&resolution_store)) {
                        if (NIL_P(connect_timeout)) {
                            user_specified_connect_timeout_storage = (struct timeval){ -1, -1 };
                        } else {
                            struct timeval connect_timeout_tv = rb_time_interval(connect_timeout);
                            user_specified_connect_timeout_storage = add_ts_to_tv(connect_timeout_tv, now);
                        }
                        user_specified_connect_timeout_at = &user_specified_connect_timeout_storage;
                    }

                    break;
                }

                last_error.type = SYSCALL_ERROR;
                last_error.ecode = errno;

                if (NIL_P(io)) {
                    close(fd);
                } else {
                    rb_io_close(io);
                }

                if (any_addrinfos(&resolution_store)) continue;
                if (in_progress_fds(arg->connection_attempt_fds_size)) break;
                if (!resolution_store.is_all_finised) break;

                if (local_status < 0) {
                    host = arg->local.host;
                    serv = arg->local.serv;
                } else {
                    host = arg->remote.host;
                    serv = arg->remote.serv;
                }
                if (last_error.type == RESOLUTION_ERROR) {
                    rsock_raise_resolution_error(syscall, last_error.ecode);
                } else {
                    rsock_syserr_fail_host_port(last_error.ecode, syscall, host, serv);
                }
            }
        }

        if (connected_fd >= 0) break;

        ends_at = select_expires_at(
            &resolution_store,
            resolution_delay_expires_at,
            connection_attempt_delay_expires_at,
            user_specified_resolv_timeout_at,
            user_specified_connect_timeout_at
        );
        if (ends_at) {
            delay = tv_to_timeout(ends_at, now);
            wait_arg.delay = &delay;
        } else {
            wait_arg.delay = NULL;
        }

        wait_arg.nfds = 0;
        if (arg->connection_attempt_fds_size) {
            FD_ZERO(wait_arg.writefds);
            int n = 0;
            for (int i = 0; i < arg->connection_attempt_fds_size; i++) {
                int cfd = arg->connection_attempt_fds[i];
                if (cfd < 0) continue;
                if (cfd > n) n = cfd;
                FD_SET(cfd, wait_arg.writefds);
            }
            if (n > 0) n++;
            wait_arg.nfds = n;
        } else {
            wait_arg.writefds = NULL;
        }

        FD_ZERO(wait_arg.readfds);
        FD_SET(hostname_resolution_waiter, wait_arg.readfds);
        if ((hostname_resolution_waiter + 1) > wait_arg.nfds) {
            wait_arg.nfds = hostname_resolution_waiter + 1;
        }

        rb_thread_call_without_gvl2(
            wait_fast_fallback,
            &wait_arg,
            cancel_fast_fallback,
            arg->getaddrinfo_shared
        );
        rb_thread_check_ints();
        if (errno == EINTR || arg->getaddrinfo_shared->cancelled) break;

        status = wait_arg.status;
        syscall = "select(2)";

        now = current_clocktime_ts();
        if (is_timeout_tv(resolution_delay_expires_at, now)) {
            resolution_delay_expires_at = NULL;
        }
        if (is_timeout_tv(connection_attempt_delay_expires_at, now)) {
            connection_attempt_delay_expires_at = NULL;
        }

        if (status < 0 && (errno && errno != EINTR)) rb_syserr_fail(errno, "select(2)");

        if (status > 0) {
            /* check for connection */
            for (int i = 0; i < arg->connection_attempt_fds_size; i++) {
                int fd = arg->connection_attempt_fds[i];
                if (fd < 0 || !FD_ISSET(fd, wait_arg.writefds)) continue;

                int err;
                socklen_t len = sizeof(err);

                if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len) == 0) {
                    if (err == 0) { /* success */
                        remove_connection_attempt_fd(
                            arg->connection_attempt_fds,
                            &arg->connection_attempt_fds_size,
                            fd
                        );
                        connected_fd = fd;
                        break;
                    };

                    /* fail */
                    errno = err;
                    close(fd);
                    remove_connection_attempt_fd(
                        arg->connection_attempt_fds,
                        &arg->connection_attempt_fds_size,
                        fd
                    );
                    continue;
                }
            }

            if (connected_fd >= 0) break;
            last_error.type = SYSCALL_ERROR;
            last_error.ecode = errno;

            if (!in_progress_fds(arg->connection_attempt_fds_size)) {
                if (any_addrinfos(&resolution_store)) {
                    connection_attempt_delay_expires_at = NULL;
                } else if (resolution_store.is_all_finised) {
                    if (local_status < 0) {
                        host = arg->local.host;
                        serv = arg->local.serv;
                    } else {
                        host = arg->remote.host;
                        serv = arg->remote.serv;
                    }
                    if (last_error.type == RESOLUTION_ERROR) {
                        rsock_raise_resolution_error(syscall, last_error.ecode);
                    } else {
                        rsock_syserr_fail_host_port(last_error.ecode, syscall, host, serv);
                    }
                }
                user_specified_connect_timeout_at = NULL;
            }

            /* check for hostname resolution */
            if (!resolution_store.is_all_finised && FD_ISSET(hostname_resolution_waiter, wait_arg.readfds)) {
                while (true) {
                    resolved_type_size = read(
                        hostname_resolution_waiter,
                        resolved_type,
                        sizeof(resolved_type) - 1
                    );

                    if (resolved_type_size > 0) {
                        resolved_type[resolved_type_size] = '\0';

                        if (resolved_type[0] == IPV6_HOSTNAME_RESOLVED) {
                            resolution_store.v6.finished = true;

                            if (arg->getaddrinfo_entries[IPV6_ENTRY_POS]->err &&
                                arg->getaddrinfo_entries[IPV6_ENTRY_POS]->err != EAI_ADDRFAMILY) {
                                last_error.type = RESOLUTION_ERROR;
                                last_error.ecode = arg->getaddrinfo_entries[IPV6_ENTRY_POS]->err;
                                syscall = "getaddrinfo(3)";
                                resolution_store.v6.has_error = true;
                            } else {
                                resolution_store.v6.ai = arg->getaddrinfo_entries[IPV6_ENTRY_POS]->ai;
                            }
                            if (resolution_store.v4.finished) {
                                resolution_store.is_all_finised = true;
                                resolution_delay_expires_at = NULL;
                                user_specified_resolv_timeout_at = NULL;
                                break;
                            }
                        } else if (resolved_type[0] == IPV4_HOSTNAME_RESOLVED) {
                            resolution_store.v4.finished = true;

                            if (arg->getaddrinfo_entries[IPV4_ENTRY_POS]->err) {
                                last_error.type = RESOLUTION_ERROR;
                                last_error.ecode = arg->getaddrinfo_entries[IPV4_ENTRY_POS]->err;
                                syscall = "getaddrinfo(3)";
                                resolution_store.v4.has_error = true;
                            } else {
                                resolution_store.v4.ai = arg->getaddrinfo_entries[IPV4_ENTRY_POS]->ai;
                            }

                            if (resolution_store.v6.finished) {
                                resolution_store.is_all_finised = true;
                                resolution_delay_expires_at = NULL;
                                user_specified_resolv_timeout_at = NULL;
                                break;
                            }
                        } else {
                            /* Retry to read from hostname_resolution_waiter */
                        }
                    } else if (resolved_type_size < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
                        errno = 0;
                        break;
                    } else {
                        /* Retry to read from hostname_resolution_waiter */
                    }

                    if (!resolution_store.v6.finished &&
                        resolution_store.v4.finished &&
                        !resolution_store.v4.has_error) {
                        set_timeout_tv(&resolution_delay_storage, 50, now);
                        resolution_delay_expires_at = &resolution_delay_storage;
                    }
                }
            }

            status = wait_arg.status = 0;
        }

        if (!any_addrinfos(&resolution_store)) {
            if (!in_progress_fds(arg->connection_attempt_fds_size) &&
                resolution_store.is_all_finised) {
                if (local_status < 0) {
                    host = arg->local.host;
                    serv = arg->local.serv;
                } else {
                    host = arg->remote.host;
                    serv = arg->remote.serv;
                }
                if (last_error.type == RESOLUTION_ERROR) {
                    rsock_raise_resolution_error(syscall, last_error.ecode);
                } else {
                    rsock_syserr_fail_host_port(last_error.ecode, syscall, host, serv);
                }
            }

            if ((is_timeout_tv(user_specified_resolv_timeout_at, now) ||
                resolution_store.is_all_finised) &&
                (is_timeout_tv(user_specified_connect_timeout_at, now) ||
                !in_progress_fds(arg->connection_attempt_fds_size))) {
                VALUE errno_module = rb_const_get(rb_cObject, rb_intern("Errno"));
                VALUE etimedout_error = rb_const_get(errno_module, rb_intern("ETIMEDOUT"));
                rb_raise(etimedout_error, "user specified timeout");
            }
        }

        if (!resolution_store.is_all_finised) {
            if (!resolution_store.v6.finished && arg->getaddrinfo_entries[IPV6_ENTRY_POS]->has_syserr) {
                resolution_store.v6.ai = arg->getaddrinfo_entries[IPV6_ENTRY_POS]->ai;
                resolution_store.v6.finished = true;

                if (resolution_store.v4.finished) {
                    resolution_store.is_all_finised = true;
                    wait_arg.readfds = NULL;
                    resolution_delay_expires_at = NULL;
                    user_specified_resolv_timeout_at = NULL;
                }
            }
            if (!resolution_store.v4.finished && arg->getaddrinfo_entries[IPV4_ENTRY_POS]->has_syserr) {
                resolution_store.v4.ai = arg->getaddrinfo_entries[IPV4_ENTRY_POS]->ai;
                resolution_store.v4.finished = true;

                if (resolution_store.v6.finished) {
                    resolution_store.is_all_finised = true;
                    wait_arg.readfds = NULL;
                    resolution_delay_expires_at = NULL;
                    user_specified_resolv_timeout_at = NULL;
                } else {
                    set_timeout_tv(&resolution_delay_storage, 50, now);
                    resolution_delay_expires_at = &resolution_delay_storage;
                }
            }
        }
    }

    rb_thread_check_ints();

    if (NIL_P(arg->io)) {
        /* create new instance */
        arg->io = rsock_init_sock(arg->self, connected_fd);
    }

    return arg->io;
}

static VALUE
fast_fallback_inetsock_cleanup(VALUE v)
{
    struct fast_fallback_inetsock_arg *arg = (void *)v;
    struct fast_fallback_getaddrinfo_shared *getaddrinfo_shared = arg->getaddrinfo_shared;

    if (arg->remote.res) {
        rb_freeaddrinfo(arg->remote.res);
        arg->remote.res = 0;
    }
    if (arg->local.res) {
        rb_freeaddrinfo(arg->local.res);
        arg->local.res = 0;
    }

    if (getaddrinfo_shared) {
        int shared_need_free = 0;
        int need_free[2] = { 0, 0 };

        rb_nativethread_lock_lock(getaddrinfo_shared->lock);
        {
            for (int i = 0; i < arg->family_size; i++) {
                if (arg->getaddrinfo_entries[i] && --(arg->getaddrinfo_entries[i]->refcount) == 0) {
                    need_free[i] = 1;
                }
            }
            if (--(getaddrinfo_shared->refcount) == 0) {
                shared_need_free = 1;
            }
        }
        rb_nativethread_lock_unlock(getaddrinfo_shared->lock);

        for (int i = 0; i < arg->family_size; i++) {
            if (need_free[i]) free_fast_fallback_getaddrinfo_entry(&arg->getaddrinfo_entries[i]);
        }
        if (shared_need_free) free_fast_fallback_getaddrinfo_shared(&getaddrinfo_shared);
    }

    int connection_attempt_fd;

    for (int i = 0; i < arg->connection_attempt_fds_size; i++) {
        connection_attempt_fd = arg->connection_attempt_fds[i];

        if (connection_attempt_fd >= 0) {
            int error = 0;
            socklen_t len = sizeof(error);
            getsockopt(connection_attempt_fd, SOL_SOCKET, SO_ERROR, &error, &len);
            if (error == 0) shutdown(connection_attempt_fd, SHUT_RDWR);
            close(connection_attempt_fd);
       }
    }

    if (arg->connection_attempt_fds) {
        free(arg->connection_attempt_fds);
        arg->connection_attempt_fds = NULL;
    }

    return Qnil;
}

VALUE
rsock_init_inetsock(VALUE self, VALUE remote_host, VALUE remote_serv, VALUE local_host, VALUE local_serv, int type, VALUE resolv_timeout, VALUE connect_timeout, VALUE fast_fallback, VALUE test_mode_settings)
{
    if (type == INET_CLIENT && FAST_FALLBACK_INIT_INETSOCK_IMPL == 1 && RTEST(fast_fallback)) {
        struct rb_addrinfo *local_res = NULL;
        char *hostp, *portp;
        char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
        int additional_flags = 0;
        hostp = host_str(remote_host, hbuf, sizeof(hbuf), &additional_flags);
        portp = port_str(remote_serv, pbuf, sizeof(pbuf), &additional_flags);

        if (!is_specified_ip_address(hostp)) {
            int target_families[2] = { 0, 0 };
            int resolving_family_size = 0;

            /*
             * Maybe also accept a local address
             */
            if (!NIL_P(local_host) || !NIL_P(local_serv)) {
                local_res = rsock_addrinfo(
                    local_host,
                    local_serv,
                    AF_UNSPEC,
                    SOCK_STREAM,
                    0
                );

                struct addrinfo *tmp_p = local_res->ai;
                for (tmp_p; tmp_p != NULL; tmp_p = tmp_p->ai_next) {
                    if (target_families[0] == 0 && tmp_p->ai_family == AF_INET6) {
                        target_families[0] = AF_INET6;
                        resolving_family_size++;
                    }
                    if (target_families[1] == 0 && tmp_p->ai_family == AF_INET) {
                        target_families[1] = AF_INET;
                        resolving_family_size++;
                    }
                }
            }  else {
                resolving_family_size = 2;
                target_families[0] = AF_INET6;
                target_families[1] = AF_INET;
            }

            struct fast_fallback_inetsock_arg fast_fallback_arg;
            memset(&fast_fallback_arg, 0, sizeof(fast_fallback_arg));

            fast_fallback_arg.self = self;
            fast_fallback_arg.io = Qnil;
            fast_fallback_arg.remote.host = remote_host;
            fast_fallback_arg.remote.serv = remote_serv;
            fast_fallback_arg.remote.res = 0;
            fast_fallback_arg.local.host = local_host;
            fast_fallback_arg.local.serv = local_serv;
            fast_fallback_arg.local.res = local_res;
            fast_fallback_arg.type = type;
            fast_fallback_arg.resolv_timeout = resolv_timeout;
            fast_fallback_arg.connect_timeout = connect_timeout;
            fast_fallback_arg.hostp = hostp;
            fast_fallback_arg.portp = portp;
            fast_fallback_arg.additional_flags = additional_flags;

            int resolving_families[resolving_family_size];
            int resolving_family_index = 0;
            for (int i = 0; 2 > i; i++) {
                if (target_families[i] != 0) {
                    resolving_families[resolving_family_index] = target_families[i];
                    resolving_family_index++;
                }
            }
            fast_fallback_arg.families = resolving_families;
            fast_fallback_arg.family_size = resolving_family_size;
            fast_fallback_arg.test_mode_settings = test_mode_settings;

            return rb_ensure(init_fast_fallback_inetsock_internal, (VALUE)&fast_fallback_arg,
                             fast_fallback_inetsock_cleanup, (VALUE)&fast_fallback_arg);
        }
    }

    struct inetsock_arg arg;
    arg.self = self;
    arg.io = Qnil;
    arg.remote.host = remote_host;
    arg.remote.serv = remote_serv;
    arg.remote.res = 0;
    arg.local.host = local_host;
    arg.local.serv = local_serv;
    arg.local.res = 0;
    arg.type = type;
    arg.resolv_timeout = resolv_timeout;
    arg.connect_timeout = connect_timeout;

    return rb_ensure(init_inetsock_internal, (VALUE)&arg,
                     inetsock_cleanup, (VALUE)&arg);
}

#endif

static ID id_numeric, id_hostname;

int
rsock_revlookup_flag(VALUE revlookup, int *norevlookup)
{
#define return_norevlookup(x) {*norevlookup = (x); return 1;}
    ID id;

    switch (revlookup) {
      case Qtrue:  return_norevlookup(0);
      case Qfalse: return_norevlookup(1);
      case Qnil: break;
      default:
        Check_Type(revlookup, T_SYMBOL);
        id = SYM2ID(revlookup);
        if (id == id_numeric) return_norevlookup(1);
        if (id == id_hostname) return_norevlookup(0);
        rb_raise(rb_eArgError, "invalid reverse_lookup flag: :%s", rb_id2name(id));
    }
    return 0;
#undef return_norevlookup
}

/*
 * call-seq:
 *   ipsocket.inspect   -> string
 *
 * Return a string describing this IPSocket object.
 */
static VALUE
ip_inspect(VALUE sock)
{
    VALUE str = rb_call_super(0, 0);
    rb_io_t *fptr = RFILE(sock)->fptr;
    union_sockaddr addr;
    socklen_t len = (socklen_t)sizeof addr;
    ID id;
    if (fptr && fptr->fd >= 0 &&
        getsockname(fptr->fd, &addr.addr, &len) >= 0 &&
        (id = rsock_intern_family(addr.addr.sa_family)) != 0) {
        VALUE family = rb_id2str(id);
        char hbuf[1024], pbuf[1024];
        long slen = RSTRING_LEN(str);
        const char last = (slen > 1 && RSTRING_PTR(str)[slen - 1] == '>') ?
            (--slen, '>') : 0;
        str = rb_str_subseq(str, 0, slen);
        rb_str_cat_cstr(str, ", ");
        rb_str_append(str, family);
        if (!rb_getnameinfo(&addr.addr, len, hbuf, sizeof(hbuf),
                            pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV)) {
            rb_str_cat_cstr(str, ", ");
            rb_str_cat_cstr(str, hbuf);
            rb_str_cat_cstr(str, ", ");
            rb_str_cat_cstr(str, pbuf);
        }
        if (last) rb_str_cat(str, &last, 1);
    }
    return str;
}

/*
 * call-seq:
 *   ipsocket.addr([reverse_lookup]) => [address_family, port, hostname, numeric_address]
 *
 * Returns the local address as an array which contains
 * address_family, port, hostname and numeric_address.
 *
 * If +reverse_lookup+ is +true+ or +:hostname+,
 * hostname is obtained from numeric_address using reverse lookup.
 * Or if it is +false+, or +:numeric+,
 * hostname is the same as numeric_address.
 * Or if it is +nil+ or omitted, obeys to +ipsocket.do_not_reverse_lookup+.
 * See +Socket.getaddrinfo+ also.
 *
 *   TCPSocket.open("www.ruby-lang.org", 80) {|sock|
 *     p sock.addr #=> ["AF_INET", 49429, "hal", "192.168.0.128"]
 *     p sock.addr(true)  #=> ["AF_INET", 49429, "hal", "192.168.0.128"]
 *     p sock.addr(false) #=> ["AF_INET", 49429, "192.168.0.128", "192.168.0.128"]
 *     p sock.addr(:hostname)  #=> ["AF_INET", 49429, "hal", "192.168.0.128"]
 *     p sock.addr(:numeric)   #=> ["AF_INET", 49429, "192.168.0.128", "192.168.0.128"]
 *   }
 *
 */
static VALUE
ip_addr(int argc, VALUE *argv, VALUE sock)
{
    union_sockaddr addr;
    socklen_t len = (socklen_t)sizeof addr;
    int norevlookup;

    if (argc < 1 || !rsock_revlookup_flag(argv[0], &norevlookup))
        norevlookup = rb_io_mode(sock) & FMODE_NOREVLOOKUP;
    if (getsockname(rb_io_descriptor(sock), &addr.addr, &len) < 0)
        rb_sys_fail("getsockname(2)");
    return rsock_ipaddr(&addr.addr, len, norevlookup);
}

/*
 * call-seq:
 *   ipsocket.peeraddr([reverse_lookup]) => [address_family, port, hostname, numeric_address]
 *
 * Returns the remote address as an array which contains
 * address_family, port, hostname and numeric_address.
 * It is defined for connection oriented socket such as TCPSocket.
 *
 * If +reverse_lookup+ is +true+ or +:hostname+,
 * hostname is obtained from numeric_address using reverse lookup.
 * Or if it is +false+, or +:numeric+,
 * hostname is the same as numeric_address.
 * Or if it is +nil+ or omitted, obeys to +ipsocket.do_not_reverse_lookup+.
 * See +Socket.getaddrinfo+ also.
 *
 *   TCPSocket.open("www.ruby-lang.org", 80) {|sock|
 *     p sock.peeraddr #=> ["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68"]
 *     p sock.peeraddr(true)  #=> ["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68"]
 *     p sock.peeraddr(false) #=> ["AF_INET", 80, "221.186.184.68", "221.186.184.68"]
 *     p sock.peeraddr(:hostname) #=> ["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68"]
 *     p sock.peeraddr(:numeric)  #=> ["AF_INET", 80, "221.186.184.68", "221.186.184.68"]
 *   }
 *
 */
static VALUE
ip_peeraddr(int argc, VALUE *argv, VALUE sock)
{
    union_sockaddr addr;
    socklen_t len = (socklen_t)sizeof addr;
    int norevlookup;

    if (argc < 1 || !rsock_revlookup_flag(argv[0], &norevlookup))
        norevlookup = rb_io_mode(sock) & FMODE_NOREVLOOKUP;
    if (getpeername(rb_io_descriptor(sock), &addr.addr, &len) < 0)
        rb_sys_fail("getpeername(2)");
    return rsock_ipaddr(&addr.addr, len, norevlookup);
}

/*
 * call-seq:
 *   ipsocket.recvfrom(maxlen)        => [mesg, ipaddr]
 *   ipsocket.recvfrom(maxlen, flags) => [mesg, ipaddr]
 *
 * Receives a message and return the message as a string and
 * an address which the message come from.
 *
 * _maxlen_ is the maximum number of bytes to receive.
 *
 * _flags_ should be a bitwise OR of Socket::MSG_* constants.
 *
 * ipaddr is the same as IPSocket#{peeraddr,addr}.
 *
 *   u1 = UDPSocket.new
 *   u1.bind("127.0.0.1", 4913)
 *   u2 = UDPSocket.new
 *   u2.send "uuuu", 0, "127.0.0.1", 4913
 *   p u1.recvfrom(10) #=> ["uuuu", ["AF_INET", 33230, "localhost", "127.0.0.1"]]
 *
 */
static VALUE
ip_recvfrom(int argc, VALUE *argv, VALUE sock)
{
    return rsock_s_recvfrom(sock, argc, argv, RECV_IP);
}

/*
 * call-seq:
 *   IPSocket.getaddress(host)        => ipaddress
 *
 * Lookups the IP address of _host_.
 *
 *   require 'socket'
 *
 *   IPSocket.getaddress("localhost")     #=> "127.0.0.1"
 *   IPSocket.getaddress("ip6-localhost") #=> "::1"
 *
 */
static VALUE
ip_s_getaddress(VALUE obj, VALUE host)
{
    union_sockaddr addr;
    struct rb_addrinfo *res = rsock_addrinfo(host, Qnil, AF_UNSPEC, SOCK_STREAM, 0);
    socklen_t len = res->ai->ai_addrlen;

    /* just take the first one */
    memcpy(&addr, res->ai->ai_addr, len);
    rb_freeaddrinfo(res);

    return rsock_make_ipaddr(&addr.addr, len);
}

void
rsock_init_ipsocket(void)
{
    /*
     * Document-class: IPSocket < BasicSocket
     *
     * IPSocket is the super class of TCPSocket and UDPSocket.
     */
    rb_cIPSocket = rb_define_class("IPSocket", rb_cBasicSocket);
    rb_define_method(rb_cIPSocket, "inspect", ip_inspect, 0);
    rb_define_method(rb_cIPSocket, "addr", ip_addr, -1);
    rb_define_method(rb_cIPSocket, "peeraddr", ip_peeraddr, -1);
    rb_define_method(rb_cIPSocket, "recvfrom", ip_recvfrom, -1);
    rb_define_singleton_method(rb_cIPSocket, "getaddress", ip_s_getaddress, 1);
    rb_undef_method(rb_cIPSocket, "getpeereid");

    id_numeric = rb_intern_const("numeric");
    id_hostname = rb_intern_const("hostname");
}