eXtl_tls.c 130 KB
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 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741
/*
  eXosip - This is the eXtended osip library.
  Copyright (C) 2001-2020 Aymeric MOIZARD amoizard@antisip.com

  eXosip is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  eXosip is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

  In addition, as a special exception, the copyright holders give
  permission to link the code of portions of this program with the
  OpenSSL library under certain conditions as described in each
  individual source file, and distribute linked combinations
  including the two.
  You must obey the GNU General Public License in all respects
  for all of the code used other than OpenSSL.  If you modify
  file(s) with this exception, you may extend this exception to your
  version of the file(s), but you are not obligated to do so.  If you
  do not wish to do so, delete this exception statement from your
  version.  If you delete this exception statement from all source
  files in the program, then also delete it here.
*/

#ifdef WIN32
#ifndef UNICODE
#define UNICODE
#endif
#endif

#include "eXosip2.h"
#include "eXtransport.h"

#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif

#ifdef HAVE_MSTCPIP_H
#include <Mstcpip.h>
#endif

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif

#ifdef HAVE_WINCRYPT_H
#include <wincrypt.h>
#endif

#if !defined(_WIN32_WCE)
#include <errno.h>
#endif

#if defined(HAVE_NETINET_TCP_H)
#include <netinet/tcp.h>
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#if defined(HAVE_WINSOCK2_H)
#define ex_errno WSAGetLastError()
#define is_wouldblock_error(r) ((r) == WSAEINTR || (r) == WSAEWOULDBLOCK)
#define is_connreset_error(r) ((r) == WSAECONNRESET || (r) == WSAECONNABORTED || (r) == WSAETIMEDOUT || (r) == WSAENETRESET || (r) == WSAENOTCONN)
#else
#define ex_errno errno
#endif
#ifndef is_wouldblock_error
#define is_wouldblock_error(r) ((r) == EINTR || (r) == EWOULDBLOCK || (r) == EAGAIN)
#define is_connreset_error(r) ((r) == ECONNRESET || (r) == ECONNABORTED || (r) == ETIMEDOUT || (r) == ENETRESET || (r) == ENOTCONN)
#endif

#ifdef HAVE_OPENSSL_SSL_H

#include <openssl/opensslconf.h>
#include <openssl/opensslv.h>

#define ex_verify_depth 10
#include <openssl/bn.h>
#ifndef OPENSSL_NO_DH
#include <openssl/dh.h>
#endif
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#ifndef OPENSSL_NO_RSA
#include <openssl/rsa.h>
#endif
#include <openssl/tls1.h>
#include <openssl/x509.h>
#if !(OPENSSL_VERSION_NUMBER < 0x10002000L)
#include <openssl/x509v3.h>
#endif

#define SSLDEBUG 1
/*#define PATH "D:/conf/"

#define PASSWORD "23-+Wert"
#define CLIENT_KEYFILE PATH"ckey.pem"
#define CLIENT_CERTFILE PATH"c.pem"
#define SERVER_KEYFILE PATH"skey.pem"
#define SERVER_CERTFILE PATH"s.pem"
#define CA_LIST PATH"cacert.pem"
#define RANDOM  PATH"random.pem"
#define DHFILE PATH"dh1024.pem"*/

#ifdef __APPLE_CC__
#include "TargetConditionals.h"
#endif

#if defined(__APPLE__) && (TARGET_OS_IPHONE == 0)
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
#include <Security/Security.h>
#endif

#if TARGET_OS_IPHONE
#include <CFNetwork/CFSocketStream.h>
#include <CoreFoundation/CFStream.h>
#define MULTITASKING_ENABLED
#endif

#if OPENSSL_VERSION_NUMBER < 0x10100000L
#define X509_STORE_get0_param(store) (store->param)
#endif

SSL_CTX *initialize_client_ctx(struct eXosip_t *excontext, eXosip_tls_ctx_t *client_ctx, int transport, const char *sni_servernameindication);

SSL_CTX *initialize_server_ctx(struct eXosip_t *excontext, eXosip_tls_ctx_t *srv_ctx, int transport);

int verify_cb(int preverify_ok, X509_STORE_CTX *store);

/* persistent connection */
struct _tls_stream {
  int socket;
  struct sockaddr ai_addr;
  socklen_t ai_addrlen;
  char sni_servernameindication[256];
  char remote_ip[65];
  int remote_port;
  char *previous_content;
  int previous_content_len;
  SSL *ssl_conn;
  SSL_CTX *ssl_ctx;
  int ssl_state;
  char *buf;      /* recv buffer */
  size_t bufsize; /* allocated size of buf */
  size_t buflen;  /* current length of buf */
  char *sendbuf;  /* send buffer */
  size_t sendbufsize;
  size_t sendbuflen;
#ifdef MULTITASKING_ENABLED
  CFReadStreamRef readStream;
  CFWriteStreamRef writeStream;
#endif
  char natted_ip[65];
  int natted_port;
  int ephemeral_port;
  int invalid;
  int is_server;
  time_t tcp_max_timeout;
  time_t tcp_inprogress_max_timeout;
  char reg_call_id[64];
  time_t ping_rfc5626;
  int pong_supported;
};

#ifndef SOCKET_TIMEOUT
/* when stream has sequence error: */
/* having SOCKET_TIMEOUT > 0 helps the system to recover */
#define SOCKET_TIMEOUT 0
#endif

static int _tls_tl_send(struct eXosip_t *excontext, SSL *ssl, const char *message, int length);

struct eXtltls {
  int tls_socket;
  struct sockaddr_storage ai_addr;
  int ai_addr_len;

  SSL_CTX *server_ctx;
  SSL_CTX *client_ctx;

  struct _tls_stream socket_tab[EXOSIP_MAX_SOCKETS];
};

static int tls_tl_init(struct eXosip_t *excontext) {
  struct eXtltls *reserved = (struct eXtltls *) osip_malloc(sizeof(struct eXtltls));

  if (reserved == NULL)
    return OSIP_NOMEM;

  reserved->tls_socket = 0;
  reserved->server_ctx = NULL;
  reserved->client_ctx = NULL;
  memset(&reserved->ai_addr, 0, sizeof(struct sockaddr_storage));
  reserved->ai_addr_len = 0;
  memset(&reserved->socket_tab, 0, sizeof(struct _tls_stream) * EXOSIP_MAX_SOCKETS);

  excontext->eXtltls_reserved = reserved;
  return OSIP_SUCCESS;
}

static void _tls_tl_close_sockinfo(struct eXosip_t *excontext, struct _tls_stream *sockinfo) {

  _eXosip_mark_all_transaction_transport_error(excontext, sockinfo->socket);

  if (sockinfo->socket > 0) {
    if (sockinfo->ssl_conn != NULL) {
      SSL_shutdown(sockinfo->ssl_conn);
      SSL_shutdown(sockinfo->ssl_conn);
      SSL_free(sockinfo->ssl_conn);
    }

    if (sockinfo->ssl_ctx != NULL)
      SSL_CTX_free(sockinfo->ssl_ctx);

    _eXosip_closesocket(sockinfo->socket);
  }

  if (sockinfo->buf != NULL)
    osip_free(sockinfo->buf);

  if (sockinfo->sendbuf != NULL)
    osip_free(sockinfo->sendbuf);

#ifdef MULTITASKING_ENABLED

  if (sockinfo->readStream != NULL) {
    CFReadStreamClose(sockinfo->readStream);
    CFRelease(sockinfo->readStream);
  }

  if (sockinfo->writeStream != NULL) {
    CFWriteStreamClose(sockinfo->writeStream);
    CFRelease(sockinfo->writeStream);
  }

#endif
  memset(sockinfo, 0, sizeof(*sockinfo));
}

static int tls_tl_free(struct eXosip_t *excontext) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int pos;

  if (reserved == NULL)
    return OSIP_SUCCESS;

  if (reserved->server_ctx != NULL)
    SSL_CTX_free(reserved->server_ctx);

  reserved->server_ctx = NULL;

  if (reserved->client_ctx != NULL)
    SSL_CTX_free(reserved->client_ctx);

  reserved->client_ctx = NULL;

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
  }

#if OPENSSL_VERSION_NUMBER < 0x10100000L
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
  ERR_remove_thread_state(NULL);
#else
  ERR_remove_state(0);
#endif
#endif

  memset(&reserved->socket_tab, 0, sizeof(struct _tls_stream) * EXOSIP_MAX_SOCKETS);

  memset(&reserved->ai_addr, 0, sizeof(struct sockaddr_storage));
  reserved->ai_addr_len = 0;

  if (reserved->tls_socket > 0)
    _eXosip_closesocket(reserved->tls_socket);

  reserved->tls_socket = 0;

  osip_free(reserved);
  excontext->eXtltls_reserved = NULL;
  return OSIP_SUCCESS;
}

static int tls_tl_reset(struct eXosip_t *excontext) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int pos;

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] wrong state: create transport layer first\n"));
    return OSIP_WRONG_STATE;
  }

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    if (reserved->socket_tab[pos].socket > 0)
      reserved->socket_tab[pos].invalid = 1;
  }

  return OSIP_SUCCESS;
}

static int _tls_add_certificates(struct eXosip_t *excontext, SSL_CTX *ctx) {
  int count = 0;

  if (excontext->tls_verify_client_certificate & 0x04) {
    return 0;
  }

#ifdef HAVE_WINCRYPT_H
  PCCERT_CONTEXT pCertCtx;
  X509 *cert = NULL;
  HCERTSTORE hStore = CertOpenSystemStore(0, L"CA");
  X509_STORE *x509_store;

  for (pCertCtx = CertEnumCertificatesInStore(hStore, NULL); pCertCtx != NULL; pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
    cert = d2i_X509(NULL, (const unsigned char **) &pCertCtx->pbCertEncoded, pCertCtx->cbCertEncoded);

    if (cert == NULL) {
      continue;
    }

    x509_store = SSL_CTX_get_cert_store(ctx);

    if (x509_store == NULL) {
      X509_free(cert);
      continue;
    }

    if (!X509_STORE_add_cert(x509_store, cert)) {
      X509_free(cert);
      continue;
    }

    count++;
    X509_free(cert);
  }

  CertCloseStore(hStore, 0);

  hStore = CertOpenSystemStore(0, L"ROOT");

  for (pCertCtx = CertEnumCertificatesInStore(hStore, NULL); pCertCtx != NULL; pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
    cert = d2i_X509(NULL, (const unsigned char **) &pCertCtx->pbCertEncoded, pCertCtx->cbCertEncoded);

    if (cert == NULL) {
      continue;
    }

    x509_store = SSL_CTX_get_cert_store(ctx);

    if (x509_store == NULL) {
      X509_free(cert);
      continue;
    }

    if (!X509_STORE_add_cert(x509_store, cert)) {
      X509_free(cert);
      continue;
    }

    count++;
    X509_free(cert);
  }

  CertCloseStore(hStore, 0);

  hStore = CertOpenSystemStore(0, L"MY");

  for (pCertCtx = CertEnumCertificatesInStore(hStore, NULL); pCertCtx != NULL; pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
    cert = d2i_X509(NULL, (const unsigned char **) &pCertCtx->pbCertEncoded, pCertCtx->cbCertEncoded);

    if (cert == NULL) {
      continue;
    }

    x509_store = SSL_CTX_get_cert_store(ctx);

    if (x509_store == NULL) {
      X509_free(cert);
      continue;
    }

    if (!X509_STORE_add_cert(x509_store, cert)) {
      X509_free(cert);
      continue;
    }

    count++;
    X509_free(cert);
  }

  CertCloseStore(hStore, 0);

  hStore = CertOpenSystemStore(0, L"Trustedpublisher");

  for (pCertCtx = CertEnumCertificatesInStore(hStore, NULL); pCertCtx != NULL; pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
    cert = d2i_X509(NULL, (const unsigned char **) &pCertCtx->pbCertEncoded, pCertCtx->cbCertEncoded);

    if (cert == NULL) {
      continue;
    }

    x509_store = SSL_CTX_get_cert_store(ctx);

    if (x509_store == NULL) {
      X509_free(cert);
      continue;
    }

    if (!X509_STORE_add_cert(x509_store, cert)) {
      X509_free(cert);
      continue;
    }

    count++;
    X509_free(cert);
  }

  CertCloseStore(hStore, 0);
#elif defined(__APPLE__) && (TARGET_OS_IPHONE == 0)
  SecKeychainSearchRef pSecKeychainSearch = NULL;
  SecKeychainRef pSecKeychain;
  OSStatus status = noErr;
  X509 *cert = NULL;
  SInt32 osx_version = 0;
  X509_STORE *x509_store;

  if (Gestalt(gestaltSystemVersion, &osx_version) != noErr) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] macosx certificate store: can't get osx version"));
    return 0;
  }

  if (osx_version >= 0x1050) {
    /* Leopard store location */
    status = SecKeychainOpen("/System/Library/Keychains/SystemRootCertificates.keychain", &pSecKeychain);

  } else {
    /* Tiger and below store location */
    status = SecKeychainOpen("/System/Library/Keychains/X509Anchors", &pSecKeychain);
  }

  if (status != noErr) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] macosx certificate store: can't get osx version"));
    return 0;
  }

  status = SecKeychainSearchCreateFromAttributes(pSecKeychain, kSecCertificateItemClass, NULL, &pSecKeychainSearch);

  for (;;) {
    SecKeychainItemRef pSecKeychainItem = nil;

    status = SecKeychainSearchCopyNext(pSecKeychainSearch, &pSecKeychainItem);

    if (status == errSecItemNotFound) {
      break;
    }

    if (status == noErr) {
      void *_pCertData;
      UInt32 _pCertLength;

      status = SecKeychainItemCopyAttributesAndData(pSecKeychainItem, NULL, NULL, NULL, &_pCertLength, &_pCertData);

      if (status == noErr && _pCertData != NULL) {
        unsigned char *ptr;

        ptr = _pCertData; /*required because d2i_X509 is modifying pointer */
        cert = d2i_X509(NULL, (const unsigned char **) &ptr, _pCertLength);

        if (cert == NULL) {
          continue;
        }

        x509_store = SSL_CTX_get_cert_store(ctx);

        if (x509_store == NULL) {
          X509_free(cert);
          continue;
        }

        if (!X509_STORE_add_cert(x509_store, cert)) {
          X509_free(cert);
          continue;
        }

        count++;
        X509_free(cert);

        status = SecKeychainItemFreeAttributesAndData(NULL, _pCertData);
      }
    }

    if (pSecKeychainItem != NULL)
      CFRelease(pSecKeychainItem);

    if (status != noErr) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] macosx certificate store: can't add certificate [%i]", status));
    }
  }

  CFRelease(pSecKeychainSearch);
  CFRelease(pSecKeychain);

#endif
  return count;
}

int verify_cb(int preverify_ok, X509_STORE_CTX *store) {
  char buf[256];
  X509 *err_cert;
  int err, depth;

  err_cert = X509_STORE_CTX_get_current_cert(store);
  err = X509_STORE_CTX_get_error(store);
  depth = X509_STORE_CTX_get_error_depth(store);

  X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);

  if (depth > ex_verify_depth /* depth -1 */) {
    preverify_ok = 0;
    err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
    X509_STORE_CTX_set_error(store, err);
  }

  if (!preverify_ok) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] invalid  depth[%d] [%s] [%d:%s]\n", depth, buf, err, X509_verify_cert_error_string(err)));

  } else {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] verified depth[%d] [%s]\n", depth, buf));
  }

  /*
   * At this point, err contains the last verification error. We can use
   * it for something special
   */
  if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
    X509 *current_cert = X509_STORE_CTX_get_current_cert(store);

    X509_NAME_oneline(X509_get_issuer_name(current_cert), buf, 256);
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] issuer [%s]\n", buf));
  }

  return 1;
  // return preverify_ok;

#if 0

  if (!preverify_ok && (err == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN)) {
    X509_NAME_oneline(X509_get_issuer_name(store->current_cert), buf, 256);
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] issuer [%s]\n", buf));
    preverify_ok = 1;
    X509_STORE_CTX_set_error(store, X509_V_OK);
  }

  if (!preverify_ok && (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)) {
    X509_NAME_oneline(X509_get_issuer_name(store->current_cert), buf, 256);
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] issuer [%s]\n", buf));
    preverify_ok = 1;
    X509_STORE_CTX_set_error(store, X509_V_OK);
  }

  if (!preverify_ok && (err == X509_V_ERR_CERT_HAS_EXPIRED)) {
    X509_NAME_oneline(X509_get_issuer_name(store->current_cert), buf, 256);
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] issuer [%s]\n", buf));
    preverify_ok = 1;
    X509_STORE_CTX_set_error(store, X509_V_OK);
  }

  if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)) {
    X509_NAME_oneline(X509_get_issuer_name(store->current_cert), buf, 256);
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] issuer [%s]\n", buf));
    preverify_ok = 1;
    X509_STORE_CTX_set_error(store, X509_V_OK);
  }

  if (!preverify_ok && (err == X509_V_ERR_CERT_UNTRUSTED)) {
    X509_NAME_oneline(X509_get_issuer_name(store->current_cert), buf, 256);
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] issuer [%s]\n", buf));
    preverify_ok = 1;
    X509_STORE_CTX_set_error(store, X509_V_OK);
  }

  if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE)) {
    X509_NAME_oneline(X509_get_issuer_name(store->current_cert), buf, 256);
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] issuer [%s]\n", buf));
    preverify_ok = 1;
    X509_STORE_CTX_set_error(store, X509_V_OK);
  }

  preverify_ok = 1;             /* configured to accept anyway! */
  return preverify_ok;
#endif
}

static int password_cb(char *buf, int num, int rwflag, void *userdata) {
  char *passwd = (char *) userdata;

  if (passwd == NULL || passwd[0] == '\0') {
    /* Suppress blocking read from stdin if password is missing or empty */
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] password required but missing\n"));
    return 0;
  }

  strncpy(buf, passwd, num);
  buf[num - 1] = '\0';
  return (int) strlen(buf);
}

static void load_dh_params(SSL_CTX *ctx, char *file) {
#ifndef OPENSSL_NO_DH
  DH *ret = 0;
  BIO *bio;

  if ((bio = BIO_new_file(file, "r")) == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot open DH file\n"));

  } else {
    ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
    BIO_free(bio);

    if (SSL_CTX_set_tmp_dh(ctx, ret) < 0)
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot set DH param\n"));
  }

#endif
}

/* RFC 5114, 2.3. 2048-bit MODP Group with 256-bit Prime Order Subgroup */
static const unsigned char dh2048_prime[] = {0x87, 0xA8, 0xE6, 0x1D, 0xB4, 0xB6, 0x66, 0x3C, 0xFF, 0xBB, 0xD1, 0x9C, 0x65, 0x19, 0x59, 0x99, 0x8C, 0xEE, 0xF6, 0x08, 0x66, 0x0D, 0xD0, 0xF2, 0x5D, 0x2C, 0xEE, 0xD4, 0x43, 0x5E, 0x3B, 0x00,
                                             0xE0, 0x0D, 0xF8, 0xF1, 0xD6, 0x19, 0x57, 0xD4, 0xFA, 0xF7, 0xDF, 0x45, 0x61, 0xB2, 0xAA, 0x30, 0x16, 0xC3, 0xD9, 0x11, 0x34, 0x09, 0x6F, 0xAA, 0x3B, 0xF4, 0x29, 0x6D, 0x83, 0x0E, 0x9A, 0x7C,
                                             0x20, 0x9E, 0x0C, 0x64, 0x97, 0x51, 0x7A, 0xBD, 0x5A, 0x8A, 0x9D, 0x30, 0x6B, 0xCF, 0x67, 0xED, 0x91, 0xF9, 0xE6, 0x72, 0x5B, 0x47, 0x58, 0xC0, 0x22, 0xE0, 0xB1, 0xEF, 0x42, 0x75, 0xBF, 0x7B,
                                             0x6C, 0x5B, 0xFC, 0x11, 0xD4, 0x5F, 0x90, 0x88, 0xB9, 0x41, 0xF5, 0x4E, 0xB1, 0xE5, 0x9B, 0xB8, 0xBC, 0x39, 0xA0, 0xBF, 0x12, 0x30, 0x7F, 0x5C, 0x4F, 0xDB, 0x70, 0xC5, 0x81, 0xB2, 0x3F, 0x76,
                                             0xB6, 0x3A, 0xCA, 0xE1, 0xCA, 0xA6, 0xB7, 0x90, 0x2D, 0x52, 0x52, 0x67, 0x35, 0x48, 0x8A, 0x0E, 0xF1, 0x3C, 0x6D, 0x9A, 0x51, 0xBF, 0xA4, 0xAB, 0x3A, 0xD8, 0x34, 0x77, 0x96, 0x52, 0x4D, 0x8E,
                                             0xF6, 0xA1, 0x67, 0xB5, 0xA4, 0x18, 0x25, 0xD9, 0x67, 0xE1, 0x44, 0xE5, 0x14, 0x05, 0x64, 0x25, 0x1C, 0xCA, 0xCB, 0x83, 0xE6, 0xB4, 0x86, 0xF6, 0xB3, 0xCA, 0x3F, 0x79, 0x71, 0x50, 0x60, 0x26,
                                             0xC0, 0xB8, 0x57, 0xF6, 0x89, 0x96, 0x28, 0x56, 0xDE, 0xD4, 0x01, 0x0A, 0xBD, 0x0B, 0xE6, 0x21, 0xC3, 0xA3, 0x96, 0x0A, 0x54, 0xE7, 0x10, 0xC3, 0x75, 0xF2, 0x63, 0x75, 0xD7, 0x01, 0x41, 0x03,
                                             0xA4, 0xB5, 0x43, 0x30, 0xC1, 0x98, 0xAF, 0x12, 0x61, 0x16, 0xD2, 0x27, 0x6E, 0x11, 0x71, 0x5F, 0x69, 0x38, 0x77, 0xFA, 0xD7, 0xEF, 0x09, 0xCA, 0xDB, 0x09, 0x4A, 0xE9, 0x1E, 0x1A, 0x15, 0x97};

static const unsigned char dh2048_generator[] = {0x3F, 0xB3, 0x2C, 0x9B, 0x73, 0x13, 0x4D, 0x0B, 0x2E, 0x77, 0x50, 0x66, 0x60, 0xED, 0xBD, 0x48, 0x4C, 0xA7, 0xB1, 0x8F, 0x21, 0xEF, 0x20, 0x54, 0x07, 0xF4, 0x79, 0x3A, 0x1A, 0x0B, 0xA1, 0x25,
                                                 0x10, 0xDB, 0xC1, 0x50, 0x77, 0xBE, 0x46, 0x3F, 0xFF, 0x4F, 0xED, 0x4A, 0xAC, 0x0B, 0xB5, 0x55, 0xBE, 0x3A, 0x6C, 0x1B, 0x0C, 0x6B, 0x47, 0xB1, 0xBC, 0x37, 0x73, 0xBF, 0x7E, 0x8C, 0x6F, 0x62,
                                                 0x90, 0x12, 0x28, 0xF8, 0xC2, 0x8C, 0xBB, 0x18, 0xA5, 0x5A, 0xE3, 0x13, 0x41, 0x00, 0x0A, 0x65, 0x01, 0x96, 0xF9, 0x31, 0xC7, 0x7A, 0x57, 0xF2, 0xDD, 0xF4, 0x63, 0xE5, 0xE9, 0xEC, 0x14, 0x4B,
                                                 0x77, 0x7D, 0xE6, 0x2A, 0xAA, 0xB8, 0xA8, 0x62, 0x8A, 0xC3, 0x76, 0xD2, 0x82, 0xD6, 0xED, 0x38, 0x64, 0xE6, 0x79, 0x82, 0x42, 0x8E, 0xBC, 0x83, 0x1D, 0x14, 0x34, 0x8F, 0x6F, 0x2F, 0x91, 0x93,
                                                 0xB5, 0x04, 0x5A, 0xF2, 0x76, 0x71, 0x64, 0xE1, 0xDF, 0xC9, 0x67, 0xC1, 0xFB, 0x3F, 0x2E, 0x55, 0xA4, 0xBD, 0x1B, 0xFF, 0xE8, 0x3B, 0x9C, 0x80, 0xD0, 0x52, 0xB9, 0x85, 0xD1, 0x82, 0xEA, 0x0A,
                                                 0xDB, 0x2A, 0x3B, 0x73, 0x13, 0xD3, 0xFE, 0x14, 0xC8, 0x48, 0x4B, 0x1E, 0x05, 0x25, 0x88, 0xB9, 0xB7, 0xD2, 0xBB, 0xD2, 0xDF, 0x01, 0x61, 0x99, 0xEC, 0xD0, 0x6E, 0x15, 0x57, 0xCD, 0x09, 0x15,
                                                 0xB3, 0x35, 0x3B, 0xBB, 0x64, 0xE0, 0xEC, 0x37, 0x7F, 0xD0, 0x28, 0x37, 0x0D, 0xF9, 0x2B, 0x52, 0xC7, 0x89, 0x14, 0x28, 0xCD, 0xC6, 0x7E, 0xB6, 0x18, 0x4B, 0x52, 0x3D, 0x1D, 0xB2, 0x46, 0xC3,
                                                 0x2F, 0x63, 0x07, 0x84, 0x90, 0xF0, 0x0E, 0xF8, 0xD6, 0x47, 0xD1, 0x48, 0xD4, 0x79, 0x54, 0x51, 0x5E, 0x23, 0x27, 0xCF, 0xEF, 0x98, 0xC5, 0x82, 0x66, 0x4B, 0x4C, 0x0F, 0x6C, 0xC4, 0x16, 0x59};

static void build_dh_params(SSL_CTX *ctx) {
#ifndef OPENSSL_NO_DH
  DH *dh = DH_new();
  BIGNUM *p;
  BIGNUM *g;

  if (!dh) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] DH_new failed\n"));
    return;
  }

  OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO3, NULL, "[eXosip] [TLS] building DH params\n"));

  p = BN_bin2bn(dh2048_prime, sizeof(dh2048_prime), NULL);
  g = BN_bin2bn(dh2048_generator, sizeof(dh2048_generator), NULL);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
  dh->p = p;
  dh->g = g;
  dh->length = 256;
  if (dh->p == NULL || dh->g == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] DH set p g failed\n"));
    return;
  }
#else
  if (!DH_set0_pqg(dh, p, NULL, g)) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] DH_set0_pqg failed\n"));
    return;
  }
#endif

  OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO3, NULL, "[eXosip] [TLS] DH params built\n"));

  SSL_CTX_set_tmp_dh(ctx, dh);
  SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);

  DH_free(dh);

  return;
#endif
}

#ifndef OPENSSL_NO_RSA
static RSA *__RSA_generate_key(int bits, unsigned long e_value, void (*callback)(int, int, void *), void *cb_arg) {
  int i;
  RSA *rsa = RSA_new();
  BIGNUM *e = BN_new();

  if (!rsa || !e)
    goto err;

  i = BN_set_word(e, e_value);

  if (i != 1)
    goto err;

  if (RSA_generate_key_ex(rsa, bits, e, NULL)) {
    BN_free(e);
    return rsa;
  }

err:

  if (e)
    BN_free(e);

  if (rsa)
    RSA_free(rsa);

  return 0;
}

static void generate_eph_rsa_key(SSL_CTX *ctx) {
  RSA *rsa;

  rsa = __RSA_generate_key(2048, RSA_F4, NULL, NULL);

  if (rsa != NULL) {
#if OPENSSL_VERSION_NUMBER < 0x10100000L

    if (!SSL_CTX_set_tmp_rsa(ctx, rsa))
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot set RSA key\n"));

#endif

    RSA_free(rsa);
  }
}
#endif

eXosip_tls_ctx_error eXosip_set_tls_ctx(struct eXosip_t *excontext, eXosip_tls_ctx_t *ctx) {
  eXosip_tls_credentials_t *ownClient = &excontext->eXosip_tls_ctx_params.client;
  eXosip_tls_credentials_t *ownServer = &excontext->eXosip_tls_ctx_params.server;

  eXosip_tls_credentials_t *client = &ctx->client;
  eXosip_tls_credentials_t *server = &ctx->server;

  /* check if public AND private keys are valid */
  if (client->cert[0] == '\0' && client->priv_key[0] != '\0') {
    /* no, one is missing */
    return TLS_ERR_MISSING_AUTH_PART;
  }

  if (client->cert[0] != '\0' && client->priv_key[0] == '\0') {
    /* no, one is missing */
    return TLS_ERR_MISSING_AUTH_PART;
  }

  /* check if public AND private keys are valid */
  if (server->cert[0] == '\0' && server->priv_key[0] != '\0') {
    /* no, one is missing */
    return TLS_ERR_MISSING_AUTH_PART;
  }

  if (server->cert[0] != '\0' && server->priv_key[0] == '\0') {
    /* no, one is missing */
    return TLS_ERR_MISSING_AUTH_PART;
  }

  /* clean up configuration */
  memset(&excontext->eXosip_tls_ctx_params, 0, sizeof(eXosip_tls_ctx_t));

  if (client->public_key_pinned[0] != '\0') {
    snprintf(ownClient->public_key_pinned, sizeof(ownClient->public_key_pinned), "%s", client->public_key_pinned);
  }

  /* check if client has own certificate */
  if (client->cert[0] != '\0') {
    snprintf(ownClient->cert, sizeof(ownClient->cert), "%s", client->cert);
    snprintf(ownClient->priv_key, sizeof(ownClient->priv_key), "%s", client->priv_key);
    snprintf(ownClient->priv_key_pw, sizeof(ownClient->priv_key_pw), "%s", client->priv_key_pw);
  }

  /* check if server has own certificate */
  if (server->cert[0] != '\0') {
    snprintf(ownServer->cert, sizeof(ownServer->cert), "%s", server->cert);
    snprintf(ownServer->priv_key, sizeof(ownServer->priv_key), "%s", server->priv_key);
    snprintf(ownServer->priv_key_pw, sizeof(ownServer->priv_key_pw), "%s", server->priv_key_pw);
  }

  snprintf(excontext->eXosip_tls_ctx_params.dh_param, sizeof(ctx->dh_param), "%s", ctx->dh_param);
  snprintf(excontext->eXosip_tls_ctx_params.random_file, sizeof(ctx->random_file), "%s", ctx->random_file);
  snprintf(excontext->eXosip_tls_ctx_params.root_ca_cert, sizeof(ctx->root_ca_cert), "%s", ctx->root_ca_cert);
  snprintf(excontext->eXosip_tls_ctx_params.cipher_list, sizeof(ctx->cipher_list), "%s", ctx->cipher_list);
  excontext->eXosip_tls_ctx_params.tls_flags = ctx->tls_flags;
  excontext->eXosip_tls_ctx_params.dtls_flags = ctx->dtls_flags;

  return TLS_OK;
}

eXosip_tls_ctx_error eXosip_tls_verify_certificate(struct eXosip_t *excontext, int _tls_verify_client_certificate) {
  excontext->tls_verify_client_certificate = _tls_verify_client_certificate;
  return TLS_OK;
}

static void _tls_load_trusted_certificates(struct eXosip_t *excontext, eXosip_tls_ctx_t *exosip_tls_cfg, SSL_CTX *ctx) {
  char *caFile = 0, *caFolder = 0;

  if (_tls_add_certificates(excontext, ctx) <= 0) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] no system certificate loaded\n"));
  }

  if (exosip_tls_cfg->root_ca_cert[0] == '\0')
    return;

  {
#ifdef WIN32
    WIN32_FIND_DATA FileData;
    HANDLE hSearch;
    char szDirPath[1024];
    WCHAR wUnicodeDirPath[2048];

    snprintf(szDirPath, sizeof(szDirPath), "%s", exosip_tls_cfg->root_ca_cert);

    MultiByteToWideChar(CP_UTF8, 0, szDirPath, -1, wUnicodeDirPath, 2048);
    hSearch = FindFirstFileEx(wUnicodeDirPath, FindExInfoStandard, &FileData, FindExSearchNameMatch, NULL, 0);

    if (hSearch != INVALID_HANDLE_VALUE) {
      if ((FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
        caFolder = exosip_tls_cfg->root_ca_cert;

      else
        caFile = exosip_tls_cfg->root_ca_cert;
      FindClose(hSearch);
    } else {
      caFile = exosip_tls_cfg->root_ca_cert;
    }

#else
    int fd = open(exosip_tls_cfg->root_ca_cert, O_RDONLY);

    if (fd >= 0) {
      struct stat fileStat;

      if (fstat(fd, &fileStat) < 0) {
      } else {
        if (S_ISDIR(fileStat.st_mode)) {
          caFolder = exosip_tls_cfg->root_ca_cert;

        } else {
          caFile = exosip_tls_cfg->root_ca_cert;
        }
      }

      close(fd);
    }

#endif
  }

  if (exosip_tls_cfg->root_ca_cert[0] == '\0') {
  } else {
    if (SSL_CTX_load_verify_locations(ctx, caFile, caFolder)) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] trusted CA PEM file loaded [%s]\n", exosip_tls_cfg->root_ca_cert));

    } else {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot read trusted CA list [%s]\n", exosip_tls_cfg->root_ca_cert));
    }
  }
}

static void _tls_use_certificate_private_key(const char *log, eXosip_tls_credentials_t *xtc, SSL_CTX *ctx) {
  /* load from file name in PEM files */
  if (xtc->cert[0] != '\0' && xtc->priv_key[0] != '\0') {
    SSL_CTX_set_default_passwd_cb_userdata(ctx, (void *) xtc->priv_key_pw);
    SSL_CTX_set_default_passwd_cb(ctx, password_cb);

    /* Load our keys and certificates */
    if (SSL_CTX_use_certificate_file(ctx, xtc->cert, SSL_FILETYPE_ASN1)) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [%s] certificate ASN1 file loaded [%s]\n", log, xtc->cert));

    } else if (SSL_CTX_use_certificate_file(ctx, xtc->cert, SSL_FILETYPE_PEM)) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [%s] certificate PEM file loaded [%s]\n", log, xtc->cert));

    } else {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] [%s] cannot read certificate file [%s]\n", log, xtc->cert));
    }

    if (SSL_CTX_use_PrivateKey_file(ctx, xtc->priv_key, SSL_FILETYPE_ASN1)) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [%s] private key ASN1 file loaded [%s]\n", log, xtc->priv_key));

    } else if (SSL_CTX_use_PrivateKey_file(ctx, xtc->priv_key, SSL_FILETYPE_PEM)) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [%s] private key PEM file loaded [%s]\n", log, xtc->priv_key));

    } else {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] [%s] cannot read private key file [%s]\n", log, xtc->priv_key));
    }

    if (!SSL_CTX_check_private_key(ctx)) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] [%s] private key does not match the public key of your certificate\n", log));
    }
  }
}

static void _tls_common_setup(eXosip_tls_ctx_t *exosip_tls_cfg, SSL_CTX *ctx) {
#ifndef SSL_CTRL_SET_ECDH_AUTO
#define SSL_CTRL_SET_ECDH_AUTO 94
#endif

  if (exosip_tls_cfg->dh_param[0] == '\0')
    build_dh_params(ctx);

  else
    load_dh_params(ctx, exosip_tls_cfg->dh_param);

  /* SSL_CTX_set_ecdh_auto (ctx, on) requires OpenSSL 1.0.2 which wraps: */
  if (SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] ctrl_set_ecdh_auto: faster PFS ciphers enabled\n"));
#if !defined(OPENSSL_NO_ECDH) && !(OPENSSL_VERSION_NUMBER < 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)

  } else {
    /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
    EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);

    if (ecdh != NULL) {
      if (SSL_CTX_set_tmp_ecdh(ctx, ecdh)) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] set_tmp_ecdh: faster PFS ciphers enabled (secp256r1)\n"));
      }

      EC_KEY_free(ecdh);
    }

#endif
  }
}

SSL_CTX *initialize_client_ctx(struct eXosip_t *excontext, eXosip_tls_ctx_t *client_ctx, int transport, const char *sni_servernameindication) {
  const SSL_METHOD *meth = NULL;
  SSL_CTX *ctx;
  int err;

  if (transport == IPPROTO_UDP) {
#if !(OPENSSL_VERSION_NUMBER < 0x10002000L)
    meth = DTLS_client_method();
#elif !(OPENSSL_VERSION_NUMBER < 0x00908000L)
    meth = DTLSv1_client_method();
#endif

  } else if (transport == IPPROTO_TCP) {
    meth = SSLv23_client_method();

  } else {
    return NULL;
  }

  ctx = SSL_CTX_new(meth);

  if (ctx == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot create SSL_CTX\n"));
    return NULL;
  }

  _tls_use_certificate_private_key("client", &client_ctx->client, ctx);

  /* Load the CAs we trust */
  _tls_load_trusted_certificates(excontext, client_ctx, ctx);

  {
    int verify_mode = SSL_VERIFY_NONE;

#if !(OPENSSL_VERSION_NUMBER < 0x10002000L)

    if (excontext->tls_verify_client_certificate > 0 && sni_servernameindication != NULL) {
      X509_STORE *pkix_validation_store = SSL_CTX_get_cert_store(ctx);
      const X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_lookup("ssl_server");

      if (param != NULL) { /* const value, we have to copy (inherit) */
        X509_VERIFY_PARAM *param_to = X509_STORE_get0_param(pkix_validation_store);

        if (X509_VERIFY_PARAM_inherit(param_to, param)) {
          X509_STORE_set_flags(pkix_validation_store, X509_V_FLAG_TRUSTED_FIRST);
          X509_STORE_set_flags(pkix_validation_store, X509_V_FLAG_PARTIAL_CHAIN);

        } else {
          OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] PARAM_inherit: failed for ssl_server\n"));
        }

        if (X509_VERIFY_PARAM_set1_host(param_to, sni_servernameindication, 0)) {
          if (excontext->tls_verify_client_certificate & 0x02) {
            X509_VERIFY_PARAM_set_hostflags(param_to, X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
          } else {
            X509_VERIFY_PARAM_set_hostflags(param_to, X509_CHECK_FLAG_NO_WILDCARDS);
          }

        } else {
          OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] PARAM_set1_host: [%s] failed\n", sni_servernameindication));
        }

      } else {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] PARAM_lookup: failed for ssl_server\n"));
      }
    }

#endif

    verify_mode = SSL_VERIFY_PEER;

    SSL_CTX_set_verify(ctx, verify_mode, &verify_cb);
    SSL_CTX_set_verify_depth(ctx, ex_verify_depth + 1);
  }

  {
    unsigned long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_SINGLE_ECDH_USE | SSL_OP_SINGLE_DH_USE;

#ifdef SSL_OP_NO_COMPRESSION
    flags |= SSL_OP_NO_COMPRESSION;
#endif

#ifdef SSL_OP_NO_TICKET
    flags |= SSL_OP_NO_TICKET;
#endif

    if (transport == IPPROTO_UDP) {
      flags |= client_ctx->dtls_flags;
    } else {
      flags |= client_ctx->tls_flags;
    }
    SSL_CTX_set_options(ctx, flags);
  }

  if (client_ctx->cipher_list[0] != '\0') {
    err = SSL_CTX_set_cipher_list(ctx, client_ctx->cipher_list);
    if (!err) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] error with cipher list\n"));
    }
  } else {
    err = SSL_CTX_set_cipher_list(ctx, "HIGH:!COMPLEMENTOFDEFAULT:!kRSA:!PSK:!SRP");
    if (!err) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] error with standard cipher list\n"));
    }
  }

  _tls_common_setup(client_ctx, ctx);

  return ctx;
}

SSL_CTX *initialize_server_ctx(struct eXosip_t *excontext, eXosip_tls_ctx_t *srv_ctx, int transport) {
  const SSL_METHOD *meth = NULL;
  SSL_CTX *ctx;
  int err;

  int s_server_session_id_context = 1;

  if (transport == IPPROTO_UDP) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO3, NULL, "[eXosip] [TLS] DTLS-UDP server method\n"));
#if !(OPENSSL_VERSION_NUMBER < 0x10002000L)
    meth = DTLS_server_method();
#elif !(OPENSSL_VERSION_NUMBER < 0x00908000L)
    meth = DTLSv1_server_method();
#endif

  } else if (transport == IPPROTO_TCP) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO3, NULL, "[eXosip] [TLS] TLS server method\n"));
    meth = SSLv23_server_method();

  } else {
    return NULL;
  }

  ctx = SSL_CTX_new(meth);

  if (ctx == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot create SSL_CTX\n"));
    SSL_CTX_free(ctx);
    return NULL;
  }

  if (transport == IPPROTO_UDP) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO3, NULL, "[eXosip] [TLS] DTLS-UDP read ahead\n"));
    SSL_CTX_set_read_ahead(ctx, 1);
  }

  _tls_use_certificate_private_key("server", &srv_ctx->server, ctx);

  /* Load the CAs we trust */
  _tls_load_trusted_certificates(excontext, srv_ctx, ctx);

  if (!SSL_CTX_check_private_key(ctx)) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] check_private_key: either no match or no cert/key: disable incoming TLS connection\n"));
    SSL_CTX_free(ctx);
    return NULL;
  }

  {
    int verify_mode = SSL_VERIFY_NONE;

    /*verify_mode = SSL_VERIFY_PEER; */

    SSL_CTX_set_verify(ctx, verify_mode, &verify_cb);
    SSL_CTX_set_verify_depth(ctx, ex_verify_depth + 1);
  }

  {
    unsigned long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_SINGLE_ECDH_USE | SSL_OP_SINGLE_DH_USE | SSL_OP_CIPHER_SERVER_PREFERENCE;

#ifdef SSL_OP_NO_COMPRESSION
    flags |= SSL_OP_NO_COMPRESSION;
#endif

#ifdef SSL_OP_NO_TICKET
    flags |= SSL_OP_NO_TICKET;
#endif

    if (transport == IPPROTO_UDP) {
      flags |= srv_ctx->dtls_flags;
    } else {
      flags |= srv_ctx->tls_flags;
    }

    SSL_CTX_set_options(ctx, flags);
  }

  if (srv_ctx->cipher_list[0] != '\0') {
    err = SSL_CTX_set_cipher_list(ctx, srv_ctx->cipher_list);
    if (!err) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] error with cipher list\n"));
    }
  } else {
    err = SSL_CTX_set_cipher_list(ctx, "HIGH:!COMPLEMENTOFDEFAULT:!kRSA:!PSK:!SRP");
    if (!err) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] error with standard cipher list\n"));
    }
  }

  _tls_common_setup(srv_ctx, ctx);

#ifndef OPENSSL_NO_RSA
  generate_eph_rsa_key(ctx);
#endif

  SSL_CTX_set_session_id_context(ctx, (void *) &s_server_session_id_context, sizeof s_server_session_id_context);

  return ctx;
}

/**
 * @brief Initializes the OpenSSL lib and the client/server contexts.
 * Depending on the previously initialized eXosip TLS context (see eXosip_set_tls_ctx() ), only the necessary contexts will be initialized.
 * The client context will be ALWAYS initialized, the server context only if certificates are available. The following chart should illustrate
 * the behaviour.
 *
 * possible certificates  | Client initialized       | Server initialized
 * -------------------------------------------------------------------------------------
 * no certificate     | yes, no cert used        | not initialized
 * only client cert     | yes, own cert (client) used    | yes, client cert used
 * only server cert     | yes, server cert used      | yes, own cert (server) used
 * server and client cert | yes, own cert (client) used    | yes, own cert (server) used
 *
 * The file for seeding the PRNG is only needed on Windows machines. If you compile under a Windows environment, please set W32 oder _WINDOWS as
 * Preprocessor directives.
 *@return < 0 if an error occured
 **/
static int tls_tl_open(struct eXosip_t *excontext) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int res;
  struct addrinfo *addrinfo = NULL;
  struct addrinfo *curinfo;
  int sock = -1;
  char *node = NULL;
  char eb[ERRBSIZ];

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] wrong state: create transport layer first\n"));
    return OSIP_WRONG_STATE;
  }

  excontext->eXtl_transport.proto_local_port = excontext->eXtl_transport.proto_port;

  if (excontext->eXtl_transport.proto_local_port < 0)
    excontext->eXtl_transport.proto_local_port = 5061;

    /* initialization (outside initialize_server_ctx) */
#if OPENSSL_VERSION_NUMBER < 0x10100000L
  SSL_library_init();
  SSL_load_error_strings();
#else
  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
#endif

  reserved->server_ctx = initialize_server_ctx(excontext, & excontext->eXosip_tls_ctx_params, IPPROTO_TCP);

  /* always initialize the client */
  reserved->client_ctx = initialize_client_ctx(excontext, &excontext->eXosip_tls_ctx_params, IPPROTO_TCP, NULL);

  /*only necessary under Windows-based OS, unix-like systems use /dev/random or /dev/urandom */
#if defined(HAVE_WINSOCK2_H)

#if 0

  /* check if a file with random data is present --> will be verified when random file is needed */
  if (reserved->eXosip_tls_ctx_params.random_file[0] == '\0') {
    return TLS_ERR_NO_RAND;
  }

#endif

  /* Load randomness */
  if (!(RAND_load_file(excontext->eXosip_tls_ctx_params.random_file, 1024 * 1024)))
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] cannot load randomness\n"));

#endif

  if (osip_strcasecmp(excontext->eXtl_transport.proto_ifs, "0.0.0.0") != 0 && osip_strcasecmp(excontext->eXtl_transport.proto_ifs, "::") != 0)
    node = excontext->eXtl_transport.proto_ifs;

  res = _eXosip_get_addrinfo(excontext, &addrinfo, node, excontext->eXtl_transport.proto_local_port, excontext->eXtl_transport.proto_num);

  if (res)
    return -1;

  for (curinfo = addrinfo; curinfo; curinfo = curinfo->ai_next) {
#ifdef ENABLE_MAIN_SOCKET
    socklen_t len;
#endif
    int type;

    if (curinfo->ai_protocol && curinfo->ai_protocol != excontext->eXtl_transport.proto_num) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO3, NULL, "[eXosip] [TLS] skipping protocol [%d]\n", curinfo->ai_protocol));
      continue;
    }

    type = curinfo->ai_socktype;
#if defined(SOCK_CLOEXEC)
    type = SOCK_CLOEXEC | type;
#endif
    sock = (int) socket(curinfo->ai_family, type, curinfo->ai_protocol);

    if (sock < 0) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot create socket %s\n", _ex_strerror(ex_errno, eb, ERRBSIZ)));
      continue;
    }

    if (curinfo->ai_family == AF_INET6) {
#ifdef IPV6_V6ONLY

      if (setsockopt_ipv6only(sock)) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot set socket option %s\n", _ex_strerror(ex_errno, eb, ERRBSIZ)));
        _eXosip_closesocket(sock);
        sock = -1;
        continue;
      }

#endif /* IPV6_V6ONLY */
    }

    {
      int valopt = 1;

      setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &valopt, sizeof(valopt));
    }

#ifdef ENABLE_MAIN_SOCKET
    res = bind(sock, curinfo->ai_addr, (socklen_t) curinfo->ai_addrlen);

    if (res < 0) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot bind socket [%s][%s] %s\n", excontext->eXtl_transport.proto_ifs, (curinfo->ai_family == AF_INET) ? "AF_INET" : "AF_INET6", _ex_strerror(ex_errno, eb, ERRBSIZ)));
      _eXosip_closesocket(sock);
      sock = -1;
      continue;
    }

    len = sizeof(reserved->ai_addr);
    res = getsockname(sock, (struct sockaddr *) &reserved->ai_addr, &len);

    if (res != 0) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot get socket name %s\n", _ex_strerror(ex_errno, eb, ERRBSIZ)));
      memcpy(&reserved->ai_addr, curinfo->ai_addr, curinfo->ai_addrlen);
    }

    reserved->ai_addr_len = len;

    if (excontext->eXtl_transport.proto_num == IPPROTO_TCP) {
      res = listen(sock, SOMAXCONN);

      if (res < 0) {
        OSIP_TRACE(
            osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot bind socket [%s][%s] %s\n", excontext->eXtl_transport.proto_ifs, (curinfo->ai_family == AF_INET) ? "AF_INET" : "AF_INET6", _ex_strerror(ex_errno, eb, ERRBSIZ)));
        _eXosip_closesocket(sock);
        sock = -1;
        continue;
      }
    }

#endif

    break;
  }

  _eXosip_freeaddrinfo(addrinfo);

  if (sock < 0) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot bind on port [%i]\n", excontext->eXtl_transport.proto_local_port));
    return -1;
  }

  reserved->tls_socket = sock;

  if (excontext->eXtl_transport.proto_local_port == 0) {
    /* get port number from socket */
    if (reserved->ai_addr.ss_family == AF_INET)
      excontext->eXtl_transport.proto_local_port = ntohs(((struct sockaddr_in *) &reserved->ai_addr)->sin_port);

    else
      excontext->eXtl_transport.proto_local_port = ntohs(((struct sockaddr_in6 *) &reserved->ai_addr)->sin6_port);

    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] binding on port [%i]\n", excontext->eXtl_transport.proto_local_port));
  }

#ifdef ENABLE_MAIN_SOCKET
#ifdef HAVE_SYS_EPOLL_H

  if (excontext->poll_method == EXOSIP_USE_EPOLL_LT) {
    struct epoll_event ev;

    memset(&ev, 0, sizeof(struct epoll_event));
    ev.events = EPOLLIN;
    ev.data.fd = sock;
    res = epoll_ctl(excontext->epfd, EPOLL_CTL_ADD, sock, &ev);

    if (res < 0) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot poll on main tls socket [%i]\n", excontext->eXtl_transport.proto_local_port));
      _eXosip_closesocket(sock);
      reserved->tls_socket = -1;
      return -1;
    }
  }

#endif
#endif

  return OSIP_SUCCESS;
}

static int tls_tl_set_fdset(struct eXosip_t *excontext, fd_set *osip_fdset, fd_set *osip_wrset, fd_set *osip_exceptset, int *fd_max, int *osip_fd_table) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int pos;
  int pos_fd = 0;

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] wrong state: create transport layer first\n"));
    return OSIP_WRONG_STATE;
  }

#ifdef ENABLE_MAIN_SOCKET

  if (reserved->tls_socket <= 0)
    return -1;

  if (osip_fdset != NULL)
    eXFD_SET(reserved->tls_socket, osip_fdset);

  if (reserved->tls_socket > *fd_max)
    *fd_max = reserved->tls_socket;

#endif

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    if (reserved->socket_tab[pos].invalid > 0) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] [fdset] socket info:[%s][%d] [sock=%d] [pos=%d] manual reset\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port,
                            reserved->socket_tab[pos].socket, pos));
      _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
      _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
      continue;
    }

    if (reserved->socket_tab[pos].socket > 0) {
      if (osip_fdset != NULL)
        eXFD_SET(reserved->socket_tab[pos].socket, osip_fdset);
      osip_fd_table[pos_fd] = reserved->socket_tab[pos].socket;
      pos_fd++;

      if (reserved->socket_tab[pos].socket > *fd_max)
        *fd_max = reserved->socket_tab[pos].socket;

      if (osip_wrset != NULL && (reserved->socket_tab[pos].sendbuflen > 0 && reserved->socket_tab[pos].ssl_state == 3))
        eXFD_SET(reserved->socket_tab[pos].socket, osip_wrset);

      //if (osip_wrset != NULL && (reserved->socket_tab[pos].ssl_state == 0 || reserved->socket_tab[pos].ssl_state == 2)) /* wait for establishment OR do handshake with incoming connection */
      if (osip_wrset != NULL && reserved->socket_tab[pos].ssl_state == 0) /* wait for establishment */
        eXFD_SET(reserved->socket_tab[pos].socket, osip_wrset);

      if (osip_exceptset != NULL && reserved->socket_tab[pos].ssl_state == 0) /* wait for establishment */
        eXFD_SET(reserved->socket_tab[pos].socket, osip_exceptset);
    }
  }

  return OSIP_SUCCESS;
}

static int _tls_print_ssl_error(int err) {
  switch (err) {
  case SSL_ERROR_NONE:
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL ERROR NONE - OK\n"));
    break;

  case SSL_ERROR_ZERO_RETURN:
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL ERROR ZERO RETURN - SHUTDOWN\n"));
    break;

  case SSL_ERROR_WANT_READ:
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL want read\n"));
    break;

  case SSL_ERROR_WANT_WRITE:
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL want write\n"));
    break;

  case SSL_ERROR_SSL:
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL ERROR\n"));
    break;

  case SSL_ERROR_SYSCALL:
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL ERROR SYSCALL\n"));
    break;

  default:
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL problem\n"));
  }

  return OSIP_SUCCESS;
}

static void tls_dump_verification_failure(long verification_result, char *reason, size_t reason_len) {
  switch (verification_result) {
  case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
    snprintf(reason, reason_len, "unable to get issuer certificate");
    break;

  case X509_V_ERR_UNABLE_TO_GET_CRL:
    snprintf(reason, reason_len, "unable to get certificate CRL");
    break;

  case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
    snprintf(reason, reason_len, "unable to decrypt certificate's signature");
    break;

  case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
    snprintf(reason, reason_len, "unable to decrypt CRL's signature");
    break;

  case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
    snprintf(reason, reason_len, "unable to decode issuer public key");
    break;

  case X509_V_ERR_CERT_SIGNATURE_FAILURE:
    snprintf(reason, reason_len, "certificate signature failure");
    break;

  case X509_V_ERR_CRL_SIGNATURE_FAILURE:
    snprintf(reason, reason_len, "CRL signature failure");
    break;

  case X509_V_ERR_CERT_NOT_YET_VALID:
    snprintf(reason, reason_len, "certificate is not yet valid");
    break;

  case X509_V_ERR_CERT_HAS_EXPIRED:
    snprintf(reason, reason_len, "certificate has expired");
    break;

  case X509_V_ERR_CRL_NOT_YET_VALID:
    snprintf(reason, reason_len, "CRL is not yet valid");
    break;

  case X509_V_ERR_CRL_HAS_EXPIRED:
    snprintf(reason, reason_len, "CRL has expired");
    break;

  case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
    snprintf(reason, reason_len, "format error in certificate's notBefore field");
    break;

  case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
    snprintf(reason, reason_len, "format error in certificate's notAfter field");
    break;

  case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
    snprintf(reason, reason_len, "format error in CRL's lastUpdate field");
    break;

  case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
    snprintf(reason, reason_len, "format error in CRL's nextUpdate field");
    break;

  case X509_V_ERR_OUT_OF_MEM:
    snprintf(reason, reason_len, "out of memory");
    break;

  case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
    snprintf(reason, reason_len, "self signed certificate");
    break;

  case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
    snprintf(reason, reason_len, "self signed certificate in certificate chain");
    break;

  case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
    snprintf(reason, reason_len, "unable to get local issuer certificate");
    break;

  case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
    snprintf(reason, reason_len, "unable to verify the first certificate");
    break;

  case X509_V_ERR_CERT_CHAIN_TOO_LONG:
    snprintf(reason, reason_len, "certificate chain too long");
    break;

  case X509_V_ERR_CERT_REVOKED:
    snprintf(reason, reason_len, "certificate revoked");
    break;

  case X509_V_ERR_INVALID_CA:
    snprintf(reason, reason_len, "invalid CA certificate");
    break;

  case X509_V_ERR_PATH_LENGTH_EXCEEDED:
    snprintf(reason, reason_len, "path length constraint exceeded");
    break;

  case X509_V_ERR_INVALID_PURPOSE:
    snprintf(reason, reason_len, "unsupported certificate purpose");
    break;

  case X509_V_ERR_CERT_UNTRUSTED:
    snprintf(reason, reason_len, "certificate not trusted");
    break;

  case X509_V_ERR_CERT_REJECTED:
    snprintf(reason, reason_len, "certificate rejected");
    break;

  case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
    snprintf(reason, reason_len, "subject issuer mismatch");
    break;

  case X509_V_ERR_AKID_SKID_MISMATCH:
    snprintf(reason, reason_len, "authority and subject key identifier mismatch");
    break;

  case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
    snprintf(reason, reason_len, "authority and issuer serial number mismatch");
    break;

  case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
    snprintf(reason, reason_len, "key usage does not include certificate signing");
    break;

  case X509_V_ERR_APPLICATION_VERIFICATION:
    snprintf(reason, reason_len, "application verification failure");
    break;

  default:
    snprintf(reason, reason_len, "unknown error");
    break;
  }

  // OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] verification failure [%s]\n", tmp));
}

static int pkp_pin_peer_pubkey(struct eXosip_t *excontext, SSL *ssl) {
  X509 *cert = NULL;
  FILE *fp = NULL;

  int len1 = 0, len2 = 0;
  unsigned char *buff1 = NULL, *buff2 = NULL;

  int ret = 0, result = -1;

  if (NULL == ssl)
    return -1;

  if (excontext->eXosip_tls_ctx_params.client.public_key_pinned[0] == '\0')
    return 0;

  OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] checking pinned public key for certificate [%s]\n", excontext->eXosip_tls_ctx_params.client.public_key_pinned));

  do {
    unsigned char *temp = NULL;
    long size;

    cert = SSL_get_peer_certificate(ssl);

    if (!(cert != NULL))
      break; /* failed */

    /* Begin Gyrations to get the subjectPublicKeyInfo       */
    /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */

    len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);

    if (!(len1 > 0))
      break; /* failed */

    buff1 = temp = OPENSSL_malloc(len1);

    if (!(buff1 != NULL))
      break; /* failed */

    len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);

    if (!((len1 == len2) && (temp != NULL) && ((temp - buff1) == len1)))
      break; /* failed */

    /* in order to get your public key file in DER format: */
    /* openssl x509 -in your-base64-certificate.pem -pubkey -noout | openssl enc -base64 -d > publickey.der */
    fp = fopen(excontext->eXosip_tls_ctx_params.client.public_key_pinned, "rb");

    if (NULL == fp)
      fp = fopen(excontext->eXosip_tls_ctx_params.client.public_key_pinned, "r");

    if (!(NULL != fp))
      break; /* failed */

    ret = fseek(fp, 0, SEEK_END);

    if (!(0 == ret))
      break; /* failed */

    size = ftell(fp);

    if (!(size != -1 && size > 0 && size < 4096))
      break; /* failed */

    ret = fseek(fp, 0, SEEK_SET);

    if (!(0 == ret))
      break; /* failed */

    buff2 = NULL;
    len2 = (int) size;

    buff2 = OPENSSL_malloc(len2);

    if (!(buff2 != NULL))
      break; /* failed */

    ret = (int) fread(buff2, (size_t) len2, 1, fp);

    if (!(ret == 1))
      break; /* failed */

    size = len1 < len2 ? len1 : len2;

    if (len1 != (int) size || len2 != (int) size || 0 != memcmp(buff1, buff2, (size_t) size))
      break; /* failed */

    result = 0;

  } while (0);

  if (fp != NULL)
    fclose(fp);

  if (NULL != buff2)
    OPENSSL_free(buff2);

  if (NULL != buff1)
    OPENSSL_free(buff1);

  if (NULL != cert)
    X509_free(cert);

  return result;
}

static const char *get_sigtype(int nid) {
  switch (nid) {
  case EVP_PKEY_RSA:
    return "RSA";

  case EVP_PKEY_DSA:
    return "DSA";

  case EVP_PKEY_EC:
    return "ECDSA";

#if OPENSSL_VERSION_NUMBER >= 0x10101000L
  case EVP_PKEY_RSA_PSS:
    return "RSA-PSS";

#if defined(NID_Ed25519)
#define NID_ED25519 NID_Ed25519
#endif
#if defined(NID_Ed448)
#define NID_ED448 NID_Ed448
#endif

  case NID_ED25519:
    return "Ed25519";

  case NID_ED448:
    return "Ed448";
#endif

#if OPENSSL_VERSION_NUMBER >= 0x0090809fL
  case NID_id_GostR3410_2001:
    return "gost2001";
#endif

#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
  case NID_id_GostR3410_2012_256:
    return "gost2012_256";

  case NID_id_GostR3410_2012_512:
    return "gost2012_512";
#endif

  default:
    return NULL;
  }
}

static void tls_dump_info(struct eXosip_t *excontext, struct _tls_stream *sockinfo) {
  char tmp_info[2048];
  size_t len_info = 0;

  X509 *peer = NULL;
  const SSL_CIPHER *c;
  long verify_err;
  int nid;

  if (excontext->tls_verify_client_certificate > 0) {
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [verification=ENABLED]");
  } else {
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [verification=DISABLED]");
  }

  peer = SSL_get_peer_certificate(sockinfo->ssl_conn);

  verify_err = SSL_get_verify_result(sockinfo->ssl_conn);
  if (peer != NULL) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
    if (verify_err == X509_V_OK) {
      const char *peername = SSL_get0_peername(sockinfo->ssl_conn);

      len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [SUCCESS");
      if (peername != NULL)
        len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " peername=%s", peername);
      len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, "]");
    } else {
      const char *reason = X509_verify_cert_error_string(verify_err);

      len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [FAILURE %s]", reason);
    }
#else
    if (verify_err == X509_V_OK) {
      len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [SUCCESS]");
    } else {
      char reason[64];
      tls_dump_verification_failure(verify_err, reason, sizeof(reason));

      len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [FAILURE %s]", reason);
    }
#endif
  } else {
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [FAILURE no peer certificate]");
  }

  len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [%s]", SSL_get_version(sockinfo->ssl_conn));

  len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [peer certificate");
  if (peer != NULL) {
    char tmp_buffer[128];

    X509_NAME_oneline(X509_get_subject_name(peer), tmp_buffer, sizeof(tmp_buffer));
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " sub=%s", tmp_buffer);
    X509_NAME_oneline(X509_get_issuer_name(peer), tmp_buffer, sizeof(tmp_buffer));
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " issuer=%s]", tmp_buffer);

  } else {
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " NONE]");
  }

#if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER)
  len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [peer");
  if (SSL_get_peer_signature_nid(sockinfo->ssl_conn, &nid) && nid != NID_undef)
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " signing digest=%s", OBJ_nid2sn(nid));
  if (SSL_get_peer_signature_type_nid(sockinfo->ssl_conn, &nid))
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " signature type=%s", get_sigtype(nid));

  {
    EVP_PKEY *key;

    if (SSL_get_peer_tmp_key(sockinfo->ssl_conn, &key)) {
      len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " temp key=");
      switch (EVP_PKEY_id(key)) {
      case EVP_PKEY_RSA:
        len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, "RSA, %dbits", EVP_PKEY_bits(key));
        break;

      case EVP_PKEY_DH:
        len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, "DH, %dbits", EVP_PKEY_bits(key));
        break;
#ifndef OPENSSL_NO_EC
      case EVP_PKEY_EC: {
        EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
        int nid;
        const char *cname;
        nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
        EC_KEY_free(ec);
        cname = EC_curve_nid2nist(nid);
        if (cname == NULL)
          cname = OBJ_nid2sn(nid);
        len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, "ECDH, %s, %dbits", cname, EVP_PKEY_bits(key));
      } break;
#endif
      default:
        len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, "%s, %dbits", OBJ_nid2sn(EVP_PKEY_id(key)), EVP_PKEY_bits(key));
      }
      EVP_PKEY_free(key);
    }
  }
  len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, "]");
#endif

  c = SSL_get_current_cipher(sockinfo->ssl_conn);
  len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [cipher %s:%s", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));

  if (peer != NULL) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
    EVP_PKEY *pktmp;

    pktmp = X509_get0_pubkey(peer);
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " peer pub.key=%ubit", EVP_PKEY_bits(pktmp));
#endif
    X509_free(peer);
  }

#ifndef OPENSSL_NO_COMP
  {
    const COMP_METHOD *comp, *expansion;
    comp = SSL_get_current_compression(sockinfo->ssl_conn);
    expansion = SSL_get_current_expansion(sockinfo->ssl_conn);
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " Compression: %s", comp ? SSL_COMP_get_name(comp) : "NONE");
    len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " Expansion: %s", expansion ? SSL_COMP_get_name(expansion) : "NONE");
  }
#endif
  len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, "]");

#if OPENSSL_VERSION_NUMBER >= 0x10100000L
  len_info += snprintf(tmp_info + len_info, sizeof(tmp_info) - len_info, " [handshake read=%ju write=%ju bytes]", BIO_number_read(SSL_get_rbio(sockinfo->ssl_conn)), BIO_number_written(SSL_get_wbio(sockinfo->ssl_conn)));
#endif

  OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [ssl connect]%s\n", tmp_info));
}

static int _tls_tl_ssl_connect_socket(struct eXosip_t *excontext, struct _tls_stream *sockinfo) {
  X509 *peer;
  BIO *sbio;
  int res;
  long cert_err;

  if (sockinfo->ssl_ctx == NULL) {
    sockinfo->ssl_ctx = initialize_client_ctx(excontext, &excontext->eXosip_tls_ctx_params, IPPROTO_TCP, sockinfo->sni_servernameindication);

    /* FIXME: changed parameter from ctx to client_ctx -> works now */
    sockinfo->ssl_conn = SSL_new(sockinfo->ssl_ctx);

    if (sockinfo->ssl_conn == NULL) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL_new error\n"));
      return -1;
    }

    sbio = BIO_new_socket(sockinfo->socket, BIO_NOCLOSE);

    if (sbio == NULL) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] BIO_new_socket error\n"));
      return -1;
    }

    SSL_set_bio(sockinfo->ssl_conn, sbio, sbio);

#ifndef OPENSSL_NO_TLSEXT

    if (!SSL_set_tlsext_host_name(sockinfo->ssl_conn, sockinfo->sni_servernameindication /* "host.name.before.dns.srv.com" */)) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] set_tlsext_host_name (SNI): no servername gets indicated\n"));
    }

#endif
  }

  res = SSL_connect(sockinfo->ssl_conn);
  res = SSL_get_error(sockinfo->ssl_conn, res);

  if (res != SSL_ERROR_NONE && res != SSL_ERROR_WANT_READ && res != SSL_ERROR_WANT_WRITE) {
    tls_dump_info(excontext, sockinfo);
    _tls_print_ssl_error(res);
    return -1;
  }

  if (!SSL_is_init_finished(sockinfo->ssl_conn)) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [ssl connect] handshake in progress\n"));
    return 1;
  }

  tls_dump_info(excontext, sockinfo);

  cert_err = SSL_get_verify_result(sockinfo->ssl_conn);

  if (excontext->tls_verify_client_certificate > 0 && cert_err != X509_V_OK) {
    return -1;
  }

  peer = SSL_get_peer_certificate(sockinfo->ssl_conn);
  if (peer == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] no certificate received\n"));
    return -1;
  }
  X509_free(peer);

  if (pkp_pin_peer_pubkey(excontext, sockinfo->ssl_conn)) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] failed to verify public key for certificate\n"));
    return -1;
  }

  SSL_set_mode(sockinfo->ssl_conn, SSL_MODE_AUTO_RETRY);

  sockinfo->ssl_state = 3;
  _eXosip_mark_all_transaction_force_send(excontext, sockinfo->socket);
  return 0;
}

/* Like strstr, but works for haystack that may contain binary data and is
   not NUL-terminated. */
static char *_tls_buffer_find(const char *haystack, size_t haystack_len, const char *needle) {
  const char *search = haystack, *end = haystack + haystack_len;
  char *p;
  size_t len = strlen(needle);

  while (search < end && (p = memchr(search, *needle, end - search)) != NULL) {
    if (p + len > end)
      break;

    if (memcmp(p, needle, len) == 0)
      return (p);

    search = p + 1;
  }

  return (NULL);
}

#define END_HEADERS_STR "\r\n\r\n"
#define CLEN_HEADER_STR "\r\ncontent-length:"
#define CLEN_HEADER_COMPACT_STR "\r\nl:"
#define CLEN_HEADER_STR2 "\r\ncontent-length "
#define CLEN_HEADER_COMPACT_STR2 "\r\nl "
#define const_strlen(x) (sizeof((x)) - 1)

/* consume any complete messages in sockinfo->buf and
   return the total number of bytes consumed */
static size_t _tls_handle_messages(struct eXosip_t *excontext, struct _tls_stream *sockinfo) {
  size_t consumed = 0;
  char *buf = sockinfo->buf;
  size_t buflen = sockinfo->buflen;
  char *end_headers;

  while (buflen > 0 && (end_headers = _tls_buffer_find(buf, buflen, END_HEADERS_STR)) != NULL) {
    int clen;
    size_t msglen;
    char *clen_header;

    if (buf == end_headers) {
      /* skip tcp standard keep-alive */
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] socket [%s][%d] rfc5626 [double]pong received [CRLFCRLF]\n", sockinfo->remote_ip, sockinfo->remote_port));
      consumed += 4;
      buflen -= 4;
      buf += 4;
      sockinfo->ping_rfc5626 = 0;
      continue;
    }

    /* stuff a nul in so we can use osip_strcasestr */
    *end_headers = '\0';

    /* ok we have complete headers, find content-length: or l: */
    clen_header = osip_strcasestr(buf, CLEN_HEADER_STR);

    if (!clen_header)
      clen_header = osip_strcasestr(buf, CLEN_HEADER_STR2);

    if (!clen_header)
      clen_header = osip_strcasestr(buf, CLEN_HEADER_COMPACT_STR);

    if (!clen_header)
      clen_header = osip_strcasestr(buf, CLEN_HEADER_COMPACT_STR2);

    if (clen_header != NULL) {
      clen_header = strchr(clen_header, ':');
      clen_header++;
    }

    if (!clen_header) {
      /* Oops, no content-length header.      Presume 0 (below) so we
         consume the headers and make forward progress.  This permits
         server-side keepalive of "\r\n\r\n". */
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] socket [%s][%d] message has no content-length: <%s>\n", sockinfo->remote_ip, sockinfo->remote_port, buf));
    }

    clen = clen_header ? atoi(clen_header) : 0;

    if (clen < 0)
      return sockinfo->buflen; /* discard data */

    /* undo our overwrite and advance end_headers */
    *end_headers = END_HEADERS_STR[0];
    end_headers += const_strlen(END_HEADERS_STR);

    /* do we have the whole message? */
    msglen = (end_headers - buf + clen);

    if (msglen > buflen) {
      /* nope */
      return consumed;
    }

    /* yep; handle the message */
    _eXosip_handle_incoming_message(excontext, buf, msglen, sockinfo->socket, sockinfo->remote_ip, sockinfo->remote_port, sockinfo->natted_ip, &sockinfo->natted_port);
    consumed += msglen;
    buflen -= msglen;
    buf += msglen;
  }

  if (buflen == 2 && buf[0] == '\r' && buf[1] == '\n') {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] socket [%s][%d] rfc5626 pong received [CRLF]\n", sockinfo->remote_ip, sockinfo->remote_port, buf));
    consumed += 2;
    buflen -= 2;
    buf += 2;
    sockinfo->ping_rfc5626 = 0;
    sockinfo->pong_supported = 1;
  }

  return consumed;
}

static int _tls_tl_recv(struct eXosip_t *excontext, struct _tls_stream *sockinfo) {
  int rlen, err;
  size_t consumed;

  if (!sockinfo->buf) {
    sockinfo->buf = (char *) osip_malloc(SIP_MESSAGE_MAX_LENGTH);

    if (sockinfo->buf == NULL)
      return OSIP_NOMEM;

    sockinfo->bufsize = SIP_MESSAGE_MAX_LENGTH;
    sockinfo->buflen = 0;
  }

  /* buffer is 100% full -> realloc with more size */
  if (sockinfo->bufsize - sockinfo->buflen <= 0) {
    sockinfo->buf = (char *) osip_realloc(sockinfo->buf, sockinfo->bufsize + 5000);

    if (sockinfo->buf == NULL)
      return OSIP_NOMEM;

    sockinfo->bufsize = sockinfo->bufsize + 5000;
  }

  /* buffer is 100% empty-> realloc with initial size */
  if (sockinfo->buflen == 0 && sockinfo->bufsize > SIP_MESSAGE_MAX_LENGTH) {
    osip_free(sockinfo->buf);
    sockinfo->buf = (char *) osip_malloc(SIP_MESSAGE_MAX_LENGTH);

    if (sockinfo->buf == NULL)
      return OSIP_NOMEM;

    sockinfo->bufsize = SIP_MESSAGE_MAX_LENGTH;
  }

  if (sockinfo->ssl_state != 3)
    return OSIP_SUCCESS;

  rlen = SSL_read(sockinfo->ssl_conn, sockinfo->buf + sockinfo->buflen, (int) (sockinfo->bufsize - sockinfo->buflen));

  if (rlen <= 0) {
    err = SSL_get_error(sockinfo->ssl_conn, rlen);

    if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) {
      _tls_print_ssl_error(err);
      /*
         The TLS/SSL connection has been closed.  If the protocol version
         is SSL 3.0 or TLS 1.0, this result code is returned only if a
         closure alert has occurred in the protocol, i.e. if the
         connection has been closed cleanly. Note that in this case
         SSL_ERROR_ZERO_RETURN does not necessarily indicate that the
         underlying transport has been closed. */
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] [recv] TLS closed\n"));

      _eXosip_mark_registration_expired(excontext, sockinfo->reg_call_id);
      _tls_tl_close_sockinfo(excontext, sockinfo);
    }
    return OSIP_UNDEFINED_ERROR;
  }

  err = OSIP_SUCCESS;

  if (SSL_pending(sockinfo->ssl_conn))
    err = -999;

  sockinfo->tcp_max_timeout = 0;
  OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] [recv] socket [%s][%d] read %d bytes\n", sockinfo->remote_ip, sockinfo->remote_port, rlen));
  sockinfo->buflen += rlen;
  consumed = _tls_handle_messages(excontext, sockinfo);

  if (consumed != 0) {
    if (sockinfo->buflen > consumed) {
      memmove(sockinfo->buf, sockinfo->buf + consumed, sockinfo->buflen - consumed);
      sockinfo->buflen -= consumed;

    } else {
      sockinfo->buflen = 0;
    }
  }

  return err; /* if -999 is returned, internal buffer of SSL still contains some data */
}

static int _tls_read_tls_main_socket(struct eXosip_t *excontext) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;

  /* accept incoming connection */
  char src6host[NI_MAXHOST];
  int recvport = 0;
  struct sockaddr_storage sa;
  int sock;
  int i;

  socklen_t slen;
  int pos;

  SSL *ssl = NULL;
  BIO *sbio;

  if (reserved->ai_addr.ss_family == AF_INET)
    slen = sizeof(struct sockaddr_in);

  else
    slen = sizeof(struct sockaddr_in6);

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    if (reserved->socket_tab[pos].socket <= 0)
      break;
  }

  if (pos == EXOSIP_MAX_SOCKETS) {
    /* delete an old one! */
    pos = 0;

    if (reserved->socket_tab[pos].socket > 0) {
      _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
      _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
    }

    memset(&reserved->socket_tab[pos], 0, sizeof(struct _tls_stream));
  }

  OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO3, NULL, "[eXosip] [TLS] creating TLS socket at index [%i]\n", pos));

  sock = (int) accept(reserved->tls_socket, (struct sockaddr *) &sa, (socklen_t *) &slen);

  if (sock < 0) {
#if defined(EBADF)
    int valopt = ex_errno;
#endif
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] error accepting TLS socket\n"));
#if defined(EBADF)

    if (valopt == EBADF) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] error accepting TLS socket [EBADF]\n"));
      memset(&reserved->ai_addr, 0, sizeof(struct sockaddr_storage));

      if (reserved->tls_socket > 0) {
        _eXosip_closesocket(reserved->tls_socket);

        for (i = 0; i < EXOSIP_MAX_SOCKETS; i++) {
          if (reserved->socket_tab[i].socket > 0 && reserved->socket_tab[i].is_server > 0) {
            _eXosip_mark_registration_expired(excontext, reserved->socket_tab[i].reg_call_id);
            _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[i]);
          }
        }
      }

      tls_tl_open(excontext);
    }

#endif

  } else {
    if (reserved->server_ctx == NULL) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] TLS connection rejected\n"));
      _eXosip_closesocket(sock);
      return -1;
    }

    if (!SSL_CTX_check_private_key(reserved->server_ctx)) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL CTX private key check error\n"));
    }

    ssl = SSL_new(reserved->server_ctx);

    if (ssl == NULL) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] cannot create ssl connection context\n"));
      return -1;
    }

    if (!SSL_check_private_key(ssl)) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL private key check error\n"));
    }

    sbio = BIO_new_socket(sock, BIO_NOCLOSE);

    if (sbio == NULL) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] BIO_new_socket error\n"));
    }

    SSL_set_bio(ssl, sbio, sbio); /* cannot fail */

    i = SSL_accept(ssl);

    if (i <= 0) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] SSL_accept error: %s\n", ERR_error_string(ERR_get_error(), NULL)));
      i = SSL_get_error(ssl, i);
      _tls_print_ssl_error(i);

      SSL_shutdown(ssl);
      _eXosip_closesocket(sock);
      SSL_free(ssl);
      return -1;
    }

    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] incoming TLS connection accepted\n"));

    reserved->socket_tab[pos].socket = sock;
    reserved->socket_tab[pos].is_server = 1;
    reserved->socket_tab[pos].ssl_conn = ssl;
    reserved->socket_tab[pos].ssl_state = 2;

    {
      int valopt = 1;

      setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &valopt, sizeof(valopt));
    }

    memset(src6host, 0, NI_MAXHOST);
    recvport = _eXosip_getport((struct sockaddr *) &sa);
    _eXosip_getnameinfo((struct sockaddr *) &sa, slen, src6host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);

    _eXosip_transport_set_dscp(excontext, sa.ss_family, sock);

    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] message received from [%s][%d]\n", src6host, recvport));
    osip_strncpy(reserved->socket_tab[pos].remote_ip, src6host, sizeof(reserved->socket_tab[pos].remote_ip) - 1);
    reserved->socket_tab[pos].remote_port = recvport;

#ifdef HAVE_SYS_EPOLL_H

    if (excontext->poll_method == EXOSIP_USE_EPOLL_LT) {
      struct epoll_event ev;
      int res;

      memset(&ev, 0, sizeof(struct epoll_event));
      ev.events = EPOLLIN;
      ev.data.fd = sock;
      res = epoll_ctl(excontext->epfd, EPOLL_CTL_ADD, sock, &ev);

      if (res < 0) {
        _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
        return -1;
      }
    }

#endif
  }

  return OSIP_SUCCESS;
}

#ifdef HAVE_SYS_EPOLL_H

static int tls_tl_epoll_read_message(struct eXosip_t *excontext, int nfds, struct epoll_event *ep_array) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int pos = 0;
  int n;

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] wrong state: create transport layer first\n"));
    return OSIP_WRONG_STATE;
  }

  for (n = 0; n < nfds; ++n) {
    if (ep_array[n].data.fd == reserved->tls_socket) {
      _tls_read_tls_main_socket(excontext);
      continue;
    }

    for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
      if (reserved->socket_tab[pos].socket > 0) {
        if (ep_array[n].data.fd == reserved->socket_tab[pos].socket) {
          if ((ep_array[n].events & EPOLLIN) && reserved->socket_tab[pos].ssl_state == 2 && reserved->socket_tab[pos].is_server > 0) {
            int r = SSL_do_handshake(reserved->socket_tab[pos].ssl_conn);
            int err = SSL_get_error(reserved->socket_tab[pos].ssl_conn, r);

            if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE)
              continue;

            if (r <= 0) {
              _tls_print_ssl_error(err);
              _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
              _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
              continue;
            }

            SSL_set_mode(reserved->socket_tab[pos].ssl_conn, SSL_MODE_AUTO_RETRY);
            reserved->socket_tab[pos].ssl_state = 3;
            continue;
          }

          if ((ep_array[n].events & EPOLLIN) || ep_array[n].events & EPOLLOUT) {
            int err = -999;
            int max = 5;

            while (err == -999 && max > 0) {
              err = _tls_tl_recv(excontext, &reserved->socket_tab[pos]);
              max--;
            }
          }
        }
      }
    }
  }

  return OSIP_SUCCESS;
}

#endif

static int tls_tl_read_message(struct eXosip_t *excontext, fd_set *osip_fdset, fd_set *osip_wrset, fd_set *osip_exceptset) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int pos = 0;

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] wrong state: create transport layer first\n"));
    return OSIP_WRONG_STATE;
  }

  if (FD_ISSET(reserved->tls_socket, osip_fdset)) {
    _tls_read_tls_main_socket(excontext);
  }

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    if (reserved->socket_tab[pos].socket > 0) {
      if (FD_ISSET(reserved->socket_tab[pos].socket, osip_exceptset)) {
        int res = _tcptls_tl_is_connected(excontext->poll_method, reserved->socket_tab[pos].socket);
        if (res < 0) {
          _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
          _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
          continue;
        } else {
          OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] [tid=-1] socket [%s][%d] except descriptor without error\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port));
        }
      } else if (FD_ISSET(reserved->socket_tab[pos].socket, osip_wrset) && reserved->socket_tab[pos].ssl_state < 2) {
      } else if (FD_ISSET(reserved->socket_tab[pos].socket, osip_wrset) && reserved->socket_tab[pos].ssl_state == 2) {
        /* this should be dead code */
        int r = SSL_do_handshake(reserved->socket_tab[pos].ssl_conn);

        if (r <= 0) {
          r = SSL_get_error(reserved->socket_tab[pos].ssl_conn, r);
          _tls_print_ssl_error(r);

          _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
          _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
          continue;
        }

        SSL_set_mode(reserved->socket_tab[pos].ssl_conn, SSL_MODE_AUTO_RETRY);
        reserved->socket_tab[pos].ssl_state = 3;
      } else if (FD_ISSET(reserved->socket_tab[pos].socket, osip_wrset) && reserved->socket_tab[pos].sendbuflen > 0) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] [tid=-1] message sent [len=%d] to [%s][%d]\n%s\n", reserved->socket_tab[pos].sendbuflen, reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port,
                              reserved->socket_tab[pos].sendbuf));
        _tls_tl_send(excontext, reserved->socket_tab[pos].ssl_conn, (const char *) reserved->socket_tab[pos].sendbuf, (int) reserved->socket_tab[pos].sendbuflen);
        reserved->socket_tab[pos].sendbuflen = 0;
      }

      if (FD_ISSET(reserved->socket_tab[pos].socket, osip_fdset)) {
        int err = -999;
        int max = 5;

        while (err == -999 && max > 0) {
          err = _tls_tl_recv(excontext, &reserved->socket_tab[pos]);
          max--;
        }
      }
    }
  }

  return OSIP_SUCCESS;
}

static int _tls_tl_find_socket(struct eXosip_t *excontext, char *host, int port) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int pos;

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    if (reserved->socket_tab[pos].socket != 0) {
      if (0 == osip_strcasecmp(reserved->socket_tab[pos].remote_ip, host) && port == reserved->socket_tab[pos].remote_port)
        return pos;
    }
  }

  return -1;
}

static int _tls_tl_new_socket(struct eXosip_t *excontext, char *host, int port, int retry, const char *sni_servernameindication) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int pos;
  int res;
  struct addrinfo *addrinfo = NULL;
  struct addrinfo *curinfo;
  int sock = -1;
  int ssl_state = 0;
  struct sockaddr selected_ai_addr;
  socklen_t selected_ai_addrlen;

  char src6host[NI_MAXHOST];
  char eb[ERRBSIZ];

  memset(src6host, 0, sizeof(src6host));

  selected_ai_addrlen = 0;
  memset(&selected_ai_addr, 0, sizeof(struct sockaddr));

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    if (reserved->socket_tab[pos].socket == 0) {
      break;
    }
  }

  if (pos == EXOSIP_MAX_SOCKETS) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] [new] reserved->socket_tab is full - cannot create new socket\n"));
    return -1;
  }

  res = _eXosip_get_addrinfo(excontext, &addrinfo, host, port, IPPROTO_TCP);

  if (res)
    return -1;

  for (curinfo = addrinfo; curinfo; curinfo = curinfo->ai_next) {
    int i;

    if (curinfo->ai_protocol && curinfo->ai_protocol != IPPROTO_TCP)
      continue;

    res = _eXosip_getnameinfo((struct sockaddr *) curinfo->ai_addr, (socklen_t) curinfo->ai_addrlen, src6host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);

    if (res != 0)
      continue;

    i = _tls_tl_find_socket(excontext, src6host, port);

    if (i >= 0) {
      _eXosip_freeaddrinfo(addrinfo);
      return i;
    }
  }

  if (retry > 0)
    return -1;

  for (curinfo = addrinfo; curinfo; curinfo = curinfo->ai_next) {
    int type;

    if (curinfo->ai_protocol && curinfo->ai_protocol != IPPROTO_TCP) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] skipping protocol [%d]\n", curinfo->ai_protocol));
      continue;
    }

    res = _eXosip_getnameinfo((struct sockaddr *) curinfo->ai_addr, (socklen_t) curinfo->ai_addrlen, src6host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);

    if (res == 0) {
      int i = _tls_tl_find_socket(excontext, src6host, port);

      if (i >= 0) {
        _eXosip_freeaddrinfo(addrinfo);
        return i;
      }

      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] [new] new binding with [%s][%d]\n", src6host, port));
    }

    type = curinfo->ai_socktype;
#if defined(SOCK_CLOEXEC)
    type = SOCK_CLOEXEC | type;
#endif
    sock = (int) socket(curinfo->ai_family, type, curinfo->ai_protocol);

    if (sock < 0) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] cannot create socket %s\n", _ex_strerror(ex_errno, eb, ERRBSIZ)));
      continue;
    }

    if (curinfo->ai_family == AF_INET6) {
#ifdef IPV6_V6ONLY

      if (setsockopt_ipv6only(sock)) {
        _eXosip_closesocket(sock);
        sock = -1;
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] cannot set socket option %s\n", _ex_strerror(ex_errno, eb, ERRBSIZ)));
        continue;
      }

#endif /* IPV6_V6ONLY */
    }

    if (reserved->ai_addr_len > 0) {
      if (excontext->reuse_tcp_port > 0) {
        struct sockaddr_storage ai_addr;
        int valopt = 1;

        setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &valopt, sizeof(valopt));

        memcpy(&ai_addr, &reserved->ai_addr, reserved->ai_addr_len);

        if (ai_addr.ss_family == AF_INET)
          ((struct sockaddr_in *) &ai_addr)->sin_port = htons(excontext->eXtl_transport.proto_local_port);

        else
          ((struct sockaddr_in6 *) &ai_addr)->sin6_port = htons(excontext->eXtl_transport.proto_local_port);

        res = bind(sock, (const struct sockaddr *) &ai_addr, reserved->ai_addr_len);

        if (res < 0) {
          OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] [new] cannot bind socket [%s] family:%d %s\n", excontext->eXtl_transport.proto_ifs, ai_addr.ss_family, _ex_strerror(ex_errno, eb, ERRBSIZ)));
        }

      } else if (excontext->oc_local_address[0] == '\0') {
        if (reserved->ai_addr.ss_family == curinfo->ai_family) {
          struct sockaddr_storage ai_addr;
          int count = 0;

          memcpy(&ai_addr, &reserved->ai_addr, reserved->ai_addr_len);

          while (count < 100) {
            if (excontext->oc_local_port_range[0] < 1024) {
              if (ai_addr.ss_family == AF_INET)
                ((struct sockaddr_in *) &ai_addr)->sin_port = htons(0);

              else
                ((struct sockaddr_in6 *) &ai_addr)->sin6_port = htons(0);

            } else {
              if (excontext->oc_local_port_current == 0)
                excontext->oc_local_port_current = excontext->oc_local_port_range[0];

              /* reset value */
              if (excontext->oc_local_port_current >= excontext->oc_local_port_range[1])
                excontext->oc_local_port_current = excontext->oc_local_port_range[0];

              if (ai_addr.ss_family == AF_INET)
                ((struct sockaddr_in *) &ai_addr)->sin_port = htons(excontext->oc_local_port_current);

              else
                ((struct sockaddr_in6 *) &ai_addr)->sin6_port = htons(excontext->oc_local_port_current);
            }

            res = bind(sock, (const struct sockaddr *) &ai_addr, reserved->ai_addr_len);

            if (res < 0) {
              OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] [new] cannot bind socket [%s] family:%d (port=%i) %s\n", excontext->eXtl_transport.proto_ifs, ai_addr.ss_family, excontext->oc_local_port_current,
                                    _ex_strerror(ex_errno, eb, ERRBSIZ)));
              count++;

              if (excontext->oc_local_port_range[0] >= 1024)
                excontext->oc_local_port_current++;

              continue;
            }

            if (excontext->oc_local_port_range[0] >= 1024)
              excontext->oc_local_port_current++;

            break;
          }
        }

      } else {
        int count = 0;

        if (excontext->oc_local_port_range[0] < 1024)
          excontext->oc_local_port_range[0] = 0;

        while (count < 100) {
          struct addrinfo *oc_addrinfo = NULL;
          struct addrinfo *oc_curinfo;

          if (excontext->oc_local_port_current == 0)
            excontext->oc_local_port_current = excontext->oc_local_port_range[0];

          if (excontext->oc_local_port_current >= excontext->oc_local_port_range[1])
            excontext->oc_local_port_current = excontext->oc_local_port_range[0];

          _eXosip_get_addrinfo(excontext, &oc_addrinfo, excontext->oc_local_address, excontext->oc_local_port_current, IPPROTO_TCP);

          for (oc_curinfo = oc_addrinfo; oc_curinfo; oc_curinfo = oc_curinfo->ai_next) {
            if (oc_curinfo->ai_protocol && oc_curinfo->ai_protocol != IPPROTO_TCP) {
              OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] skipping protocol [%d]\n", oc_curinfo->ai_protocol));
              continue;
            }

            break;
          }

          if (oc_curinfo == NULL) {
            OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] not able to find any address to bind\n"));
            _eXosip_freeaddrinfo(oc_addrinfo);
            break;
          }

          res = bind(sock, (const struct sockaddr *) oc_curinfo->ai_addr, (socklen_t) oc_curinfo->ai_addrlen);

          if (res < 0) {
            OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] [new] cannot bind socket [%s] family:%d (port=%i) %s\n", excontext->oc_local_address, curinfo->ai_addr->sa_family, excontext->oc_local_port_current,
                                  _ex_strerror(ex_errno, eb, ERRBSIZ)));
            count++;

            if (excontext->oc_local_port_range[0] != 0)
              excontext->oc_local_port_current++;

            continue;
          }

          _eXosip_freeaddrinfo(oc_addrinfo);

          if (excontext->oc_local_port_range[0] != 0)
            excontext->oc_local_port_current++;

          break;
        }
      }
    }

#if defined(HAVE_WINSOCK2_H)
    {
      unsigned long nonBlock = 1;
      int val;

      ioctlsocket(sock, FIONBIO, &nonBlock);

      val = 1;

      if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *) &val, sizeof(val)) == -1) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] cannot set socket SO_KEEPALIVE\n"));
      }
    }
#ifdef HAVE_MSTCPIP_H
    {
      DWORD err = 0L;
      DWORD dwBytes = 0L;
      struct tcp_keepalive kalive = {0};
      struct tcp_keepalive kaliveOut = {0};
      kalive.onoff = 1;
      kalive.keepalivetime = 30000;    /* Keep Alive every 30 seconds */
      kalive.keepaliveinterval = 3000; /* Resend if No-Reply */
      err = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(kalive), &kaliveOut, sizeof(kaliveOut), &dwBytes, NULL, NULL);

      if (err != 0) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] [new] cannot set keepalive interval\n"));
      }
    }
#endif
#else
    {
      int val;

      val = fcntl(sock, F_GETFL);

      if (val < 0) {
        _eXosip_closesocket(sock);
        sock = -1;
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] cannot get socket flag\n"));
        continue;
      }

      val |= O_NONBLOCK;

      if (fcntl(sock, F_SETFL, val) < 0) {
        _eXosip_closesocket(sock);
        sock = -1;
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] cannot set socket flag\n"));
        continue;
      }

#if SO_KEEPALIVE
      val = 1;

      if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1) {
      }

#endif
#if 0
      val = 30;                 /* 30 sec before starting probes */
      setsockopt(sock, SOL_TCP, TCP_KEEPIDLE, &val, sizeof(val));
      val = 2;                  /* 2 probes max */
      setsockopt(sock, SOL_TCP, TCP_KEEPCNT, &val, sizeof(val));
      val = 10;                 /* 10 seconds between each probe */
      setsockopt(sock, SOL_TCP, TCP_KEEPINTVL, &val, sizeof(val));
#endif
#if SO_NOSIGPIPE
      val = 1;
      setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (void *) &val, sizeof(int));
#endif

#if TCP_NODELAY
      val = 1;

      if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &val, sizeof(int)) != 0) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] cannot set socket flag (TCP_NODELAY)\n"));
      }

#endif
    }
#endif
#if TCP_USER_TIMEOUT
    {
      int val = 9000;
      if (setsockopt(sock, IPPROTO_TCP, TCP_USER_TIMEOUT, &val, sizeof(val)) != 0) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] cannot set socket flag (TCP_USER_TIMEOUT)\n"));
      }
    }
#endif

    _eXosip_transport_set_dscp(excontext, curinfo->ai_family, sock);

    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] socket [%s] [sock=%d] family:%d\n", host, sock, curinfo->ai_family));
    res = connect(sock, curinfo->ai_addr, (socklen_t) curinfo->ai_addrlen);

    if (res < 0) {
      int valopt = ex_errno;

#if defined(HAVE_WINSOCK2_H)

      if (valopt != WSAEWOULDBLOCK) {
#else

      if (valopt != EINPROGRESS) {
#endif
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] cannot connect socket [%s] family:%d %s\n", host, curinfo->ai_family, _ex_strerror(valopt, eb, ERRBSIZ)));

        _eXosip_closesocket(sock);
        sock = -1;
        continue;

      } else {
        res = _tcptls_tl_is_connected(excontext->poll_method, sock);

        if (res > 0) {
          OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] socket [%s] [sock=%d] [pos=%d] family:%d, in progress\n", host, sock, pos, curinfo->ai_family));
          selected_ai_addrlen = (socklen_t) curinfo->ai_addrlen;
          memcpy(&selected_ai_addr, curinfo->ai_addr, sizeof(struct sockaddr));
          break;

        } else if (res == 0) {
#ifdef MULTITASKING_ENABLED
          reserved->socket_tab[pos].readStream = NULL;
          reserved->socket_tab[pos].writeStream = NULL;
          CFStreamCreatePairWithSocket(kCFAllocatorDefault, sock, &reserved->socket_tab[pos].readStream, &reserved->socket_tab[pos].writeStream);

          if (reserved->socket_tab[pos].readStream != NULL)
            CFReadStreamSetProperty(reserved->socket_tab[pos].readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);

          if (reserved->socket_tab[pos].writeStream != NULL)
            CFWriteStreamSetProperty(reserved->socket_tab[pos].writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);

          if (CFReadStreamOpen(reserved->socket_tab[pos].readStream)) {
            OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] CFReadStreamOpen Succeeded\n"));
          }

          CFWriteStreamOpen(reserved->socket_tab[pos].writeStream);
#endif
          OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] socket [%s] [sock=%d] [pos=%d] family:%d, connected\n", host, sock, pos, curinfo->ai_family));
          selected_ai_addrlen = 0;
          memcpy(&selected_ai_addr, curinfo->ai_addr, sizeof(struct sockaddr));
          ssl_state = 1;
          break;

        } else {
          _eXosip_closesocket(sock);
          sock = -1;
          continue;
        }
      }
    }

    break;
  }

  _eXosip_freeaddrinfo(addrinfo);

  if (sock > 0) {
    reserved->socket_tab[pos].socket = sock;

    reserved->socket_tab[pos].ai_addrlen = selected_ai_addrlen;
    memset(&reserved->socket_tab[pos].ai_addr, 0, sizeof(struct sockaddr));

    if (selected_ai_addrlen > 0)
      memcpy(&reserved->socket_tab[pos].ai_addr, &selected_ai_addr, selected_ai_addrlen);

    if (src6host[0] == '\0')
      osip_strncpy(reserved->socket_tab[pos].remote_ip, host, sizeof(reserved->socket_tab[pos].remote_ip) - 1);

    else
      osip_strncpy(reserved->socket_tab[pos].remote_ip, src6host, sizeof(reserved->socket_tab[pos].remote_ip) - 1);

    reserved->socket_tab[pos].remote_port = port;
    reserved->socket_tab[pos].ssl_conn = NULL;
    reserved->socket_tab[pos].ssl_state = ssl_state;
    reserved->socket_tab[pos].ssl_ctx = NULL;

    /* sni should be set to the domain portion of the "Application Unique String (AUS)" */
    /* Usually, this should end up being the domain of the "From" header (but if a Route is set in exosip, it will be the domain from the Route) */
    /* this code prevents Man-In-The-Middle Attack where the attacker is modifying the NAPTR result to route the request somewhere else */
    if (sni_servernameindication != NULL)
      osip_strncpy(reserved->socket_tab[pos].sni_servernameindication, sni_servernameindication, sizeof(reserved->socket_tab[pos].sni_servernameindication) - 1);

    else
      osip_strncpy(reserved->socket_tab[pos].sni_servernameindication, host, sizeof(reserved->socket_tab[pos].sni_servernameindication) - 1);

    {
      struct sockaddr_storage local_ai_addr;
      socklen_t selected_ai_addrlen;

      memset(&local_ai_addr, 0, sizeof(struct sockaddr_storage));
      selected_ai_addrlen = sizeof(struct sockaddr_storage);
      res = getsockname(sock, (struct sockaddr *) &local_ai_addr, &selected_ai_addrlen);

      if (res == 0) {
        if (local_ai_addr.ss_family == AF_INET)
          reserved->socket_tab[pos].ephemeral_port = ntohs(((struct sockaddr_in *) &local_ai_addr)->sin_port);

        else
          reserved->socket_tab[pos].ephemeral_port = ntohs(((struct sockaddr_in6 *) &local_ai_addr)->sin6_port);

        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [new] outgoing socket created on port [%i]\n", reserved->socket_tab[pos].ephemeral_port));
      }
    }

    reserved->socket_tab[pos].tcp_inprogress_max_timeout = osip_getsystemtime(NULL) + 32;

#ifdef HAVE_SYS_EPOLL_H

    if (excontext->poll_method == EXOSIP_USE_EPOLL_LT) {
      struct epoll_event ev;

      memset(&ev, 0, sizeof(struct epoll_event));

      if (reserved->socket_tab[pos].ssl_state == 1)
        ev.events = EPOLLIN;

      else
        ev.events = EPOLLIN | EPOLLOUT;

      ev.data.fd = sock;
      res = epoll_ctl(excontext->epfd, EPOLL_CTL_ADD, sock, &ev);

      if (res < 0) {
        _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
        return -1;
      }
    }

#endif

    return pos;
  }

  return -1;
}

static int _tls_tl_send(struct eXosip_t *excontext, SSL *ssl, const char *message, int length) {
  int i = 0;

  while (length > 0) {
    i = SSL_write(ssl, (const void *) message, (int) length);

    if (i <= 0) {
      i = SSL_get_error(ssl, i);

      if (i == SSL_ERROR_WANT_READ || i == SSL_ERROR_WANT_WRITE)
        continue;

      _tls_print_ssl_error(i);

      return -1;
    }

    length = length - i;
    message += i;
  }

  return OSIP_SUCCESS;
}

static int _tls_tl_update_contact(struct eXosip_t *excontext, osip_message_t *req, char *natted_ip, int natted_port) {
  if (req->application_data != (void *) 0x1)
    return OSIP_SUCCESS;

  if ((natted_ip != NULL && natted_ip[0] != '\0') || natted_port > 0) {
    osip_list_iterator_t it;
    osip_contact_t *co = (osip_contact_t *) osip_list_get_first(&req->contacts, &it);

    while (co != NULL) {
      if (co != NULL && co->url != NULL && co->url->host != NULL) {
        if (natted_port > 0) {
          if (co->url->port)
            osip_free(co->url->port);

          co->url->port = (char *) osip_malloc(10);
          snprintf(co->url->port, 9, "%i", natted_port);
          osip_message_force_update(req);
        }

        if (natted_ip != NULL && natted_ip[0] != '\0') {
          osip_free(co->url->host);
          co->url->host = osip_strdup(natted_ip);
          osip_message_force_update(req);
        }
      }

      co = (osip_contact_t *) osip_list_get_next(&it);
    }
  }

  return OSIP_SUCCESS;
}

static int _tls_tl_build_message(struct eXosip_t *excontext, osip_message_t *sip, int pos, char *host, char **message, size_t *length) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int i;

  _eXosip_request_viamanager(excontext, sip, reserved->socket_tab[pos].ai_addr.sa_family, IPPROTO_TCP, NULL, reserved->socket_tab[pos].ephemeral_port, reserved->socket_tab[pos].socket, host);

  if (excontext->use_ephemeral_port == 1)
    _eXosip_message_contactmanager(excontext, sip, reserved->socket_tab[pos].ai_addr.sa_family, IPPROTO_TCP, NULL, reserved->socket_tab[pos].ephemeral_port, reserved->socket_tab[pos].socket, host);

  else
    _eXosip_message_contactmanager(excontext, sip, reserved->socket_tab[pos].ai_addr.sa_family, IPPROTO_TCP, NULL, excontext->eXtl_transport.proto_local_port, reserved->socket_tab[pos].socket, host);

  if (excontext->tls_firewall_ip[0] != '\0' || excontext->auto_masquerade_contact > 0)
    _tls_tl_update_contact(excontext, sip, reserved->socket_tab[pos].natted_ip, reserved->socket_tab[pos].natted_port);

  /* remove preloaded route if there is no tag in the To header
   */
  {
    osip_route_t *route = NULL;
    osip_generic_param_t *tag = NULL;

    if (excontext->remove_prerouteset > 0) {
      osip_message_get_route(sip, 0, &route);
      osip_to_get_tag(sip->to, &tag);

      if (tag == NULL && route != NULL && route->url != NULL) {
        osip_list_remove(&sip->routes, 0);
        osip_message_force_update(sip);
      }
    }

    i = osip_message_to_str(sip, message, length);

    if (tag == NULL && route != NULL && route->url != NULL) {
      osip_list_add(&sip->routes, route, 0);
    }
  }
  return i;
}

static int tls_tl_send_message(struct eXosip_t *excontext, osip_transaction_t *tr, osip_message_t *sip, char *host, int port, int out_socket) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  size_t length = 0;
  char *message;
  int i;

  int pos;
  osip_naptr_t *naptr_record = NULL;

  SSL *ssl = NULL;
  int tid = -1;

  if (tr != NULL)
    tid = tr->transactionid;

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] [tid=%i] wrong state: create transport layer first\n", tid));
    return OSIP_WRONG_STATE;
  }

  if (host == NULL) {
    host = sip->req_uri->host;

    if (sip->req_uri->port != NULL)
      port = osip_atoi(sip->req_uri->port);

    else
      port = 5061;
  }

  if (port == 5060)
    port = 5061;

  i = _tl_resolv_naptr_destination(excontext, tr, sip, &host, &port, &naptr_record);
  if (i == OSIP_SUCCESS + 1)
    return i;
  if (i < OSIP_SUCCESS)
    return i;

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    if (reserved->socket_tab[pos].invalid > 0) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] [send] socket info:[%s][%d] [sock=%d] [pos=%d] manual reset\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port,
                            reserved->socket_tab[pos].socket, pos));
      _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
      _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
      continue;
    }
  }

  if (out_socket > 0) {
    for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
      if (reserved->socket_tab[pos].socket != 0) {
        if (reserved->socket_tab[pos].socket == out_socket) {
          out_socket = reserved->socket_tab[pos].socket;
          ssl = reserved->socket_tab[pos].ssl_conn;
          OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] [tid=%i] reusing REQUEST connection to [%s][%d]\n", tid, reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port));
          break;
        }
      }
    }

    if (pos == EXOSIP_MAX_SOCKETS) {
      out_socket = 0;
      if (tr != NULL)
        osip_transaction_set_out_socket(tr, 0);
    }

    if (out_socket > 0) {
      int pos2;

      /* If we have SEVERAL sockets to same destination with different port
         number, we search for the one with "SAME port" number.
         The specification is not clear about re-using the existing transaction
         in that use-case...
         Such test, will help mainly with server having 2 sockets: one for
         incoming transaction and one for outgoing transaction?
       */
      pos2 = _tls_tl_find_socket(excontext, host, port);

      if (pos2 >= 0) {
        out_socket = reserved->socket_tab[pos2].socket;
        pos = pos2;
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] [tid=%i] reusing connection --with exact port-- to [%s][%d]\n", tid, reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port));
        if (tr != NULL)
          osip_transaction_set_out_socket(tr, out_socket);
      }
    }
  }

  /* Step 1: find existing socket to send message */
  if (out_socket <= 0) {
    pos = _tls_tl_find_socket(excontext, host, port);

    /* Step 2: create new socket with host:port */
    if (pos < 0) {
      const char *sni = NULL;

      if (naptr_record != NULL) {
        sni = naptr_record->domain;
      }
      if (sni == NULL) {
        /* when connection is failing, there are some messages that are routed with IP instead of the DNS name */
        /* for example: ACK out of transaction, message in-dialog (BYE, re-INVITE...), or answers. */
        /* in order to establish a TLS connection, we REQUIRE the SNI verification, and thus, require the domain name */
        /* unfortunatly, there is still some issue with selecting the "domain name" or the "sip server domain name" (before/after NAPTR) */

        /* first lookup for a DNS name for our IP target in the cache */
        for (i = 0; i < MAX_EXOSIP_DNS_ENTRY; i++) {
          if (excontext->dns_entries[i].host[0] != '\0' && 0 == osip_strcasecmp(excontext->dns_entries[i].ip, host)) {
            /* update entry */
            sni = excontext->dns_entries[i].host;
            break;
          }
        }

        /* then, lookup for a "domain" in an NAPTR cache result */
        if (sni != NULL) {
          const char *domain = _eXosip_dnsutils_find_sni(excontext, sni);
          if (domain != NULL)
            sni = domain;
        }
      }

      if (tr == NULL) {
        pos = _tls_tl_new_socket(excontext, host, port, 0, sni);
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] [tid=%i] message out of transaction: trying to send to [%s][%d]\n", tid, host, port));

        if (pos < 0) {
          return -1;
        }

      } else {
        pos = _tls_tl_new_socket(excontext, host, port, 0, sni);

        if (pos < 0) {
          if (MSG_IS_REGISTER(sip) || MSG_IS_OPTIONS(sip)) {
            /* reg_call_id is not set! */
            _eXosip_mark_registration_expired(excontext, sip->call_id->number);
          }

          if (tr != NULL)
            osip_transaction_set_out_socket(tr, 0);
          return -1;
        }
      }
    }

    if (pos >= 0) {
      out_socket = reserved->socket_tab[pos].socket;
      ssl = reserved->socket_tab[pos].ssl_conn;
      if (tr != NULL)
        osip_transaction_set_out_socket(tr, out_socket);
    }
  }

  if (out_socket <= 0) {
    if (naptr_record != NULL && MSG_IS_REGISTER(sip)) {
      /* reg_call_id is not set! */
      _eXosip_mark_registration_expired(excontext, sip->call_id->number);
    }

    if (tr != NULL)
      osip_transaction_set_out_socket(tr, 0);
    return -1;
  }

  if (MSG_IS_REGISTER(sip)) {
    /* this value is saved: when a connection breaks, we will ask to retry the registration */
    snprintf(reserved->socket_tab[pos].reg_call_id, sizeof(reserved->socket_tab[pos].reg_call_id), "%s", sip->call_id->number);
  }

  if (reserved->socket_tab[pos].ssl_state < 3) {
    time_t now;

    if (tr != NULL) {
      now = osip_getsystemtime(NULL);

      if (tr != NULL && now - tr->birth_time > 10) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [tid=%i] socket [%s] [sock=%d] [pos=%d] timeout\n", tid, host, out_socket, pos));
        _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
        if (naptr_record != NULL && (MSG_IS_REGISTER(sip) || MSG_IS_OPTIONS(sip))) {
          if (pos >= 0)
            _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
        }

        if (tr != NULL)
          osip_transaction_set_out_socket(tr, 0);
        return -1;
      }
    }
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [tid=%i] socket [%s] [sock=%d] [pos=%d] not yet ready\n", tid, host, out_socket, pos));

    if (tr == NULL) {
      /* a connection was probably broken: we tried to send a message without transaction, but it failed */
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] [tid=%i] a connection is missing for to [%s][%d]\n", tid, host, port));
      _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);

      i = _tls_tl_build_message(excontext, sip, pos, host, &message, &length);

      if (i != 0 || length <= 0) {
        osip_free(message);
        return -1;
      }
      if (reserved->socket_tab[pos].sendbuflen + length + 1 > reserved->socket_tab[pos].sendbufsize) {
        reserved->socket_tab[pos].sendbuf = osip_realloc(reserved->socket_tab[pos].sendbuf, reserved->socket_tab[pos].sendbuflen + length + 1);
        reserved->socket_tab[pos].sendbufsize = reserved->socket_tab[pos].sendbuflen + length + 1;
      }
      memcpy(reserved->socket_tab[pos].sendbuf + reserved->socket_tab[pos].sendbuflen, message, length + 1); /* also memcpy extra \0 */
      reserved->socket_tab[pos].sendbuflen = reserved->socket_tab[pos].sendbuflen + length;

      osip_free(message);
    }
    return 1;
  }

  ssl = reserved->socket_tab[pos].ssl_conn;

  if (ssl == NULL) {
    if (tr != NULL)
      osip_transaction_set_out_socket(tr, 0);
    return -1;
  }

#ifdef MULTITASKING_ENABLED

  if (reserved->socket_tab[pos].readStream == NULL) {
    reserved->socket_tab[pos].readStream = NULL;
    reserved->socket_tab[pos].writeStream = NULL;
    CFStreamCreatePairWithSocket(kCFAllocatorDefault, reserved->socket_tab[pos].socket, &reserved->socket_tab[pos].readStream, &reserved->socket_tab[pos].writeStream);

    if (reserved->socket_tab[pos].readStream != NULL)
      CFReadStreamSetProperty(reserved->socket_tab[pos].readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);

    if (reserved->socket_tab[pos].writeStream != NULL)
      CFWriteStreamSetProperty(reserved->socket_tab[pos].writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);

    if (CFReadStreamOpen(reserved->socket_tab[pos].readStream)) {
      OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [tid=%i] CFReadStreamOpen Succeeded\n", tid));
    }

    CFWriteStreamOpen(reserved->socket_tab[pos].writeStream);
  }

#endif

  i = _tls_tl_build_message(excontext, sip, pos, host, &message, &length);

  if (i != 0 || length <= 0) {
    if (tr != NULL)
      osip_transaction_set_out_socket(tr, 0);
    return -1;
  }

  OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO1, NULL, "[eXosip] [TLS] [tid=%i] message sent [len=%d] to [%s][%d]\n%s\n", tid, length, host, port, message));

  if (pos >= 0 && excontext->enable_dns_cache == 1 && osip_strcasecmp(host, reserved->socket_tab[pos].remote_ip) != 0 && MSG_IS_REQUEST(sip)) {
    if (MSG_IS_REGISTER(sip)) {
      struct eXosip_dns_cache entry;

      memset(&entry, 0, sizeof(struct eXosip_dns_cache));
      snprintf(entry.host, sizeof(entry.host), "%s", host);
      snprintf(entry.ip, sizeof(entry.ip), "%s", reserved->socket_tab[pos].remote_ip);
      eXosip_set_option(excontext, EXOSIP_OPT_ADD_DNS_CACHE, (void *) &entry);
    }
  }

  i = _tls_tl_send(excontext, ssl, (const char *) message, (int) length);

  if (i < 0) {
    if (pos >= 0) {
      _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
      _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
    }
    if (tr != NULL)
      osip_transaction_set_out_socket(tr, 0);
  }

  if (i == 0 && tr != NULL && MSG_IS_REGISTER(sip) && pos >= 0) {
    /* start a timeout to destroy connection if no answer */
    reserved->socket_tab[pos].tcp_max_timeout = osip_getsystemtime(NULL) + 32;
  }

  osip_free(message);
  return OSIP_SUCCESS;
}

static int tls_tl_keepalive(struct eXosip_t *excontext) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  char buf[5] = "\r\n\r\n";
  int pos;
  int i;

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] wrong state: create transport layer first\n"));
    return OSIP_WRONG_STATE;
  }

  if (reserved->tls_socket <= 0)
    return OSIP_UNDEFINED_ERROR;

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    if (excontext->ka_interval > 0) {
      if (reserved->socket_tab[pos].socket > 0 && reserved->socket_tab[pos].ssl_state > 2) {
        // SSL_set_mode(reserved->socket_tab[pos].ssl_conn, SSL_MODE_AUTO_RETRY);

        while (1) {
          i = SSL_write(reserved->socket_tab[pos].ssl_conn, (const void *) buf, 4);

          if (i <= 0) {
            i = SSL_get_error(reserved->socket_tab[pos].ssl_conn, i);

            if (i == SSL_ERROR_WANT_READ || i == SSL_ERROR_WANT_WRITE)
              continue;

            _tls_print_ssl_error(i);
          }

          reserved->socket_tab[pos].ping_rfc5626 = osip_getsystemtime(NULL) + 9;
          OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_WARNING, NULL, "[eXosip] [TLS] [keepalive] [ret=%i] socket [%s] [sock=%d] [pos=%d]\n", i, reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].socket, pos));
          break;
        }
      }
    }
  }

  return OSIP_SUCCESS;
}

static int tls_tl_set_socket(struct eXosip_t *excontext, int socket) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] wrong state: create transport layer first\n"));
    return OSIP_WRONG_STATE;
  }

  reserved->tls_socket = socket;

  return OSIP_SUCCESS;
}

static int tls_tl_masquerade_contact(struct eXosip_t *excontext, const char *public_address, int port) {
  if (public_address == NULL || public_address[0] == '\0') {
    memset(excontext->tls_firewall_ip, '\0', sizeof(excontext->tls_firewall_ip));
    memset(excontext->tls_firewall_port, '\0', sizeof(excontext->tls_firewall_port));
    return OSIP_SUCCESS;
  }

  snprintf(excontext->tls_firewall_ip, sizeof(excontext->tls_firewall_ip), "%s", public_address);

  if (port > 0) {
    snprintf(excontext->tls_firewall_port, sizeof(excontext->tls_firewall_port), "%i", port);
  }

  return OSIP_SUCCESS;
}

static int tls_tl_get_masquerade_contact(struct eXosip_t *excontext, char *ip, int ip_size, char *port, int port_size) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;

  memset(ip, 0, ip_size);
  memset(port, 0, port_size);

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] wrong state: create transport layer first\n"));
    return OSIP_WRONG_STATE;
  }

  if (excontext->tls_firewall_ip[0] != '\0')
    snprintf(ip, ip_size, "%s", excontext->tls_firewall_ip);

  if (excontext->tls_firewall_port[0] != '\0')
    snprintf(port, port_size, "%s", excontext->tls_firewall_port);

  return OSIP_SUCCESS;
}

static int tls_tl_update_contact(struct eXosip_t *excontext, osip_message_t *req) {
  req->application_data = (void *) 0x1; /* request for masquerading */
  return OSIP_SUCCESS;
}

static int tls_tl_check_all_connection(struct eXosip_t *excontext) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int pos;
  int i;

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] wrong state: create transport layer first\n"));
    return OSIP_WRONG_STATE;
  }

  if (reserved->tls_socket <= 0)
    return OSIP_UNDEFINED_ERROR;

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    if (reserved->socket_tab[pos].socket > 0) {
      i = _tcptls_tl_is_connected(excontext->poll_method, reserved->socket_tab[pos].socket);

      if (i > 0) {
        if (reserved->socket_tab[pos].socket > 0 && reserved->socket_tab[pos].tcp_inprogress_max_timeout > 0) {
          time_t now = osip_getsystemtime(NULL);

          if (now > reserved->socket_tab[pos].tcp_inprogress_max_timeout) {
            OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [checkall] socket is in progress since 32 seconds / close socket\n"));
            reserved->socket_tab[pos].tcp_inprogress_max_timeout = 0;
            _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
            _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
            continue;
          }
        }

        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [checkall] socket info:[%s][%d] [sock=%d] [pos=%d] in progress\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port,
                              reserved->socket_tab[pos].socket, pos));
        continue;

      } else if (i == 0) {
#ifdef HAVE_SYS_EPOLL_H
        if (excontext->poll_method == EXOSIP_USE_EPOLL_LT && reserved->socket_tab[pos].tcp_inprogress_max_timeout > 0) {
          struct epoll_event ev;
          /* no need for EPOLLOUT anymore */
          memset(&ev, 0, sizeof(struct epoll_event));
          ev.events = EPOLLIN;
          ev.data.fd = reserved->socket_tab[pos].socket;
          epoll_ctl(excontext->epfd, EPOLL_CTL_MOD, reserved->socket_tab[pos].socket, &ev);
        }
#endif

        reserved->socket_tab[pos].tcp_inprogress_max_timeout = 0; /* reset value */

        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [checkall] socket info:[%s][%d] [sock=%d] [pos=%d] connected\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port,
                              reserved->socket_tab[pos].socket, pos));

        if (reserved->socket_tab[pos].socket > 0 && reserved->socket_tab[pos].ssl_state > 2 && reserved->socket_tab[pos].tcp_max_timeout > 0) {
          time_t now = osip_getsystemtime(NULL);

          if (now > reserved->socket_tab[pos].tcp_max_timeout) {
            OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [checkall] we expected a reply on established sockets / close socket\n"));
            reserved->socket_tab[pos].tcp_max_timeout = 0;
            _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
            _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
            continue;
          }
        }

        if (reserved->socket_tab[pos].ssl_state == 0 || reserved->socket_tab[pos].ssl_state == 1) { /* TCP connected but not TLS connected */
          reserved->socket_tab[pos].ssl_state = 1;
          i = _tls_tl_ssl_connect_socket(excontext, &reserved->socket_tab[pos]);

          if (i < 0) {
            _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
            _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
            continue;

          } else if (i > 0) {
            OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [checkall] socket info:[%s][%d] [sock=%d] [pos=%d] connected (ssl in progress)\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port,
                                  reserved->socket_tab[pos].socket, pos));
            continue;
          }
        }

        if (reserved->socket_tab[pos].ping_rfc5626 > 0 && reserved->socket_tab[pos].pong_supported > 0) {
          time_t now = osip_getsystemtime(NULL);

          if (now > reserved->socket_tab[pos].ping_rfc5626) {
            OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TCP] [checkall] no pong[CRLF] for ping[CRLFCRLF]\n"));
            reserved->socket_tab[pos].tcp_max_timeout = 0;
            _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
            _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
            continue;
          }
        }

        continue;

      } else {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] [checkall] socket info:[%s][%d] [sock=%d] [pos=%d] error\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port,
                              reserved->socket_tab[pos].socket, pos));
        _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
        _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
        continue;
      }
    }
  }

  return OSIP_SUCCESS;
}

static int tls_tl_check_connection(struct eXosip_t *excontext, int socket) {
  struct eXtltls *reserved = (struct eXtltls *) excontext->eXtltls_reserved;
  int pos;
  int i;

  if (reserved == NULL) {
    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] wrong state: create transport layer first\n"));
    return OSIP_WRONG_STATE;
  }

  if (reserved->tls_socket <= 0)
    return OSIP_UNDEFINED_ERROR;

  if (socket == -1) {
    return tls_tl_check_all_connection(excontext);
  }

  for (pos = 0; pos < EXOSIP_MAX_SOCKETS; pos++) {
    if (reserved->socket_tab[pos].socket == socket)
      break;
  }

  if (pos == EXOSIP_MAX_SOCKETS)
    return OSIP_NOTFOUND;

  i = _tcptls_tl_is_connected(excontext->poll_method, reserved->socket_tab[pos].socket);

  if (i > 0) {
    if (reserved->socket_tab[pos].socket > 0 && reserved->socket_tab[pos].tcp_inprogress_max_timeout > 0) {
      time_t now = osip_getsystemtime(NULL);

      if (now > reserved->socket_tab[pos].tcp_inprogress_max_timeout) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [check] socket is in progress since 32 seconds / close socket\n"));
        reserved->socket_tab[pos].tcp_inprogress_max_timeout = 0;
        _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
        _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
        return OSIP_SUCCESS;
      }
    }

    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [check] socket info:[%s][%d] [sock=%d] [pos=%d] in progress\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port,
                          reserved->socket_tab[pos].socket, pos));
    return OSIP_SUCCESS;

  } else if (i == 0) {
#ifdef HAVE_SYS_EPOLL_H
    if (excontext->poll_method == EXOSIP_USE_EPOLL_LT && reserved->socket_tab[pos].tcp_inprogress_max_timeout > 0) {
      struct epoll_event ev;
      /* no need for EPOLLOUT anymore */
      memset(&ev, 0, sizeof(struct epoll_event));
      ev.events = EPOLLIN;
      ev.data.fd = reserved->socket_tab[pos].socket;
      epoll_ctl(excontext->epfd, EPOLL_CTL_MOD, reserved->socket_tab[pos].socket, &ev);
    }
#endif

    reserved->socket_tab[pos].tcp_inprogress_max_timeout = 0; /* reset value */

    OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [check] socket info:[%s][%d] [sock=%d] [pos=%d] connected\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port,
                          reserved->socket_tab[pos].socket, pos));

    if (reserved->socket_tab[pos].socket > 0 && reserved->socket_tab[pos].ssl_state > 2 && reserved->socket_tab[pos].tcp_max_timeout > 0) {
      time_t now = osip_getsystemtime(NULL);

      if (now > reserved->socket_tab[pos].tcp_max_timeout) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [check] we expected a reply on established sockets / close socket\n"));
        reserved->socket_tab[pos].tcp_max_timeout = 0;
        _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
        _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
        return OSIP_SUCCESS;
      }
    }

    if (reserved->socket_tab[pos].ssl_state == 0 || reserved->socket_tab[pos].ssl_state == 1) { /* TCP connected but not TLS connected */
      reserved->socket_tab[pos].ssl_state = 1;
      i = _tls_tl_ssl_connect_socket(excontext, &reserved->socket_tab[pos]);

      if (i < 0) {
        _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
        _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
        return -1;

      } else if (i > 0) {
        OSIP_TRACE(osip_trace(__FILE__, __LINE__, OSIP_INFO2, NULL, "[eXosip] [TLS] [check] socket info:[%s][%d] [sock=%d] [pos=%d] connected (ssl in progress)\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port,
                              reserved->socket_tab[pos].socket, pos));
        return 1;
      }
    }

    return OSIP_SUCCESS;

  } else {
    OSIP_TRACE(
        osip_trace(__FILE__, __LINE__, OSIP_ERROR, NULL, "[eXosip] [TLS] [check] socket info:[%s][%d] [sock=%d] [pos=%d] error\n", reserved->socket_tab[pos].remote_ip, reserved->socket_tab[pos].remote_port, reserved->socket_tab[pos].socket, pos));
    _eXosip_mark_registration_expired(excontext, reserved->socket_tab[pos].reg_call_id);
    _tls_tl_close_sockinfo(excontext, &reserved->socket_tab[pos]);
    return OSIP_SUCCESS;
  }

  return OSIP_SUCCESS;
}

static struct eXtl_protocol eXtl_tls = {1,
                                        5061,
                                        "TLS",
                                        "0.0.0.0",
                                        IPPROTO_TCP,
                                        AF_INET,
                                        0,
                                        0,
                                        0,

                                        &tls_tl_init,
                                        &tls_tl_free,
                                        &tls_tl_open,
                                        &tls_tl_set_fdset,
                                        &tls_tl_read_message,
#ifdef HAVE_SYS_EPOLL_H
                                        &tls_tl_epoll_read_message,
#endif
                                        &tls_tl_send_message,
                                        &tls_tl_keepalive,
                                        &tls_tl_set_socket,
                                        &tls_tl_masquerade_contact,
                                        &tls_tl_get_masquerade_contact,
                                        &tls_tl_update_contact,
                                        &tls_tl_reset,
                                        &tls_tl_check_connection};

void eXosip_transport_tls_init(struct eXosip_t *excontext) {
  memcpy(&excontext->eXtl_transport, &eXtl_tls, sizeof(struct eXtl_protocol));
}

#else

eXosip_tls_ctx_error eXosip_tls_verify_certificate(struct eXosip_t* excontext, int _tls_verify_client_certificate) {
  return -1; /* NOT IMPLEMENTED */
}

eXosip_tls_ctx_error eXosip_set_tls_ctx(struct eXosip_t* excontext, eXosip_tls_ctx_t* ctx) {
  return -1; /* NOT IMPLEMENTED */
}

#endif

/**
  Various explanation on using openssl with eXosip2. (Written on June 26, 2018)

  First, you should understand that it is unlikely that you need to configure
  the "server" side of eXosip. eXosip2 is a User-Agent and will receive in 99%
  of use-case incoming message on "client initiated connection". It should even
  be in 100% of use-case. Thus, I advise you to compile eXosip2 without
  #define ENABLE_MAIN_SOCKET. This will prevent people connecting to your User-Agent
  via unsecured TLS connection. I also don't maintain this server side socket code
  security, so if you want to use it, you should really make sure you do things
  correctly. (may be with code modifications?)

  CAUTIOUS: Please understand that if you use an old version of openssl, we will get unsecure
  cipher, vulnerabilities, etc...
  Configuration of client side sockets:

1/ default configuration.
   By default, eXosip2 will load certificates from WINDOWS STORE on WINDOWS ONLY.
   By default, eXosip2 will load certificates from MACOSX STORE on MACOSX ONLY.
   By default, eXosip2 won't verify certificates

2/ on WINDOWS and MACOSX, to enable certificate verification:
   int optval = 1;
   eXosip_set_option (exosip_context, EXOSIP_OPT_SET_TLS_VERIFY_CERTIFICATE, &optval);

3/ on OTHER platforms, you need to add either ONE or a full list of ROOT CERTIFICATES
   and configure to require certificate verification:

   Google is providing a file containing a list of known trusted root certificates. This
   is the easiest way you can retreive an up-to-date file.
   https://pki.google.com/roots.pem
   SIDENOTE: you need to download this file REGULARLY. Because some of the root certificates may
   be revoked.

   eXosip_tls_ctx_t _tls_description;
   memset(&_tls_description, 0, sizeof(eXosip_tls_ctx_t));
   snprintf(_tls_description.root_ca_cert, sizeof(_tls_description.root_ca_cert), "%s", "roots.pem");
   eXosip_set_option(exosip_context, EXOSIP_OPT_SET_TLS_CERTIFICATES_INFO, (void*)&_tls_description);

   int optval = 1;
   eXosip_set_option (exosip_context, EXOSIP_OPT_SET_TLS_VERIFY_CERTIFICATE, &optval);

4/ If your service(server) request a client certificate from you, you will need to configure one
   by configuring your certificate, private key and password.

   eXosip_tls_ctx_t _tls_description;
   memset(&_tls_description, 0, sizeof(eXosip_tls_ctx_t));
   snprintf(_tls_description.root_ca_cert, sizeof(_tls_description.root_ca_cert), "%s", "roots.pem");

   snprintf(_tls_description.client.priv_key_pw, sizeof(_tls_description.client.priv_key_pw), "%s", "hello");
   snprintf(_tls_description.client.priv_key, sizeof(_tls_description.client.priv_key), "%s", "selfsigned-key.pem");
   snprintf(_tls_description.client.cert, sizeof(_tls_description.client.cert), "%s", "selfsigned-cert.pem");

   eXosip_set_option(exosip_context, EXOSIP_OPT_SET_TLS_CERTIFICATES_INFO, (void*)&_tls_description);

5/ Today, I have removed the ability to use a client certificate from windows store: the feature was limited
   to RSA with SHA1 which is never negociated if you wish to have correct security. This makes the feature obsolete
   and mostly not working. So... just removed. EXOSIP_OPT_SET_TLS_CLIENT_CERTIFICATE_NAME
   and EXOSIP_OPT_SET_TLS_SERVER_CERTIFICATE_NAME have been kept, but returns -1 only.

6/ A recent feature has been introduced: Certificate pinning.

   In order to get your public key file in DER format, which is required for eXosip2 code, you
   can use the following command line to retreive the publickey from your certificate and encode
   it into base64:

   $> openssl x509 -in your-base64-certificate.pem -pubkey -noout | openssl enc -base64 -d > publickey.der

   In order to activate the check, you need to configure the "public_key_pinned" parameter:

   eXosip_tls_ctx_t _tls_description;
   memset(&_tls_description, 0, sizeof(eXosip_tls_ctx_t));
   snprintf(_tls_description.root_ca_cert, sizeof(_tls_description.root_ca_cert), "%s", "roots.pem");

   snprintf(_tls_description.client.priv_key_pw, sizeof(_tls_description.client.priv_key_pw), "%s", "hello");
   snprintf(_tls_description.client.priv_key, sizeof(_tls_description.client.priv_key), "%s", "selfsigned-key.pem");
   snprintf(_tls_description.client.cert, sizeof(_tls_description.client.cert), "%s", "selfsigned-cert.pem");

   snprintf(_tls_description.client.cert, sizeof(_tls_description.client.public_key_pinned), "%s", "pub_key.der");

   eXosip_set_option(exosip_context, EXOSIP_OPT_SET_TLS_CERTIFICATES_INFO, (void*)&_tls_description);

7/ Depending on the openssl version you use, you will NOT have the same behavior and features.
   I advise you to use the LATEST openssl version. This is for security purpose (openssl vulnerabilities)
   as well as to use the latest secured cipher list.

   There are other features only enabled or disabled with recent versions of openssl. Among them:
   * SNI server verification: v1.0.2 -> OPENSSL_VERSION_NUMBER >= 0x10002000L
   * RSA is removed since v1.1.0 OPENSSL_VERSION_NUMBER < 0x10100000L
   * ECDHE based cipher suites faster than DHE since 1.0.0 OPENSSL_VERSION_NUMBER > 0x10000000L
   * ...

   If your app accept old/deprecated/unsecure ciphers, please: update your openssl version. If you
   have no choice, you can update the internal code to specify, or remove ciphers. The default in
   eXosip is always the "HIGH:-COMPLEMENTOFDEFAULT" which is expected to be the most secure configuration
   known by openssl upon releasing the openssl version.

     SSL_CTX_set_cipher_list (ctx, "HIGH:-COMPLEMENTOFDEFAULT")

  SIDEINFO for testing purpose: If you wish to test client certifiate with
  kamailio, here is a possible configuration on a specific port number. The
  ca_list contains the selfsigned certificate that is configured on client
  side in eXosip2. (server-key and server-certificate are the server side info)

  [server:91.121.30.149:29091]
  method = TLSv1+
  verify_certificate = no
  require_certificate = yes
  private_key = /etc/kamailio/server-key.key
  certificate = /etc/kamailio/server-certificate.pem
  ca_list = /etc/kamailio/client-selfsigned-cert-aymeric.pem
  cipher_list = HIGH:-COMPLEMENTOFDEFAULT

  */