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
//! SSL/TLS encryption support using Secure Transport.
//!
//! # Examples
//!
//! To connect as a client to a server with a certificate trusted by the system:
//!
//! ```rust
//! use std::io::prelude::*;
//! use std::net::TcpStream;
//! use security_framework::secure_transport::ClientBuilder;
//!
//! let stream = TcpStream::connect("google.com:443").unwrap();
//! let mut stream = ClientBuilder::new().handshake("google.com", stream).unwrap();
//!
//! stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
//! let mut page = vec![];
//! stream.read_to_end(&mut page).unwrap();
//! println!("{}", String::from_utf8_lossy(&page));
//! ```
//!
//! To connect to a server with a certificate that's *not* trusted by the
//! system, specify the root certificates for the server's chain to the
//! `ClientBuilder`:
//!
//! ```rust,no_run
//! use std::io::prelude::*;
//! use std::net::TcpStream;
//! use security_framework::secure_transport::ClientBuilder;
//!
//! # let root_cert = unsafe { std::mem::zeroed() };
//! let stream = TcpStream::connect("my_server.com:443").unwrap();
//! let mut stream = ClientBuilder::new()
//!                      .anchor_certificates(&[root_cert])
//!                      .handshake("my_server.com", stream)
//!                      .unwrap();
//!
//! stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
//! let mut page = vec![];
//! stream.read_to_end(&mut page).unwrap();
//! println!("{}", String::from_utf8_lossy(&page));
//! ```
//!
//! For more advanced configuration, the `SslContext` type can be used directly.
//!
//! To run a server:
//!
//! ```rust,no_run
//! use std::net::TcpListener;
//! use std::thread;
//! use security_framework::secure_transport::{SslContext, SslProtocolSide, SslConnectionType};
//!
//! // Create a TCP listener and start accepting on it.
//! let mut listener = TcpListener::bind("0.0.0.0:443").unwrap();
//!
//! for stream in listener.incoming() {
//!     let stream = stream.unwrap();
//!     thread::spawn(move || {
//!         // Create a new context configured to operate on the server side of
//!         // a traditional SSL/TLS session.
//!         let mut ctx = SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)
//!                           .unwrap();
//!
//!         // Install the certificate chain that we will be using.
//!         # let identity = unsafe { std::mem::zeroed() };
//!         # let intermediate_cert = unsafe { std::mem::zeroed() };
//!         # let root_cert = unsafe { std::mem::zeroed() };
//!         ctx.set_certificate(identity, &[intermediate_cert, root_cert]).unwrap();
//!
//!         // Perform the SSL/TLS handshake and get our stream.
//!         let mut stream = ctx.handshake(stream).unwrap();
//!     });
//! }
//!
//! ```
#[allow(unused_imports)]
use core_foundation::array::{CFArray, CFArrayRef};

use core_foundation::base::{Boolean, TCFType};
#[cfg(feature = "alpn")]
use core_foundation::string::CFString;
use core_foundation_sys::base::{kCFAllocatorDefault, OSStatus};
use std::os::raw::c_void;

#[allow(unused_imports)]
use security_framework_sys::base::{
    errSecBadReq, errSecIO, errSecNotTrusted, errSecSuccess, errSecTrustSettingDeny,
    errSecUnimplemented,
};

use security_framework_sys::secure_transport::*;
use std::any::Any;
use std::cmp;
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::marker::PhantomData;
use std::mem;
use std::panic::{self, AssertUnwindSafe};
use std::ptr;
use std::result;
use std::slice;

use crate::base::{Error, Result};
use crate::certificate::SecCertificate;
use crate::cipher_suite::CipherSuite;
use crate::identity::SecIdentity;
use crate::policy::SecPolicy;
use crate::trust::{SecTrust, TrustResult};
use crate::{cvt, AsInner};

/// Specifies a side of a TLS session.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct SslProtocolSide(SSLProtocolSide);

impl SslProtocolSide {
    /// The server side of the session.
    pub const SERVER: Self = Self(kSSLServerSide);

    /// The client side of the session.
    pub const CLIENT: Self = Self(kSSLClientSide);
}

/// Specifies the type of TLS session.
#[derive(Debug, Copy, Clone)]
pub struct SslConnectionType(SSLConnectionType);

impl SslConnectionType {
    /// A traditional TLS stream.
    pub const STREAM: Self = Self(kSSLStreamType);

    /// A DTLS session.
    pub const DATAGRAM: Self = Self(kSSLDatagramType);
}

/// An error or intermediate state after a TLS handshake attempt.
#[derive(Debug)]
pub enum HandshakeError<S> {
    /// The handshake failed.
    Failure(Error),
    /// The handshake was interrupted midway through.
    Interrupted(MidHandshakeSslStream<S>),
}

impl<S> From<Error> for HandshakeError<S> {
    fn from(err: Error) -> Self {
        Self::Failure(err)
    }
}

/// An error or intermediate state after a TLS handshake attempt.
#[derive(Debug)]
pub enum ClientHandshakeError<S> {
    /// The handshake failed.
    Failure(Error),
    /// The handshake was interrupted midway through.
    Interrupted(MidHandshakeClientBuilder<S>),
}

impl<S> From<Error> for ClientHandshakeError<S> {
    fn from(err: Error) -> Self {
        Self::Failure(err)
    }
}

/// An SSL stream midway through the handshake process.
#[derive(Debug)]
pub struct MidHandshakeSslStream<S> {
    stream: SslStream<S>,
    error: Error,
}

impl<S> MidHandshakeSslStream<S> {
    /// Returns a shared reference to the inner stream.
    pub fn get_ref(&self) -> &S {
        self.stream.get_ref()
    }

    /// Returns a mutable reference to the inner stream.
    pub fn get_mut(&mut self) -> &mut S {
        self.stream.get_mut()
    }

    /// Returns a shared reference to the `SslContext` of the stream.
    pub fn context(&self) -> &SslContext {
        self.stream.context()
    }

    /// Returns a mutable reference to the `SslContext` of the stream.
    pub fn context_mut(&mut self) -> &mut SslContext {
        self.stream.context_mut()
    }

    /// Returns `true` iff `break_on_server_auth` was set and the handshake has
    /// progressed to that point.
    pub fn server_auth_completed(&self) -> bool {
        self.error.code() == errSSLPeerAuthCompleted
    }

    /// Returns `true` iff `break_on_cert_requested` was set and the handshake
    /// has progressed to that point.
    pub fn client_cert_requested(&self) -> bool {
        self.error.code() == errSSLClientCertRequested
    }

    /// Returns `true` iff the underlying stream returned an error with the
    /// `WouldBlock` kind.
    pub fn would_block(&self) -> bool {
        self.error.code() == errSSLWouldBlock
    }

    /// Returns the error which caused the handshake interruption.
    pub fn error(&self) -> &Error {
        &self.error
    }

    /// Restarts the handshake process.
    pub fn handshake(self) -> result::Result<SslStream<S>, HandshakeError<S>> {
        self.stream.handshake()
    }
}

/// An SSL stream midway through the handshake process.
#[derive(Debug)]
pub struct MidHandshakeClientBuilder<S> {
    stream: MidHandshakeSslStream<S>,
    domain: Option<String>,
    certs: Vec<SecCertificate>,
    trust_certs_only: bool,
    danger_accept_invalid_certs: bool,
}

impl<S> MidHandshakeClientBuilder<S> {
    /// Returns a shared reference to the inner stream.
    pub fn get_ref(&self) -> &S {
        self.stream.get_ref()
    }

    /// Returns a mutable reference to the inner stream.
    pub fn get_mut(&mut self) -> &mut S {
        self.stream.get_mut()
    }

    /// Returns the error which caused the handshake interruption.
    pub fn error(&self) -> &Error {
        self.stream.error()
    }

    /// Restarts the handshake process.
    pub fn handshake(self) -> result::Result<SslStream<S>, ClientHandshakeError<S>> {
        let MidHandshakeClientBuilder {
            stream,
            domain,
            certs,
            trust_certs_only,
            danger_accept_invalid_certs,
        } = self;

        let mut result = stream.handshake();
        loop {
            let stream = match result {
                Ok(stream) => return Ok(stream),
                Err(HandshakeError::Interrupted(stream)) => stream,
                Err(HandshakeError::Failure(err)) => {
                    return Err(ClientHandshakeError::Failure(err))
                }
            };

            if stream.would_block() {
                let ret = MidHandshakeClientBuilder {
                    stream,
                    domain,
                    certs,
                    trust_certs_only,
                    danger_accept_invalid_certs,
                };
                return Err(ClientHandshakeError::Interrupted(ret));
            }

            if stream.server_auth_completed() {
                if danger_accept_invalid_certs {
                    result = stream.handshake();
                    continue;
                }
                let mut trust = match stream.context().peer_trust2()? {
                    Some(trust) => trust,
                    None => {
                        result = stream.handshake();
                        continue;
                    }
                };
                trust.set_anchor_certificates(&certs)?;
                trust.set_trust_anchor_certificates_only(self.trust_certs_only)?;
                let policy =
                    SecPolicy::create_ssl(SslProtocolSide::SERVER, domain.as_ref().map(|s| &**s));
                trust.set_policy(&policy)?;
                let trusted = trust.evaluate()?;
                match trusted {
                    TrustResult::PROCEED | TrustResult::UNSPECIFIED => {
                        result = stream.handshake();
                        continue;
                    }
                    TrustResult::DENY => {
                        let err = Error::from_code(errSecTrustSettingDeny);
                        return Err(ClientHandshakeError::Failure(err));
                    }
                    TrustResult::RECOVERABLE_TRUST_FAILURE | TrustResult::FATAL_TRUST_FAILURE => {
                        let err = Error::from_code(errSecNotTrusted);
                        return Err(ClientHandshakeError::Failure(err));
                    }
                    TrustResult::INVALID | TrustResult::OTHER_ERROR | _ => {
                        let err = Error::from_code(errSecBadReq);
                        return Err(ClientHandshakeError::Failure(err));
                    }
                }
            }

            let err = Error::from_code(stream.error().code());
            return Err(ClientHandshakeError::Failure(err));
        }
    }
}

/// Specifies the state of a TLS session.
#[derive(Debug, PartialEq, Eq)]
pub struct SessionState(SSLSessionState);

impl SessionState {
    /// The session has not yet started.
    pub const IDLE: Self = Self(kSSLIdle);

    /// The session is in the handshake process.
    pub const HANDSHAKE: Self = Self(kSSLHandshake);

    /// The session is connected.
    pub const CONNECTED: Self = Self(kSSLConnected);

    /// The session has been terminated.
    pub const CLOSED: Self = Self(kSSLClosed);

    /// The session has been aborted due to an error.
    pub const ABORTED: Self = Self(kSSLAborted);
}

/// Specifies a server's requirement for client certificates.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct SslAuthenticate(SSLAuthenticate);

impl SslAuthenticate {
    /// Do not request a client certificate.
    pub const NEVER: Self = Self(kNeverAuthenticate);

    /// Require a client certificate.
    pub const ALWAYS: Self = Self(kAlwaysAuthenticate);

    /// Request but do not require a client certificate.
    pub const TRY: Self = Self(kTryAuthenticate);
}

/// Specifies the state of client certificate processing.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct SslClientCertificateState(SSLClientCertificateState);

impl SslClientCertificateState {
    /// A client certificate has not been requested or sent.
    pub const NONE: Self = Self(kSSLClientCertNone);

    /// A client certificate has been requested but not recieved.
    pub const REQUESTED: Self = Self(kSSLClientCertRequested);
    /// A client certificate has been received and successfully validated.
    pub const SENT: Self = Self(kSSLClientCertSent);

    /// A client certificate has been received but has failed to validate.
    pub const REJECTED: Self = Self(kSSLClientCertRejected); }

/// Specifies protocol versions.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct SslProtocol(SSLProtocol);

impl SslProtocol {
    /// No protocol has been or should be negotiated or specified; use the default.
    pub const UNKNOWN: Self = Self(kSSLProtocolUnknown);

    /// The SSL 3.0 protocol is preferred, though SSL 2.0 may be used if the peer does not support
    /// SSL 3.0.
    pub const SSL3: Self = Self(kSSLProtocol3);

    /// The TLS 1.0 protocol is preferred, though lower versions may be used
    /// if the peer does not support TLS 1.0.
    pub const TLS1: Self = Self(kTLSProtocol1);

    /// The TLS 1.1 protocol is preferred, though lower versions may be used
    /// if the peer does not support TLS 1.1.
    pub const TLS11: Self = Self(kTLSProtocol11);

    /// The TLS 1.2 protocol is preferred, though lower versions may be used
    /// if the peer does not support TLS 1.2.
    pub const TLS12: Self = Self(kTLSProtocol12);

    /// The TLS 1.3 protocol is preferred, though lower versions may be used
    /// if the peer does not support TLS 1.3.
    pub const TLS13: Self = Self(kTLSProtocol13);

    /// Only the SSL 2.0 protocol is accepted.
    pub const SSL2: Self = Self(kSSLProtocol2);

    /// The DTLSv1 protocol is preferred.
    pub const DTLS1: Self = Self(kDTLSProtocol1);

    /// Only the SSL 3.0 protocol is accepted.
    pub const SSL3_ONLY: Self = Self(kSSLProtocol3Only);

    /// Only the TLS 1.0 protocol is accepted.
    pub const TLS1_ONLY: Self = Self(kTLSProtocol1Only);

    /// All supported TLS/SSL versions are accepted.
    pub const ALL: Self = Self(kSSLProtocolAll);
}

declare_TCFType! {
    /// A Secure Transport SSL/TLS context object.
    SslContext, SSLContextRef
}

impl_TCFType!(SslContext, SSLContextRef, SSLContextGetTypeID);

impl fmt::Debug for SslContext {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut builder = fmt.debug_struct("SslContext");
        if let Ok(state) = self.state() {
            builder.field("state", &state);
        }
        builder.finish()
    }
}

unsafe impl Sync for SslContext {}
unsafe impl Send for SslContext {}

impl AsInner for SslContext {
    type Inner = SSLContextRef;

    fn as_inner(&self) -> SSLContextRef {
        self.0
    }
}

macro_rules! impl_options {
    ($($(#[$a:meta])* const $opt:ident: $get:ident & $set:ident,)*) => {
        $(
            $(#[$a])*
            pub fn $set(&mut self, value: bool) -> Result<()> {
                unsafe { cvt(SSLSetSessionOption(self.0, $opt, value as Boolean)) }
            }

            $(#[$a])*
            pub fn $get(&self) -> Result<bool> {
                let mut value = 0;
                unsafe { cvt(SSLGetSessionOption(self.0, $opt, &mut value))?; }
                Ok(value != 0)
            }
        )*
    }
}

impl SslContext {
    /// Creates a new `SslContext` for the specified side and type of SSL
    /// connection.
    pub fn new(side: SslProtocolSide, type_: SslConnectionType) -> Result<Self> {
        unsafe {
            let ctx = SSLCreateContext(kCFAllocatorDefault, side.0, type_.0);
            Ok(Self(ctx))
        }
    }

    /// Sets the fully qualified domain name of the peer.
    ///
    /// This will be used on the client side of a session to validate the
    /// common name field of the server's certificate. It has no effect if
    /// called on a server-side `SslContext`.
    ///
    /// It is *highly* recommended to call this method before starting the
    /// handshake process.
    pub fn set_peer_domain_name(&mut self, peer_name: &str) -> Result<()> {
        unsafe {
            // SSLSetPeerDomainName doesn't need a null terminated string
            cvt(SSLSetPeerDomainName(
                self.0,
                peer_name.as_ptr() as *const _,
                peer_name.len(),
            ))
        }
    }

    /// Returns the peer domain name set by `set_peer_domain_name`.
    pub fn peer_domain_name(&self) -> Result<String> {
        unsafe {
            let mut len = 0;
            cvt(SSLGetPeerDomainNameLength(self.0, &mut len))?;
            let mut buf = vec![0; len];
            cvt(SSLGetPeerDomainName(
                self.0,
                buf.as_mut_ptr() as *mut _,
                &mut len,
            ))?;
            Ok(String::from_utf8(buf).unwrap())
        }
    }

    /// Sets the certificate to be used by this side of the SSL session.
    ///
    /// This must be called before the handshake for server-side connections,
    /// and can be used on the client-side to specify a client certificate.
    ///
    /// The `identity` corresponds to the leaf certificate and private
    /// key, and the `certs` correspond to extra certificates in the chain.
    pub fn set_certificate(
        &mut self,
        identity: &SecIdentity,
        certs: &[SecCertificate],
    ) -> Result<()> {
        let mut arr = vec![identity.as_CFType()];
        arr.extend(certs.iter().map(|c| c.as_CFType()));
        let certs = CFArray::from_CFTypes(&arr);

        unsafe { cvt(SSLSetCertificate(self.0, certs.as_concrete_TypeRef())) }
    }

    /// Sets the peer ID of this session.
    ///
    /// A peer ID is an opaque sequence of bytes that will be used by Secure
    /// Transport to identify the peer of an SSL session. If the peer ID of
    /// this session matches that of a previously terminated session, the
    /// previous session can be resumed without requiring a full handshake.
    pub fn set_peer_id(&mut self, peer_id: &[u8]) -> Result<()> {
        unsafe {
            cvt(SSLSetPeerID(
                self.0,
                peer_id.as_ptr() as *const _,
                peer_id.len(),
            ))
        }
    }

    /// Returns the peer ID of this session.
    pub fn peer_id(&self) -> Result<Option<&[u8]>> {
        unsafe {
            let mut ptr = ptr::null();
            let mut len = 0;
            cvt(SSLGetPeerID(self.0, &mut ptr, &mut len))?;
            if ptr.is_null() {
                Ok(None)
            } else {
                Ok(Some(slice::from_raw_parts(ptr as *const _, len)))
            }
        }
    }

    /// Returns the list of ciphers that are supported by Secure Transport.
    pub fn supported_ciphers(&self) -> Result<Vec<CipherSuite>> {
        unsafe {
            let mut num_ciphers = 0;
            cvt(SSLGetNumberSupportedCiphers(self.0, &mut num_ciphers))?;
            let mut ciphers = vec![0; num_ciphers];
            cvt(SSLGetSupportedCiphers(
                self.0,
                ciphers.as_mut_ptr(),
                &mut num_ciphers,
            ))?;
            Ok(ciphers.iter().map(|c| CipherSuite::from_raw(*c)).collect())
        }
    }

    /// Returns the list of ciphers that are eligible to be used for
    /// negotiation.
    pub fn enabled_ciphers(&self) -> Result<Vec<CipherSuite>> {
        unsafe {
            let mut num_ciphers = 0;
            cvt(SSLGetNumberEnabledCiphers(self.0, &mut num_ciphers))?;
            let mut ciphers = vec![0; num_ciphers];
            cvt(SSLGetEnabledCiphers(
                self.0,
                ciphers.as_mut_ptr(),
                &mut num_ciphers,
            ))?;
            Ok(ciphers.iter().map(|c| CipherSuite::from_raw(*c)).collect())
        }
    }

    /// Sets the list of ciphers that are eligible to be used for negotiation.
    pub fn set_enabled_ciphers(&mut self, ciphers: &[CipherSuite]) -> Result<()> {
        let ciphers = ciphers.iter().map(|c| c.to_raw()).collect::<Vec<_>>();
        unsafe {
            cvt(SSLSetEnabledCiphers(
                self.0,
                ciphers.as_ptr(),
                ciphers.len(),
            ))
        }
    }

    /// Returns the cipher being used by the session.
    pub fn negotiated_cipher(&self) -> Result<CipherSuite> {
        unsafe {
            let mut cipher = 0;
            cvt(SSLGetNegotiatedCipher(self.0, &mut cipher))?;
            Ok(CipherSuite::from_raw(cipher))
        }
    }

    /// Sets the requirements for client certificates.
    ///
    /// Should only be called on server-side sessions.
    pub fn set_client_side_authenticate(&mut self, auth: SslAuthenticate) -> Result<()> {
        unsafe { cvt(SSLSetClientSideAuthenticate(self.0, auth.0)) }
    }

    /// Returns the state of client certificate processing.
    pub fn client_certificate_state(&self) -> Result<SslClientCertificateState> {
        let mut state = 0;

        unsafe {
            cvt(SSLGetClientCertificateState(self.0, &mut state))?;
        }
        Ok(SslClientCertificateState(state))
    }

    /// Returns the `SecTrust` object corresponding to the peer.
    ///
    /// This can be used in conjunction with `set_break_on_server_auth` to
    /// validate certificates which do not have roots in the default set.
    pub fn peer_trust2(&self) -> Result<Option<SecTrust>> {
        // Calling SSLCopyPeerTrust on an idle connection does not seem to be well defined,
        // so explicitly check for that
        if self.state()? == SessionState::IDLE {
            return Err(Error::from_code(errSecBadReq));
        }

        unsafe {
            let mut trust = ptr::null_mut();
            cvt(SSLCopyPeerTrust(self.0, &mut trust))?;
            if trust.is_null() {
                Ok(None)
            } else {
                Ok(Some(SecTrust::wrap_under_create_rule(trust)))
            }
        }
    }

    /// Returns the state of the session.
    pub fn state(&self) -> Result<SessionState> {
        unsafe {
            let mut state = 0;
            cvt(SSLGetSessionState(self.0, &mut state))?;
            Ok(SessionState(state))
        }
    }

    /// Returns the protocol version being used by the session.
    pub fn negotiated_protocol_version(&self) -> Result<SslProtocol> {
        unsafe {
            let mut version = 0;
            cvt(SSLGetNegotiatedProtocolVersion(self.0, &mut version))?;
            Ok(SslProtocol(version))
        }
    }

    /// Returns the maximum protocol version allowed by the session.
    pub fn protocol_version_max(&self) -> Result<SslProtocol> {
        unsafe {
            let mut version = 0;
            cvt(SSLGetProtocolVersionMax(self.0, &mut version))?;
            Ok(SslProtocol(version))
        }
    }

    /// Sets the maximum protocol version allowed by the session.
    pub fn set_protocol_version_max(&mut self, max_version: SslProtocol) -> Result<()> {
        unsafe { cvt(SSLSetProtocolVersionMax(self.0, max_version.0)) }
    }

    /// Returns the minimum protocol version allowed by the session.
    pub fn protocol_version_min(&self) -> Result<SslProtocol> {
        unsafe {
            let mut version = 0;
            cvt(SSLGetProtocolVersionMin(self.0, &mut version))?;
            Ok(SslProtocol(version))
        }
    }

    /// Sets the minimum protocol version allowed by the session.
    pub fn set_protocol_version_min(&mut self, min_version: SslProtocol) -> Result<()> {
        unsafe { cvt(SSLSetProtocolVersionMin(self.0, min_version.0)) }
    }

    /// Returns the set of protocols selected via ALPN if it succeeded.
    #[cfg(feature = "alpn")]
    pub fn alpn_protocols(&self) -> Result<Vec<String>> {
        let mut array: CFArrayRef = ptr::null();
        unsafe {
            #[cfg(feature = "OSX_10_13")]
            {
                cvt(SSLCopyALPNProtocols(self.0, &mut array))?;
            }

            #[cfg(not(feature = "OSX_10_13"))]
            {
                dlsym! { fn SSLCopyALPNProtocols(SSLContextRef, *mut CFArrayRef) -> OSStatus }
                if let Some(f) = SSLCopyALPNProtocols.get() {
                    cvt(f(self.0, &mut array))?;
                } else {
                    return Err(Error::from_code(errSecUnimplemented));
                }
            }

            if array.is_null() {
                return Ok(vec![]);
            }

            let array = CFArray::<CFString>::wrap_under_create_rule(array);
            Ok(array.into_iter().map(|p| p.to_string()).collect())
        }
    }

    /// Configures the set of protocols use for ALPN.
    ///
    /// This is only used for client-side connections.
    #[cfg(feature = "alpn")]
    pub fn set_alpn_protocols(&mut self, protocols: &[&str]) -> Result<()> {
        // When CFMutableArray is added to core-foundation and IntoIterator trait
        // is implemented for CFMutableArray, the code below should directly collect
        // into a CFMutableArray.
        let protocols = CFArray::from_CFTypes(
            &protocols
                .iter()
                .map(|proto| CFString::new(proto))
                .collect::<Vec<_>>(),
        );

        #[cfg(feature = "OSX_10_13")]
        {
            unsafe { cvt(SSLSetALPNProtocols(self.0, protocols.as_concrete_TypeRef())) }
        }
        #[cfg(not(feature = "OSX_10_13"))]
        {
            dlsym! { fn SSLSetALPNProtocols(SSLContextRef, CFArrayRef) -> OSStatus }
            if let Some(f) = SSLSetALPNProtocols.get() {
                unsafe { cvt(f(self.0, protocols.as_concrete_TypeRef())) }
            } else {
                Err(Error::from_code(errSecUnimplemented))
            }
        }
    }

    /// Sets whether the client sends the `SessionTicket` extension in its `ClientHello`.
    ///
    /// On its own, this will just cause the client to send an empty `SessionTicket` extension on
    /// every connection. [`SslContext::set_peer_id`] must also be used to key the session
    /// ticket returned by the server.
    ///
    /// [`SslContext::set_peer_id`]: #method.set_peer_id
    #[cfg(feature = "session-tickets")]
    pub fn set_session_tickets_enabled(&mut self, enabled: bool) -> Result<()> {
        #[cfg(feature = "OSX_10_13")]
        {
            unsafe { cvt(SSLSetSessionTicketsEnabled(self.0, enabled as Boolean)) }
        }
        #[cfg(not(feature = "OSX_10_13"))]
        {
            dlsym! { fn SSLSetSessionTicketsEnabled(SSLContextRef, Boolean) -> OSStatus }
            if let Some(f) = SSLSetSessionTicketsEnabled.get() {
                unsafe { cvt(f(self.0, enabled as Boolean)) }
            } else {
                Err(Error::from_code(errSecUnimplemented))
            }
        }
    }

    /// Sets whether a protocol is enabled or not.
    ///
    /// # Note
    ///
    /// On OSX this is a deprecated API in favor of `set_protocol_version_max` and
    /// `set_protocol_version_min`, although if you're working with OSX 10.8 or before you may have
    /// to use this API instead.
    #[cfg(target_os = "macos")]
    #[deprecated(note = "use `set_protocol_version_max`")]
    pub fn set_protocol_version_enabled(
        &mut self,
        protocol: SslProtocol,
        enabled: bool,
    ) -> Result<()> {
        unsafe {
            cvt(SSLSetProtocolVersionEnabled(
                self.0,
                protocol.0,
                enabled as Boolean,
            ))
        }
    }

    /// Returns the number of bytes which can be read without triggering a
    /// `read` call in the underlying stream.
    pub fn buffered_read_size(&self) -> Result<usize> {
        unsafe {
            let mut size = 0;
            cvt(SSLGetBufferedReadSize(self.0, &mut size))?;
            Ok(size)
        }
    }

    impl_options! {
        /// If enabled, the handshake process will pause and return instead of
        /// automatically validating a server's certificate.
        const kSSLSessionOptionBreakOnServerAuth: break_on_server_auth & set_break_on_server_auth,
        /// If enabled, the handshake process will pause and return after
        /// the server requests a certificate from the client.
        const kSSLSessionOptionBreakOnCertRequested: break_on_cert_requested & set_break_on_cert_requested,
        /// If enabled, the handshake process will pause and return instead of
        /// automatically validating a client's certificate.
        const kSSLSessionOptionBreakOnClientAuth: break_on_client_auth & set_break_on_client_auth,
        /// If enabled, TLS false start will be performed if an appropriate
        /// cipher suite is negotiated.
        ///
        /// Requires the `OSX_10_9` (or greater) feature.
        #[cfg(feature = "OSX_10_9")]
        const kSSLSessionOptionFalseStart: false_start & set_false_start,
        /// If enabled, 1/n-1 record splitting will be enabled for TLS 1.0
        /// connections using block ciphers to mitigate the BEAST attack.
        ///
        /// Requires the `OSX_10_9` (or greater) feature.
        #[cfg(feature = "OSX_10_9")]
        const kSSLSessionOptionSendOneByteRecord: send_one_byte_record & set_send_one_byte_record,
    }

    fn into_stream<S>(self, stream: S) -> Result<SslStream<S>>
    where
        S: Read + Write,
    {
        unsafe {
            let ret = SSLSetIOFuncs(self.0, read_func::<S>, write_func::<S>);
            if ret != errSecSuccess {
                return Err(Error::from_code(ret));
            }

            let stream = Connection {
                stream,
                err: None,
                panic: None,
            };
            let stream = Box::into_raw(Box::new(stream));
            let ret = SSLSetConnection(self.0, stream as *mut _);
            if ret != errSecSuccess {
                let _conn = Box::from_raw(stream);
                return Err(Error::from_code(ret));
            }

            Ok(SslStream {
                ctx: self,
                _m: PhantomData,
            })
        }
    }

    /// Performs the SSL/TLS handshake.
    pub fn handshake<S>(self, stream: S) -> result::Result<SslStream<S>, HandshakeError<S>>
    where
        S: Read + Write,
    {
        self.into_stream(stream)
            .map_err(HandshakeError::Failure)
            .and_then(SslStream::handshake)
    }
}

struct Connection<S> {
    stream: S,
    err: Option<io::Error>,
    panic: Option<Box<dyn Any + Send>>,
}

// the logic here is based off of libcurl's

fn translate_err(e: &io::Error) -> OSStatus {
    match e.kind() {
        io::ErrorKind::NotFound => errSSLClosedGraceful,
        io::ErrorKind::ConnectionReset => errSSLClosedAbort,
        io::ErrorKind::WouldBlock |
        io::ErrorKind::NotConnected => errSSLWouldBlock,
        _ => errSecIO,
    }
}

unsafe extern "C" fn read_func<S>(
    connection: SSLConnectionRef,
    data: *mut c_void,
    data_length: *mut usize,
) -> OSStatus
where
    S: Read,
{
    let conn: &mut Connection<S> = &mut *(connection as *mut _);
    let data = slice::from_raw_parts_mut(data as *mut u8, *data_length);
    let mut start = 0;
    let mut ret = errSecSuccess;

    while start < data.len() {
        match panic::catch_unwind(AssertUnwindSafe(|| conn.stream.read(&mut data[start..]))) {
            Ok(Ok(0)) => {
                ret = errSSLClosedNoNotify;
                break;
            }
            Ok(Ok(len)) => start += len,
            Ok(Err(e)) => {
                ret = translate_err(&e);
                conn.err = Some(e);
                break;
            }
            Err(e) => {
                ret = errSecIO;
                conn.panic = Some(e);
                break;
            }
        }
    }

    *data_length = start;
    ret
}

unsafe extern "C" fn write_func<S>(
    connection: SSLConnectionRef,
    data: *const c_void,
    data_length: *mut usize,
) -> OSStatus
where
    S: Write,
{
    let conn: &mut Connection<S> = &mut *(connection as *mut _);
    let data = slice::from_raw_parts(data as *mut u8, *data_length);
    let mut start = 0;
    let mut ret = errSecSuccess;

    while start < data.len() {
        match panic::catch_unwind(AssertUnwindSafe(|| conn.stream.write(&data[start..]))) {
            Ok(Ok(0)) => {
                ret = errSSLClosedNoNotify;
                break;
            }
            Ok(Ok(len)) => start += len,
            Ok(Err(e)) => {
                ret = translate_err(&e);
                conn.err = Some(e);
                break;
            }
            Err(e) => {
                ret = errSecIO;
                conn.panic = Some(e);
                break;
            }
        }
    }

    *data_length = start;
    ret
}

/// A type implementing SSL/TLS encryption over an underlying stream.
pub struct SslStream<S> {
    ctx: SslContext,
    _m: PhantomData<S>,
}

impl<S: fmt::Debug> fmt::Debug for SslStream<S> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("SslStream")
            .field("context", &self.ctx)
            .field("stream", self.get_ref())
            .finish()
    }
}

impl<S> Drop for SslStream<S> {
    fn drop(&mut self) {
        unsafe {
            let mut conn = ptr::null();
            let ret = SSLGetConnection(self.ctx.0, &mut conn);
            assert!(ret == errSecSuccess);
            Box::<Connection<S>>::from_raw(conn as *mut _);
        }
    }
}

impl<S> SslStream<S> {
    fn handshake(mut self) -> result::Result<Self, HandshakeError<S>> {
        match unsafe { SSLHandshake(self.ctx.0) } {
            errSecSuccess => Ok(self),
            reason @ errSSLPeerAuthCompleted
            | reason @ errSSLClientCertRequested
            | reason @ errSSLWouldBlock
            | reason @ errSSLClientHelloReceived => {
                Err(HandshakeError::Interrupted(MidHandshakeSslStream {
                    stream: self,
                    error: Error::from_code(reason),
                }))
            }
            err => {
                self.check_panic();
                Err(HandshakeError::Failure(Error::from_code(err)))
            }
        }
    }

    /// Returns a shared reference to the inner stream.
    pub fn get_ref(&self) -> &S {
        &self.connection().stream
    }

    /// Returns a mutable reference to the underlying stream.
    pub fn get_mut(&mut self) -> &mut S {
        &mut self.connection_mut().stream
    }

    /// Returns a shared reference to the `SslContext` of the stream.
    pub fn context(&self) -> &SslContext {
        &self.ctx
    }

    /// Returns a mutable reference to the `SslContext` of the stream.
    pub fn context_mut(&mut self) -> &mut SslContext {
        &mut self.ctx
    }

    /// Shuts down the connection.
    pub fn close(&mut self) -> result::Result<(), io::Error> {
        unsafe {
            let ret = SSLClose(self.ctx.0);
            if ret == errSecSuccess {
                Ok(())
            } else {
                Err(self.get_error(ret))
            }
        }
    }

    fn connection(&self) -> &Connection<S> {
        unsafe {
            let mut conn = ptr::null();
            let ret = SSLGetConnection(self.ctx.0, &mut conn);
            assert!(ret == errSecSuccess);

            mem::transmute(conn)
        }
    }

    fn connection_mut(&mut self) -> &mut Connection<S> {
        unsafe {
            let mut conn = ptr::null();
            let ret = SSLGetConnection(self.ctx.0, &mut conn);
            assert!(ret == errSecSuccess);

            mem::transmute(conn)
        }
    }

    fn check_panic(&mut self) {
        let conn = self.connection_mut();
        if let Some(err) = conn.panic.take() {
            panic::resume_unwind(err);
        }
    }

    fn get_error(&mut self, ret: OSStatus) -> io::Error {
        self.check_panic();

        if let Some(err) = self.connection_mut().err.take() {
            err
        } else {
            io::Error::new(io::ErrorKind::Other, Error::from_code(ret))
        }
    }
}

impl<S: Read + Write> Read for SslStream<S> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        // Below we base our return value off the amount of data read, so a
        // zero-length buffer might cause us to erroneously interpret this
        // request as an error. Instead short-circuit that logic and return
        // `Ok(0)` instead.
        if buf.is_empty() {
            return Ok(0);
        }

        // If some data was buffered but not enough to fill `buf`, SSLRead
        // will try to read a new packet. This is bad because there may be
        // no more data but the socket is remaining open (e.g HTTPS with
        // Connection: keep-alive).
        let buffered = self.context().buffered_read_size().unwrap_or(0);
        let to_read = if buffered > 0 {
            cmp::min(buffered, buf.len())
        } else {
            buf.len()
        };

        unsafe {
            let mut nread = 0;
            let ret = SSLRead(self.ctx.0, buf.as_mut_ptr() as *mut _, to_read, &mut nread);
            // SSLRead can return an error at the same time it returns the last
            // chunk of data (!)
            if nread > 0 {
                return Ok(nread as usize);
            }

            match ret {
                errSSLClosedGraceful | errSSLClosedAbort | errSSLClosedNoNotify => Ok(0),
                _ => Err(self.get_error(ret)),
            }
        }
    }
}

impl<S: Read + Write> Write for SslStream<S> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        // Like above in read, short circuit a 0-length write
        if buf.is_empty() {
            return Ok(0);
        }
        unsafe {
            let mut nwritten = 0;
            let ret = SSLWrite(
                self.ctx.0,
                buf.as_ptr() as *const _,
                buf.len(),
                &mut nwritten,
            );
            // just to be safe, base success off of nwritten rather than ret
            // for the same reason as in read
            if nwritten > 0 {
                Ok(nwritten as usize)
            } else {
                Err(self.get_error(ret))
            }
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        self.connection_mut().stream.flush()
    }
}

/// A builder type to simplify the creation of client side `SslStream`s.
#[derive(Debug)]
pub struct ClientBuilder {
    identity: Option<SecIdentity>,
    certs: Vec<SecCertificate>,
    chain: Vec<SecCertificate>,
    protocol_min: Option<SslProtocol>,
    protocol_max: Option<SslProtocol>,
    trust_certs_only: bool,
    use_sni: bool,
    danger_accept_invalid_certs: bool,
    danger_accept_invalid_hostnames: bool,
    whitelisted_ciphers: Vec<CipherSuite>,
    blacklisted_ciphers: Vec<CipherSuite>,
    alpn: Option<Vec<String>>,
    enable_session_tickets: bool,
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl ClientBuilder {
    /// Creates a new builder with default options.
    pub fn new() -> Self {
        Self {
            identity: None,
            certs: Vec::new(),
            chain: Vec::new(),
            protocol_min: None,
            protocol_max: None,
            trust_certs_only: false,
            use_sni: true,
            danger_accept_invalid_certs: false,
            danger_accept_invalid_hostnames: false,
            whitelisted_ciphers: Vec::new(),
            blacklisted_ciphers: Vec::new(),
            alpn: None,
            enable_session_tickets: false,
        }
    }

    /// Specifies the set of root certificates to trust when
    /// verifying the server's certificate.
    pub fn anchor_certificates(&mut self, certs: &[SecCertificate]) -> &mut Self {
        self.certs = certs.to_owned();
        self
    }

    /// Specifies whether to trust the built-in certificates in addition
    /// to specified anchor certificates.
    pub fn trust_anchor_certificates_only(&mut self, only: bool) -> &mut Self {
        self.trust_certs_only = only;
        self
    }

    /// Specifies whether to trust invalid certificates.
    ///
    /// # Warning
    ///
    /// You should think very carefully before using this method. If invalid
    /// certificates are trusted, *any* certificate for *any* site will be
    /// trusted for use. This includes expired certificates. This introduces
    /// significant vulnerabilities, and should only be used as a last resort.
    pub fn danger_accept_invalid_certs(&mut self, noverify: bool) -> &mut Self {
        self.danger_accept_invalid_certs = noverify;
        self
    }

    /// Specifies whether to use Server Name Indication (SNI).
    pub fn use_sni(&mut self, use_sni: bool) -> &mut Self {
        self.use_sni = use_sni;
        self
    }

    /// Specifies whether to verify that the server's hostname matches its certificate.
    ///
    /// # Warning
    ///
    /// You should think very carefully before using this method. If hostnames are not verified,
    /// *any* valid certificate for *any* site will be trusted for use. This introduces significant
    /// vulnerabilities, and should only be used as a last resort.
    pub fn danger_accept_invalid_hostnames(
        &mut self,
        danger_accept_invalid_hostnames: bool,
    ) -> &mut Self {
        self.danger_accept_invalid_hostnames = danger_accept_invalid_hostnames;
        self
    }

    /// Set a whitelist of enabled ciphers. Any ciphers not whitelisted will be disabled.
    pub fn whitelist_ciphers(&mut self, whitelisted_ciphers: &[CipherSuite]) -> &mut Self {
        self.whitelisted_ciphers = whitelisted_ciphers.to_owned();
        self
    }

    /// Set a blacklist of disabled ciphers. Blacklisted ciphers will be disabled.
    pub fn blacklist_ciphers(&mut self, blacklisted_ciphers: &[CipherSuite]) -> &mut Self {
        self.blacklisted_ciphers = blacklisted_ciphers.to_owned();
        self
    }

    /// Use the specified identity as a SSL/TLS client certificate.
    pub fn identity(&mut self, identity: &SecIdentity, chain: &[SecCertificate]) -> &mut Self {
        self.identity = Some(identity.clone());
        self.chain = chain.to_owned();
        self
    }

    /// Configure the minimum protocol that this client will support.
    pub fn protocol_min(&mut self, min: SslProtocol) -> &mut Self {
        self.protocol_min = Some(min);
        self
    }

    /// Configure the minimum protocol that this client will support.
    pub fn protocol_max(&mut self, max: SslProtocol) -> &mut Self {
        self.protocol_max = Some(max);
        self
    }

    /// Configures the set of protocols used for ALPN.
    #[cfg(feature = "alpn")]
    pub fn alpn_protocols(&mut self, protocols: &[&str]) -> &mut Self {
        self.alpn = Some(protocols.iter().map(|s| s.to_string()).collect());
        self
    }

    /// Configures the use of the RFC 5077 `SessionTicket` extension.
    ///
    /// Defaults to `false`.
    #[cfg(feature = "session-tickets")]
    pub fn enable_session_tickets(&mut self, enable: bool) -> &mut Self {
        self.enable_session_tickets = enable;
        self
    }

    /// Initiates a new SSL/TLS session over a stream connected to the specified domain.
    ///
    /// If both SNI and hostname verification are disabled, the value of `domain` will be ignored.
    pub fn handshake<S>(
        &self,
        domain: &str,
        stream: S,
    ) -> result::Result<SslStream<S>, ClientHandshakeError<S>>
    where
        S: Read + Write,
    {
        // the logic for trust validation is in MidHandshakeClientBuilder::connect, so run all
        // of the handshake logic through that.
        let stream = MidHandshakeSslStream {
            stream: self.ctx_into_stream(domain, stream)?,
            error: Error::from(errSecSuccess),
        };

        let certs = self.certs.clone();
        let stream = MidHandshakeClientBuilder {
            stream,
            domain: if self.danger_accept_invalid_hostnames {
                None
            } else {
                Some(domain.to_string())
            },
            certs,
            trust_certs_only: self.trust_certs_only,
            danger_accept_invalid_certs: self.danger_accept_invalid_certs,
        };
        stream.handshake()
    }

    fn ctx_into_stream<S>(&self, domain: &str, stream: S) -> Result<SslStream<S>>
    where
        S: Read + Write,
    {
        let mut ctx = SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)?;

        if self.use_sni {
            ctx.set_peer_domain_name(domain)?;
        }
        if let Some(ref identity) = self.identity {
            ctx.set_certificate(identity, &self.chain)?;
        }
        #[cfg(feature = "alpn")]
        {
            if let Some(ref alpn) = self.alpn {
                ctx.set_alpn_protocols(&alpn.iter().map(|s| &**s).collect::<Vec<_>>())?;
            }
        }
        #[cfg(feature = "session-tickets")]
        {
            if self.enable_session_tickets {
                // We must use the domain here to ensure that we go through certificate validation
                // again rather than resuming the session if the domain changes.
                ctx.set_peer_id(domain.as_bytes())?;
                ctx.set_session_tickets_enabled(true)?;
            }
        }
        ctx.set_break_on_server_auth(true)?;
        self.configure_protocols(&mut ctx)?;
        self.configure_ciphers(&mut ctx)?;

        ctx.into_stream(stream)
    }

    fn configure_protocols(&self, ctx: &mut SslContext) -> Result<()> {
        if let Some(min) = self.protocol_min {
            ctx.set_protocol_version_min(min)?;
        }
        if let Some(max) = self.protocol_max {
            ctx.set_protocol_version_max(max)?;
        }
        Ok(())
    }

    fn configure_ciphers(&self, ctx: &mut SslContext) -> Result<()> {
        let mut ciphers = if self.whitelisted_ciphers.is_empty() {
            ctx.enabled_ciphers()?
        } else {
            self.whitelisted_ciphers.clone()
        };

        if !self.blacklisted_ciphers.is_empty() {
            ciphers.retain(|cipher| !self.blacklisted_ciphers.contains(cipher));
        }

        ctx.set_enabled_ciphers(&ciphers)?;
        Ok(())
    }
}

/// A builder type to simplify the creation of server-side `SslStream`s.
#[derive(Debug)]
pub struct ServerBuilder {
    identity: SecIdentity,
    certs: Vec<SecCertificate>,
}

impl ServerBuilder {
    /// Creates a new `ServerBuilder` which will use the specified identity
    /// and certificate chain for handshakes.
    pub fn new(identity: &SecIdentity, certs: &[SecCertificate]) -> Self {
        Self {
            identity: identity.clone(),
            certs: certs.to_owned(),
        }
    }

    /// Initiates a new SSL/TLS session over a stream.
    pub fn handshake<S>(&self, stream: S) -> Result<SslStream<S>>
    where
        S: Read + Write,
    {
        let mut ctx = SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)?;
        ctx.set_certificate(&self.identity, &self.certs)?;
        match ctx.handshake(stream) {
            Ok(stream) => Ok(stream),
            Err(HandshakeError::Interrupted(stream)) => Err(stream.error().clone()),
            Err(HandshakeError::Failure(err)) => Err(err),
        }
    }
}

#[cfg(test)]
mod test {
    use std::io;
    use std::io::prelude::*;
    use std::net::TcpStream;

    use super::*;

    #[test]
    fn connect() {
        let mut ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        p!(ctx.set_peer_domain_name("google.com"));
        let stream = p!(TcpStream::connect("google.com:443"));
        p!(ctx.handshake(stream));
    }

    #[test]
    fn connect_bad_domain() {
        let mut ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        p!(ctx.set_peer_domain_name("foobar.com"));
        let stream = p!(TcpStream::connect("google.com:443"));
        match ctx.handshake(stream) {
            Ok(_) => panic!("expected failure"),
            Err(_) => {}
        }
    }

    #[test]
    fn load_page() {
        let mut ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        p!(ctx.set_peer_domain_name("google.com"));
        let stream = p!(TcpStream::connect("google.com:443"));
        let mut stream = p!(ctx.handshake(stream));
        p!(stream.write_all(b"GET / HTTP/1.0\r\n\r\n"));
        p!(stream.flush());
        let mut buf = vec![];
        p!(stream.read_to_end(&mut buf));
        println!("{}", String::from_utf8_lossy(&buf));
    }

    #[test]
    fn client_no_session_ticket_resumption() {
        for _ in 0..2 {
            let stream = p!(TcpStream::connect("google.com:443"));

            // Manually handshake here.
            let stream = MidHandshakeSslStream {
                stream: ClientBuilder::new()
                    .ctx_into_stream("google.com", stream)
                    .unwrap(),
                error: Error::from(errSecSuccess),
            };

            let mut result = stream.handshake();

            if let Err(HandshakeError::Interrupted(stream)) = result {
                assert!(stream.server_auth_completed());
                result = stream.handshake();
            } else {
                panic!("Unexpectedly skipped server auth");
            }

            assert!(result.is_ok());
        }
    }

    #[test]
    #[cfg(feature = "session-tickets")]
    fn client_session_ticket_resumption() {
        // The first time through this loop, we should do a full handshake. The second time, we
        // should immediately finish the handshake without breaking on server auth.
        for i in 0..2 {
            let stream = p!(TcpStream::connect("google.com:443"));
            let mut builder = ClientBuilder::new();
            builder.enable_session_tickets(true);

            // Manually handshake here.
            let stream = MidHandshakeSslStream {
                stream: builder.ctx_into_stream("google.com", stream).unwrap(),
                error: Error::from(errSecSuccess),
            };

            let mut result = stream.handshake();

            if let Err(HandshakeError::Interrupted(stream)) = result {
                assert!(stream.server_auth_completed());
                assert_eq!(
                    i, 0,
                    "Session ticket resumption did not work, server auth was not skipped"
                );
                result = stream.handshake();
            } else {
                assert_eq!(i, 1, "Unexpectedly skipped server auth");
            }

            assert!(result.is_ok());
        }
    }

    #[test]
    #[cfg(feature = "alpn")]
    fn client_alpn_accept() {
        let mut ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        p!(ctx.set_peer_domain_name("google.com"));
        p!(ctx.set_alpn_protocols(&vec!["h2"]));
        let stream = p!(TcpStream::connect("google.com:443"));
        let stream = ctx.handshake(stream).unwrap();
        assert_eq!(vec!["h2"], stream.context().alpn_protocols().unwrap());
    }

    #[test]
    #[cfg(feature = "alpn")]
    fn client_alpn_reject() {
        let mut ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        p!(ctx.set_peer_domain_name("google.com"));
        p!(ctx.set_alpn_protocols(&vec!["h2c"]));
        let stream = p!(TcpStream::connect("google.com:443"));
        let stream = ctx.handshake(stream).unwrap();
        assert!(stream.context().alpn_protocols().is_err());
    }

    #[test]
    fn client_no_anchor_certs() {
        let stream = p!(TcpStream::connect("google.com:443"));
        assert!(ClientBuilder::new()
            .trust_anchor_certificates_only(true)
            .handshake("google.com", stream)
            .is_err());
    }

    #[test]
    fn client_bad_domain() {
        let stream = p!(TcpStream::connect("google.com:443"));
        assert!(ClientBuilder::new()
            .handshake("foobar.com", stream)
            .is_err());
    }

    #[test]
    fn client_bad_domain_ignored() {
        let stream = p!(TcpStream::connect("google.com:443"));
        ClientBuilder::new()
            .danger_accept_invalid_hostnames(true)
            .handshake("foobar.com", stream)
            .unwrap();
    }

    #[test]
    fn connect_no_verify_ssl() {
        let stream = p!(TcpStream::connect("expired.badssl.com:443"));
        let mut builder = ClientBuilder::new();
        builder.danger_accept_invalid_certs(true);
        builder.handshake("expired.badssl.com", stream).unwrap();
    }

    #[test]
    fn load_page_client() {
        let stream = p!(TcpStream::connect("google.com:443"));
        let mut stream = p!(ClientBuilder::new().handshake("google.com", stream));
        p!(stream.write_all(b"GET / HTTP/1.0\r\n\r\n"));
        p!(stream.flush());
        let mut buf = vec![];
        p!(stream.read_to_end(&mut buf));
        println!("{}", String::from_utf8_lossy(&buf));
    }

    #[test]
    #[cfg_attr(target_os = "ios", ignore)] // FIXME what's going on with ios?
    fn cipher_configuration() {
        let mut ctx = p!(SslContext::new(
            SslProtocolSide::SERVER,
            SslConnectionType::STREAM
        ));
        let ciphers = p!(ctx.enabled_ciphers());
        let ciphers = ciphers
            .iter()
            .enumerate()
            .filter_map(|(i, c)| if i % 2 == 0 { Some(*c) } else { None })
            .collect::<Vec<_>>();
        p!(ctx.set_enabled_ciphers(&ciphers));
        assert_eq!(ciphers, p!(ctx.enabled_ciphers()));
    }

    #[test]
    fn test_builder_whitelist_ciphers() {
        let stream = p!(TcpStream::connect("google.com:443"));

        let ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        assert!(p!(ctx.enabled_ciphers()).len() > 1);

        let ciphers = p!(ctx.enabled_ciphers());
        let cipher = ciphers.first().unwrap();
        let stream = p!(ClientBuilder::new()
            .whitelist_ciphers(&[*cipher])
            .ctx_into_stream("google.com", stream));

        assert_eq!(1, p!(stream.context().enabled_ciphers()).len());
    }

    #[test]
    #[cfg_attr(target_os = "ios", ignore)] // FIXME same issue as cipher_configuration
    fn test_builder_blacklist_ciphers() {
        let stream = p!(TcpStream::connect("google.com:443"));

        let ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        let num = p!(ctx.enabled_ciphers()).len();
        assert!(num > 1);

        let ciphers = p!(ctx.enabled_ciphers());
        let cipher = ciphers.first().unwrap();
        let stream = p!(ClientBuilder::new()
            .blacklist_ciphers(&[*cipher])
            .ctx_into_stream("google.com", stream));

        assert_eq!(num - 1, p!(stream.context().enabled_ciphers()).len());
    }

    #[test]
    fn idle_context_peer_trust() {
        let ctx = p!(SslContext::new(
            SslProtocolSide::SERVER,
            SslConnectionType::STREAM
        ));
        assert!(ctx.peer_trust2().is_err());
    }

    #[test]
    fn peer_id() {
        let mut ctx = p!(SslContext::new(
            SslProtocolSide::SERVER,
            SslConnectionType::STREAM
        ));
        assert!(p!(ctx.peer_id()).is_none());
        p!(ctx.set_peer_id(b"foobar"));
        assert_eq!(p!(ctx.peer_id()), Some(&b"foobar"[..]));
    }

    #[test]
    fn peer_domain_name() {
        let mut ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        assert_eq!("", p!(ctx.peer_domain_name()));
        p!(ctx.set_peer_domain_name("foobar.com"));
        assert_eq!("foobar.com", p!(ctx.peer_domain_name()));
    }

    #[test]
    #[should_panic(expected = "blammo")]
    fn write_panic() {
        struct ExplodingStream(TcpStream);

        impl Read for ExplodingStream {
            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
                self.0.read(buf)
            }
        }

        impl Write for ExplodingStream {
            fn write(&mut self, _: &[u8]) -> io::Result<usize> {
                panic!("blammo");
            }

            fn flush(&mut self) -> io::Result<()> {
                self.0.flush()
            }
        }

        let mut ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        p!(ctx.set_peer_domain_name("google.com"));
        let stream = p!(TcpStream::connect("google.com:443"));
        let _ = ctx.handshake(ExplodingStream(stream));
    }

    #[test]
    #[should_panic(expected = "blammo")]
    fn read_panic() {
        struct ExplodingStream(TcpStream);

        impl Read for ExplodingStream {
            fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
                panic!("blammo");
            }
        }

        impl Write for ExplodingStream {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.write(buf)
            }

            fn flush(&mut self) -> io::Result<()> {
                self.0.flush()
            }
        }

        let mut ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        p!(ctx.set_peer_domain_name("google.com"));
        let stream = p!(TcpStream::connect("google.com:443"));
        let _ = ctx.handshake(ExplodingStream(stream));
    }

    #[test]
    fn zero_length_buffers() {
        let mut ctx = p!(SslContext::new(
            SslProtocolSide::CLIENT,
            SslConnectionType::STREAM
        ));
        p!(ctx.set_peer_domain_name("google.com"));
        let stream = p!(TcpStream::connect("google.com:443"));
        let mut stream = ctx.handshake(stream).unwrap();
        assert_eq!(stream.write(b"").unwrap(), 0);
        assert_eq!(stream.read(&mut []).unwrap(), 0);
    }
}