summaryrefslogtreecommitdiff
path: root/lib/erl_interface/src/connect/ei_connect.c
blob: e536f14fcd30c1d0810b3fc3afa7f2aac19100fc (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
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
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
/*
 * %CopyrightBegin%
 *
 * Copyright Ericsson AB 2000-2020. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * %CopyrightEnd%
 */
/*
 * Purpose: Connect to any node at any host. (EI version)
 */

#include "eidef.h"

#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>

#ifdef __WIN32__
#include <winsock2.h>
#include <windows.h>
#include <winbase.h>

#else /* some unix */
#include <unistd.h>
#include <sys/times.h>

#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
#  include <sys/time.h>
# else
#  include <time.h>
# endif
#endif

#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h> 
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/utsname.h>  /* for gen_challenge (NEED FIX?) */
#include <time.h>
#endif

/* common includes */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <stddef.h>

#include "eiext.h"
#include "ei_portio.h"
#include "ei_internal.h"
#include "ei_connect_int.h"
#include "ei_locking.h"
#include "eisend.h"
#include "eirecv.h"
#include "eimd5.h"
#include "putget.h"
#include "ei_resolve.h"
#include "ei_epmd.h"
#include "ei_internal.h"

static int ei_connect_initialized = 0;
int ei_tracelevel = 0;

#define COOKIE_FILE "/.erlang.cookie"
#define EI_MAX_HOME_PATH 1024

#define EI_SOCKET_CALLBACKS_SZ_V1                       \
    (offsetof(ei_socket_callbacks, get_fd)              \
     + sizeof(int (*)(void *)))

static char *null_cookie = "";

static int get_cookie(char *buf, int len);
static int get_home(char *buf, int size);

/* forwards */
static unsigned gen_challenge(void);
static void gen_digest(unsigned challenge, char cookie[], 
		       unsigned char digest[16]);
static int send_status(ei_socket_callbacks *cbs, void *ctx,
                       int pkt_sz, char *status, unsigned ms);
static int recv_status(ei_cnode*, void *ctx,
                       int pkt_sz, unsigned ms);
static int send_challenge(ei_cnode *ec, void *ctx, int pkt_sz,
                          unsigned challenge,
                          DistFlags version, unsigned ms);
static int recv_challenge(ei_socket_callbacks *cbs, void *ctx, int pkt_sz,
                          unsigned *challenge, unsigned *version,
			  DistFlags *flags, char *namebuf, unsigned ms);
static int send_challenge_reply(ei_socket_callbacks *cbs, void *ctx,
                                int pkt_sz, unsigned char digest[16], 
				unsigned challenge, unsigned ms);
static int recv_complement(ei_socket_callbacks *cbs, void *ctx,
                           int pkt_sz, unsigned ms);
static int recv_challenge_reply(ei_socket_callbacks *cbs, void *ctx,
                                int pkt_sz, unsigned our_challenge,
				char cookie[], 
				unsigned *her_challenge, unsigned ms);
static int send_challenge_ack(ei_socket_callbacks *cbs, void *ctx,
                              int pkt_sz, unsigned char digest[16],
                              unsigned ms);
static int recv_challenge_ack(ei_socket_callbacks *cbs, void *ctx, 
			      int pkt_sz, unsigned our_challenge,
			      char cookie[], unsigned ms);
static int send_name(ei_cnode *ec, void *ctx, int pkt_sz,
                     unsigned version, unsigned ms);
static int send_complement(ei_cnode *ec, void *ctx, int pkt_sz,
                            unsigned epmd_says_version, DistFlags her_flags,
                            unsigned ms);
static int recv_name(ei_socket_callbacks *cbs, void *ctx, int pkt_sz,
                     char* send_name_tag, DistFlags *flags,
                     char *namebuf, unsigned ms);
static int ei_connect_helper(ei_cnode* ec,
                             Erl_IpAddr ip_addr,
                             char *alivename,
                             unsigned ms,
                             int rport,
                             int epmd_says_version);

static struct hostent*
dyn_gethostbyname_r(const char *name, struct hostent *hostp, char **buffer_p,
                    int buflen, int *h_errnop);

static void abort_connection(ei_socket_callbacks *cbs, void *ctx);
static int close_connection(ei_socket_callbacks *cbs, void *ctx, int fd);

static char *
estr(int e)
{
    char *str = strerror(e);
    if (!str)
        return "unknown error";
    return str;
}


/***************************************************************************
 *
 *  For each file descriptor returned from ei_connect() we save information
 *  about distribution protocol version, node information for this node
 *  and the cookie.
 *
 ***************************************************************************/

typedef struct ei_socket_info_s {
    int socket;
    ei_socket_callbacks *cbs;
    void *ctx;
    int dist_version;
    ei_cnode cnode;	/* A copy, not a pointer. We don't know when freed */
    char cookie[EI_MAX_COOKIE_SIZE+1];
} ei_socket_info;

/***************************************************************************
 *
 *  XXX
 *
 ***************************************************************************/

#ifndef ETHR_HAVE___atomic_compare_exchange_n
#  define ETHR_HAVE___atomic_compare_exchange_n 0
#endif
#ifndef ETHR_HAVE___atomic_load_n
#  define ETHR_HAVE___atomic_load_n 0
#endif
#ifndef ETHR_HAVE___atomic_store_n
#  define ETHR_HAVE___atomic_store_n 0
#endif

#if defined(_REENTRANT)                                                 \
    && (!(ETHR_HAVE___atomic_compare_exchange_n & SIZEOF_VOID_P)        \
        || !(ETHR_HAVE___atomic_load_n & SIZEOF_VOID_P)                 \
        || !(ETHR_HAVE___atomic_store_n & SIZEOF_VOID_P))
#  undef EI_DISABLE_SEQ_SOCKET_INFO
#  define EI_DISABLE_SEQ_SOCKET_INFO
#endif

#ifdef __WIN32__
#  undef EI_DISABLE_SEQ_SOCKET_INFO
#  define EI_DISABLE_SEQ_SOCKET_INFO
#endif

#ifndef EI_DISABLE_SEQ_SOCKET_INFO

#ifdef _REENTRANT

#define EI_ATOMIC_CMPXCHG_ACQ_REL(VARP, XCHGP, NEW) \
    __atomic_compare_exchange_n((VARP), (XCHGP), (NEW), 0, \
                                __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)
#define EI_ATOMIC_LOAD_ACQ(VARP) \
    __atomic_load_n((VARP), __ATOMIC_ACQUIRE)
#define EI_ATOMIC_STORE_REL(VARP, NEW) \
    __atomic_store_n((VARP), (NEW), __ATOMIC_RELEASE)

#else /* ! _REENTRANT */

#define EI_ATOMIC_CMPXCHG_ACQ_REL(VARP, XCHGP, NEW)    \
    (*(VARP) == *(XCHGP)                               \
     ? ((*(VARP) = (NEW)), !0)                         \
     : ((*(XCHGP) = *(VARP)), 0))
#define EI_ATOMIC_LOAD_ACQ(VARP) (*(VARP))
#define EI_ATOMIC_STORE_REL(VARP, NEW) (*(VARP) = (NEW))

#endif /* ! _REENTRANT */

#define EI_SOCKET_INFO_SEG_BITS 5
#define EI_SOCKET_INFO_SEG_SIZE (1 << EI_SOCKET_INFO_SEG_BITS)
#define EI_SOCKET_INFO_SEG_MASK (EI_SOCKET_INFO_SEG_SIZE - 1)

typedef struct {
    int max_fds;
    ei_socket_info *segments[1]; /* Larger in reality... */
} ei_socket_info_data__;

static ei_socket_info_data__ *socket_info_data = NULL;

static int init_socket_info(int late)
{
    int max_fds;
    int i;
    size_t segments_len;
    ei_socket_info_data__ *info_data, *xchg;

    if (EI_ATOMIC_LOAD_ACQ(&socket_info_data) != NULL)
        return 0; /* Already initialized... */
    
#if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
    max_fds = sysconf(_SC_OPEN_MAX);
#else
    max_fds = 1024;
#endif

    if (max_fds < 0)
        return EIO;

    segments_len = ((max_fds-1)/EI_SOCKET_INFO_SEG_SIZE + 1);
    
    info_data = malloc(sizeof(ei_socket_info_data__)
                       + (sizeof(ei_socket_info *)*(segments_len-1)));
    if (!info_data)
        return ENOMEM;

    info_data->max_fds = max_fds;
    for (i = 0; i < segments_len; i++)
        info_data->segments[i] = NULL;

    xchg = NULL;
    if (!EI_ATOMIC_CMPXCHG_ACQ_REL(&socket_info_data, &xchg, info_data))
        free(info_data); /* Already initialized... */

    return 0;
}

static int put_ei_socket_info(int fd, int dist_version, char* cookie, ei_cnode *ec,
                              ei_socket_callbacks *cbs, void *ctx)
{
    int six;
    ei_socket_info *seg, *si;
    int socket;

    if (fd < 0 || socket_info_data->max_fds <= fd)
        return -1;

    socket = fd;
    six = fd >> EI_SOCKET_INFO_SEG_BITS;
    seg = EI_ATOMIC_LOAD_ACQ(&socket_info_data->segments[six]);
    
    if (!seg) {
        ei_socket_info *xchg;
        int i;
        seg = malloc(sizeof(ei_socket_info)*EI_SOCKET_INFO_SEG_SIZE);
        if (!seg)
            return -1;
        for (i = 0; i < EI_SOCKET_INFO_SEG_SIZE; i++) {
            seg[i].socket = -1;
        }

        xchg = NULL;
        if (!EI_ATOMIC_CMPXCHG_ACQ_REL(&socket_info_data->segments[six], &xchg, seg)) {
            free(seg);
            seg = xchg;
        }
    }

    si = &seg[fd & EI_SOCKET_INFO_SEG_MASK];

    if (dist_version < 0) {
        socket = -1;
        si->cbs = NULL;
        si->ctx = NULL;
    }
    else {
        si->dist_version = dist_version;
        si->cnode = *ec;
        si->cbs = cbs;
        si->ctx = ctx;
        strcpy(si->cookie, cookie);
    }

    EI_ATOMIC_STORE_REL(&si->socket, socket);

    return 0;
}

static ei_socket_info* get_ei_socket_info(int fd)
{
    int six, socket;
    ei_socket_info *seg, *si;
    
    if (fd < 0 || socket_info_data->max_fds <= fd)
        return NULL;
    
    six = fd >> EI_SOCKET_INFO_SEG_BITS;
    seg = EI_ATOMIC_LOAD_ACQ(&socket_info_data->segments[six]);

    if (!seg)
        return NULL;
    
    si = &seg[fd & EI_SOCKET_INFO_SEG_MASK];
    socket = EI_ATOMIC_LOAD_ACQ(&si->socket);
    if (socket != fd)
        return NULL;
    return si;
}
    
#else /* EI_DISABLE_SEQ_SOCKET_INFO */

int ei_n_sockets = 0, ei_sz_sockets = 0;
ei_socket_info *ei_sockets = NULL;

#ifdef _REENTRANT
ei_mutex_t* ei_sockets_lock = NULL;
#endif /* _REENTRANT */

static int init_socket_info(int late)
{
#ifdef _REENTRANT
    if (late)
        return ENOTSUP; /* Refuse doing unsafe initialization... */
    ei_sockets_lock = ei_mutex_create();
    if (!ei_sockets_lock)
        return ENOMEM;
#endif /* _REENTRANT */
    return 0;
}

static int put_ei_socket_info(int fd, int dist_version, char* cookie, ei_cnode *ec,
                              ei_socket_callbacks *cbs, void *ctx)
{
    int i;

#ifdef _REENTRANT
    ei_mutex_lock(ei_sockets_lock, 0);
#endif /* _REENTRANT */
    for (i = 0; i < ei_n_sockets; ++i) {
	if (ei_sockets[i].socket == fd) {
	    if (dist_version == -1) {
                memmove(&ei_sockets[i], &ei_sockets[i+1],
			sizeof(ei_sockets[0])*(ei_n_sockets-i-1));
	    } else {
		ei_sockets[i].dist_version = dist_version;
		/* Copy the content, see ei_socket_info */
                ei_sockets[i].cbs = cbs;
                ei_sockets[i].ctx = ctx;
		ei_sockets[i].cnode = *ec;
		strcpy(ei_sockets[i].cookie, cookie);
	    }
#ifdef _REENTRANT
	    ei_mutex_unlock(ei_sockets_lock);
#endif /* _REENTRANT */
	    return 0;
	}
    }
    if (ei_n_sockets == ei_sz_sockets) {
	ei_sz_sockets += 5;
	ei_sockets = realloc(ei_sockets,
			     sizeof(ei_sockets[0])*ei_sz_sockets);
	if (ei_sockets == NULL) {
	    ei_sz_sockets = ei_n_sockets = 0;
#ifdef _REENTRANT
	    ei_mutex_unlock(ei_sockets_lock);
#endif /* _REENTRANT */
	    return -1;
	}
    }
    ei_sockets[ei_n_sockets].socket = fd;
    ei_sockets[ei_n_sockets].dist_version = dist_version;
    ei_sockets[ei_n_sockets].cnode = *ec;
    ei_sockets[ei_n_sockets].cbs = cbs;
    ei_sockets[ei_n_sockets].ctx = ctx;
    strcpy(ei_sockets[ei_n_sockets].cookie, cookie);
    ++ei_n_sockets;
#ifdef _REENTRANT
    ei_mutex_unlock(ei_sockets_lock);
#endif /* _REENTRANT */
    return 0;
}

static ei_socket_info* get_ei_socket_info(int fd)
{
    int i;
#ifdef _REENTRANT
    ei_mutex_lock(ei_sockets_lock, 0);
#endif /* _REENTRANT */
    for (i = 0; i < ei_n_sockets; ++i)
	if (ei_sockets[i].socket == fd) {
	    /*fprintf("get_ei_socket_info %d  %d \"%s\"\n",
		    fd, ei_sockets[i].dist_version, ei_sockets[i].cookie);*/
#ifdef _REENTRANT
	    ei_mutex_unlock(ei_sockets_lock);
#endif /* _REENTRANT */
	    return &ei_sockets[i];
	}
#ifdef _REENTRANT
    ei_mutex_unlock(ei_sockets_lock);
#endif /* _REENTRANT */
    return NULL;
}

#endif /* EI_DISABLE_SEQ_SOCKET_INFO */

static int remove_ei_socket_info(int fd)
{
    return put_ei_socket_info(fd, -1, NULL, NULL, NULL, NULL);
}

ei_cnode *ei_fd_to_cnode(int fd)
{
    ei_socket_info *sockinfo = get_ei_socket_info(fd);
    if (sockinfo == NULL) return NULL;
    return &sockinfo->cnode;
}

int ei_get_cbs_ctx__(ei_socket_callbacks **cbs, void **ctx, int fd)
{
    ei_socket_info *sockinfo = get_ei_socket_info(fd);
    if (sockinfo) {
        *cbs = sockinfo->cbs;
        *ctx = sockinfo->ctx;
        return 0;
    }

    *cbs = NULL;
    *ctx = NULL;
    return EBADF;
}

/***************************************************************************
 *  Get/Set tracelevel
 ***************************************************************************/

void ei_set_tracelevel(int level) {
    ei_tracelevel = level;
}

int ei_get_tracelevel(void) {
    return ei_tracelevel;
}


/***************************************************************************
 *  Distversion 
 ***************************************************************************/

int ei_distversion(int fd)
{
    ei_socket_info* e = get_ei_socket_info(fd);
    if (e == NULL)
	return -1;
    else
	return e->dist_version;
}

static const char* ei_cookie(int fd)
{
    ei_socket_info* e = get_ei_socket_info(fd);
    if (e == NULL)
	return NULL;
    else
	return e->cookie;
}

const char *ei_thisnodename(const ei_cnode* ec)
{
    return ec->thisnodename;
}

const char *ei_thishostname(const ei_cnode* ec)
{
    return ec->thishostname;
}

const char *ei_thisalivename(const ei_cnode* ec)
{
    return ec->thisalivename;
}

short ei_thiscreation(const ei_cnode* ec)
{
    return ec->creation;
}

/* FIXME: this function is not an api, why not? */
const char *ei_thiscookie(const ei_cnode* ec)
{
    return (const char *)ec->ei_connect_cookie;
}

erlang_pid *ei_self(ei_cnode* ec)
{
    return &ec->self;
}

/* two internal functions that will let us support different cookies
* (to be able to connect to other nodes that don't have the same
* cookie as each other or us)
*/
const char *ei_getfdcookie(int fd)
{
    const char* r = ei_cookie(fd);
    if (r == NULL) r = "";
    return r;
}

static int get_int32(unsigned char *s)
{
    return ((s[0] << 24) | (s[1] << 16) | (s[2] << 8) | (s[3] ));
}


#ifdef __WIN32__
void win32_error(char *buf, int buflen)
{
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
	0,	/* n/a */
	WSAGetLastError(), /* error code */
	MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* language */
	buf,
	buflen,
	NULL);
    return;
}

static int initWinSock(void)
{
    WORD wVersionRequested;  
    WSADATA wsaData; 
    int i; 

    static LONG volatile initialized = 0;
    
    wVersionRequested = MAKEWORD(1, 1); 
    if (InterlockedCompareExchange((LPLONG) &initialized,1L,0L) == 0L) {
	/* FIXME not terminate, just a message?! */
	if ((i = WSAStartup(wVersionRequested, &wsaData))) {
	    EI_TRACE_ERR1("ei_connect_init",
			  "ERROR: can't initialize windows sockets: %d",i);
	    initialized = 2L;
	    return 0;
	}
	
	if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) { 
	    EI_TRACE_ERR0("initWinSock","ERROR: this version of windows "
			  "sockets not supported");
	    WSACleanup(); 
	    initialized = 2L;
	    return 0;
	}
	initialized = 3L;
    } else while (initialized < 2) {
	SwitchToThread();
    }
    return (int) (initialized - 2);
}
#endif

static int init_connect(int late)
{
    int error;

    /*
     * 'late' is non-zero when not called via ei_init(). Such a
     * call is not supported, but we for now save the day if
     * it easy to do so; otherwise, return ENOTSUP.
     */

#ifdef __WIN32__
    if (!initWinSock()) {
	EI_TRACE_ERR0("ei_init_connect","can't initiate winsock");
	return EIO;
    }
#endif /* win32 */

    error = init_socket_info(late);
    if (error) {
        EI_TRACE_ERR0("ei_init_connect","can't initiate socket info");
        return error;
    }

    ei_connect_initialized = !0;
    return 0;
}

int ei_init_connect(void)
{
    return init_connect(0);
}

/*
* Perhaps run this routine instead of ei_connect_init/2 ?
* Initailize by setting:
* thishostname, thisalivename, thisnodename and thisipaddr
*/
int ei_connect_xinit_ussi(ei_cnode* ec, const char *thishostname,
                          const char *thisalivename, const char *thisnodename,
                          Erl_IpAddr thisipaddr, const char *cookie,
                          const short creation, ei_socket_callbacks *cbs,
                          int cbs_sz, void *setup_context)
{
    char *dbglevel;

    if (!ei_connect_initialized)
        init_connect(!0);

    if (cbs != &ei_default_socket_callbacks)
        EI_SET_HAVE_PLUGIN_SOCKET_IMPL__;
    
    if (cbs_sz < EI_SOCKET_CALLBACKS_SZ_V1) {
	EI_TRACE_ERR0("ei_connect_xinit","invalid size of ei_socket_callbacks struct");
        return ERL_ERROR;
    }
    
    ec->creation = creation;
    
    if (cookie) {
	if (strlen(cookie) >= sizeof(ec->ei_connect_cookie)) { 
	    EI_TRACE_ERR0("ei_connect_xinit",
			  "ERROR: Cookie size too large");
	    return ERL_ERROR;
	} else {
	    strcpy(ec->ei_connect_cookie, cookie);
	}
    } else if (!get_cookie(ec->ei_connect_cookie, sizeof(ec->ei_connect_cookie))) {
	return ERL_ERROR;
    }
    
    if (strlen(thishostname) >= sizeof(ec->thishostname)) {
	EI_TRACE_ERR0("ei_connect_xinit","ERROR: Thishostname too long");
	return ERL_ERROR;
    }
    strcpy(ec->thishostname, thishostname);
    
    if (thisalivename) {
        if (strlen(thisalivename) >= sizeof(ec->thisalivename)) {
            EI_TRACE_ERR0("ei_connect_init","Thisalivename too long");
            return ERL_ERROR;
        }

        strcpy(ec->thisalivename, thisalivename);

        if (strlen(thisnodename) >= sizeof(ec->thisnodename)) {
            EI_TRACE_ERR0("ei_connect_init","Thisnodename too long");
            return ERL_ERROR;
        }
        strcpy(ec->thisnodename, thisnodename);

        strcpy(ec->self.node, thisnodename);
        ec->self.num = 0;
        ec->self.serial = 0;
        ec->self.creation = creation;
    }
    else {
        /* dynamic name */
        ec->thisalivename[0] = 0;
        ec->thisnodename[0] = 0;
    }

/* FIXME right now this_ipaddr is never used */    
    /*    memmove(&ec->this_ipaddr, thisipaddr, sizeof(ec->this_ipaddr)); */
    

    ec->cbs = cbs;
    ec->setup_context = setup_context;

    if ((dbglevel = getenv("EI_TRACELEVEL")) != NULL ||
	(dbglevel = getenv("ERL_DEBUG_DIST")) != NULL)
	ei_tracelevel = atoi(dbglevel);

    return 0;
}

int ei_connect_xinit(ei_cnode* ec, const char *thishostname,
                     const char *thisalivename, const char *thisnodename,
                     Erl_IpAddr thisipaddr, const char *cookie,
                     const short creation)
{
    return ei_connect_xinit_ussi(ec, thishostname, thisalivename, thisnodename,
                                 thisipaddr, cookie, creation,
                                 &ei_default_socket_callbacks,
                                 sizeof(ei_default_socket_callbacks),
                                 NULL);
}

/*
* Initialize by set: thishostname, thisalivename, 
* thisnodename and thisipaddr. At success return 0,
* otherwise return -1.
*/
int ei_connect_init_ussi(ei_cnode* ec, const char* this_node_name,
                         const char *cookie, short creation,
                         ei_socket_callbacks *cbs, int cbs_sz,
                         void *setup_context)
{
    char thishostname[EI_MAXHOSTNAMELEN+1];
    char thisnodename[MAXNODELEN+1];
    char thisalivename[EI_MAXALIVELEN+1];
    struct hostent host, *hp;
    char buffer[1024];
    char *buf = buffer;
    int ei_h_errno;
    int res;

    if (!ei_connect_initialized)
        init_connect(!0);
    
    /* gethostname requires len to be max(hostname) + 1 */
    if (gethostname(thishostname, EI_MAXHOSTNAMELEN+1) == -1) {
#ifdef __WIN32__
	EI_TRACE_ERR1("ei_connect_init","Failed to get host name: %d",
		      WSAGetLastError());
#else
	EI_TRACE_ERR1("ei_connect_init","Failed to get host name: %d", errno);
#endif /* win32 */
	return ERL_ERROR;
    }

    if (this_node_name == NULL) {
	sprintf(thisalivename, "c%d", (int) getpid());
    } else if (strlen(this_node_name) >= sizeof(thisalivename)) {
	EI_TRACE_ERR0("ei_connect_init","ERROR: this_node_name too long");
	return ERL_ERROR;
    } else {
	strcpy(thisalivename, this_node_name);
    }
    
    hp = dyn_gethostbyname_r(thishostname,&host,&buf,sizeof(buffer),&ei_h_errno);
    if (hp == NULL) {
	/* Looking up IP given hostname fails. We must be on a standalone
	   host so let's use loopback for communication instead. */
	hp = dyn_gethostbyname_r("localhost", &host, &buf, sizeof(buffer),
                                 &ei_h_errno);
        if (hp == NULL) {
#ifdef __WIN32__
	    char reason[1024];
	
	    win32_error(reason,sizeof(reason));
	    EI_TRACE_ERR2("ei_connect_init",
			  "Can't get ip address for host %s: %s",
			  thishostname, reason);
#else
	    EI_TRACE_ERR2("ei_connect_init",
			  "Can't get ip address for host %s: %d",
			  thishostname, h_errno);
#endif /* win32 */
	    return ERL_ERROR;
	}
    }
    {
	char* ct;
	if (strcmp(hp->h_name, "localhost") == 0) {
	    /* We use a short node name */    
	    if ((ct = strchr(thishostname, '.')) != NULL) *ct = '\0';
	} else {
	    /* We use a short node name */    
	    if ((ct = strchr(hp->h_name, '.')) != NULL) *ct = '\0';
	    strcpy(thishostname, hp->h_name);
	}
    }
    if (strlen(this_node_name) + 1 + strlen(thishostname) > MAXNODELEN) {
        EI_TRACE_ERR0("ei_connect_init_ussi","this node name is too long");
        return ERL_ERROR;
    }
    sprintf(thisnodename, "%s@%s", this_node_name, thishostname);
    res = ei_connect_xinit_ussi(ec, thishostname, thisalivename, thisnodename,
                                (struct in_addr *)*hp->h_addr_list, cookie, creation,
                                cbs, cbs_sz, setup_context);
    if (buf != buffer)
        free(buf);
    return res;
}

int ei_connect_init(ei_cnode* ec, const char* this_node_name,
                    const char *cookie, short creation)
{
    return ei_connect_init_ussi(ec, this_node_name, cookie, creation,
                                &ei_default_socket_callbacks,
                                sizeof(ei_default_socket_callbacks),
                                NULL);
}

/*
 * Same as ei_gethostbyname_r, but also handles ERANGE error
 * and may allocate larger buffer with malloc.
 */
static
struct hostent *dyn_gethostbyname_r(const char *name,
                                    struct hostent *hostp,
                                    char **buffer_p,
				    int buflen,
				    int *h_errnop)
{
#ifdef __WIN32__
    /*
     * Apparently ei_gethostbyname_r not implemented for Windows (?)
     * Fall back on ei_gethostbyname like before.
     */
    return ei_gethostbyname(name);
#else
    char* buf = *buffer_p;
    struct hostent *hp;

    while (1) {
        hp = ei_gethostbyname_r(name, hostp, buf, buflen, h_errnop);
        if (hp) {
            *buffer_p = buf;
            break;
        }

        if (*h_errnop != ERANGE) {
            if (buf != *buffer_p)
                free(buf);
            break;
        }

        buflen *= 2;
        if (buf == *buffer_p)
            buf = malloc(buflen);
        else {
            char* buf2 = realloc(buf, buflen);
            if (buf2)
                buf = buf2;
            else {
                free(buf);
                buf = NULL;
            }
        }
        if (!buf) {
            *h_errnop = ENOMEM;
            break;
        }
    }
    return hp;
#endif
}

/* Finds the the IP address for hostname and saves that IP address at
   the location that ip_wb points to. Returns a negative error code if
   the IP address cannot be found for the hostname. */
static int ip_address_from_hostname(char* hostname,
                                    char** buffer_p,
                                    size_t buffer_size,
                                    Erl_IpAddr* ip_wb)
{
    struct hostent *hp;
#ifndef __WIN32__
    /* these are needed for the call to gethostbyname_r */
    struct hostent host;
    int ei_h_errno;
    hp = dyn_gethostbyname_r(hostname,&host,buffer_p,buffer_size,&ei_h_errno);
    if (hp == NULL) {
	char thishostname[EI_MAXHOSTNAMELEN+1];
        /* gethostname requies len to be max(hostname) + 1*/
	if (gethostname(thishostname,EI_MAXHOSTNAMELEN+1) < 0) {
	    EI_TRACE_ERR0("ip_address_from_hostname",
			  "Failed to get name of this host");
	    erl_errno = EHOSTUNREACH;
	    return ERL_ERROR;
	} else {
	    char *ct;
	    /* We use a short node name */
	    if ((ct = strchr(thishostname, '.')) != NULL) *ct = '\0';
	}
	if (strcmp(hostname,thishostname) == 0)
	    /* Both nodes on same standalone host, use loopback */
	    hp = dyn_gethostbyname_r("localhost",&host,buffer_p,buffer_size,&ei_h_errno);
	if (hp == NULL) {
	    EI_TRACE_ERR2("ei_connect",
			  "Can't find host for %s: %d\n",hostname,ei_h_errno);
	    erl_errno = EHOSTUNREACH;
	    return ERL_ERROR;
	}
    }
    *ip_wb = (Erl_IpAddr) *hp->h_addr_list;
#else /* __WIN32__ */
    if ((hp = ei_gethostbyname(hostname)) == NULL) {
	char thishostname[EI_MAXHOSTNAMELEN+1];
        /* gethostname requires len to be max(hostname) + 1 */
	if (gethostname(thishostname,EI_MAXHOSTNAMELEN+1) < 0) {
	    EI_TRACE_ERR1("ip_address_from_hostname",
			  "Failed to get name of this host: %d",
			  WSAGetLastError());
	    erl_errno = EHOSTUNREACH;
	    return ERL_ERROR;
	} else {
	    char *ct;
	    /* We use a short node name */
	    if ((ct = strchr(thishostname, '.')) != NULL) *ct = '\0';
	}
	if (strcmp(hostname,thishostname) == 0)
	    /* Both nodes on same standalone host, use loopback */
	    hp = ei_gethostbyname("localhost");
	if (hp == NULL) {
	    char reason[1024];
	    win32_error(reason,sizeof(reason));
	    EI_TRACE_ERR2("ei_connect",
			  "Can't find host for %s: %s",hostname,reason);
	    erl_errno = EHOSTUNREACH;
	    return ERL_ERROR;
	}
    }
    *ip_wb = (Erl_IpAddr) *hp->h_addr_list;
#endif /* win32 */
    return 0;
}

/* Helper function for ei_connect family of functions */
static int ei_connect_helper(ei_cnode* ec,
                             Erl_IpAddr ip_addr,  /* network byte order */
                             char *alivename,
                             unsigned ms,
                             int rport,
                             int epmd_says_version)
{
    ei_socket_callbacks *cbs = ec->cbs;
    void *ctx;
    int sockd;
    unsigned her_version;
    DistFlags her_flags;
    unsigned our_challenge, her_challenge;
    unsigned char our_digest[16];
    int err;
    int pkt_sz;
    struct sockaddr_in addr;
    unsigned tmo = ms == 0 ? EI_SCLBK_INF_TMO : ms;
    
    erl_errno = EIO;		/* Default error code */

    if (alivename != NULL) {
        EI_TRACE_CONN1("ei_xconnect","-> CONNECT attempt to connect to %s",
                       alivename);
    } else {
        EI_TRACE_CONN1("ei_xconnect","-> CONNECT attempt to connect to port %d",
                       rport);
    }

    if (epmd_says_version < EI_DIST_LOW) {
	EI_TRACE_ERR1("ei_xconnect","-> CONNECT remote version %d not compatible",
                      epmd_says_version);
	return ERL_ERROR;
    }

    err = ei_socket_ctx__(cbs, &ctx, ec->setup_context);
    if (err) {
        EI_TRACE_ERR2("ei_xconnect","-> SOCKET failed: %s (%d)",
                      estr(err), err);
        erl_errno = err;
        return ERL_CONNECT_FAIL;
    }

    memset((void *) &addr, 0, sizeof(struct sockaddr_in));
    memcpy((void *) &addr.sin_addr, (void *) ip_addr, sizeof(addr.sin_addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(rport);

    err = ei_connect_ctx_t__(cbs, ctx, (void *) &addr, sizeof(addr), tmo);
    if (err) {
        EI_TRACE_ERR2("ei_xconnect","-> CONNECT socket connect failed: %s (%d)",
                      estr(err), err);
        abort_connection(cbs, ctx);
        erl_errno = err;
        return ERL_CONNECT_FAIL;
    }
    
    EI_TRACE_CONN0("ei_xconnect","-> CONNECT connected to remote");

    err = EI_GET_FD__(cbs, ctx, &sockd);
    if (err) {
        EI_CONN_SAVE_ERRNO__(err);
        goto error;
    }

    err = cbs->handshake_packet_header_size(ctx, &pkt_sz);
    if (err) {
        EI_CONN_SAVE_ERRNO__(err);
        goto error;
    }
        
    if (send_name(ec, ctx, pkt_sz, epmd_says_version, tmo))
        goto error;
    if (recv_status(ec, ctx, pkt_sz, tmo))
        goto error;
    if (recv_challenge(cbs, ctx, pkt_sz, &her_challenge, &her_version,
                       &her_flags, NULL, tmo))
        goto error;
    her_version = (her_flags & DFLAG_HANDSHAKE_23) ? EI_DIST_6 : EI_DIST_5;
    our_challenge = gen_challenge();
    gen_digest(her_challenge, ec->ei_connect_cookie, our_digest);
    if (send_complement(ec, ctx, pkt_sz, epmd_says_version, her_flags, tmo))
        goto error;
    if (send_challenge_reply(cbs, ctx, pkt_sz, our_digest, our_challenge, tmo))
        goto error;
    if (recv_challenge_ack(cbs, ctx, pkt_sz, our_challenge, 
                           ec->ei_connect_cookie, tmo))
        goto error;
    if (put_ei_socket_info(sockd, her_version, null_cookie, ec, cbs, ctx) != 0)
        goto error;

    if (cbs->connect_handshake_complete) {
        err = cbs->connect_handshake_complete(ctx);
        if (err) {
            EI_TRACE_ERR2("ei_xconnect","-> CONNECT failed: %s (%d)",
                          estr(err), err);
            close_connection(cbs, ctx, sockd);
            EI_CONN_SAVE_ERRNO__(err);
            return ERL_ERROR;
        }
    }    

    if (alivename != NULL) {
        EI_TRACE_CONN1("ei_xconnect","-> CONNECT (ok) remote = %s",alivename);
    } else {
        EI_TRACE_CONN1("ei_xconnect","-> CONNECT (ok) remote port = %d",rport);
    }

    erl_errno = 0;
    return sockd;
    
error:
    EI_TRACE_ERR0("ei_xconnect","-> CONNECT failed");
    abort_connection(cbs, ctx);
    return ERL_ERROR;
} /* ei_xconnect */

  /* 
  * Set up a connection to a given Node, and 
  * interchange hand shake messages with it.
  * Returns a valid file descriptor at success,
  * otherwise a negative error code.
*/
int ei_connect_tmo(ei_cnode* ec, char *nodename, unsigned ms)
{
    char *hostname, alivename[BUFSIZ];
    Erl_IpAddr ip;
    int res;
    char buffer[1024];
    char* buf = buffer;

    if (strlen(nodename) > MAXNODELEN) {
	EI_TRACE_ERR0("ei_connect","Too long nodename");
	return ERL_ERROR;
    }
    
    /* extract the host and alive parts from nodename */
    if (!(hostname = strchr(nodename,'@'))) {
	EI_TRACE_ERR0("ei_connect","Node name has no @ in name");
	return ERL_ERROR;
    } else {
	strncpy(alivename, nodename, hostname - nodename);
	alivename[hostname - nodename] = 0x0;
	hostname++;
    }

    res = ip_address_from_hostname(hostname, &buf, sizeof(buffer), &ip);

    if (res < 0) {
      return res;
    }

    res = ei_xconnect_tmo(ec, ip, alivename, ms);

    if(buf != buffer) {
        free(buf);
    }

    return res;
} /* ei_connect */

int ei_connect(ei_cnode* ec, char *nodename)
{
    return ei_connect_tmo(ec, nodename, 0);
}

int ei_connect_host_port_tmo(ei_cnode* ec, char *host, int port, unsigned ms)
{
    Erl_IpAddr ip;
    char buffer[1024];
    char* buf = buffer;
    int res = ip_address_from_hostname(host, &buf, sizeof(buffer), &ip);
    if (res < 0) {
      return res;
    }
    if(buf != buffer) {
        free(buf);
    }
    return ei_xconnect_host_port_tmo(ec, ip, port, ms);
}

int ei_connect_host_port(ei_cnode* ec, char *host, int port)
{
    return ei_connect_host_port_tmo(ec, host, port, 0);
}

int ei_xconnect_tmo(ei_cnode* ec, Erl_IpAddr ip_addr, char *alivename, unsigned ms)
{
    int epmd_says_version = 0;
    int port;
    unsigned tmo = ms == 0 ? EI_SCLBK_INF_TMO : ms;
    if ((port = ei_epmd_port_tmo(ip_addr,alivename,&epmd_says_version, tmo)) < 0) {
	EI_TRACE_ERR0("ei_xconnect","-> CONNECT can't get remote port");
	/* ei_epmd_port_tmo() has set erl_errno */
	return ERL_NO_PORT;
    }
    return ei_connect_helper(ec, ip_addr, alivename, ms, port, epmd_says_version);
}

int ei_xconnect(ei_cnode* ec, Erl_IpAddr ip_addr, char *alivename)
{
    return ei_xconnect_tmo(ec, ip_addr, alivename, 0);
}

int ei_xconnect_host_port_tmo(ei_cnode* ec, Erl_IpAddr ip_addr, int port, unsigned ms)
{
    return ei_connect_helper(ec, ip_addr, NULL, ms, port, EI_DIST_LOW);
}

int ei_xconnect_host_port(ei_cnode* ec, Erl_IpAddr ip_addr, int port)
{
    return ei_xconnect_host_port_tmo(ec, ip_addr, port, 0);
}

int ei_listen(ei_cnode *ec, int *port, int backlog)
{
    struct in_addr ip_addr;
    ip_addr.s_addr = htonl(INADDR_ANY);
    return ei_xlisten(ec, &ip_addr, port, backlog);
}

int ei_xlisten(ei_cnode *ec, struct in_addr *ip_addr, int *port, int backlog)
{
    ei_socket_callbacks *cbs = ec->cbs;
    struct sockaddr_in sock_addr;
    void *ctx;
    int fd, err, len;

    err = ei_socket_ctx__(cbs, &ctx, ec->setup_context);
    if (err) {
        EI_TRACE_ERR2("ei_xlisten","-> SOCKET failed: %s (%d)",
                      estr(err), err);
        erl_errno = err;
        return ERL_ERROR;
    }

    memset((void *) &sock_addr, 0, sizeof(struct sockaddr_in));
    memcpy((void *) &sock_addr.sin_addr, (void *) ip_addr, sizeof(*ip_addr));
    sock_addr.sin_family = AF_INET;
    sock_addr.sin_port = htons((short) *port);

    len = sizeof(sock_addr);
    err = ei_listen_ctx__(cbs, ctx, (void *) &sock_addr, &len, backlog);
    if (err) {
        EI_TRACE_ERR2("ei_xlisten","-> listen failed: %s (%d)",
                      estr(err), err);
        erl_errno = err;
        goto error;
    }

    if (len != sizeof(sock_addr)) {
        if (len < offsetof(struct sockaddr_in, sin_addr) + sizeof(sock_addr.sin_addr)
            || len < offsetof(struct sockaddr_in, sin_port) + sizeof(sock_addr.sin_port)) {
            erl_errno = EIO;
            EI_TRACE_ERR0("ei_xlisten","-> get info failed");
            goto error;
        }
    }

    memcpy((void *) ip_addr, (void *) &sock_addr.sin_addr, sizeof(*ip_addr));
    *port = (int) ntohs(sock_addr.sin_port);
    
    err = EI_GET_FD__(cbs, ctx, &fd);
    if (err) {
        erl_errno = err;
        goto error;
    }

    if (put_ei_socket_info(fd, 0, null_cookie, ec, cbs, ctx) != 0) {
        EI_TRACE_ERR0("ei_xlisten","-> save socket info failed");
        erl_errno = EIO;
        goto error;
    }
    
    erl_errno = 0;

    return fd;
    
error:
    abort_connection(cbs, ctx);
    return ERL_ERROR;
}
    
static int close_connection(ei_socket_callbacks *cbs, void *ctx, int fd)
{
    int err;
    remove_ei_socket_info(fd);
    err = ei_close_ctx__(cbs, ctx);
    if (err) {
        erl_errno = err;
        return ERL_ERROR;
    }
    return 0;
}

int ei_close_connection(int fd)
{
    ei_socket_callbacks *cbs;
    void *ctx;
    int err = EI_GET_CBS_CTX__(&cbs, &ctx, fd);
    if (err)
        erl_errno = err;
    else {
        if (close_connection(cbs, ctx, fd) == 0)
            return 0;
    }
    EI_TRACE_ERR2("ei_close_connection","<- CLOSE socket close failed: %s (%d)",
                  estr(erl_errno), erl_errno);
    return ERL_ERROR;
} /* ei_close_connection */

static void abort_connection(ei_socket_callbacks *cbs, void *ctx)
{
    (void) ei_close_ctx__(cbs, ctx);
}

  /*
  * Accept and initiate a connection from another
  * Erlang node. Return a file descriptor at success,
  * otherwise -1;
*/
int ei_accept(ei_cnode* ec, int lfd, ErlConnect *conp)
{
    return ei_accept_tmo(ec, lfd, conp, 0);
}

int ei_accept_tmo(ei_cnode* ec, int lfd, ErlConnect *conp, unsigned ms)
{
    int fd;
    DistFlags her_flags;
    char tmp_nodename[MAXNODELEN+1];
    char send_name_tag;
    char *her_name;
    int pkt_sz, err;
    struct sockaddr_in addr;
    int addr_len = sizeof(struct sockaddr_in);
    ei_socket_callbacks *cbs;
    void *ctx;
    unsigned tmo = ms == 0 ? EI_SCLBK_INF_TMO : ms;

    erl_errno = EIO;		/* Default error code */
    
    err = EI_GET_CBS_CTX__(&cbs, &ctx, lfd);
    if (err) {
        if (lfd < 0) {
            EI_CONN_SAVE_ERRNO__(err);
            return ERL_ERROR;
        }
        /*
         * This can be a listen socket created without ei_listen or ei_xlisten,
         * so we must assume it is.
         */
        cbs = &ei_default_socket_callbacks;
        ctx = EI_FD_AS_CTX__(lfd);
    }

    if (ec->cbs != cbs) {
        EI_CONN_SAVE_ERRNO__(EINVAL);
        return ERL_ERROR;
    }

    EI_TRACE_CONN0("ei_accept","<- ACCEPT waiting for connection");

    if (conp) {
        her_name = &conp->nodename[0];
    }
    else {
        her_name = &tmp_nodename[0];
    }
    
    /*
     * ei_accept_ctx_t__() replaces the pointer to the listen context
     * with a pointer to the accepted connection context on success.
     */
    err = ei_accept_ctx_t__(cbs, &ctx, (void *) &addr, &addr_len, tmo);
    if (err) {
	EI_TRACE_ERR2("ei_accept","<- ACCEPT socket accept failed: %s (%d)",
                      estr(err), err);
        EI_CONN_SAVE_ERRNO__(err);
        return ERL_ERROR;
    }

    err = EI_GET_FD__(cbs, ctx, &fd);
    if (err) {
	EI_TRACE_ERR2("ei_accept","<- ACCEPT get fd failed: %s (%d)",
                      estr(err), err);
        EI_CONN_SAVE_ERRNO__(err);
    }

    if (addr_len != sizeof(struct sockaddr_in)) {
        if (addr_len < (offsetof(struct sockaddr_in, sin_addr)
                        + sizeof(addr.sin_addr))) {
            EI_TRACE_ERR0("ei_accept","<- ACCEPT get addr failed");
            goto error;
        }
    }

    err = cbs->handshake_packet_header_size(ctx, &pkt_sz);
    if (err) {
	EI_TRACE_ERR2("ei_accept","<- ACCEPT get packet size failed: %s (%d)",
                      estr(err), err);
        EI_CONN_SAVE_ERRNO__(err);
    }
    
    EI_TRACE_CONN0("ei_accept","<- ACCEPT connected to remote");
    
    if (recv_name(cbs, ctx, pkt_sz, &send_name_tag, &her_flags,
                  her_name, tmo)) {
	EI_TRACE_ERR0("ei_accept","<- ACCEPT initial ident failed");
	goto error;
    }
    
    {
        unsigned her_version = (her_flags & DFLAG_HANDSHAKE_23) ? 6 : 5;
	unsigned our_challenge;
	unsigned her_challenge;
	unsigned char our_digest[16];
        
	if (send_status(cbs, ctx, pkt_sz, "ok", tmo))
	    goto error;
	our_challenge = gen_challenge();
	if (send_challenge(ec, ctx, pkt_sz, our_challenge, her_flags, tmo))
	    goto error;
        if (send_name_tag == 'n' && (her_flags & DFLAG_HANDSHAKE_23)) {
            if (recv_complement(cbs, ctx, pkt_sz, tmo))
                goto error;
        }
	if (recv_challenge_reply(cbs, ctx, pkt_sz, our_challenge, 
                                 ec->ei_connect_cookie, &her_challenge, tmo))
	    goto error;
	gen_digest(her_challenge, ec->ei_connect_cookie, our_digest);
	if (send_challenge_ack(cbs, ctx, pkt_sz, our_digest, tmo))
	    goto error;
	if (put_ei_socket_info(fd, her_version, null_cookie, ec, cbs, ctx) != 0)
            goto error;
    }
    if (conp) {
        memcpy((void *) conp->ipadr, (void *) &addr.sin_addr, sizeof(conp->ipadr));
    }

    if (cbs->accept_handshake_complete) {
        err = cbs->accept_handshake_complete(ctx);
        if (err) {
            EI_TRACE_ERR2("ei_xconnect","-> ACCEPT handshake failed: %s (%d)",
                          estr(err), err);
            close_connection(cbs, ctx, fd);
            EI_CONN_SAVE_ERRNO__(err);
            return ERL_ERROR;
        }
    }
    
    EI_TRACE_CONN1("ei_accept","<- ACCEPT (ok) remote = %s",her_name);

    erl_errno = 0;		/* No error */
    return fd;
    
error:
    EI_TRACE_ERR0("ei_accept","<- ACCEPT failed");
    abort_connection(cbs, ctx);
    return ERL_ERROR;
} /* ei_accept */


/* Receives a message from an Erlang socket.
 * If the message was a TICK it is immediately
 * answered. Returns: ERL_ERROR, ERL_TICK or
 * the number of bytes read.
 */
int ei_receive_tmo(int fd, unsigned char *bufp, int bufsize, unsigned ms) 
{
    ssize_t len;
    unsigned char fourbyte[4]={0,0,0,0};
    int err;
    ei_socket_callbacks *cbs;
    void *ctx;
    unsigned tmo = ms == 0 ? EI_SCLBK_INF_TMO : ms;

    err = EI_GET_CBS_CTX__(&cbs, &ctx, fd);
    if (err) {
        EI_CONN_SAVE_ERRNO__(err);
        return ERL_ERROR;
    }

    len = (ssize_t) 4;
    err = ei_read_fill_ctx_t__(cbs, ctx, (char *) bufp, &len, tmo);
    if (!err && len != (ssize_t) 4)
        err = EIO;
    if (err) {
        EI_CONN_SAVE_ERRNO__(err);
	return ERL_ERROR;
    }
    
    /* Tick handling */
    len = get_int32(bufp);
    if (len == ERL_TICK) {
        len = 4;
	ei_write_fill_ctx_t__(cbs, ctx, (char *) fourbyte, &len, tmo);
	/* FIXME ok to ignore error or timeout? */
	erl_errno = EAGAIN;
	return ERL_TICK;
    }
    
    if (len > bufsize) {
	/* FIXME: We should drain the message. */
	erl_errno = EMSGSIZE;
	return ERL_ERROR;
    }
    else {
        ssize_t need = len;
        err = ei_read_fill_ctx_t__(cbs, ctx, (char *) bufp, &len, tmo);
        if (err) {
            EI_CONN_SAVE_ERRNO__(err);
            return ERL_ERROR;
        }
        if (len != need) {
            erl_errno = EIO;
            return ERL_ERROR;
        }
    }
    
    return (int) len;
    
}

int ei_receive(int fd, unsigned char *bufp, int bufsize) 
{
    return ei_receive_tmo(fd, bufp, bufsize, 0);
} 

int ei_reg_send_tmo(ei_cnode* ec, int fd, char *server_name,
		    char* buf, int len, unsigned ms)
{
    /* erl_errno and return code is set by ei_reg_send_encoded_tmo() */
    return ei_send_reg_encoded_tmo(fd, ei_self(ec), server_name, buf, len, ms);
}


int ei_reg_send(ei_cnode* ec, int fd, char *server_name, char* buf, int len)
{
    return ei_reg_send_tmo(ec,fd,server_name,buf,len,0);
}

/* 
* Sends an Erlang message to a process at an Erlang node
*/
int ei_send_tmo(int fd, erlang_pid* to, char* buf, int len, unsigned ms)
{
    /* erl_errno and return code is set by ei_reg_send_encoded_tmo() */
    return ei_send_encoded_tmo(fd, to, buf, len, ms);
}

int ei_send(int fd, erlang_pid* to, char* buf, int len)
{
    return ei_send_tmo(fd, to, buf, len, 0);
}


/* 
* Try to receive an Erlang message on a given socket. Returns
* ERL_TICK, ERL_MSG, or ERL_ERROR. Sets `erl_errno' on ERL_ERROR and
* ERL_TICK (to EAGAIN in the latter case).
*/

int ei_do_receive_msg(int fd, int staticbuffer_p, 
		      erlang_msg* msg, ei_x_buff* x, unsigned ms)
{
    int msglen;
    int i;
    
    if (!(i=ei_recv_internal(fd, &x->buff, &x->buffsz, msg, &msglen, 
	staticbuffer_p, ms))) {
	erl_errno = EAGAIN;
	return ERL_TICK;
    }
    if (i<0) {
	/* erl_errno set by ei_recv_internal() */
	return ERL_ERROR;
    }
    if (staticbuffer_p && msglen > x->buffsz)
    {
	erl_errno = EMSGSIZE;
	return ERL_ERROR;
    }
    x->index = msglen;
    switch (msg->msgtype) {	/* FIXME does not handle trace tokens and monitors */
    case ERL_SEND:
    case ERL_REG_SEND:
    case ERL_LINK:
    case ERL_UNLINK:
    case ERL_GROUP_LEADER:
    case ERL_EXIT:
    case ERL_EXIT2:
	return ERL_MSG;
	
    default:
	/*if (emsg->to) 'erl'_free_term(emsg->to);
	  if (emsg->from) 'erl'_free_term(emsg->from);
	  if (emsg->msg) 'erl'_free_term(emsg->msg);
	  emsg->to = NULL;
	  emsg->from = NULL;
	  emsg->msg = NULL;*/
	
	erl_errno = EIO;
	return ERL_ERROR;
    }
} /* do_receive_msg */


int ei_receive_msg(int fd, erlang_msg* msg, ei_x_buff* x)
{
    return ei_do_receive_msg(fd, 1, msg, x, 0);
}

int ei_xreceive_msg(int fd, erlang_msg *msg, ei_x_buff *x)
{
    return ei_do_receive_msg(fd, 0, msg, x, 0);
}

int ei_receive_msg_tmo(int fd, erlang_msg* msg, ei_x_buff* x, unsigned ms)
{
    return ei_do_receive_msg(fd, 1, msg, x, ms);
}

int ei_xreceive_msg_tmo(int fd, erlang_msg *msg, ei_x_buff *x, unsigned ms)
{
    return ei_do_receive_msg(fd, 0, msg, x, ms);
}

/* 
* The RPC consists of two parts, send and receive.
* Here is the send part ! 
* { PidFrom, { call, Mod, Fun, Args, user }} 
*/
/*
* Now returns non-negative number for success, negative for failure.
*/
int ei_rpc_to(ei_cnode *ec, int fd, char *mod, char *fun,
	      const char *buf, int len)
{

    ei_x_buff x;
    erlang_pid *self = ei_self(ec);
    int err = ERL_ERROR;

    /* encode header */
    if (ei_x_new_with_version(&x) < 0)
        goto einval;
    if (ei_x_encode_tuple_header(&x, 2) < 0)  /* A */
        goto einval;
    
    if (ei_x_encode_pid(&x, self) < 0)	      /* A 1 */
        goto einval;
    
    if (ei_x_encode_tuple_header(&x, 5) < 0)  /* B A 2 */
        goto einval;
    if (ei_x_encode_atom(&x, "call") < 0)     /* B 1 */
        goto einval;
    if (ei_x_encode_atom(&x, mod) < 0)	      /* B 2 */
        goto einval;
    if (ei_x_encode_atom(&x, fun) < 0)	      /* B 3 */
        goto einval;
    if (ei_x_append_buf(&x, buf, len) < 0)    /* B 4 */
        goto einval;
    if (ei_x_encode_atom(&x, "user") < 0)     /* B 5 */
        goto einval;
    
    err = ei_send_reg_encoded(fd, self, "rex", x.buff, x.index);
    if (err)
        goto error;
    
    ei_x_free(&x);	

    return 0;

einval:
    EI_CONN_SAVE_ERRNO__(EINVAL);

error:
    if (x.buff != NULL)
        ei_x_free(&x);
    return err;
} /* rpc_to */

  /*
  * And here is the rpc receiving part. A negative
  * timeout means 'infinity'. Returns either of: ERL_MSG,
  * ERL_TICK, ERL_ERROR or ERL_TIMEOUT.
*/
int ei_rpc_from(ei_cnode *ec, int fd, int timeout, erlang_msg *msg,
		ei_x_buff *x) 
{
    unsigned tmo = timeout < 0 ? EI_SCLBK_INF_TMO : (unsigned) timeout;
    int res = ei_xreceive_msg_tmo(fd, msg, x, tmo);
    if (res < 0 && erl_errno == ETIMEDOUT)
        return ERL_TIMEOUT;
    return res;
} /* rpc_from */

int ei_rpc(ei_cnode* ec, int fd, char *mod, char *fun,
	   const char* inbuf, int inbuflen, ei_x_buff* x)
{
    int i, index;
    ei_term t;
    erlang_msg msg;
    char rex[MAXATOMLEN];

    if (ei_rpc_to(ec, fd, mod, fun, inbuf, inbuflen) < 0) {
	return ERL_ERROR;
    }

    /* ei_rpc_from() responds with a tick if it gets one... */
    while ((i = ei_rpc_from(ec, fd, ERL_NO_TIMEOUT, &msg, x)) == ERL_TICK)
	;

    if (i == ERL_ERROR)  return i;
    
    /* Expect: {rex, RPC_Reply} */

    index = 0;
    if (ei_decode_version(x->buff, &index, &i) < 0)
        goto ebadmsg;

    if (ei_decode_ei_term(x->buff, &index, &t) < 0)
        goto ebadmsg;

    if (t.ei_type != ERL_SMALL_TUPLE_EXT && t.ei_type != ERL_LARGE_TUPLE_EXT)
        goto ebadmsg;

    if (t.arity != 2)
        goto ebadmsg;

    if (ei_decode_atom(x->buff, &index, rex) < 0)
        goto ebadmsg;

    if (strcmp("rex", rex) != 0)
        goto ebadmsg;

    /* remove header */
    x->index -= index;
    memmove(x->buff, &x->buff[index], x->index);
    return 0;
    
ebadmsg:
    
    EI_CONN_SAVE_ERRNO__(EBADMSG);
    return ERL_ERROR;
}


  /*
  ** Handshake
*/


/* FROM RTP RFC 1889  (except that we use all bits, bug in RFC?) */
static unsigned int md_32(char* string, int length)
{
    MD5_CTX ctx;
    union {
	char c[16];
	unsigned x[4];
    } digest;
    ei_MD5Init(&ctx);
    ei_MD5Update(&ctx, (unsigned char *) string, 
	       (unsigned) length);
    ei_MD5Final((unsigned char *) digest.c, &ctx);
    return (digest.x[0] ^ digest.x[1] ^ digest.x[2] ^ digest.x[3]);
}

#if defined(__WIN32__)
unsigned int gen_challenge(void)
{
    struct {
	SYSTEMTIME tv;
	DWORD cpu;
	int pid;
    } s;
    GetSystemTime(&s.tv);
    s.cpu  = GetTickCount();
    s.pid  = getpid();
    return md_32((char*) &s, sizeof(s));
}

#else  /* some unix */

static unsigned int gen_challenge(void)
{
    struct {
	struct timeval tv;
	clock_t cpu;
	pid_t pid;
	u_long hid;
	uid_t uid;
	gid_t gid;
	struct utsname name;
    } s;

    memset(&s, 0, sizeof(s));
    gettimeofday(&s.tv, 0);
    uname(&s.name);
    s.cpu  = clock();
    s.pid  = getpid();
#ifndef __ANDROID__
    s.hid  = gethostid();
#else
    s.hid  = 0;
#endif
    s.uid  = getuid();
    s.gid  = getgid();

    return md_32((char*) &s, sizeof(s));
}
#endif

static void gen_digest(unsigned challenge, char cookie[], 
		       unsigned char digest[16])
{
    MD5_CTX c;
    
    char chbuf[21];
    
    sprintf(chbuf,"%u", challenge);
    ei_MD5Init(&c);
    ei_MD5Update(&c, (unsigned char *) cookie, 
	       (unsigned) strlen(cookie));
    ei_MD5Update(&c, (unsigned char *) chbuf, 
	       (unsigned) strlen(chbuf));
    ei_MD5Final(digest, &c);
}


static char *hex(char digest[16], char buff[33])
{
    static char tab[] = "0123456789abcdef";
    unsigned char *d = (unsigned char *) digest;
    //static char buff[sizeof(digest)*2 + 1];
    char *p = buff;
    int i;
    
    for (i = 0; i < 16; ++i) {
	*p++ = tab[(int)((*d) >> 4)];
	*p++ = tab[(int)((*d++) & 0xF)];
    }
    *p = '\0';
    return buff;
}

static int read_hs_package(ei_socket_callbacks *cbs, void *ctx,
                           int pkt_sz, char **buf, int *buflen, 
                           int *is_static, unsigned ms)
{
    unsigned char nbuf[4];
    unsigned char *x = nbuf;
    ssize_t len, need;
    int err;

    len = (ssize_t) pkt_sz;
    err = ei_read_fill_ctx_t__(cbs, ctx, (char *)nbuf, &len, ms);
    if (!err && len != (ssize_t) pkt_sz)
        err = EIO;
    if (err) {
        EI_CONN_SAVE_ERRNO__(err);
	return -1;
    }
    
    switch (pkt_sz) {
    case 2:
        len = get16be(x);
        break;
    case 4:
        len = get32be(x);
        break;
    default:
        return -1;
    }
    
    if (len > *buflen) {
	if (*is_static) {
	    char *tmp = malloc(len);
	    if (!tmp) {
		erl_errno = ENOMEM;
		return -1;
	    }
	    *buf = tmp;
	    *is_static = 0;
	    *buflen = len;
	} else {
	    char *tmp = realloc(*buf, len);
	    if (!tmp) {
		erl_errno = ENOMEM;
		return -1;
	    }
	    *buf = tmp;
	    *buflen = len;
	}
    }
    need = len;
    err = ei_read_fill_ctx_t__(cbs, ctx, *buf, &len, ms);
    if (!err && len != need)
        err = EIO;
    if (err) {
        EI_CONN_SAVE_ERRNO__(err);
	return -1;
    }
    return len;
}


static int send_status(ei_socket_callbacks *cbs, void *ctx,
                       int pkt_sz, char *status, unsigned ms)
{
    char *buf, *s;
    char dbuf[DEFBUF_SIZ];
    int siz = strlen(status) + 1 + pkt_sz;
    int err;
    ssize_t len;

    buf = (siz > DEFBUF_SIZ) ? malloc(siz) : dbuf;
    if (!buf) {
	erl_errno = ENOMEM;
	return -1;
    }
    s = buf;
    switch (pkt_sz) {
    case 2:
        put16be(s,siz - 2);
        break;
    case 4:
        put32be(s,siz - 4);
        break;
    default:
        return -1;
    }
    put8(s, 's');
    memcpy(s, status, strlen(status));
    len = (ssize_t) siz;
    err = ei_write_fill_ctx_t__(cbs, ctx, buf, &len, ms);
    if (!err && len != (ssize_t) siz)
        err = EIO;
    if (err) {
	EI_TRACE_ERR2("send_status","-> SEND_STATUS socket write failed: %s (%d)",
                      estr(err), err);
	if (buf != dbuf)
	    free(buf);        
        EI_CONN_SAVE_ERRNO__(err);
	return -1;
    }
    EI_TRACE_CONN1("send_status","-> SEND_STATUS (%s)",status);

    if (buf != dbuf)
	free(buf);
    return 0;
}

static int recv_status(ei_cnode *ec, void *ctx,
                       int pkt_sz, unsigned ms)
{
    char dbuf[DEFBUF_SIZ];
    char *buf = dbuf;
    int is_static = 1;
    int buflen = DEFBUF_SIZ;
    int rlen;
    
    if ((rlen = read_hs_package(ec->cbs, ctx, pkt_sz,
                                &buf, &buflen, &is_static, ms)) <= 0) {
	EI_TRACE_ERR1("recv_status",
		      "<- RECV_STATUS socket read failed (%d)", rlen);
	goto error;
    }

    EI_TRACE_CONN2("recv_status",
                   "<- RECV_STATUS (%.*s)", (rlen>20 ? 20 : rlen), buf);

    if (ec->thisnodename[0]) {
        if (rlen >= 3 && buf[0] == 's' && buf[1] == 'o' && buf[2] == 'k') {
            /* Expecting "sok" or "sok_simultaneous" */
            if (!is_static)
                free(buf);
            return 0;
        }
    }
    else { /* dynamic node name */
        const char* at;
        int namelen;
        if (rlen >= 7 && strncmp(buf, "snamed:", 7) == 0) {
            buf += 7;
            rlen -= 7;
            namelen = get16be(buf);
            rlen -= 2;
            if (namelen > MAXNODELEN || (namelen+4) > rlen) {
                EI_TRACE_ERR1("recv_status","<- RECV_STATUS nodename too long (%d)",
                              namelen);
                goto error;
            }
            memcpy(ec->thisnodename, buf, namelen);
            ec->thisnodename[namelen] = '\0';
            buf += namelen;
            ec->creation = get32be(buf);

            /* extract alive part from nodename */
            if (!(at = strchr(ec->thisnodename,'@'))) {
                EI_TRACE_ERR0("ei_connect","Dynamic node name has no @ in name");
                return ERL_ERROR;
            } else {
                const int alen = at - ec->thisnodename;
                strncpy(ec->thisalivename, ec->thisnodename, alen);
                ec->thisalivename[alen] = '\0';
            }

            strcpy(ec->self.node, ec->thisnodename);
            ec->self.num = 0;
            ec->self.serial = 0;
            ec->self.creation = ec->creation;
            return 0;
        }
    }
error:
    if (!is_static)
	free(buf);
    return -1;
}

static DistFlags preferred_flags(void)
{
    DistFlags flags =
        DFLAG_EXTENDED_REFERENCES
        | DFLAG_DIST_MONITOR
        | DFLAG_EXTENDED_PIDS_PORTS
        | DFLAG_FUN_TAGS
        | DFLAG_NEW_FUN_TAGS
        | DFLAG_NEW_FLOATS
        | DFLAG_SMALL_ATOM_TAGS
        | DFLAG_UTF8_ATOMS
        | DFLAG_MAP_TAG
        | DFLAG_BIG_CREATION
        | DFLAG_EXPORT_PTR_TAG
        | DFLAG_BIT_BINARIES
        | DFLAG_HANDSHAKE_23;
    if (ei_internal_use_21_bitstr_expfun()) {
        flags &= ~(DFLAG_EXPORT_PTR_TAG
                   | DFLAG_BIT_BINARIES);
    }
    return flags;
}

static int send_name(ei_cnode *ec,
                     void *ctx,
                     int pkt_sz,
                     unsigned version,
                     unsigned ms)
{
    char *buf;
    unsigned char *s;
    char dbuf[DEFBUF_SIZ];
    const char* name_ptr;
    unsigned int name_len;
    int siz;
    int err;
    ssize_t len;
    DistFlags flags = preferred_flags();
    char tag;

    if (ec->thisnodename[0]) {
        name_ptr = ec->thisnodename;
        tag = (version == EI_DIST_5) ? 'n' : 'N';
    }
    else {
        /* dynamic node name */
        name_ptr = ec->thishostname;
        tag = 'N'; /* presume ver 6 */
        flags |= DFLAG_NAME_ME;
    }

    name_len = strlen(name_ptr);

    if (tag == 'n')
        siz = pkt_sz + 1 + 2 + 4 + name_len;
    else
        siz = pkt_sz + 1 + 8 + 4 + 2 + name_len;

    buf = (siz > DEFBUF_SIZ) ? malloc(siz) : dbuf;
    if (!buf) {
	erl_errno = ENOMEM;
	return -1;
    }
    s = (unsigned char *)buf;
    switch (pkt_sz) {
    case 2:
        put16be(s,siz - 2);
        break;
    case 4:
        put32be(s,siz - 4);
        break;
    default:
        return -1;
    }

    put8(s, tag);
    if (tag == 'n') {
        put16be(s, EI_DIST_5); /* some impl (jinterface) demand ver==5 */
        put32be(s, flags);
    }
    else { /* tag == 'N' */
        put64be(s, flags);
        put32be(s, ec->creation);
        put16be(s, name_len);
    }
    memcpy(s, name_ptr, name_len);
    len = (ssize_t) siz;
    err = ei_write_fill_ctx_t__(ec->cbs, ctx, buf, &len, ms);
    if (!err && len != (ssize_t) siz)
        err = EIO;
    if (err) {
	EI_TRACE_ERR0("send_name", "SEND_NAME -> socket write failed");
	if (buf != dbuf)
	    free(buf);
        EI_CONN_SAVE_ERRNO__(err);
	return -1;
    }

    if (buf != dbuf)
	free(buf);
    return 0;
}

static int send_challenge(ei_cnode *ec,
                          void *ctx,
                          int pkt_sz,
                          unsigned challenge,
                          DistFlags her_flags,
                          unsigned ms)
{
    char *buf;
    unsigned char *s;
    char dbuf[DEFBUF_SIZ];
    const unsigned int nodename_len = strlen(ec->thisnodename);
    int siz;
    int err;
    ssize_t len;
    DistFlags flags;
    const char tag = (her_flags & DFLAG_HANDSHAKE_23) ? 'N' : 'n';

    if (tag == 'n')
        siz = pkt_sz + 1 + 2 + 4 + 4 + nodename_len;
    else
        siz = pkt_sz + 1 + 8 + 4 + 4 + 2 + nodename_len;

    buf = (siz > DEFBUF_SIZ) ? malloc(siz) : dbuf;
    if (!buf) {
	erl_errno = ENOMEM;
	return -1;
    }
    s = (unsigned char *)buf;
    switch (pkt_sz) {
    case 2:
        put16be(s,siz - 2);
        break;
    case 4:
        put32be(s,siz - 4);
        break;
    default:
        return -1;
    }

    flags = preferred_flags();
    put8(s, tag);
    if (tag == 'n') {
        put16be(s, EI_DIST_5);  /* choosen version */
        put32be(s, flags);
        put32be(s, challenge);
    }
    else {
        put64be(s, flags);
        put32be(s, challenge);
        put32be(s, ec->creation);
        put16be(s, nodename_len);
    }
    memcpy(s, ec->thisnodename, nodename_len);
    len = (ssize_t) siz;
    err = ei_write_fill_ctx_t__(ec->cbs, ctx, buf, &len, ms);
    if (!err && len != (ssize_t) siz)
        err = EIO;
    if (err) {
	EI_TRACE_ERR0("send_challenge", "-> SEND_CHALLENGE socket write failed");
	if (buf != dbuf)
	    free(buf);
        EI_CONN_SAVE_ERRNO__(err);
	return -1;
    }
    
    if (buf != dbuf)
	free(buf);
    return 0;
}

static int recv_challenge(ei_socket_callbacks *cbs, void *ctx,
                          int pkt_sz, unsigned *challenge, unsigned *version,
			  DistFlags *flags, char *namebuf, unsigned ms)
{
    char dbuf[DEFBUF_SIZ];
    char *buf = dbuf;
    int is_static = 1;
    int buflen = DEFBUF_SIZ;
    int rlen, nodename_len;
    char *s;
    char tag;
    char tmp_nodename[MAXNODELEN+1];

    erl_errno = EIO;		/* Default */

    if ((rlen = read_hs_package(cbs, ctx, pkt_sz, &buf, &buflen,
                                &is_static, ms)) <= 0) {
	EI_TRACE_ERR1("recv_challenge",
		      "<- RECV_CHALLENGE socket read failed (%d)",rlen);
	goto error;
    }
    s = buf;
    tag = get8(s);
    if (tag != 'n' && tag != 'N') {
	EI_TRACE_ERR2("recv_challenge",
		      "<- RECV_CHALLENGE incorrect tag, "
		      "expected 'n' or 'N', got '%c' (%u)",tag,tag);
	goto error;
    }
    if (tag == 'n') { /* OLD */
        unsigned int version;
        if (rlen < 1+2+4+4) {
            EI_TRACE_ERR1("recv_challenge","<- RECV_CHALLENGE 'n' packet too short (%d)",
                          rlen)
            goto error;
        }

        version = get16be(s);
        if (version != EI_DIST_5) {
            EI_TRACE_ERR1("recv_challenge",
                          "<- RECV_CHALLENGE 'n' incorrect version=%d",
                          version);
            goto error;
        }
        *flags = get32be(s);
        *challenge = get32be(s);
        nodename_len = (buf + rlen) - s;
    }
    else { /* NEW */
        if (rlen < 1+8+4+4+2) {
            EI_TRACE_ERR1("recv_challenge","<- RECV_CHALLENGE 'N' packet too short (%d)",
                          rlen)
            goto error;
        }
        *version = EI_DIST_6;
        *flags = get64be(s);
        *challenge = get32be(s);
        s += 4; /* ignore peer 'creation' */
        nodename_len = get16be(s);
        if (nodename_len > (buf + rlen) - s) {
            EI_TRACE_ERR1("recv_challenge",
                          "<- RECV_CHALLENGE 'N' nodename too long (%d)",
                          nodename_len);
            goto error;
        }
    }

    if (nodename_len > MAXNODELEN) {
        EI_TRACE_ERR1("recv_challenge",
                      "<- RECV_CHALLENGE nodename too long (%d)", nodename_len);
        goto error;
    }

    if (!(*flags & DFLAG_EXTENDED_REFERENCES)) {
	EI_TRACE_ERR0("recv_challenge","<- RECV_CHALLENGE peer cannot "
		      "handle extended references");
	goto error;
    }

    if (!(*flags & DFLAG_EXTENDED_PIDS_PORTS)) {
	EI_TRACE_ERR0("recv_challenge","<- RECV_CHALLENGE peer cannot "
		      "handle extended pids and ports");
	erl_errno = EIO;
	goto error;
    }
	    
    if (!(*flags & DFLAG_NEW_FLOATS)) {
	EI_TRACE_ERR0("recv_challenge","<- RECV_CHALLENGE peer cannot "
		      "handle binary float encoding");
	goto error;
    }

    if (!namebuf)
        namebuf = &tmp_nodename[0];
    
    memcpy(namebuf, s, nodename_len);
    namebuf[nodename_len] = '\0';
    
    if (!is_static)
	free(buf);
    EI_TRACE_CONN4("recv_challenge","<- RECV_CHALLENGE (ok) node = %s, "
	    "version = %u, "
	    "flags = %u, "
	    "challenge = %d",
	    namebuf,
	    *version,
	    *flags,
	    *challenge
	    );
    erl_errno = 0;
    return 0;
error:
    if (!is_static)
	free(buf);
    return -1;
}

static int send_complement(ei_cnode *ec,
                            void *ctx,
                            int pkt_sz,
                            unsigned epmd_says_version,
                            DistFlags her_flags,
                            unsigned ms)
{
    if (epmd_says_version == EI_DIST_5 && (her_flags & DFLAG_HANDSHAKE_23)) {
        char *buf;
        unsigned char *s;
        char dbuf[DEFBUF_SIZ];
        int err;
        ssize_t len;
        unsigned int flagsHigh;
        const int siz = pkt_sz + 1 + 4 + 4;

        buf = (siz > DEFBUF_SIZ) ? malloc(siz) : dbuf;
        if (!buf) {
            erl_errno = ENOMEM;
            return -1;
        }
        s = (unsigned char *)buf;
        switch (pkt_sz) {
        case 2:
            put16be(s,siz - 2);
            break;
        case 4:
            put32be(s,siz - 4);
            break;
        default:
            return -1;
        }
        flagsHigh = preferred_flags() >> 32;

        put8(s, 'c');
        put32be(s, flagsHigh);
        put32be(s, ec->creation);

        len = (ssize_t) siz;
        err = ei_write_fill_ctx_t__(ec->cbs, ctx, buf, &len, ms);
        if (!err && len != (ssize_t) siz)
            err = EIO;
        if (err) {
            EI_TRACE_ERR0("send_name", "SEND_NAME -> socket write failed");
            if (buf != dbuf)
                free(buf);
            EI_CONN_SAVE_ERRNO__(err);
            return -1;
        }

        if (buf != dbuf)
            free(buf);
    }
    return 0;
}


static int send_challenge_reply(ei_socket_callbacks *cbs, void *ctx,
                                int pkt_sz, unsigned char digest[16], 
				unsigned challenge, unsigned ms) 
{
    char *s;
    char buf[DEFBUF_SIZ];
    int siz = pkt_sz + 1 + 4 + 16;
    int err;
    ssize_t len;

    s = buf;
    switch (pkt_sz) {
    case 2:
        put16be(s,siz - 2);
        break;
    case 4:
        put32be(s,siz - 4);
        break;
    default:
        return -1;
    }
    put8(s, 'r');
    put32be(s, challenge);
    memcpy(s, digest, 16);

    len = (ssize_t) siz;
    err = ei_write_fill_ctx_t__(cbs, ctx, buf, &len, ms);
    if (!err && len != (ssize_t) siz)
        err = EIO;
    if (err) {
	EI_TRACE_ERR2("send_challenge_reply",
		      "-> SEND_CHALLENGE_REPLY socket write failed: %s (%d)",
                      estr(err), err);
        EI_CONN_SAVE_ERRNO__(err);
	return -1;
    }
    
    if (ei_tracelevel >= 3) {
	char buffer[33];	
   	EI_TRACE_CONN2("send_challenge_reply",
		   "-> SEND_CHALLENGE_REPLY (ok) challenge = %d, digest = %s",
		   challenge,hex((char*)digest, buffer));
    }
    return 0;
}

static int recv_complement(ei_socket_callbacks *cbs,
                           void *ctx,
                           int pkt_sz,
                           unsigned ms)
{
    char dbuf[DEFBUF_SIZ];
    char *buf = dbuf;
    int is_static = 1;
    int buflen = DEFBUF_SIZ;
    int rlen;
    char *s;
    char tag;
    unsigned int creation;

    erl_errno = EIO;		/* Default */

    if ((rlen = read_hs_package(cbs, ctx, pkt_sz, &buf, &buflen, &is_static, ms)) != 21) {
	EI_TRACE_ERR1("recv_complement",
		      "<- RECV_COMPLEMENT socket read failed (%d)",rlen);
	goto error;
    }

    s = buf;
    if ((tag = get8(s)) != 'c') {
	EI_TRACE_ERR2("recv_complement",
		      "<- RECV_COMPLEMENT incorrect tag, "
		      "expected 'c' got '%c' (%u)",tag,tag);
	goto error;
    }
    creation = get32be(s);
    if (!is_static)
	free(buf);

    if (ei_tracelevel >= 3) {
        EI_TRACE_CONN1("recv_complement",
                       "<- RECV_COMPLEMENT (ok) creation = %u",
                       creation);
    }
    /* We don't have any use for 'creation' of other node, so we drop it */
    erl_errno = 0;
    return 0;

error:
    if (!is_static)
	free(buf);
    return -1;
}

static int recv_challenge_reply(ei_socket_callbacks *cbs,
                                void *ctx,
                                int pkt_sz,
                                unsigned our_challenge,
                                char cookie[], 
                                unsigned *her_challenge,
                                unsigned ms)
{
    char dbuf[DEFBUF_SIZ];
    char *buf = dbuf;
    int is_static = 1;
    int buflen = DEFBUF_SIZ;
    int rlen;
    char *s;
    char tag;
    char her_digest[16], expected_digest[16];
    
    erl_errno = EIO;		/* Default */

    if ((rlen = read_hs_package(cbs, ctx, pkt_sz, &buf, &buflen, &is_static, ms)) != 21) {
	EI_TRACE_ERR1("recv_challenge_reply",
		      "<- RECV_CHALLENGE_REPLY socket read failed (%d)",rlen);
	goto error;
    }
    
    s = buf;
    if ((tag = get8(s)) != 'r') {
	EI_TRACE_ERR2("recv_challenge_reply",
		      "<- RECV_CHALLENGE_REPLY incorrect tag, "
		      "expected 'r' got '%c' (%u)",tag,tag);
	goto error;
    }
    *her_challenge = get32be(s);
    memcpy(her_digest, s, 16);
    gen_digest(our_challenge, cookie, (unsigned char*)expected_digest);
    if (memcmp(her_digest, expected_digest, 16)) {
	EI_TRACE_ERR0("recv_challenge_reply",
		      "<- RECV_CHALLENGE_REPLY authorization failure");
	goto error;
    }
    if (!is_static)
	free(buf);

   
    if (ei_tracelevel >= 3) {
	char buffer[33];	
        EI_TRACE_CONN2("recv_challenge_reply",
		   "<- RECV_CHALLENGE_REPLY (ok) challenge = %u, digest = %s",
		   *her_challenge,hex(her_digest,buffer));
    }
    erl_errno = 0;
    return 0;
    
error:
    if (!is_static)
	free(buf);
    return -1;
}

static int send_challenge_ack(ei_socket_callbacks *cbs, void *ctx, int pkt_sz,
                              unsigned char digest[16], unsigned ms) 
{
    char *s;
    char buf[DEFBUF_SIZ];
    int siz = pkt_sz + 1 + 16;
    int err;
    ssize_t len;

    s = buf;
    switch (pkt_sz) {
    case 2:
        put16be(s,siz - 2);
        break;
    case 4:
        put32be(s,siz - 4);
        break;
    default:
        return -1;
    }
    put8(s, 'a');
    memcpy(s, digest, 16);

    len = (ssize_t) siz;
    err = ei_write_fill_ctx_t__(cbs, ctx, buf, &len, ms);
    if (!err && len != (ssize_t) siz)
        err = EIO;
    if (err) {
	EI_TRACE_ERR2("recv_challenge_reply",
		      "-> SEND_CHALLENGE_ACK socket write failed: %s (%d)",
                      estr(err), err);
        EI_CONN_SAVE_ERRNO__(err);
	return -1;
    }
    
    if (ei_tracelevel >= 3) {
	char buffer[33];	
    	EI_TRACE_CONN1("recv_challenge_reply",
		   "-> SEND_CHALLENGE_ACK (ok) digest = %s",hex((char *)digest,buffer));
    }
    
    return 0;
}

static int recv_challenge_ack(ei_socket_callbacks *cbs, void *ctx,
			      int pkt_sz, unsigned our_challenge,
			      char cookie[], unsigned ms)
{
    char dbuf[DEFBUF_SIZ];
    char *buf = dbuf;
    int is_static = 1;
    int buflen = DEFBUF_SIZ;
    int rlen;
    char *s;
    char tag;
    char her_digest[16], expected_digest[16];
    
    erl_errno = EIO;		/* Default */

    if ((rlen = read_hs_package(cbs, ctx, pkt_sz, &buf, &buflen, &is_static, ms)) != 17) {
	EI_TRACE_ERR1("recv_challenge_ack",
		      "<- RECV_CHALLENGE_ACK socket read failed (%d)",rlen);
	goto error;
    }
    
    s = buf;
    if ((tag = get8(s)) != 'a') {
	EI_TRACE_ERR2("recv_challenge_ack",
		      "<- RECV_CHALLENGE_ACK incorrect tag, "
		      "expected 'a' got '%c' (%u)",tag,tag);
	goto error;
    }
    memcpy(her_digest, s, 16);
    gen_digest(our_challenge, cookie, (unsigned char *)expected_digest);
    if (memcmp(her_digest, expected_digest, 16)) {
	EI_TRACE_ERR0("recv_challenge_ack",
		      "<- RECV_CHALLENGE_ACK authorization failure");
	goto error;
    }
    if (!is_static)
	free(buf);

    if (ei_tracelevel >= 3) {
	char buffer[33];	
	EI_TRACE_CONN1("recv_challenge_ack",
		   "<- RECV_CHALLENGE_ACK (ok) digest = %s",hex(her_digest,buffer));
    }
    erl_errno = 0;
    return 0;

error:
    if (!is_static)
	free(buf);
    return -1;
}

static int recv_name(ei_socket_callbacks *cbs, void *ctx,
                     int pkt_sz, char *send_name_tag,
                     DistFlags *flags, char *namebuf, unsigned ms)
{
    char dbuf[DEFBUF_SIZ];
    char *buf = dbuf;
    int is_static = 1;
    int buflen = DEFBUF_SIZ;
    int rlen;
    unsigned int namelen;
    char *s;
    char tmp_nodename[MAXNODELEN+1];
    char tag;
    
    erl_errno = EIO;		/* Default */

    if ((rlen = read_hs_package(cbs, ctx, pkt_sz, &buf, &buflen,
                                &is_static, ms)) <= 0) {
	EI_TRACE_ERR1("recv_name","<- RECV_NAME socket read failed (%d)",rlen);
	goto error;
    }
    s = buf;
    tag = get8(s);
    *send_name_tag = tag;
    if (tag != 'n' && tag != 'N') {
	EI_TRACE_ERR2("recv_name","<- RECV_NAME incorrect tag, "
		      "expected 'n' or 'N', got '%c' (%u)",tag,tag);
	goto error;
    }
    if (tag == 'n') {
        unsigned int version;
        if (rlen < 1+2+4) {
            EI_TRACE_ERR1("recv_name","<- RECV_NAME 'n' packet too short (%d)",
                          rlen)
            goto error;
        }
        version = get16be(s);
        if (version < EI_DIST_5) {
            EI_TRACE_ERR1("recv_name","<- RECV_NAME 'n' invalid version=%d",
                          version)
            goto error;
        }
        *flags = get32be(s);
        namelen = rlen - (1+2+4);
    }
    else { /* tag == 'N' */
        if (rlen < 1+8+4+2) {
            EI_TRACE_ERR1("recv_name","<- RECV_NAME 'N' packet too short (%d)",
                          rlen)
            goto error;
        }
        *flags = get64be(s);
        s += 4; /* ignore peer 'creation' */
        namelen = get16be(s);
    }

    if (!(*flags & DFLAG_EXTENDED_REFERENCES)) {
	EI_TRACE_ERR0("recv_name","<- RECV_NAME peer cannot handle"
		      "extended references");
	goto error;
    }

    if (!(*flags & DFLAG_EXTENDED_PIDS_PORTS)) {
	EI_TRACE_ERR0("recv_name","<- RECV_NAME peer cannot "
		      "handle extended pids and ports");
	erl_errno = EIO;
	goto error;
    }

    if (!namebuf)
        namebuf = &tmp_nodename[0];
    
    if (namelen > MAXNODELEN || s+namelen > buf+rlen) {
        EI_TRACE_ERR2("recv_name","<- RECV_NAME '%c' nodename too long (%d)",
                      tag, namelen);
        goto error;
    }

    memcpy(namebuf, s, namelen);
    namebuf[namelen] = '\0';

    if (!is_static)
	free(buf);
    EI_TRACE_CONN3("recv_name",
		   "<- RECV_NAME (ok) node = %s, tag = %c, flags = %u",
		   namebuf,tag,*flags);
    erl_errno = 0;
    return 0;
    
error:
    if (!is_static)
	free(buf);
    return -1;
}

/***************************************************************************
 *
 *  Returns 1 on success and 0 on failure.
 *
 ***************************************************************************/


/* size is the buffer size, e.i. string length + 1 */

static int get_home(char *buf, int size)
{
#ifdef __WIN32__
    char* homedrive = getenv("HOMEDRIVE");
    char* homepath = getenv("HOMEPATH");
    
    if (homedrive && homepath) {
	if (strlen(homedrive)+strlen(homepath) >= size)
	    return 0;
	strcpy(buf, homedrive);
	strcat(buf, homepath);
	return 1;
    }
    else {
	int len = GetWindowsDirectory(buf, size);
	if (len) {
	    return (len < size);
	}
    }
#else
    char* homepath = getenv("HOME");
    if (homepath) {
	if (strlen(homepath) >= size)
	    return 0;
	strcpy(buf, homepath);
	return 1;
    }
#endif

    buf[0] = '.';
    buf[1] = '\0';
    return 1;
}


static int get_cookie(char *buf, int bufsize)
{
    char fname[EI_MAX_HOME_PATH + sizeof(COOKIE_FILE) + 1];
    int fd;
    int len;
    unsigned char next_c;
    
    if (!get_home(fname, EI_MAX_HOME_PATH+1)) {
	fprintf(stderr,"<ERROR> get_cookie: too long path to home");
	return 0;
    }

    strcat(fname, COOKIE_FILE);
    if ((fd = open(fname, O_RDONLY, 0777)) < 0) {
	fprintf(stderr,"<ERROR> get_cookie: can't open cookie file");
	return 0;
    }
    
    if ((len = read(fd, buf, bufsize-1)) < 0) {
	fprintf(stderr,"<ERROR> get_cookie: reading cookie file");
	close(fd);
	return 0;
    }

    /* If more to read it is too long. Not 100% correct test but will do. */
    if (read(fd, &next_c, 1) > 0 && !isspace(next_c)) {
	fprintf(stderr,"<ERROR> get_cookie: cookie in %s is too long",fname);
	close(fd);
	return 0;
    }

    close(fd);

    /* Remove all newlines after the first newline */
    buf[len] = '\0';		/* Terminate string */
    len = strcspn(buf,"\r\n");
    buf[len] = '\0';		/* Terminate string again */

    return 1;			/* Success! */
}