summaryrefslogtreecommitdiff
path: root/ext/openssl/xp_ssl.c
blob: fe7aeda06d67a88df1fde565cc2fbdd2022f2040 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
/*
  +----------------------------------------------------------------------+
  | PHP Version 7                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2017 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Authors: Wez Furlong <wez@thebrainroom.com>                          |
  |          Daniel Lowrey <rdlowrey@php.net>                            |
  |          Chris Wright <daverandom@php.net>                           |
  +----------------------------------------------------------------------+
*/

/* $Id$ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "ext/standard/file.h"
#include "ext/standard/url.h"
#include "streams/php_streams_int.h"
#include "zend_smart_str.h"
#include "php_openssl.h"
#include "php_network.h"
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>

#if OPENSSL_VERSION_NUMBER >= 0x10002000L
#include <openssl/bn.h>
#include <openssl/dh.h>
#endif

#ifdef PHP_WIN32
#include "win32/winutil.h"
#include "win32/time.h"
#include <Wincrypt.h>
/* These are from Wincrypt.h, they conflict with OpenSSL */
#undef X509_NAME
#undef X509_CERT_PAIR
#undef X509_EXTENSIONS
#endif

#ifndef OPENSSL_NO_SSL3
#define HAVE_SSL3 1
#endif

#define HAVE_TLS11 1
#define HAVE_TLS12 1

#ifndef OPENSSL_NO_ECDH
#define HAVE_ECDH 1
#endif

#ifndef OPENSSL_NO_TLSEXT
#define HAVE_TLS_SNI 1
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
#define HAVE_TLS_ALPN 1
#endif
#endif

#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
#define HAVE_SEC_LEVEL 1
#endif

/* Flags for determining allowed stream crypto methods */
#define STREAM_CRYPTO_IS_CLIENT            (1<<0)
#define STREAM_CRYPTO_METHOD_SSLv2         (1<<1)
#define STREAM_CRYPTO_METHOD_SSLv3         (1<<2)
#define STREAM_CRYPTO_METHOD_TLSv1_0       (1<<3)
#define STREAM_CRYPTO_METHOD_TLSv1_1       (1<<4)
#define STREAM_CRYPTO_METHOD_TLSv1_2       (1<<5)

/* Simplify ssl context option retrieval */
#define GET_VER_OPT(name) \
	(PHP_STREAM_CONTEXT(stream) && (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", name)) != NULL)
#define GET_VER_OPT_STRING(name, str) \
	if (GET_VER_OPT(name)) { convert_to_string_ex(val); str = Z_STRVAL_P(val); }
#define GET_VER_OPT_LONG(name, num) \
	if (GET_VER_OPT(name)) { convert_to_long_ex(val); num = Z_LVAL_P(val); }

/* Used for peer verification in windows */
#define PHP_X509_NAME_ENTRY_TO_UTF8(ne, i, out) \
	ASN1_STRING_to_UTF8(&out, X509_NAME_ENTRY_get_data(X509_NAME_get_entry(ne, i)))

#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined (LIBRESSL_VERSION_NUMBER)
static RSA *php_openssl_tmp_rsa_cb(SSL *s, int is_export, int keylength);
#endif

extern php_stream* php_openssl_get_stream_from_ssl_handle(const SSL *ssl);
extern zend_string* php_openssl_x509_fingerprint(X509 *peer, const char *method, zend_bool raw);
extern int php_openssl_get_ssl_stream_data_index();
extern int php_openssl_get_x509_list_id(void);
static struct timeval php_openssl_subtract_timeval(struct timeval a, struct timeval b);
static int php_openssl_compare_timeval(struct timeval a, struct timeval b);
static size_t php_openssl_sockop_io(int read, php_stream *stream, char *buf, size_t count);

php_stream_ops php_openssl_socket_ops;

/* Certificate contexts used for server-side SNI selection */
typedef struct _php_openssl_sni_cert_t {
	char *name;
	SSL_CTX *ctx;
} php_openssl_sni_cert_t;

/* Provides leaky bucket handhsake renegotiation rate-limiting  */
typedef struct _php_openssl_handshake_bucket_t {
	zend_long prev_handshake;
	zend_long limit;
	zend_long window;
	float tokens;
	unsigned should_close;
} php_openssl_handshake_bucket_t;

#ifdef HAVE_TLS_ALPN
/* Holds the available server ALPN protocols for negotiation */
typedef struct _php_openssl_alpn_ctx_t {
	unsigned char *data;
	unsigned short len;
} php_openssl_alpn_ctx;
#endif

/* This implementation is very closely tied to the that of the native
 * sockets implemented in the core.
 * Don't try this technique in other extensions!
 * */
typedef struct _php_openssl_netstream_data_t {
	php_netstream_data_t s;
	SSL *ssl_handle;
	SSL_CTX *ctx;
	struct timeval connect_timeout;
	int enable_on_connect;
	int is_client;
	int ssl_active;
	php_stream_xport_crypt_method_t method;
	php_openssl_handshake_bucket_t *reneg;
	php_openssl_sni_cert_t *sni_certs;
	unsigned sni_cert_count;
#ifdef HAVE_TLS_ALPN
	php_openssl_alpn_ctx alpn_ctx;
#endif
	char *url_name;
	unsigned state_set:1;
	unsigned _spare:31;
} php_openssl_netstream_data_t;

/* it doesn't matter that we do some hash traversal here, since it is done only
 * in an error condition arising from a network connection problem */
static int php_openssl_is_http_stream_talking_to_iis(php_stream *stream) /* {{{ */
{
	if (Z_TYPE(stream->wrapperdata) == IS_ARRAY &&
		stream->wrapper &&
		strcasecmp(stream->wrapper->wops->label, "HTTP") == 0
	) {
		/* the wrapperdata is an array zval containing the headers */
		zval *tmp;

#define SERVER_MICROSOFT_IIS	"Server: Microsoft-IIS"
#define SERVER_GOOGLE "Server: GFE/"

		ZEND_HASH_FOREACH_VAL(Z_ARRVAL(stream->wrapperdata), tmp) {
			if (strncasecmp(Z_STRVAL_P(tmp), SERVER_MICROSOFT_IIS, sizeof(SERVER_MICROSOFT_IIS)-1) == 0) {
				return 1;
			} else if (strncasecmp(Z_STRVAL_P(tmp), SERVER_GOOGLE, sizeof(SERVER_GOOGLE)-1) == 0) {
				return 1;
			}
		} ZEND_HASH_FOREACH_END();
	}
	return 0;
}
/* }}} */

static int php_openssl_handle_ssl_error(php_stream *stream, int nr_bytes, zend_bool is_init) /* {{{ */
{
	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
	int err = SSL_get_error(sslsock->ssl_handle, nr_bytes);
	char esbuf[512];
	smart_str ebuf = {0};
	unsigned long ecode;
	int retry = 1;

	switch(err) {
		case SSL_ERROR_ZERO_RETURN:
			/* SSL terminated (but socket may still be active) */
			retry = 0;
			break;
		case SSL_ERROR_WANT_READ:
		case SSL_ERROR_WANT_WRITE:
			/* re-negotiation, or perhaps the SSL layer needs more
			 * packets: retry in next iteration */
			errno = EAGAIN;
			retry = is_init ? 1 : sslsock->s.is_blocked;
			break;
		case SSL_ERROR_SYSCALL:
			if (ERR_peek_error() == 0) {
				if (nr_bytes == 0) {
					if (!php_openssl_is_http_stream_talking_to_iis(stream) && ERR_get_error() != 0) {
						php_error_docref(NULL, E_WARNING, "SSL: fatal protocol error");
					}
					SSL_set_shutdown(sslsock->ssl_handle, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
					stream->eof = 1;
					retry = 0;
				} else {
					char *estr = php_socket_strerror(php_socket_errno(), NULL, 0);

					php_error_docref(NULL, E_WARNING,
							"SSL: %s", estr);

					efree(estr);
					retry = 0;
				}
				break;
			}


			/* fall through */
		default:
			/* some other error */
			ecode = ERR_get_error();

			switch (ERR_GET_REASON(ecode)) {
				case SSL_R_NO_SHARED_CIPHER:
					php_error_docref(NULL, E_WARNING,
							"SSL_R_NO_SHARED_CIPHER: no suitable shared cipher could be used.  "
							"This could be because the server is missing an SSL certificate "
							"(local_cert context option)");
					retry = 0;
					break;

				default:
					do {
						/* NULL is automatically added */
						ERR_error_string_n(ecode, esbuf, sizeof(esbuf));
						if (ebuf.s) {
							smart_str_appendc(&ebuf, '\n');
						}
						smart_str_appends(&ebuf, esbuf);
					} while ((ecode = ERR_get_error()) != 0);

					smart_str_0(&ebuf);

					php_error_docref(NULL, E_WARNING,
							"SSL operation failed with code %d. %s%s",
							err,
							ebuf.s ? "OpenSSL Error messages:\n" : "",
							ebuf.s ? ZSTR_VAL(ebuf.s) : "");
					if (ebuf.s) {
						smart_str_free(&ebuf);
					}
			}

			retry = 0;
			errno = 0;
	}
	return retry;
}
/* }}} */

static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) /* {{{ */
{
	php_stream *stream;
	SSL *ssl;
	int err, depth, ret;
	zval *val;
	zend_ulong allowed_depth = OPENSSL_DEFAULT_STREAM_VERIFY_DEPTH;


	ret = preverify_ok;

	/* determine the status for the current cert */
	err = X509_STORE_CTX_get_error(ctx);
	depth = X509_STORE_CTX_get_error_depth(ctx);

	/* conjure the stream & context to use */
	ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
	stream = (php_stream*)SSL_get_ex_data(ssl, php_openssl_get_ssl_stream_data_index());

	/* if allow_self_signed is set, make sure that verification succeeds */
	if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT &&
		GET_VER_OPT("allow_self_signed") &&
		zend_is_true(val)
	) {
		ret = 1;
	}

	/* check the depth */
	GET_VER_OPT_LONG("verify_depth", allowed_depth);
	if ((zend_ulong)depth > allowed_depth) {
		ret = 0;
		X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_CHAIN_TOO_LONG);
	}

	return ret;
}
/* }}} */

static int php_openssl_x509_fingerprint_cmp(X509 *peer, const char *method, const char *expected)
{
	zend_string *fingerprint;
	int result = -1;

	fingerprint = php_openssl_x509_fingerprint(peer, method, 0);
	if (fingerprint) {
		result = strcasecmp(expected, ZSTR_VAL(fingerprint));
		zend_string_release(fingerprint);
	}

	return result;
}

static zend_bool php_openssl_x509_fingerprint_match(X509 *peer, zval *val)
{
	if (Z_TYPE_P(val) == IS_STRING) {
		const char *method = NULL;

		switch (Z_STRLEN_P(val)) {
			case 32:
				method = "md5";
				break;

			case 40:
				method = "sha1";
				break;
		}

		return method && php_openssl_x509_fingerprint_cmp(peer, method, Z_STRVAL_P(val)) == 0;
	} else if (Z_TYPE_P(val) == IS_ARRAY) {
		zval *current;
		zend_string *key;

		if (!zend_hash_num_elements(Z_ARRVAL_P(val))) {
			php_error_docref(NULL, E_WARNING, "Invalid peer_fingerprint array; [algo => fingerprint] form required");
			return 0;
		}

		ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(val), key, current) {
			if (key == NULL || Z_TYPE_P(current) != IS_STRING) {
				php_error_docref(NULL, E_WARNING, "Invalid peer_fingerprint array; [algo => fingerprint] form required");
				return 0;
			}
			if (php_openssl_x509_fingerprint_cmp(peer, ZSTR_VAL(key), Z_STRVAL_P(current)) != 0) {
				return 0;
			}
		} ZEND_HASH_FOREACH_END();

		return 1;
	} else {
		php_error_docref(NULL, E_WARNING,
			"Invalid peer_fingerprint value; fingerprint string or array of the form [algo => fingerprint] required");
	}

	return 0;
}

static zend_bool php_openssl_matches_wildcard_name(const char *subjectname, const char *certname) /* {{{ */
{
	char *wildcard = NULL;
	ptrdiff_t prefix_len;
	size_t suffix_len, subject_len;

	if (strcasecmp(subjectname, certname) == 0) {
		return 1;
	}

	/* wildcard, if present, must only be present in the left-most component */
	if (!(wildcard = strchr(certname, '*')) || memchr(certname, '.', wildcard - certname)) {
		return 0;
	}

	/* 1) prefix, if not empty, must match subject */
	prefix_len = wildcard - certname;
	if (prefix_len && strncasecmp(subjectname, certname, prefix_len) != 0) {
		return 0;
	}

	suffix_len = strlen(wildcard + 1);
	subject_len = strlen(subjectname);
	if (suffix_len <= subject_len) {
		/* 2) suffix must match
		 * 3) no . between prefix and suffix
		 **/
		return strcasecmp(wildcard + 1, subjectname + subject_len - suffix_len) == 0 &&
			memchr(subjectname + prefix_len, '.', subject_len - suffix_len - prefix_len) == NULL;
	}

	return 0;
}
/* }}} */

static zend_bool php_openssl_matches_san_list(X509 *peer, const char *subject_name) /* {{{ */
{
	int i, len;
	unsigned char *cert_name = NULL;
	char ipbuffer[64];

	GENERAL_NAMES *alt_names = X509_get_ext_d2i(peer, NID_subject_alt_name, 0, 0);
	int alt_name_count = sk_GENERAL_NAME_num(alt_names);

	for (i = 0; i < alt_name_count; i++) {
		GENERAL_NAME *san = sk_GENERAL_NAME_value(alt_names, i);

		if (san->type == GEN_DNS) {
			ASN1_STRING_to_UTF8(&cert_name, san->d.dNSName);
			if ((size_t)ASN1_STRING_length(san->d.dNSName) != strlen((const char*)cert_name)) {
				OPENSSL_free(cert_name);
				/* prevent null-byte poisoning*/
				continue;
			}

			/* accommodate valid FQDN entries ending in "." */
			len = strlen((const char*)cert_name);
			if (len && strcmp((const char *)&cert_name[len-1], ".") == 0) {
				cert_name[len-1] = '\0';
			}

			if (php_openssl_matches_wildcard_name(subject_name, (const char *)cert_name)) {
				OPENSSL_free(cert_name);
				return 1;
			}
			OPENSSL_free(cert_name);
		} else if (san->type == GEN_IPADD) {
			if (san->d.iPAddress->length == 4) {
				sprintf(ipbuffer, "%d.%d.%d.%d",
					san->d.iPAddress->data[0],
					san->d.iPAddress->data[1],
					san->d.iPAddress->data[2],
					san->d.iPAddress->data[3]
				);
				if (strcasecmp(subject_name, (const char*)ipbuffer) == 0) {
					return 1;
				}
			}
			/* No, we aren't bothering to check IPv6 addresses. Why?
			 * Because IP SAN names are officially deprecated and are
			 * not allowed by CAs starting in 2015. Deal with it.
			 */
		}
	}

	return 0;
}
/* }}} */

static zend_bool php_openssl_matches_common_name(X509 *peer, const char *subject_name) /* {{{ */
{
	char buf[1024];
	X509_NAME *cert_name;
	zend_bool is_match = 0;
	int cert_name_len;

	cert_name = X509_get_subject_name(peer);
	cert_name_len = X509_NAME_get_text_by_NID(cert_name, NID_commonName, buf, sizeof(buf));

	if (cert_name_len == -1) {
		php_error_docref(NULL, E_WARNING, "Unable to locate peer certificate CN");
	} else if ((size_t)cert_name_len != strlen(buf)) {
		php_error_docref(NULL, E_WARNING, "Peer certificate CN=`%.*s' is malformed", cert_name_len, buf);
	} else if (php_openssl_matches_wildcard_name(subject_name, buf)) {
		is_match = 1;
	} else {
		php_error_docref(NULL, E_WARNING,
			"Peer certificate CN=`%.*s' did not match expected CN=`%s'",
			cert_name_len, buf, subject_name);
	}

	return is_match;
}
/* }}} */

static int php_openssl_apply_peer_verification_policy(SSL *ssl, X509 *peer, php_stream *stream) /* {{{ */
{
	zval *val = NULL;
	char *peer_name = NULL;
	int err,
		must_verify_peer,
		must_verify_peer_name,
		must_verify_fingerprint;

	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;

	must_verify_peer = GET_VER_OPT("verify_peer")
		? zend_is_true(val)
		: sslsock->is_client;

	must_verify_peer_name = GET_VER_OPT("verify_peer_name")
		? zend_is_true(val)
		: sslsock->is_client;

	must_verify_fingerprint = GET_VER_OPT("peer_fingerprint");

	if ((must_verify_peer || must_verify_peer_name || must_verify_fingerprint) && peer == NULL) {
		php_error_docref(NULL, E_WARNING, "Could not get peer certificate");
		return FAILURE;
	}

	/* Verify the peer against using CA file/path settings */
	if (must_verify_peer) {
		err = SSL_get_verify_result(ssl);
		switch (err) {
			case X509_V_OK:
				/* fine */
				break;
			case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
				if (GET_VER_OPT("allow_self_signed") && zend_is_true(val)) {
					/* allowed */
					break;
				}
				/* not allowed, so fall through */
			default:
				php_error_docref(NULL, E_WARNING,
						"Could not verify peer: code:%d %s",
						err,
						X509_verify_cert_error_string(err)
				);
				return FAILURE;
		}
	}

	/* If a peer_fingerprint match is required this trumps peer and peer_name verification */
	if (must_verify_fingerprint) {
		if (Z_TYPE_P(val) == IS_STRING || Z_TYPE_P(val) == IS_ARRAY) {
			if (!php_openssl_x509_fingerprint_match(peer, val)) {
				php_error_docref(NULL, E_WARNING,
					"peer_fingerprint match failure"
				);
				return FAILURE;
			}
		} else {
			php_error_docref(NULL, E_WARNING,
				"Expected peer fingerprint must be a string or an array"
			);
			return FAILURE;
		}
	}

	/* verify the host name presented in the peer certificate */
	if (must_verify_peer_name) {
		GET_VER_OPT_STRING("peer_name", peer_name);

		/* If no peer name was specified we use the autodetected url name in client environments */
		if (peer_name == NULL && sslsock->is_client) {
			peer_name = sslsock->url_name;
		}

		if (peer_name) {
			if (php_openssl_matches_san_list(peer, peer_name)) {
				return SUCCESS;
			} else if (php_openssl_matches_common_name(peer, peer_name)) {
				return SUCCESS;
			} else {
				return FAILURE;
			}
		} else {
			return FAILURE;
		}
	}

	return SUCCESS;
}
/* }}} */

static int php_openssl_passwd_callback(char *buf, int num, int verify, void *data) /* {{{ */
{
	php_stream *stream = (php_stream *)data;
	zval *val = NULL;
	char *passphrase = NULL;
	/* TODO: could expand this to make a callback into PHP user-space */

	GET_VER_OPT_STRING("passphrase", passphrase);

	if (passphrase) {
		if (Z_STRLEN_P(val) < (size_t)num - 1) {
			memcpy(buf, Z_STRVAL_P(val), Z_STRLEN_P(val)+1);
			return (int)Z_STRLEN_P(val);
		}
	}
	return 0;
}
/* }}} */

#ifdef PHP_WIN32
#define RETURN_CERT_VERIFY_FAILURE(code) X509_STORE_CTX_set_error(x509_store_ctx, code); return 0;
static int php_openssl_win_cert_verify_callback(X509_STORE_CTX *x509_store_ctx, void *arg) /* {{{ */
{
	PCCERT_CONTEXT cert_ctx = NULL;
	PCCERT_CHAIN_CONTEXT cert_chain_ctx = NULL;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
	X509 *cert = x509_store_ctx->cert;
#else
	X509 *cert = X509_STORE_CTX_get0_cert(x509_store_ctx);
#endif

	php_stream *stream;
	php_openssl_netstream_data_t *sslsock;
	zval *val;
	zend_bool is_self_signed = 0;


	stream = (php_stream*)arg;
	sslsock = (php_openssl_netstream_data_t*)stream->abstract;

	{ /* First convert the x509 struct back to a DER encoded buffer and let Windows decode it into a form it can work with */
		unsigned char *der_buf = NULL;
		int der_len;

		der_len = i2d_X509(cert, &der_buf);
		if (der_len < 0) {
			unsigned long err_code, e;
			char err_buf[512];

			while ((e = ERR_get_error()) != 0) {
				err_code = e;
			}

			php_error_docref(NULL, E_WARNING, "Error encoding X509 certificate: %d: %s", err_code, ERR_error_string(err_code, err_buf));
			RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
		}

		cert_ctx = CertCreateCertificateContext(X509_ASN_ENCODING, der_buf, der_len);
		OPENSSL_free(der_buf);

		if (cert_ctx == NULL) {
			php_error_docref(NULL, E_WARNING, "Error creating certificate context: %s", php_win_err());
			RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
		}
	}

	{ /* Next fetch the relevant cert chain from the store */
		CERT_ENHKEY_USAGE enhkey_usage = {0};
		CERT_USAGE_MATCH cert_usage = {0};
		CERT_CHAIN_PARA chain_params = {sizeof(CERT_CHAIN_PARA)};
		LPSTR usages[] = {szOID_PKIX_KP_SERVER_AUTH, szOID_SERVER_GATED_CRYPTO, szOID_SGC_NETSCAPE};
		DWORD chain_flags = 0;
		unsigned long allowed_depth = OPENSSL_DEFAULT_STREAM_VERIFY_DEPTH;
		unsigned int i;

		enhkey_usage.cUsageIdentifier = 3;
		enhkey_usage.rgpszUsageIdentifier = usages;
		cert_usage.dwType = USAGE_MATCH_TYPE_OR;
		cert_usage.Usage = enhkey_usage;
		chain_params.RequestedUsage = cert_usage;
		chain_flags = CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;

		if (!CertGetCertificateChain(NULL, cert_ctx, NULL, NULL, &chain_params, chain_flags, NULL, &cert_chain_ctx)) {
			php_error_docref(NULL, E_WARNING, "Error getting certificate chain: %s", php_win_err());
			CertFreeCertificateContext(cert_ctx);
			RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
		}

		/* check if the cert is self-signed */
		if (cert_chain_ctx->cChain > 0 && cert_chain_ctx->rgpChain[0]->cElement > 0
			&& (cert_chain_ctx->rgpChain[0]->rgpElement[0]->TrustStatus.dwInfoStatus & CERT_TRUST_IS_SELF_SIGNED) != 0) {
			is_self_signed = 1;
		}

		/* check the depth */
		GET_VER_OPT_LONG("verify_depth", allowed_depth);

		for (i = 0; i < cert_chain_ctx->cChain; i++) {
			if (cert_chain_ctx->rgpChain[i]->cElement > allowed_depth) {
				CertFreeCertificateChain(cert_chain_ctx);
				CertFreeCertificateContext(cert_ctx);
				RETURN_CERT_VERIFY_FAILURE(X509_V_ERR_CERT_CHAIN_TOO_LONG);
			}
		}
	}

	{ /* Then verify it against a policy */
		SSL_EXTRA_CERT_CHAIN_POLICY_PARA ssl_policy_params = {sizeof(SSL_EXTRA_CERT_CHAIN_POLICY_PARA)};
		CERT_CHAIN_POLICY_PARA chain_policy_params = {sizeof(CERT_CHAIN_POLICY_PARA)};
		CERT_CHAIN_POLICY_STATUS chain_policy_status = {sizeof(CERT_CHAIN_POLICY_STATUS)};
		LPWSTR server_name = NULL;
		BOOL verify_result;

		{ /* This looks ridiculous and it is - but we validate the name ourselves using the peer_name
		     ctx option, so just use the CN from the cert here */

			X509_NAME *cert_name;
			unsigned char *cert_name_utf8;
			int index, cert_name_utf8_len;
			DWORD num_wchars;

			cert_name = X509_get_subject_name(cert);
			index = X509_NAME_get_index_by_NID(cert_name, NID_commonName, -1);
			if (index < 0) {
				php_error_docref(NULL, E_WARNING, "Unable to locate certificate CN");
				CertFreeCertificateChain(cert_chain_ctx);
				CertFreeCertificateContext(cert_ctx);
				RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
			}

			cert_name_utf8_len = PHP_X509_NAME_ENTRY_TO_UTF8(cert_name, index, cert_name_utf8);

			num_wchars = MultiByteToWideChar(CP_UTF8, 0, (char*)cert_name_utf8, -1, NULL, 0);
			if (num_wchars == 0) {
				php_error_docref(NULL, E_WARNING, "Unable to convert %s to wide character string", cert_name_utf8);
				OPENSSL_free(cert_name_utf8);
				CertFreeCertificateChain(cert_chain_ctx);
				CertFreeCertificateContext(cert_ctx);
				RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
			}

			server_name = emalloc((num_wchars * sizeof(WCHAR)) + sizeof(WCHAR));

			num_wchars = MultiByteToWideChar(CP_UTF8, 0, (char*)cert_name_utf8, -1, server_name, num_wchars);
			if (num_wchars == 0) {
				php_error_docref(NULL, E_WARNING, "Unable to convert %s to wide character string", cert_name_utf8);
				efree(server_name);
				OPENSSL_free(cert_name_utf8);
				CertFreeCertificateChain(cert_chain_ctx);
				CertFreeCertificateContext(cert_ctx);
				RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
			}

			OPENSSL_free(cert_name_utf8);
		}

		ssl_policy_params.dwAuthType = (sslsock->is_client) ? AUTHTYPE_SERVER : AUTHTYPE_CLIENT;
		ssl_policy_params.pwszServerName = server_name;
		chain_policy_params.pvExtraPolicyPara = &ssl_policy_params;

		verify_result = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, cert_chain_ctx, &chain_policy_params, &chain_policy_status);

		efree(server_name);
		CertFreeCertificateChain(cert_chain_ctx);
		CertFreeCertificateContext(cert_ctx);

		if (!verify_result) {
			php_error_docref(NULL, E_WARNING, "Error verifying certificate chain policy: %s", php_win_err());
			RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
		}

		if (chain_policy_status.dwError != 0) {
			/* The chain does not match the policy */
			if (is_self_signed && chain_policy_status.dwError == CERT_E_UNTRUSTEDROOT
				&& GET_VER_OPT("allow_self_signed") && zend_is_true(val)) {
				/* allow self-signed certs */
				X509_STORE_CTX_set_error(x509_store_ctx, X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
			} else {
				RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
			}
		}
	}

	return 1;
}
/* }}} */
#endif

static long php_openssl_load_stream_cafile(X509_STORE *cert_store, const char *cafile) /* {{{ */
{
	php_stream *stream;
	X509 *cert;
	BIO *buffer;
	int buffer_active = 0;
	char *line = NULL;
	size_t line_len;
	long certs_added = 0;

	stream = php_stream_open_wrapper(cafile, "rb", 0, NULL);

	if (stream == NULL) {
		php_error(E_WARNING, "failed loading cafile stream: `%s'", cafile);
		return 0;
	} else if (stream->wrapper->is_url) {
		php_stream_close(stream);
		php_error(E_WARNING, "remote cafile streams are disabled for security purposes");
		return 0;
	}

	cert_start: {
		line = php_stream_get_line(stream, NULL, 0, &line_len);
		if (line == NULL) {
			goto stream_complete;
		} else if (!strcmp(line, "-----BEGIN CERTIFICATE-----\n") ||
			!strcmp(line, "-----BEGIN CERTIFICATE-----\r\n")
		) {
			buffer = BIO_new(BIO_s_mem());
			buffer_active = 1;
			goto cert_line;
		} else {
			efree(line);
			goto cert_start;
		}
	}

	cert_line: {
		BIO_puts(buffer, line);
		efree(line);
		line = php_stream_get_line(stream, NULL, 0, &line_len);
		if (line == NULL) {
			goto stream_complete;
		} else if (!strcmp(line, "-----END CERTIFICATE-----") ||
			!strcmp(line, "-----END CERTIFICATE-----\n") ||
			!strcmp(line, "-----END CERTIFICATE-----\r\n")
		) {
			goto add_cert;
		} else {
			goto cert_line;
		}
	}

	add_cert: {
		BIO_puts(buffer, line);
		efree(line);
		cert = PEM_read_bio_X509(buffer, NULL, 0, NULL);
		BIO_free(buffer);
		buffer_active = 0;
		if (cert && X509_STORE_add_cert(cert_store, cert)) {
			++certs_added;
		}
		goto cert_start;
	}

	stream_complete: {
		php_stream_close(stream);
		if (buffer_active == 1) {
			BIO_free(buffer);
		}
	}

	if (certs_added == 0) {
		php_error(E_WARNING, "no valid certs found cafile stream: `%s'", cafile);
	}

	return certs_added;
}
/* }}} */

static int php_openssl_enable_peer_verification(SSL_CTX *ctx, php_stream *stream) /* {{{ */
{
	zval *val = NULL;
	char *cafile = NULL;
	char *capath = NULL;
	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;

	GET_VER_OPT_STRING("cafile", cafile);
	GET_VER_OPT_STRING("capath", capath);

	if (cafile == NULL) {
		cafile = zend_ini_string("openssl.cafile", sizeof("openssl.cafile")-1, 0);
		cafile = strlen(cafile) ? cafile : NULL;
	} else if (!sslsock->is_client) {
		/* Servers need to load and assign CA names from the cafile */
		STACK_OF(X509_NAME) *cert_names = SSL_load_client_CA_file(cafile);
		if (cert_names != NULL) {
			SSL_CTX_set_client_CA_list(ctx, cert_names);
		} else {
			php_error(E_WARNING, "SSL: failed loading CA names from cafile");
			return FAILURE;
		}
	}

	if (capath == NULL) {
		capath = zend_ini_string("openssl.capath", sizeof("openssl.capath")-1, 0);
		capath = strlen(capath) ? capath : NULL;
	}

	if (cafile || capath) {
		if (!SSL_CTX_load_verify_locations(ctx, cafile, capath)) {
			if (cafile && !php_openssl_load_stream_cafile(SSL_CTX_get_cert_store(ctx), cafile)) {
				return FAILURE;
			}
		}
	} else {
#ifdef PHP_WIN32
		SSL_CTX_set_cert_verify_callback(ctx, php_openssl_win_cert_verify_callback, (void *)stream);
		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
#else
		if (sslsock->is_client && !SSL_CTX_set_default_verify_paths(ctx)) {
			php_error_docref(NULL, E_WARNING,
				"Unable to set default verify locations and no CA settings specified");
			return FAILURE;
		}
#endif
	}

	SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);

	return SUCCESS;
}
/* }}} */

static void php_openssl_disable_peer_verification(SSL_CTX *ctx, php_stream *stream) /* {{{ */
{
	SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
}
/* }}} */

static int php_openssl_set_local_cert(SSL_CTX *ctx, php_stream *stream) /* {{{ */
{
	zval *val = NULL;
	char *certfile = NULL;

	GET_VER_OPT_STRING("local_cert", certfile);

	if (certfile) {
		char resolved_path_buff[MAXPATHLEN];
		const char *private_key = NULL;

		if (VCWD_REALPATH(certfile, resolved_path_buff)) {
			/* a certificate to use for authentication */
			if (SSL_CTX_use_certificate_chain_file(ctx, resolved_path_buff) != 1) {
				php_error_docref(NULL, E_WARNING,
					"Unable to set local cert chain file `%s'; Check that your cafile/capath "
					"settings include details of your certificate and its issuer",
					certfile);
				return FAILURE;
			}
			GET_VER_OPT_STRING("local_pk", private_key);

			if (private_key) {
				char resolved_path_buff_pk[MAXPATHLEN];
				if (VCWD_REALPATH(private_key, resolved_path_buff_pk)) {
					if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff_pk, SSL_FILETYPE_PEM) != 1) {
						php_error_docref(NULL, E_WARNING, "Unable to set private key file `%s'", resolved_path_buff_pk);
						return FAILURE;
					}
				}
			} else {
				if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff, SSL_FILETYPE_PEM) != 1) {
					php_error_docref(NULL, E_WARNING, "Unable to set private key file `%s'", resolved_path_buff);
					return FAILURE;
				}
			}

			if (!SSL_CTX_check_private_key(ctx)) {
				php_error_docref(NULL, E_WARNING, "Private key does not match certificate!");
			}
		}
	}

	return SUCCESS;
}
/* }}} */

static const SSL_METHOD *php_openssl_select_crypto_method(zend_long method_value, int is_client) /* {{{ */
{
	if (method_value == STREAM_CRYPTO_METHOD_SSLv2) {
		php_error_docref(NULL, E_WARNING,
				"SSLv2 unavailable in this PHP version");
		return NULL;
	} else if (method_value == STREAM_CRYPTO_METHOD_SSLv3) {
#ifdef HAVE_SSL3
		return is_client ? SSLv3_client_method() : SSLv3_server_method();
#else
		php_error_docref(NULL, E_WARNING,
				"SSLv3 unavailable in the OpenSSL library against which PHP is linked");
		return NULL;
#endif
	} else if (method_value == STREAM_CRYPTO_METHOD_TLSv1_0) {
		return is_client ? TLSv1_client_method() : TLSv1_server_method();
	} else if (method_value == STREAM_CRYPTO_METHOD_TLSv1_1) {
#ifdef HAVE_TLS11
		return is_client ? TLSv1_1_client_method() : TLSv1_1_server_method();
#else
		php_error_docref(NULL, E_WARNING,
				"TLSv1.1 unavailable in the OpenSSL library against which PHP is linked");
		return NULL;
#endif
	} else if (method_value == STREAM_CRYPTO_METHOD_TLSv1_2) {
#ifdef HAVE_TLS12
		return is_client ? TLSv1_2_client_method() : TLSv1_2_server_method();
#else
		php_error_docref(NULL, E_WARNING,
				"TLSv1.2 unavailable in the OpenSSL library against which PHP is linked");
		return NULL;
#endif
	} else {
		php_error_docref(NULL, E_WARNING,
				"Invalid crypto method");
		return NULL;
	}
}
/* }}} */

#define PHP_SSL_MAX_VERSION_LEN 32

static char *php_openssl_cipher_get_version(const SSL_CIPHER *c, char *buffer, size_t max_len) /* {{{ */
{
	const char *version = SSL_CIPHER_get_version(c);

	strncpy(buffer, version, max_len);
	if (max_len <= strlen(version)) {
		buffer[max_len - 1] = 0;
	}

	return buffer;
}
/* }}} */

static int php_openssl_get_crypto_method_ctx_flags(int method_flags) /* {{{ */
{
	int ssl_ctx_options = SSL_OP_ALL;

#ifdef SSL_OP_NO_SSLv2
	ssl_ctx_options |= SSL_OP_NO_SSLv2;
#endif
#ifdef HAVE_SSL3
	if (!(method_flags & STREAM_CRYPTO_METHOD_SSLv3)) {
		ssl_ctx_options |= SSL_OP_NO_SSLv3;
	}
#endif
	if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_0)) {
		ssl_ctx_options |= SSL_OP_NO_TLSv1;
	}
#ifdef HAVE_TLS11
	if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_1)) {
		ssl_ctx_options |= SSL_OP_NO_TLSv1_1;
	}
#endif
#ifdef HAVE_TLS12
	if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_2)) {
		ssl_ctx_options |= SSL_OP_NO_TLSv1_2;
	}
#endif

	return ssl_ctx_options;
}
/* }}} */

static void php_openssl_limit_handshake_reneg(const SSL *ssl) /* {{{ */
{
	php_stream *stream;
	php_openssl_netstream_data_t *sslsock;
	struct timeval now;
	zend_long elapsed_time;

	stream = php_openssl_get_stream_from_ssl_handle(ssl);
	sslsock = (php_openssl_netstream_data_t*)stream->abstract;
	gettimeofday(&now, NULL);

	/* The initial handshake is never rate-limited */
	if (sslsock->reneg->prev_handshake == 0) {
		sslsock->reneg->prev_handshake = now.tv_sec;
		return;
	}

	elapsed_time = (now.tv_sec - sslsock->reneg->prev_handshake);
	sslsock->reneg->prev_handshake = now.tv_sec;
	sslsock->reneg->tokens -= (elapsed_time * (sslsock->reneg->limit / sslsock->reneg->window));

	if (sslsock->reneg->tokens < 0) {
		sslsock->reneg->tokens = 0;
	}
	++sslsock->reneg->tokens;

	/* The token level exceeds our allowed limit */
	if (sslsock->reneg->tokens > sslsock->reneg->limit) {
		zval *val;


		sslsock->reneg->should_close = 1;

		if (PHP_STREAM_CONTEXT(stream) && (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream),
				"ssl", "reneg_limit_callback")) != NULL
		) {
			zval param, retval;

			php_stream_to_zval(stream, &param);

			/* Closing the stream inside this callback would segfault! */
			stream->flags |= PHP_STREAM_FLAG_NO_FCLOSE;
			if (FAILURE == call_user_function_ex(EG(function_table), NULL, val, &retval, 1, &param, 0, NULL)) {
				php_error(E_WARNING, "SSL: failed invoking reneg limit notification callback");
			}
			stream->flags ^= PHP_STREAM_FLAG_NO_FCLOSE;

			/* If the reneg_limit_callback returned true don't auto-close */
			if (Z_TYPE(retval) == IS_TRUE) {
				sslsock->reneg->should_close = 0;
			}

			zval_ptr_dtor(&retval);
		} else {
			php_error_docref(NULL, E_WARNING,
				"SSL: client-initiated handshake rate limit exceeded by peer");
		}
	}
}
/* }}} */

static void php_openssl_info_callback(const SSL *ssl, int where, int ret) /* {{{ */
{
	/* Rate-limit client-initiated handshake renegotiation to prevent DoS */
	if (where & SSL_CB_HANDSHAKE_START) {
		php_openssl_limit_handshake_reneg(ssl);
	}
}
/* }}} */

static void php_openssl_init_server_reneg_limit(php_stream *stream, php_openssl_netstream_data_t *sslsock) /* {{{ */
{
	zval *val;
	zend_long limit = OPENSSL_DEFAULT_RENEG_LIMIT;
	zend_long window = OPENSSL_DEFAULT_RENEG_WINDOW;

	if (PHP_STREAM_CONTEXT(stream) &&
		NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "reneg_limit"))
	) {
		convert_to_long(val);
		limit = Z_LVAL_P(val);
	}

	/* No renegotiation rate-limiting */
	if (limit < 0) {
		return;
	}

	if (PHP_STREAM_CONTEXT(stream) &&
		NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "reneg_window"))
	) {
		convert_to_long(val);
		window = Z_LVAL_P(val);
	}

	sslsock->reneg = (void*)pemalloc(sizeof(php_openssl_handshake_bucket_t),
		php_stream_is_persistent(stream)
	);

	sslsock->reneg->limit = limit;
	sslsock->reneg->window = window;
	sslsock->reneg->prev_handshake = 0;
	sslsock->reneg->tokens = 0;
	sslsock->reneg->should_close = 0;

	SSL_set_info_callback(sslsock->ssl_handle, php_openssl_info_callback);
}
/* }}} */

#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined (LIBRESSL_VERSION_NUMBER)
static RSA *php_openssl_tmp_rsa_cb(SSL *s, int is_export, int keylength)
{
	BIGNUM *bn = NULL;
	static RSA *rsa_tmp = NULL;

	if (!rsa_tmp && ((bn = BN_new()) == NULL)) {
		php_error_docref(NULL, E_WARNING, "allocation error generating RSA key");
	}
	if (!rsa_tmp && bn) {
		if (!BN_set_word(bn, RSA_F4) || ((rsa_tmp = RSA_new()) == NULL) ||
			!RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) {
			if (rsa_tmp) {
				RSA_free(rsa_tmp);
			}
			rsa_tmp = NULL;
		}
		BN_free(bn);
	}

	return (rsa_tmp);
}
#endif

static int php_openssl_set_server_dh_param(php_stream * stream, SSL_CTX *ctx) /* {{{ */
{
	DH *dh;
	BIO* bio;
	zval *zdhpath;

	zdhpath = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "dh_param");
	if (zdhpath == NULL) {
#if 0
	/* Coming in OpenSSL 1.1 ... eventually we'll want to enable this
	 * in the absence of an explicit dh_param.
	 */
	SSL_CTX_set_dh_auto(ctx, 1);
#endif
		return SUCCESS;
	}

	convert_to_string_ex(zdhpath);
	bio = BIO_new_file(Z_STRVAL_P(zdhpath), PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY));

	if (bio == NULL) {
		php_error_docref(NULL, E_WARNING, "invalid dh_param");
		return FAILURE;
	}

	dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
	BIO_free(bio);

	if (dh == NULL) {
		php_error_docref(NULL, E_WARNING, "failed reading DH params");
		return FAILURE;
	}

	if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
		php_error_docref(NULL, E_WARNING, "failed assigning DH params");
		DH_free(dh);
		return FAILURE;
	}

	DH_free(dh);

	return SUCCESS;
}
/* }}} */

#if defined(HAVE_ECDH) && (OPENSSL_VERSION_NUMBER < 0x10100000L || defined (LIBRESSL_VERSION_NUMBER))
static int php_openssl_set_server_ecdh_curve(php_stream *stream, SSL_CTX *ctx) /* {{{ */
{
	zval *zvcurve;
	int curve_nid;
	EC_KEY *ecdh;

	zvcurve = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "ecdh_curve");
	if (zvcurve == NULL) {
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
		SSL_CTX_set_ecdh_auto(ctx, 1);
		return SUCCESS;
#else
		curve_nid = NID_X9_62_prime256v1;
#endif
	} else {
		convert_to_string_ex(zvcurve);
		curve_nid = OBJ_sn2nid(Z_STRVAL_P(zvcurve));
		if (curve_nid == NID_undef) {
			php_error_docref(NULL, E_WARNING, "invalid ecdh_curve specified");
			return FAILURE;
		}
	}

	ecdh = EC_KEY_new_by_curve_name(curve_nid);
	if (ecdh == NULL) {
		php_error_docref(NULL, E_WARNING, "failed generating ECDH curve");
		return FAILURE;
	}

	SSL_CTX_set_tmp_ecdh(ctx, ecdh);
	EC_KEY_free(ecdh);

	return SUCCESS;
}
/* }}} */
#endif

static int php_openssl_set_server_specific_opts(php_stream *stream, SSL_CTX *ctx) /* {{{ */
{
	zval *zv;
	long ssl_ctx_options = SSL_CTX_get_options(ctx);

#if defined(HAVE_ECDH) && (OPENSSL_VERSION_NUMBER < 0x10100000L || defined (LIBRESSL_VERSION_NUMBER))
	if (php_openssl_set_server_ecdh_curve(stream, ctx) == FAILURE) {
		return FAILURE;
	}
#endif

#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined (LIBRESSL_VERSION_NUMBER)
	SSL_CTX_set_tmp_rsa_callback(ctx, php_openssl_tmp_rsa_cb);
#endif
	/* We now use php_openssl_tmp_rsa_cb to generate a key of appropriate size whenever necessary */
	if (php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "rsa_key_size") != NULL) {
		php_error_docref(NULL, E_WARNING, "rsa_key_size context option has been removed");
	}

	php_openssl_set_server_dh_param(stream, ctx);
	zv = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "single_dh_use");
	if (zv == NULL || zend_is_true(zv)) {
		ssl_ctx_options |= SSL_OP_SINGLE_DH_USE;
	}

	zv = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "honor_cipher_order");
	if (zv == NULL || zend_is_true(zv)) {
		ssl_ctx_options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
	}

	SSL_CTX_set_options(ctx, ssl_ctx_options);

	return SUCCESS;
}
/* }}} */

#ifdef HAVE_TLS_SNI
static int php_openssl_server_sni_callback(SSL *ssl_handle, int *al, void *arg) /* {{{ */
{
	php_stream *stream;
	php_openssl_netstream_data_t *sslsock;
	unsigned i;
	const char *server_name;

	server_name = SSL_get_servername(ssl_handle, TLSEXT_NAMETYPE_host_name);

	if (!server_name) {
		return SSL_TLSEXT_ERR_NOACK;
	}

	stream = (php_stream*)SSL_get_ex_data(ssl_handle, php_openssl_get_ssl_stream_data_index());
	sslsock = (php_openssl_netstream_data_t*)stream->abstract;

	if (!(sslsock->sni_cert_count && sslsock->sni_certs)) {
		return SSL_TLSEXT_ERR_NOACK;
	}

	for (i=0; i < sslsock->sni_cert_count; i++) {
		if (php_openssl_matches_wildcard_name(server_name, sslsock->sni_certs[i].name)) {
			SSL_set_SSL_CTX(ssl_handle, sslsock->sni_certs[i].ctx);
			return SSL_TLSEXT_ERR_OK;
		}
	}

	return SSL_TLSEXT_ERR_NOACK;
}
/* }}} */

static SSL_CTX *php_openssl_create_sni_server_ctx(char *cert_path, char *key_path)  /* {{{ */
{
	/* The hello method is not inherited by SSL structs when assigning a new context
	 * inside the SNI callback, so the just use SSLv23 */
	SSL_CTX *ctx = SSL_CTX_new(SSLv23_server_method());

	if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) != 1) {
		php_error_docref(NULL, E_WARNING,
			"failed setting local cert chain file `%s'; " \
			"check that your cafile/capath settings include " \
			"details of your certificate and its issuer",
			cert_path
		);
		SSL_CTX_free(ctx);
		return NULL;
	} else if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) != 1) {
		php_error_docref(NULL, E_WARNING,
			"failed setting private key from file `%s'",
			key_path
		);
		SSL_CTX_free(ctx);
		return NULL;
	}

	return ctx;
}
/* }}} */

static int php_openssl_enable_server_sni(php_stream *stream, php_openssl_netstream_data_t *sslsock)  /* {{{ */
{
	zval *val;
	zval *current;
	zend_string *key;
	zend_ulong key_index;
	int i = 0;
	char resolved_path_buff[MAXPATHLEN];
	SSL_CTX *ctx;

	/* If the stream ctx disables SNI we're finished here */
	if (GET_VER_OPT("SNI_enabled") && !zend_is_true(val)) {
		return SUCCESS;
	}

	/* If no SNI cert array is specified we're finished here */
	if (!GET_VER_OPT("SNI_server_certs")) {
		return SUCCESS;
	}

	if (Z_TYPE_P(val) != IS_ARRAY) {
		php_error_docref(NULL, E_WARNING,
			"SNI_server_certs requires an array mapping host names to cert paths"
		);
		return FAILURE;
	}

	sslsock->sni_cert_count = zend_hash_num_elements(Z_ARRVAL_P(val));
	if (sslsock->sni_cert_count == 0) {
		php_error_docref(NULL, E_WARNING,
			"SNI_server_certs host cert array must not be empty"
		);
		return FAILURE;
	}

	sslsock->sni_certs = (php_openssl_sni_cert_t*)safe_pemalloc(sslsock->sni_cert_count,
		sizeof(php_openssl_sni_cert_t), 0, php_stream_is_persistent(stream)
	);
	memset(sslsock->sni_certs, 0, sslsock->sni_cert_count * sizeof(php_openssl_sni_cert_t));

	ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(val), key_index, key, current) {
		(void) key_index;

		if (!key) {
			php_error_docref(NULL, E_WARNING,
				"SNI_server_certs array requires string host name keys"
			);
			return FAILURE;
		}

		if (Z_TYPE_P(current) == IS_ARRAY) {
			zval *local_pk, *local_cert;
			char resolved_cert_path_buff[MAXPATHLEN], resolved_pk_path_buff[MAXPATHLEN];

			local_cert = zend_hash_str_find(Z_ARRVAL_P(current), "local_cert", sizeof("local_cert")-1);
			if (local_cert == NULL) {
				php_error_docref(NULL, E_WARNING,
					"local_cert not present in the array",
					Z_STRVAL_P(local_cert)
				);
				return FAILURE;
			}
			convert_to_string_ex(local_cert);
			if (!VCWD_REALPATH(Z_STRVAL_P(local_cert), resolved_cert_path_buff)) {
				php_error_docref(NULL, E_WARNING,
					"failed setting local cert chain file `%s'; file not found"
				);
				return FAILURE;
			}
			local_pk = zend_hash_str_find(Z_ARRVAL_P(current), "local_pk", sizeof("local_pk")-1);
			if (local_pk == NULL) {
				php_error_docref(NULL, E_WARNING,
					"local_pk not present in the array"
				);
				return FAILURE;
			}
			convert_to_string_ex(local_pk);
			if (!VCWD_REALPATH(Z_STRVAL_P(local_pk), resolved_pk_path_buff)) {
				php_error_docref(NULL, E_WARNING,
					"failed setting local private key file `%s'; file not found",
					Z_STRVAL_P(local_pk)
				);
				return FAILURE;
			}

			ctx = php_openssl_create_sni_server_ctx(resolved_cert_path_buff, resolved_pk_path_buff);

		} else if (VCWD_REALPATH(Z_STRVAL_P(current), resolved_path_buff)) {
			ctx = php_openssl_create_sni_server_ctx(resolved_path_buff, resolved_path_buff);
		} else {
			php_error_docref(NULL, E_WARNING,
				"failed setting local cert chain file `%s'; file not found",
				Z_STRVAL_P(current)
			);
			return FAILURE;
		}

		if (ctx == NULL) {
			return FAILURE;
		}

		sslsock->sni_certs[i].name = pestrdup(ZSTR_VAL(key), php_stream_is_persistent(stream));
		sslsock->sni_certs[i].ctx = ctx;
		++i;

	} ZEND_HASH_FOREACH_END();

	SSL_CTX_set_tlsext_servername_callback(sslsock->ctx, php_openssl_server_sni_callback);

	return SUCCESS;
}
/* }}} */

static void php_openssl_enable_client_sni(php_stream *stream, php_openssl_netstream_data_t *sslsock) /* {{{ */
{
	zval *val;
	char *sni_server_name;

	/* If SNI is explicitly disabled we're finished here */
	if (GET_VER_OPT("SNI_enabled") && !zend_is_true(val)) {
		return;
	}

	sni_server_name = sslsock->url_name;

	GET_VER_OPT_STRING("peer_name", sni_server_name);

	if (sni_server_name) {
		SSL_set_tlsext_host_name(sslsock->ssl_handle, sni_server_name);
	}
}
/* }}} */
#endif

#ifdef HAVE_TLS_ALPN
/**
 * Parses a comma-separated list of strings into a string suitable for SSL_CTX_set_next_protos_advertised
 *   outlen: (output) set to the length of the resulting buffer on success.
 *   err: (maybe NULL) on failure, an error message line is written to this BIO.
 *   in: a NULL terminated string like "abc,def,ghi"
 *
 *   returns: an emalloced buffer or NULL on failure.
 */
static unsigned char *php_openssl_alpn_protos_parse(unsigned short *outlen, const char *in) /* {{{ */
{
	size_t len;
	unsigned char *out;
	size_t i, start = 0;

	len = strlen(in);
	if (len >= 65535) {
		return NULL;
	}

	out = emalloc(strlen(in) + 1);

	for (i = 0; i <= len; ++i) {
		if (i == len || in[i] == ',') {
			if (i - start > 255) {
				efree(out);
				return NULL;
			}
			out[start] = i - start;
			start = i + 1;
		} else {
			out[i + 1] = in[i];
		}
	}

	*outlen = len + 1;

	return out;
}
/* }}} */

static int php_openssl_server_alpn_callback(SSL *ssl_handle,
		const unsigned char **out, unsigned char *outlen,
		const unsigned char *in, unsigned int inlen, void *arg) /* {{{ */
{
	php_openssl_netstream_data_t *sslsock = arg;

	if (SSL_select_next_proto((unsigned char **)out, outlen, sslsock->alpn_ctx.data, sslsock->alpn_ctx.len, in, inlen) != OPENSSL_NPN_NEGOTIATED) {
		return SSL_TLSEXT_ERR_NOACK;
	}

	return SSL_TLSEXT_ERR_OK;
}
/* }}} */

#endif

int php_openssl_setup_crypto(php_stream *stream,
		php_openssl_netstream_data_t *sslsock,
		php_stream_xport_crypto_param *cparam) /* {{{ */
{
	const SSL_METHOD *method;
	int ssl_ctx_options;
	int method_flags;
	char *cipherlist = NULL;
	char *alpn_protocols = NULL;
	zval *val;

	if (sslsock->ssl_handle) {
		if (sslsock->s.is_blocked) {
			php_error_docref(NULL, E_WARNING, "SSL/TLS already set-up for this stream");
			return FAILURE;
		} else {
			return SUCCESS;
		}
	}

	ERR_clear_error();

	/* We need to do slightly different things based on client/server method
	 * so lets remember which method was selected */
	sslsock->is_client = cparam->inputs.method & STREAM_CRYPTO_IS_CLIENT;
	method_flags = ((cparam->inputs.method >> 1) << 1);

	/* Should we use a specific crypto method or is generic SSLv23 okay? */
	if ((method_flags & (method_flags-1)) == 0) {
		ssl_ctx_options = SSL_OP_ALL;
		method = php_openssl_select_crypto_method(method_flags, sslsock->is_client);
		if (method == NULL) {
			return FAILURE;
		}
	} else {
		method = sslsock->is_client ? SSLv23_client_method() : SSLv23_server_method();
		ssl_ctx_options = php_openssl_get_crypto_method_ctx_flags(method_flags);
		if (ssl_ctx_options == -1) {
			return FAILURE;
		}
	}

	sslsock->ctx = SSL_CTX_new(method);

	if (sslsock->ctx == NULL) {
		php_error_docref(NULL, E_WARNING, "SSL context creation failure");
		return FAILURE;
	}

	if (GET_VER_OPT("no_ticket") && zend_is_true(val)) {
		ssl_ctx_options |= SSL_OP_NO_TICKET;
	}

	ssl_ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;

	if (!GET_VER_OPT("disable_compression") || zend_is_true(val)) {
		ssl_ctx_options |= SSL_OP_NO_COMPRESSION;
	}

	if (GET_VER_OPT("verify_peer") && !zend_is_true(val)) {
		php_openssl_disable_peer_verification(sslsock->ctx, stream);
	} else if (FAILURE == php_openssl_enable_peer_verification(sslsock->ctx, stream)) {
		return FAILURE;
	}

	/* callback for the passphrase (for localcert) */
	if (GET_VER_OPT("passphrase")) {
		SSL_CTX_set_default_passwd_cb_userdata(sslsock->ctx, stream);
		SSL_CTX_set_default_passwd_cb(sslsock->ctx, php_openssl_passwd_callback);
	}

	GET_VER_OPT_STRING("ciphers", cipherlist);
#ifndef USE_OPENSSL_SYSTEM_CIPHERS
	if (!cipherlist) {
		cipherlist = OPENSSL_DEFAULT_STREAM_CIPHERS;
	}
#endif
	if (cipherlist) {
		if (SSL_CTX_set_cipher_list(sslsock->ctx, cipherlist) != 1) {
			return FAILURE;
		}
	}

	if (GET_VER_OPT("security_level")) {
#ifdef HAVE_SEC_LEVEL
		convert_to_long(val);
		if (Z_LVAL_P(val) < 0 || Z_LVAL_P(val) > 5) {
			php_error_docref(NULL, E_WARNING, "Security level must be between 0 and 5");
		}
		SSL_CTX_set_security_level(sslsock->ctx, Z_LVAL_P(val));
#else
		php_error_docref(NULL, E_WARNING,
				"security_level is not supported by the linked OpenSSL library "
				"- it is supported from version 1.1.0");
#endif
	}

	GET_VER_OPT_STRING("alpn_protocols", alpn_protocols);
	if (alpn_protocols) {
#ifdef HAVE_TLS_ALPN
		{
			unsigned short alpn_len;
			unsigned char *alpn = php_openssl_alpn_protos_parse(&alpn_len, alpn_protocols);

			if (alpn == NULL) {
				php_error_docref(NULL, E_WARNING, "Failed parsing comma-separated TLS ALPN protocol string");
				SSL_CTX_free(sslsock->ctx);
				sslsock->ctx = NULL;
				return FAILURE;
			}
			if (sslsock->is_client) {
				SSL_CTX_set_alpn_protos(sslsock->ctx, alpn, alpn_len);
			} else {
				sslsock->alpn_ctx.data = (unsigned char *) pestrndup((const char*)alpn, alpn_len, php_stream_is_persistent(stream));
				sslsock->alpn_ctx.len = alpn_len;
				SSL_CTX_set_alpn_select_cb(sslsock->ctx, php_openssl_server_alpn_callback, sslsock);
			}

			efree(alpn);
		}
#else
		php_error_docref(NULL, E_WARNING,
			"alpn_protocols support is not compiled into the OpenSSL library against which PHP is linked");
#endif
	}

	if (FAILURE == php_openssl_set_local_cert(sslsock->ctx, stream)) {
		return FAILURE;
	}

	SSL_CTX_set_options(sslsock->ctx, ssl_ctx_options);

	if (sslsock->is_client == 0 &&
		PHP_STREAM_CONTEXT(stream) &&
		FAILURE == php_openssl_set_server_specific_opts(stream, sslsock->ctx)
	) {
		return FAILURE;
	}

	sslsock->ssl_handle = SSL_new(sslsock->ctx);

	if (sslsock->ssl_handle == NULL) {
		php_error_docref(NULL, E_WARNING, "SSL handle creation failure");
		SSL_CTX_free(sslsock->ctx);
		sslsock->ctx = NULL;
#ifdef HAVE_TLS_ALPN
		if (sslsock->alpn_ctx.data) {
			pefree(sslsock->alpn_ctx.data, php_stream_is_persistent(stream));
			sslsock->alpn_ctx.data = NULL;
		}
#endif
		return FAILURE;
	} else {
		SSL_set_ex_data(sslsock->ssl_handle, php_openssl_get_ssl_stream_data_index(), stream);
	}

	if (!SSL_set_fd(sslsock->ssl_handle, sslsock->s.socket)) {
		php_openssl_handle_ssl_error(stream, 0, 1);
	}

#ifdef HAVE_TLS_SNI
	/* Enable server-side SNI */
	if (!sslsock->is_client && php_openssl_enable_server_sni(stream, sslsock) == FAILURE) {
		return FAILURE;
	}
#endif

	/* Enable server-side handshake renegotiation rate-limiting */
	if (!sslsock->is_client) {
		php_openssl_init_server_reneg_limit(stream, sslsock);
	}

#ifdef SSL_MODE_RELEASE_BUFFERS
	SSL_set_mode(sslsock->ssl_handle, SSL_get_mode(sslsock->ssl_handle) | SSL_MODE_RELEASE_BUFFERS);
#endif

	if (cparam->inputs.session) {
		if (cparam->inputs.session->ops != &php_openssl_socket_ops) {
			php_error_docref(NULL, E_WARNING, "supplied session stream must be an SSL enabled stream");
		} else if (((php_openssl_netstream_data_t*)cparam->inputs.session->abstract)->ssl_handle == NULL) {
			php_error_docref(NULL, E_WARNING, "supplied SSL session stream is not initialized");
		} else {
			SSL_copy_session_id(sslsock->ssl_handle, ((php_openssl_netstream_data_t*)cparam->inputs.session->abstract)->ssl_handle);
		}
	}

	return SUCCESS;
}
/* }}} */

static zend_array *php_openssl_capture_session_meta(SSL *ssl_handle) /* {{{ */
{
	zval meta_arr;
	char *proto_str;
	long proto = SSL_version(ssl_handle);
	const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl_handle);
	char version_str[PHP_SSL_MAX_VERSION_LEN];

	switch (proto) {
#ifdef HAVE_TLS12
		case TLS1_2_VERSION:
			proto_str = "TLSv1.2";
			break;
#endif
#ifdef HAVE_TLS11
		case TLS1_1_VERSION:
			proto_str = "TLSv1.1";
			break;
#endif
		case TLS1_VERSION:
			proto_str = "TLSv1";
			break;
#ifdef HAVE_SSL3
		case SSL3_VERSION:
			proto_str = "SSLv3";
			break;
#endif
		default: proto_str = "UNKNOWN";
	}

	array_init(&meta_arr);
	add_assoc_string(&meta_arr, "protocol", proto_str);
	add_assoc_string(&meta_arr, "cipher_name", (char *) SSL_CIPHER_get_name(cipher));
	add_assoc_long(&meta_arr, "cipher_bits", SSL_CIPHER_get_bits(cipher, NULL));
	add_assoc_string(&meta_arr, "cipher_version",
			php_openssl_cipher_get_version(cipher, version_str, PHP_SSL_MAX_VERSION_LEN));

	return Z_ARR(meta_arr);
}
/* }}} */

static int php_openssl_capture_peer_certs(php_stream *stream,
		php_openssl_netstream_data_t *sslsock, X509 *peer_cert) /* {{{ */
{
	zval *val, zcert;
	int cert_captured = 0;

	if (NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream),
			"ssl", "capture_peer_cert")) &&
		zend_is_true(val)
	) {
		ZVAL_RES(&zcert, zend_register_resource(peer_cert, php_openssl_get_x509_list_id()));
		php_stream_context_set_option(PHP_STREAM_CONTEXT(stream), "ssl", "peer_certificate", &zcert);
		zval_ptr_dtor(&zcert);
		cert_captured = 1;
	}

	if (NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream),
			"ssl", "capture_peer_cert_chain")) &&
		zend_is_true(val)
	) {
		zval arr;
		STACK_OF(X509) *chain;

		chain = SSL_get_peer_cert_chain(sslsock->ssl_handle);

		if (chain && sk_X509_num(chain) > 0) {
			int i;
			array_init(&arr);

			for (i = 0; i < sk_X509_num(chain); i++) {
				X509 *mycert = X509_dup(sk_X509_value(chain, i));
				ZVAL_RES(&zcert, zend_register_resource(mycert, php_openssl_get_x509_list_id()));
				add_next_index_zval(&arr, &zcert);
			}

		} else {
			ZVAL_NULL(&arr);
		}

		php_stream_context_set_option(PHP_STREAM_CONTEXT(stream), "ssl", "peer_certificate_chain", &arr);
		zval_ptr_dtor(&arr);
	}

	return cert_captured;
}
/* }}} */

static int php_openssl_enable_crypto(php_stream *stream,
		php_openssl_netstream_data_t *sslsock,
		php_stream_xport_crypto_param *cparam) /* {{{ */
{
	int n;
	int retry = 1;
	int cert_captured;
	X509 *peer_cert;

	if (cparam->inputs.activate && !sslsock->ssl_active) {
		struct timeval start_time, *timeout;
		int	blocked = sslsock->s.is_blocked, has_timeout = 0;

#ifdef HAVE_TLS_SNI
		if (sslsock->is_client) {
			php_openssl_enable_client_sni(stream, sslsock);
		}
#endif

		if (!sslsock->state_set) {
			if (sslsock->is_client) {
				SSL_set_connect_state(sslsock->ssl_handle);
			} else {
				SSL_set_accept_state(sslsock->ssl_handle);
			}
			sslsock->state_set = 1;
		}

		if (SUCCESS == php_set_sock_blocking(sslsock->s.socket, 0)) {
			sslsock->s.is_blocked = 0;
			/* The following mode are added only if we are able to change socket
			 * to non blocking mode which is also used for read and write */
			SSL_set_mode(
				sslsock->ssl_handle,
				(
					SSL_get_mode(sslsock->ssl_handle) |
					SSL_MODE_ENABLE_PARTIAL_WRITE |
					SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
				)
			);
		}

		timeout = sslsock->is_client ? &sslsock->connect_timeout : &sslsock->s.timeout;
		has_timeout = !sslsock->s.is_blocked && (timeout->tv_sec || timeout->tv_usec);
		/* gettimeofday is not monotonic; using it here is not strictly correct */
		if (has_timeout) {
			gettimeofday(&start_time, NULL);
		}

		do {
			struct timeval cur_time, elapsed_time;
			
			if (sslsock->is_client) {
				n = SSL_connect(sslsock->ssl_handle);
			} else {
				n = SSL_accept(sslsock->ssl_handle);
			}

			if (has_timeout) {
				gettimeofday(&cur_time, NULL);
				elapsed_time = php_openssl_subtract_timeval(cur_time, start_time);
			
				if (php_openssl_compare_timeval( elapsed_time, *timeout) > 0) {
					php_error_docref(NULL, E_WARNING, "SSL: Handshake timed out");
					return -1;
				}
			}

			if (n <= 0) {
				/* in case of SSL_ERROR_WANT_READ/WRITE, do not retry in non-blocking mode */
				retry = php_openssl_handle_ssl_error(stream, n, blocked);
				if (retry) {
					/* wait until something interesting happens in the socket. It may be a
					 * timeout. Also consider the unlikely of possibility of a write block  */
					int err = SSL_get_error(sslsock->ssl_handle, n);
					struct timeval left_time;

					if (has_timeout) {
						left_time = php_openssl_subtract_timeval(*timeout, elapsed_time);
					}
					php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_READ) ?
						(POLLIN|POLLPRI) : POLLOUT, has_timeout ? &left_time : NULL);
				}
			} else {
				retry = 0;
			}
		} while (retry);

		if (sslsock->s.is_blocked != blocked && SUCCESS == php_set_sock_blocking(sslsock->s.socket, blocked)) {
			sslsock->s.is_blocked = blocked;
		}

		if (n == 1) {
			peer_cert = SSL_get_peer_certificate(sslsock->ssl_handle);
			if (peer_cert && PHP_STREAM_CONTEXT(stream)) {
				cert_captured = php_openssl_capture_peer_certs(stream, sslsock, peer_cert);
			}

			if (FAILURE == php_openssl_apply_peer_verification_policy(sslsock->ssl_handle, peer_cert, stream)) {
				SSL_shutdown(sslsock->ssl_handle);
				n = -1;
			} else {
				sslsock->ssl_active = 1;

				if (PHP_STREAM_CONTEXT(stream)) {
					zval *val;
					if (NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream),
						"ssl", "capture_session_meta"))
					) {
						 php_error(E_DEPRECATED,
							"capture_session_meta is deprecated; its information is now available via stream_get_meta_data()"
                        );
					}

					if (val && zend_is_true(val)) {
						zval meta_arr;
						ZVAL_ARR(&meta_arr, php_openssl_capture_session_meta(sslsock->ssl_handle));
						php_stream_context_set_option(PHP_STREAM_CONTEXT(stream), "ssl", "session_meta", &meta_arr);
						zval_ptr_dtor(&meta_arr);
					}
				}
			}
		} else if (errno == EAGAIN) {
			n = 0;
		} else {
			n = -1;
			/* We want to capture the peer cert even if verification fails*/
			peer_cert = SSL_get_peer_certificate(sslsock->ssl_handle);
			if (peer_cert && PHP_STREAM_CONTEXT(stream)) {
				cert_captured = php_openssl_capture_peer_certs(stream, sslsock, peer_cert);
			}
		}

		if (n && peer_cert && cert_captured == 0) {
			X509_free(peer_cert);
		}

		return n;

	} else if (!cparam->inputs.activate && sslsock->ssl_active) {
		/* deactivate - common for server/client */
		SSL_shutdown(sslsock->ssl_handle);
		sslsock->ssl_active = 0;
	}

	return -1;
}
/* }}} */

static size_t php_openssl_sockop_read(php_stream *stream, char *buf, size_t count) /* {{{ */
{
	return php_openssl_sockop_io( 1, stream, buf, count );
}
/* }}} */

static size_t php_openssl_sockop_write(php_stream *stream, const char *buf, size_t count) /* {{{ */
{
	return php_openssl_sockop_io( 0, stream, (char*)buf, count );
}
/* }}} */

/**
 * Factored out common functionality (blocking, timeout, loop management) for read and write.
 * Perform IO (read or write) to an SSL socket. If we have a timeout, we switch to non-blocking mode
 * for the duration of the operation, using select to do our waits. If we time out, or we have an error
 * report that back to PHP
 */
static size_t php_openssl_sockop_io(int read, php_stream *stream, char *buf, size_t count) /* {{{ */
{
	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;

	/* Only do this if SSL is active. */
	if (sslsock->ssl_active) {
		int retry = 1;
		struct timeval start_time;
		struct timeval *timeout = NULL;
		int began_blocked = sslsock->s.is_blocked;
		int has_timeout = 0;
		int nr_bytes = 0;

		/* prevent overflow in openssl */
		if (count > INT_MAX) {
			count = INT_MAX;
		}

		/* never use a timeout with non-blocking sockets */
		if (began_blocked) {
			timeout = &sslsock->s.timeout;
		}

		if (timeout && php_set_sock_blocking(sslsock->s.socket, 0) == SUCCESS) {
			sslsock->s.is_blocked = 0;
		}

		if (!sslsock->s.is_blocked && timeout && (timeout->tv_sec || timeout->tv_usec)) {
			has_timeout = 1;
			/* gettimeofday is not monotonic; using it here is not strictly correct */
			gettimeofday(&start_time, NULL);
		}

		/* Main IO loop. */
		do {
			struct timeval cur_time, elapsed_time, left_time;

			/* If we have a timeout to check, figure out how much time has elapsed since we started. */
			if (has_timeout) {
				gettimeofday(&cur_time, NULL);

				/* Determine how much time we've taken so far. */
				elapsed_time = php_openssl_subtract_timeval(cur_time, start_time);

				/* and return an error if we've taken too long. */
				if (php_openssl_compare_timeval(elapsed_time, *timeout) > 0 ) {
					/* If the socket was originally blocking, set it back. */
					if (began_blocked) {
						php_set_sock_blocking(sslsock->s.socket, 1);
						sslsock->s.is_blocked = 1;
					}
					sslsock->s.timeout_event = 1;
					return -1;
				}
			}

			/* Now, do the IO operation. Don't block if we can't complete... */
			if (read) {
				nr_bytes = SSL_read(sslsock->ssl_handle, buf, (int)count);

				if (sslsock->reneg && sslsock->reneg->should_close) {
					/* renegotiation rate limiting triggered */
					php_stream_xport_shutdown(stream, (stream_shutdown_t)SHUT_RDWR);
					nr_bytes = 0;
					stream->eof = 1;
					 break;
				}
			} else {
				nr_bytes = SSL_write(sslsock->ssl_handle, buf, (int)count);
			}

			/* Now, how much time until we time out? */
			if (has_timeout) {
				left_time = php_openssl_subtract_timeval( *timeout, elapsed_time );
			}

			/* If we didn't do anything on the last loop (or an error) check to see if we should retry or exit. */
			if (nr_bytes <= 0) {

				/* Get the error code from SSL, and check to see if it's an error or not. */
				int err = SSL_get_error(sslsock->ssl_handle, nr_bytes );
				retry = php_openssl_handle_ssl_error(stream, nr_bytes, 0);

				/* If we get this (the above doesn't check) then we'll retry as well. */
				if (errno == EAGAIN && err == SSL_ERROR_WANT_READ && read) {
					retry = 1;
				}
				if (errno == EAGAIN && err == SSL_ERROR_WANT_WRITE && read == 0) {
					retry = 1;
				}
				
				/* Also, on reads, we may get this condition on an EOF. We should check properly. */
				if (read) {
					stream->eof = (retry == 0 && errno != EAGAIN && !SSL_pending(sslsock->ssl_handle));
				}

				/* Don't loop indefinitely in non-blocking mode if no data is available */
				if (began_blocked == 0) {
					break;
				}

				/* Now, if we have to wait some time, and we're supposed to be blocking, wait for the socket to become
				 * available. Now, php_pollfd_for uses select to wait up to our time_left value only...
				 */
				if (retry) {
					if (read) {
						php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_WRITE) ?
							(POLLOUT|POLLPRI) : (POLLIN|POLLPRI), has_timeout ? &left_time : NULL);
					} else {
						php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_READ) ?
							(POLLIN|POLLPRI) : (POLLOUT|POLLPRI), has_timeout ? &left_time : NULL);
					}
				}
			} else {
				/* Else, if we got bytes back, check for possible errors. */
				int err = SSL_get_error(sslsock->ssl_handle, nr_bytes);

				/* If we didn't get any error, then let's return it to PHP. */
				if (err == SSL_ERROR_NONE) {
					break;
				}

				/* Otherwise, we need to wait again (up to time_left or we get an error) */
				if (began_blocked) {
					if (read) {
						php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_WRITE) ?
							(POLLOUT|POLLPRI) : (POLLIN|POLLPRI), has_timeout ? &left_time : NULL);
					} else {
						php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_READ) ?
							(POLLIN|POLLPRI) : (POLLOUT|POLLPRI), has_timeout ? &left_time : NULL);
					}
				}
			}

			/* Finally, we keep going until we got data, and an SSL_ERROR_NONE, unless we had an error. */			
		} while (retry);

		/* Tell PHP if we read / wrote bytes. */
		if (nr_bytes > 0) {
			php_stream_notify_progress_increment(PHP_STREAM_CONTEXT(stream), nr_bytes, 0);
		}

		/* And if we were originally supposed to be blocking, let's reset the socket to that. */
		if (began_blocked && php_set_sock_blocking(sslsock->s.socket, 1) == SUCCESS) {
			sslsock->s.is_blocked = 1;
		}

		return 0 > nr_bytes ? 0 : nr_bytes;
	} else {
		size_t nr_bytes = 0;

		/* This block is if we had no timeout... We will just sit and wait forever on the IO operation. */
		if (read) {
			nr_bytes = php_stream_socket_ops.read(stream, buf, count);
		} else {
			nr_bytes = php_stream_socket_ops.write(stream, buf, count);
		}

		return nr_bytes;
	}
}
/* }}} */

static struct timeval php_openssl_subtract_timeval(struct timeval a, struct timeval b) /* {{{ */
{
	struct timeval difference;

	difference.tv_sec  = a.tv_sec  - b.tv_sec;
	difference.tv_usec = a.tv_usec - b.tv_usec;

	if (a.tv_usec < b.tv_usec) {
	  	b.tv_sec  -= 1L;
	   	b.tv_usec += 1000000L;
	}

	return difference;
}
/* }}} */

static int php_openssl_compare_timeval( struct timeval a, struct timeval b )
{
	if (a.tv_sec > b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_usec > b.tv_usec) ) {
		return 1;
	} else if( a.tv_sec == b.tv_sec && a.tv_usec == b.tv_usec ) {
		return 0;
	} else {
		return -1;
	}
}

static int php_openssl_sockop_close(php_stream *stream, int close_handle) /* {{{ */
{
	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
#ifdef PHP_WIN32
	int n;
#endif
	unsigned i;

	if (close_handle) {
		if (sslsock->ssl_active) {
			SSL_shutdown(sslsock->ssl_handle);
			sslsock->ssl_active = 0;
		}
		if (sslsock->ssl_handle) {
			SSL_free(sslsock->ssl_handle);
			sslsock->ssl_handle = NULL;
		}
		if (sslsock->ctx) {
			SSL_CTX_free(sslsock->ctx);
			sslsock->ctx = NULL;
		}
#ifdef HAVE_TLS_ALPN
		if (sslsock->alpn_ctx.data) {
			pefree(sslsock->alpn_ctx.data, php_stream_is_persistent(stream));
		}
#endif
#ifdef PHP_WIN32
		if (sslsock->s.socket == -1)
			sslsock->s.socket = SOCK_ERR;
#endif
		if (sslsock->s.socket != SOCK_ERR) {
#ifdef PHP_WIN32
			/* prevent more data from coming in */
			shutdown(sslsock->s.socket, SHUT_RD);

			/* try to make sure that the OS sends all data before we close the connection.
			 * Essentially, we are waiting for the socket to become writeable, which means
			 * that all pending data has been sent.
			 * We use a small timeout which should encourage the OS to send the data,
			 * but at the same time avoid hanging indefinitely.
			 * */
			do {
				n = php_pollfd_for_ms(sslsock->s.socket, POLLOUT, 500);
			} while (n == -1 && php_socket_errno() == EINTR);
#endif
			closesocket(sslsock->s.socket);
			sslsock->s.socket = SOCK_ERR;
		}
	}

	if (sslsock->sni_certs) {
		for (i = 0; i < sslsock->sni_cert_count; i++) {
			if (sslsock->sni_certs[i].ctx) {
				SSL_CTX_free(sslsock->sni_certs[i].ctx);
				pefree(sslsock->sni_certs[i].name, php_stream_is_persistent(stream));
			}
		}
		pefree(sslsock->sni_certs, php_stream_is_persistent(stream));
		sslsock->sni_certs = NULL;
	}

	if (sslsock->url_name) {
		pefree(sslsock->url_name, php_stream_is_persistent(stream));
	}

	if (sslsock->reneg) {
		pefree(sslsock->reneg, php_stream_is_persistent(stream));
	}

	pefree(sslsock, php_stream_is_persistent(stream));

	return 0;
}
/* }}} */

static int php_openssl_sockop_flush(php_stream *stream) /* {{{ */
{
	return php_stream_socket_ops.flush(stream);
}
/* }}} */

static int php_openssl_sockop_stat(php_stream *stream, php_stream_statbuf *ssb) /* {{{ */
{
	return php_stream_socket_ops.stat(stream, ssb);
}
/* }}} */

static inline int php_openssl_tcp_sockop_accept(php_stream *stream, php_openssl_netstream_data_t *sock,
		php_stream_xport_param *xparam STREAMS_DC)  /* {{{ */
{
	int clisock;
	zend_bool nodelay = 0;
	zval *tmpzval = NULL;
	
	xparam->outputs.client = NULL;

	if ((tmpzval = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "socket", "tcp_nodelay")) != NULL &&
		zend_is_true(tmpzval)) {
		nodelay = 1;
	}

	clisock = php_network_accept_incoming(sock->s.socket,
		xparam->want_textaddr ? &xparam->outputs.textaddr : NULL,
		xparam->want_addr ? &xparam->outputs.addr : NULL,
		xparam->want_addr ? &xparam->outputs.addrlen : NULL,
		xparam->inputs.timeout,
		xparam->want_errortext ? &xparam->outputs.error_text : NULL,
		&xparam->outputs.error_code,
		nodelay);

	if (clisock >= 0) {
		php_openssl_netstream_data_t *clisockdata = (php_openssl_netstream_data_t*) emalloc(sizeof(*clisockdata));

		/* copy underlying tcp fields */
		memset(clisockdata, 0, sizeof(*clisockdata));
		memcpy(clisockdata, sock, sizeof(clisockdata->s));

		clisockdata->s.socket = clisock;

		xparam->outputs.client = php_stream_alloc_rel(stream->ops, clisockdata, NULL, "r+");
		if (xparam->outputs.client) {
			xparam->outputs.client->ctx = stream->ctx;
			if (stream->ctx) {
				GC_REFCOUNT(stream->ctx)++;
			}
		}

		if (xparam->outputs.client && sock->enable_on_connect) {
			/* remove the client bit */
			if (sock->method & STREAM_CRYPTO_IS_CLIENT) {
				sock->method = ((sock->method >> 1) << 1);
			}

			clisockdata->method = sock->method;

			if (php_stream_xport_crypto_setup(xparam->outputs.client, clisockdata->method,
					NULL) < 0 || php_stream_xport_crypto_enable(
					xparam->outputs.client, 1) < 0) {
				php_error_docref(NULL, E_WARNING, "Failed to enable crypto");

				php_stream_close(xparam->outputs.client);
				xparam->outputs.client = NULL;
				xparam->outputs.returncode = -1;
			}
		}
	}

	return xparam->outputs.client == NULL ? -1 : 0;
}
/* }}} */

static int php_openssl_sockop_set_option(php_stream *stream, int option, int value, void *ptrparam)  /* {{{ */
{
	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
	php_stream_xport_crypto_param *cparam = (php_stream_xport_crypto_param *)ptrparam;
	php_stream_xport_param *xparam = (php_stream_xport_param *)ptrparam;

	switch (option) {
		case PHP_STREAM_OPTION_META_DATA_API:
			if (sslsock->ssl_active) {
				zval tmp;
				char *proto_str;
				char version_str[PHP_SSL_MAX_VERSION_LEN];
				const SSL_CIPHER *cipher;

				array_init(&tmp);

				switch (SSL_version(sslsock->ssl_handle)) {
#ifdef HAVE_TLS12
					case TLS1_2_VERSION: proto_str = "TLSv1.2"; break;
#endif
#ifdef HAVE_TLS11
					case TLS1_1_VERSION: proto_str = "TLSv1.1"; break;
#endif
					case TLS1_VERSION: proto_str = "TLSv1"; break;
#ifdef HAVE_SSL3
					case SSL3_VERSION: proto_str = "SSLv3"; break;
#endif
					default: proto_str = "UNKNOWN";
				}

				cipher = SSL_get_current_cipher(sslsock->ssl_handle);

				add_assoc_string(&tmp, "protocol", proto_str);
				add_assoc_string(&tmp, "cipher_name", (char *) SSL_CIPHER_get_name(cipher));
				add_assoc_long(&tmp, "cipher_bits", SSL_CIPHER_get_bits(cipher, NULL));
				add_assoc_string(&tmp, "cipher_version",
						php_openssl_cipher_get_version(cipher, version_str, PHP_SSL_MAX_VERSION_LEN));

#ifdef HAVE_TLS_ALPN
				{
					const unsigned char *alpn_proto = NULL;
					unsigned int alpn_proto_len = 0;

					SSL_get0_alpn_selected(sslsock->ssl_handle, &alpn_proto, &alpn_proto_len);
					if (alpn_proto) {
						add_assoc_stringl(&tmp, "alpn_protocol", (char *)alpn_proto, alpn_proto_len);
					}
				}
#endif
				add_assoc_zval((zval *)ptrparam, "crypto", &tmp);
			}

			add_assoc_bool((zval *)ptrparam, "timed_out", sslsock->s.timeout_event);
			add_assoc_bool((zval *)ptrparam, "blocked", sslsock->s.is_blocked);
			add_assoc_bool((zval *)ptrparam, "eof", stream->eof);

			return PHP_STREAM_OPTION_RETURN_OK;

		case PHP_STREAM_OPTION_CHECK_LIVENESS:
			{
				struct timeval tv;
				char buf;
				int alive = 1;

				if (value == -1) {
					if (sslsock->s.timeout.tv_sec == -1) {
#ifdef _WIN32
						tv.tv_sec = (long)FG(default_socket_timeout);
#else
						tv.tv_sec = (time_t)FG(default_socket_timeout);
#endif
						tv.tv_usec = 0;
					} else {
						tv = sslsock->connect_timeout;
					}
				} else {
					tv.tv_sec = value;
					tv.tv_usec = 0;
				}

				if (sslsock->s.socket == -1) {
					alive = 0;
				} else if (php_pollfd_for(sslsock->s.socket, PHP_POLLREADABLE|POLLPRI, &tv) > 0) {
					if (sslsock->ssl_active) {
						int n;

						do {
							n = SSL_peek(sslsock->ssl_handle, &buf, sizeof(buf));
							if (n <= 0) {
								int err = SSL_get_error(sslsock->ssl_handle, n);

								if (err == SSL_ERROR_SYSCALL) {
									alive = php_socket_errno() == EAGAIN;
									break;
								}

								if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
									/* re-negotiate */
									continue;
								}

								/* any other problem is a fatal error */
								alive = 0;
							}
							/* either peek succeeded or there was an error; we
							 * have set the alive flag appropriately */
							break;
						} while (1);
					} else if (0 == recv(sslsock->s.socket, &buf, sizeof(buf), MSG_PEEK) && php_socket_errno() != EAGAIN) {
						alive = 0;
					}
				}
				return alive ? PHP_STREAM_OPTION_RETURN_OK : PHP_STREAM_OPTION_RETURN_ERR;
			}

		case PHP_STREAM_OPTION_CRYPTO_API:

			switch(cparam->op) {

				case STREAM_XPORT_CRYPTO_OP_SETUP:
					cparam->outputs.returncode = php_openssl_setup_crypto(stream, sslsock, cparam);
					return PHP_STREAM_OPTION_RETURN_OK;
					break;
				case STREAM_XPORT_CRYPTO_OP_ENABLE:
					cparam->outputs.returncode = php_openssl_enable_crypto(stream, sslsock, cparam);
					return PHP_STREAM_OPTION_RETURN_OK;
					break;
				default:
					/* fall through */
					break;
			}

			break;

		case PHP_STREAM_OPTION_XPORT_API:
			switch(xparam->op) {

				case STREAM_XPORT_OP_CONNECT:
				case STREAM_XPORT_OP_CONNECT_ASYNC:
					/* TODO: Async connects need to check the enable_on_connect option when
					 * we notice that the connect has actually been established */
					php_stream_socket_ops.set_option(stream, option, value, ptrparam);

					if ((sslsock->enable_on_connect) &&
						((xparam->outputs.returncode == 0) ||
						(xparam->op == STREAM_XPORT_OP_CONNECT_ASYNC &&
						xparam->outputs.returncode == 1 && xparam->outputs.error_code == EINPROGRESS)))
					{
						if (php_stream_xport_crypto_setup(stream, sslsock->method, NULL) < 0 ||
								php_stream_xport_crypto_enable(stream, 1) < 0) {
							php_error_docref(NULL, E_WARNING, "Failed to enable crypto");
							xparam->outputs.returncode = -1;
						}
					}
					return PHP_STREAM_OPTION_RETURN_OK;

				case STREAM_XPORT_OP_ACCEPT:
					/* we need to copy the additional fields that the underlying tcp transport
					 * doesn't know about */
					xparam->outputs.returncode = php_openssl_tcp_sockop_accept(stream, sslsock, xparam STREAMS_CC);


					return PHP_STREAM_OPTION_RETURN_OK;

				default:
					/* fall through */
					break;
			}
	}

	return php_stream_socket_ops.set_option(stream, option, value, ptrparam);
}
/* }}} */

static int php_openssl_sockop_cast(php_stream *stream, int castas, void **ret)  /* {{{ */
{
	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;

	switch(castas)	{
		case PHP_STREAM_AS_STDIO:
			if (sslsock->ssl_active) {
				return FAILURE;
			}
			if (ret)	{
				*ret = fdopen(sslsock->s.socket, stream->mode);
				if (*ret) {
					return SUCCESS;
				}
				return FAILURE;
			}
			return SUCCESS;

		case PHP_STREAM_AS_FD_FOR_SELECT:
			if (ret) {
				size_t pending;
				if (stream->writepos == stream->readpos
					&& sslsock->ssl_active
					&& (pending = (size_t)SSL_pending(sslsock->ssl_handle)) > 0) {
						php_stream_fill_read_buffer(stream, pending < stream->chunk_size
							? pending
							: stream->chunk_size);
				}

				*(php_socket_t *)ret = sslsock->s.socket;
			}
			return SUCCESS;

		case PHP_STREAM_AS_FD:
		case PHP_STREAM_AS_SOCKETD:
			if (sslsock->ssl_active) {
				return FAILURE;
			}
			if (ret) {
				*(php_socket_t *)ret = sslsock->s.socket;
			}
			return SUCCESS;
		default:
			return FAILURE;
	}
}
/* }}} */

php_stream_ops php_openssl_socket_ops = {
	php_openssl_sockop_write, php_openssl_sockop_read,
	php_openssl_sockop_close, php_openssl_sockop_flush,
	"tcp_socket/ssl",
	NULL, /* seek */
	php_openssl_sockop_cast,
	php_openssl_sockop_stat,
	php_openssl_sockop_set_option,
};

static zend_long php_openssl_get_crypto_method(
		php_stream_context *ctx, zend_long crypto_method)  /* {{{ */
{
	zval *val;

	if (ctx && (val = php_stream_context_get_option(ctx, "ssl", "crypto_method")) != NULL) {
		convert_to_long_ex(val);
		crypto_method = (zend_long)Z_LVAL_P(val);
		crypto_method |= STREAM_CRYPTO_IS_CLIENT;
	}

	return crypto_method;
}
/* }}} */

static char *php_openssl_get_url_name(const char *resourcename,
		size_t resourcenamelen, int is_persistent)  /* {{{ */
{
	php_url *url;

	if (!resourcename) {
		return NULL;
	}

	url = php_url_parse_ex(resourcename, resourcenamelen);
	if (!url) {
		return NULL;
	}

	if (url->host) {
		const char * host = url->host;
		char * url_name = NULL;
		size_t len = strlen(host);

		/* skip trailing dots */
		while (len && host[len-1] == '.') {
			--len;
		}

		if (len) {
			url_name = pestrndup(host, len, is_persistent);
		}

		php_url_free(url);
		return url_name;
	}

	php_url_free(url);
	return NULL;
}
/* }}} */

php_stream *php_openssl_ssl_socket_factory(const char *proto, size_t protolen,
		const char *resourcename, size_t resourcenamelen,
		const char *persistent_id, int options, int flags,
		struct timeval *timeout,
		php_stream_context *context STREAMS_DC) /* {{{ */
{
	php_stream *stream = NULL;
	php_openssl_netstream_data_t *sslsock = NULL;

	sslsock = pemalloc(sizeof(php_openssl_netstream_data_t), persistent_id ? 1 : 0);
	memset(sslsock, 0, sizeof(*sslsock));

	sslsock->s.is_blocked = 1;
	/* this timeout is used by standard stream funcs, therefor it should use the default value */
#ifdef _WIN32
	sslsock->s.timeout.tv_sec = (long)FG(default_socket_timeout);
#else
	sslsock->s.timeout.tv_sec = (time_t)FG(default_socket_timeout);
#endif
	sslsock->s.timeout.tv_usec = 0;

	/* use separate timeout for our private funcs */
	sslsock->connect_timeout.tv_sec = timeout->tv_sec;
	sslsock->connect_timeout.tv_usec = timeout->tv_usec;

	/* we don't know the socket until we have determined if we are binding or
	 * connecting */
	sslsock->s.socket = -1;

	/* Initialize context as NULL */
	sslsock->ctx = NULL;

	stream = php_stream_alloc_rel(&php_openssl_socket_ops, sslsock, persistent_id, "r+");

	if (stream == NULL)	{
		pefree(sslsock, persistent_id ? 1 : 0);
		return NULL;
	}

	if (strncmp(proto, "ssl", protolen) == 0) {
		sslsock->enable_on_connect = 1;
		sslsock->method = php_openssl_get_crypto_method(context, STREAM_CRYPTO_METHOD_TLS_ANY_CLIENT);
	} else if (strncmp(proto, "sslv2", protolen) == 0) {
		php_error_docref(NULL, E_WARNING, "SSLv2 unavailable in this PHP version");
		php_stream_close(stream);
		return NULL;
	} else if (strncmp(proto, "sslv3", protolen) == 0) {
#ifdef HAVE_SSL3
		sslsock->enable_on_connect = 1;
		sslsock->method = STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
#else
		php_error_docref(NULL, E_WARNING,
			"SSLv3 support is not compiled into the OpenSSL library against which PHP is linked");
		php_stream_close(stream);
		return NULL;
#endif
	} else if (strncmp(proto, "tls", protolen) == 0) {
		sslsock->enable_on_connect = 1;
		sslsock->method = php_openssl_get_crypto_method(context, STREAM_CRYPTO_METHOD_TLS_ANY_CLIENT);
	} else if (strncmp(proto, "tlsv1.0", protolen) == 0) {
		sslsock->enable_on_connect = 1;
		sslsock->method = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT;
	} else if (strncmp(proto, "tlsv1.1", protolen) == 0) {
#ifdef HAVE_TLS11
		sslsock->enable_on_connect = 1;
		sslsock->method = STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
#else
		php_error_docref(NULL, E_WARNING,
			"TLSv1.1 support is not compiled into the OpenSSL library against which PHP is linked");
		php_stream_close(stream);
		return NULL;
#endif
	} else if (strncmp(proto, "tlsv1.2", protolen) == 0) {
#ifdef HAVE_TLS12
		sslsock->enable_on_connect = 1;
		sslsock->method = STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
#else
		php_error_docref(NULL, E_WARNING,
			"TLSv1.2 support is not compiled into the OpenSSL library against which PHP is linked");
		php_stream_close(stream);
		return NULL;
#endif
	}

	sslsock->url_name = php_openssl_get_url_name(resourcename, resourcenamelen, !!persistent_id);

	return stream;
}
/* }}} */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */