summaryrefslogtreecommitdiff
path: root/kdecore/network/ktcpsocket.cpp
blob: cdffccf9fe3dc65a0e5b1a8e5ef9437a49ec8c82 (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
/* This file is part of the KDE libraries
    Copyright (C) 2007, 2008 Andreas Hartmetz <ahartmetz@gmail.com>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "ktcpsocket.h"
#include "ktcpsocket_p.h"

#include <kdebug.h>
#include <kurl.h>
#include <kglobal.h>
// #include <ksslcertificatemanager.h>
#include <kstandarddirs.h>
#include <klocale.h>

#include <QtCore/QStringList>
#include <QtNetwork/QSslKey>
#include <QtNetwork/QSslCipher>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QNetworkProxy>

static KTcpSocket::SslVersion kSslVersionFromQ(QSsl::SslProtocol protocol)
{
    switch (protocol) {
    case QSsl::SslV2:
        return KTcpSocket::SslV2;
    case QSsl::SslV3:
        return KTcpSocket::SslV3;
    case QSsl::TlsV1:
        return KTcpSocket::TlsV1;
    case QSsl::AnyProtocol:
        return KTcpSocket::AnySslVersion;
#if QT_VERSION >= 0x040800
    case QSsl::TlsV1SslV3:
        return KTcpSocket::TlsV1SslV3;
    case QSsl::SecureProtocols:
        return KTcpSocket::SecureProtocols;
#endif
    default:
        return KTcpSocket::UnknownSslVersion;
    }
}


static QSsl::SslProtocol qSslProtocolFromK(KTcpSocket::SslVersion sslVersion)
{
    //### this lowlevel bit-banging is a little dangerous and a likely source of bugs
    if (sslVersion == KTcpSocket::AnySslVersion) {
        return QSsl::AnyProtocol;
    }
    //does it contain any valid protocol?
    KTcpSocket::SslVersions validVersions (KTcpSocket::SslV2 | KTcpSocket::SslV3 | KTcpSocket::TlsV1);
#if QT_VERSION >= 0x040800
    validVersions |= KTcpSocket::TlsV1SslV3;
    validVersions |= KTcpSocket::SecureProtocols;
#endif
    if (!(sslVersion & validVersions)) {
        return QSsl::UnknownProtocol;
    }

    switch (sslVersion) {
    case KTcpSocket::SslV2:
        return QSsl::SslV2;
    case KTcpSocket::SslV3:
        return QSsl::SslV3;
    case KTcpSocket::TlsV1:
        return QSsl::TlsV1;
#if QT_VERSION >= 0x040800
    case KTcpSocket::TlsV1SslV3:
        return QSsl::TlsV1SslV3;
    case KTcpSocket::SecureProtocols:
        return QSsl::SecureProtocols;
#endif

    default:
        //QSslSocket doesn't really take arbitrary combinations. It's one or all.
        return QSsl::AnyProtocol;
    }
}


//cipher class converter KSslCipher -> QSslCipher
class CipherCc
{
public:
    CipherCc()
    {
        foreach (const QSslCipher &c, QSslSocket::supportedCiphers()) {
            allCiphers.insert(c.name(), c);
        }
    }

    QSslCipher converted(const KSslCipher &ksc)
    {
        return allCiphers.value(ksc.name());
    }

private:
    QHash<QString, QSslCipher> allCiphers;
};


class KSslErrorPrivate
{
public:
    static KSslError::Error errorFromQSslError(QSslError::SslError e)
    {
        switch (e) {
        case QSslError::NoError:
            return KSslError::NoError;
        case QSslError::UnableToGetLocalIssuerCertificate:
        case QSslError::InvalidCaCertificate:
            return KSslError::InvalidCertificateAuthorityCertificate;
        case QSslError::InvalidNotBeforeField:
        case QSslError::InvalidNotAfterField:
        case QSslError::CertificateNotYetValid:
        case QSslError::CertificateExpired:
            return KSslError::ExpiredCertificate;
        case QSslError::UnableToDecodeIssuerPublicKey:
        case QSslError::SubjectIssuerMismatch:
        case QSslError::AuthorityIssuerSerialNumberMismatch:
            return KSslError::InvalidCertificate;
        case QSslError::SelfSignedCertificate:
        case QSslError::SelfSignedCertificateInChain:
            return KSslError::SelfSignedCertificate;
        case QSslError::CertificateRevoked:
            return KSslError::RevokedCertificate;
        case QSslError::InvalidPurpose:
            return KSslError::InvalidCertificatePurpose;
        case QSslError::CertificateUntrusted:
            return KSslError::UntrustedCertificate;
        case QSslError::CertificateRejected:
            return KSslError::RejectedCertificate;
        case QSslError::NoPeerCertificate:
            return KSslError::NoPeerCertificate;
        case QSslError::HostNameMismatch:
            return KSslError::HostNameMismatch;
        case QSslError::UnableToVerifyFirstCertificate:
        case QSslError::UnableToDecryptCertificateSignature:
        case QSslError::UnableToGetIssuerCertificate:
        case QSslError::CertificateSignatureFailed:
            return KSslError::CertificateSignatureFailed;
        case QSslError::PathLengthExceeded:
            return KSslError::PathLengthExceeded;
        case QSslError::UnspecifiedError:
        case QSslError::NoSslSupport:
        default:
            return KSslError::UnknownError;
        }
    }

    static QString errorString(KSslError::Error e)
    {
        switch (e) {
        case KSslError::NoError:
            return i18nc("SSL error","No error");
        case KSslError::InvalidCertificateAuthorityCertificate:
            return i18nc("SSL error","The certificate authority's certificate is invalid");
        case KSslError::ExpiredCertificate:
            return i18nc("SSL error","The certificate has expired");
        case KSslError::InvalidCertificate:
            return i18nc("SSL error","The certificate is invalid");
        case KSslError::SelfSignedCertificate:
            return i18nc("SSL error","The certificate is not signed by any trusted certificate authority");
        case KSslError::RevokedCertificate:
            return i18nc("SSL error","The certificate has been revoked");
        case KSslError::InvalidCertificatePurpose:
            return i18nc("SSL error","The certificate is unsuitable for this purpose");
        case KSslError::UntrustedCertificate:
            return i18nc("SSL error","The root certificate authority's certificate is not trusted for this purpose");
        case KSslError::RejectedCertificate:
            return i18nc("SSL error","The certificate authority's certificate is marked to reject this certificate's purpose");
        case KSslError::NoPeerCertificate:
            return i18nc("SSL error","The peer did not present any certificate");
        case KSslError::HostNameMismatch:
            return i18nc("SSL error","The certificate does not apply to the given host");
        case KSslError::CertificateSignatureFailed:
            return i18nc("SSL error","The certificate cannot be verified for internal reasons");
        case KSslError::PathLengthExceeded:
            return i18nc("SSL error","The certificate chain is too long");
        case KSslError::UnknownError:
        default:
            return i18nc("SSL error","Unknown error");
        }
    }

    KSslError::Error error;
    QSslCertificate certificate;
};


KSslError::KSslError(Error errorCode, const QSslCertificate &certificate)
 : d(new KSslErrorPrivate())
{
    d->error = errorCode;
    d->certificate = certificate;
}


KSslError::KSslError(const QSslError &other)
 : d(new KSslErrorPrivate())
{
    d->error = KSslErrorPrivate::errorFromQSslError(other.error());
    d->certificate = other.certificate();
}


KSslError::KSslError(const KSslError &other)
 : d(new KSslErrorPrivate())
{
    *d = *other.d;
}


KSslError::~KSslError()
{
    delete d;
}


KSslError &KSslError::operator=(const KSslError &other)
{
    *d = *other.d;
    return *this;
}


KSslError::Error KSslError::error() const
{
    return d->error;
}


QString KSslError::errorString() const
{
    return KSslErrorPrivate::errorString(d->error);
}


QSslCertificate KSslError::certificate() const
{
    return d->certificate;
}


class KTcpSocketPrivate
{
public:
    KTcpSocketPrivate(KTcpSocket *qq)
     : q(qq),
       certificatesLoaded(false),
       emittedReadyRead(false)
    {
        // create the instance, which sets Qt's static internal cert set to empty.
//         KSslCertificateManager::self();
    }

    KTcpSocket::State state(QAbstractSocket::SocketState s)
    {
        switch (s) {
        case QAbstractSocket::UnconnectedState:
            return KTcpSocket::UnconnectedState;
        case QAbstractSocket::HostLookupState:
            return KTcpSocket::HostLookupState;
        case QAbstractSocket::ConnectingState:
            return KTcpSocket::ConnectingState;
        case QAbstractSocket::ConnectedState:
            return KTcpSocket::ConnectedState;
        case QAbstractSocket::ClosingState:
            return KTcpSocket::ClosingState;
        case QAbstractSocket::BoundState:
        case QAbstractSocket::ListeningState:
            //### these two are not relevant as long as this can't be a server socket
        default:
            return KTcpSocket::UnconnectedState; //the closest to "error"
        }
    }

    KTcpSocket::EncryptionMode encryptionMode(QSslSocket::SslMode mode)
    {
        switch (mode) {
        case QSslSocket::SslClientMode:
            return KTcpSocket::SslClientMode;
        case QSslSocket::SslServerMode:
            return KTcpSocket::SslServerMode;
        default:
            return KTcpSocket::UnencryptedMode;
        }
    }

    KTcpSocket::Error errorFromAbsSocket(QAbstractSocket::SocketError e)
    {
        switch (e) {
        case QAbstractSocket::ConnectionRefusedError:
            return KTcpSocket::ConnectionRefusedError;
        case QAbstractSocket::RemoteHostClosedError:
            return KTcpSocket::RemoteHostClosedError;
        case QAbstractSocket::HostNotFoundError:
            return KTcpSocket::HostNotFoundError;
        case QAbstractSocket::SocketAccessError:
            return KTcpSocket::SocketAccessError;
        case QAbstractSocket::SocketResourceError:
            return KTcpSocket::SocketResourceError;
        case QAbstractSocket::SocketTimeoutError:
            return KTcpSocket::SocketTimeoutError;
        case QAbstractSocket::NetworkError:
            return KTcpSocket::NetworkError;
        case QAbstractSocket::UnsupportedSocketOperationError:
            return KTcpSocket::UnsupportedSocketOperationError;
        case QAbstractSocket::SslHandshakeFailedError:
            return KTcpSocket::SslHandshakeFailedError;
        case QAbstractSocket::DatagramTooLargeError:
            //we don't do UDP
        case QAbstractSocket::AddressInUseError:
        case QAbstractSocket::SocketAddressNotAvailableError:
            //### own values if/when we ever get server socket support
        case QAbstractSocket::ProxyAuthenticationRequiredError:
            //### maybe we need an enum value for this
        case QAbstractSocket::UnknownSocketError:
        default:
            return KTcpSocket::UnknownError;
        }
    }

    //private slots
    void reemitSocketError(QAbstractSocket::SocketError e)
    {
        emit q->error(errorFromAbsSocket(e));
    }

    void reemitSslErrors(const QList<QSslError> &errors)
    {
        q->showSslErrors(); //H4X
        QList<KSslError> kErrors;
        foreach (const QSslError &e, errors) {
            kErrors.append(KSslError(e));
        }
        emit q->sslErrors(kErrors);
    }

    void reemitStateChanged(QAbstractSocket::SocketState s)
    {
        emit q->stateChanged(state(s));
    }

    void reemitModeChanged(QSslSocket::SslMode m)
    {
        emit q->encryptionModeChanged(encryptionMode(m));
    }

    // This method is needed because we might emit readyRead() due to this QIODevice
    // having some data buffered, so we need to care about blocking, too.
    //### useless ATM as readyRead() now just calls d->sock.readyRead().
    void reemitReadyRead()
    {
        if (!emittedReadyRead) {
            emittedReadyRead = true;
            emit q->readyRead();
            emittedReadyRead = false;
        }
    }

    void maybeLoadCertificates()
    {
        if (!certificatesLoaded) {
//             sock.setCaCertificates(KSslCertificateManager::self()->caCertificates());
            certificatesLoaded = true;
        }
    }

    KTcpSocket *const q;
    bool certificatesLoaded;
    bool emittedReadyRead;
    QSslSocket sock;
    QList<KSslCipher> ciphers;
    KTcpSocket::SslVersion advertisedSslVersion;
    CipherCc ccc;
};


KTcpSocket::KTcpSocket(QObject *parent)
 : QIODevice(parent),
   d(new KTcpSocketPrivate(this))
{
    d->advertisedSslVersion = SslV3;

    connect(&d->sock, SIGNAL(aboutToClose()), this, SIGNAL(aboutToClose()));
    connect(&d->sock, SIGNAL(bytesWritten(qint64)), this, SIGNAL(bytesWritten(qint64)));
    connect(&d->sock, SIGNAL(encryptedBytesWritten(qint64)), this, SIGNAL(encryptedBytesWritten(qint64)));
    connect(&d->sock, SIGNAL(readyRead()), this, SLOT(reemitReadyRead()));
    connect(&d->sock, SIGNAL(connected()), this, SIGNAL(connected()));
    connect(&d->sock, SIGNAL(encrypted()), this, SIGNAL(encrypted()));
    connect(&d->sock, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
#ifndef QT_NO_NETWORKPROXY
    connect(&d->sock, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
            this, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
#endif
    connect(&d->sock, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(reemitSocketError(QAbstractSocket::SocketError)));
    connect(&d->sock, SIGNAL(sslErrors(QList<QSslError>)),
            this, SLOT(reemitSslErrors(QList<QSslError>)));
    connect(&d->sock, SIGNAL(hostFound()), this, SIGNAL(hostFound()));
    connect(&d->sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this, SLOT(reemitStateChanged(QAbstractSocket::SocketState)));
    connect(&d->sock, SIGNAL(modeChanged(QSslSocket::SslMode)),
            this, SLOT(reemitModeChanged(QSslSocket::SslMode)));
}


KTcpSocket::~KTcpSocket()
{
    delete d;
}

////////////////////////////// (mostly) virtuals from QIODevice

bool KTcpSocket::atEnd() const
{
    return d->sock.atEnd() && QIODevice::atEnd();
}


qint64 KTcpSocket::bytesAvailable() const
{
    return d->sock.bytesAvailable() + QIODevice::bytesAvailable();
}


qint64 KTcpSocket::bytesToWrite() const
{
    return d->sock.bytesToWrite();
}


bool KTcpSocket::canReadLine() const
{
    return d->sock.canReadLine() || QIODevice::canReadLine();
}


void KTcpSocket::close()
{
    d->sock.close();
    QIODevice::close();
}


bool KTcpSocket::isSequential() const
{
    return true;
}


bool KTcpSocket::open(QIODevice::OpenMode open)
{
    bool ret = d->sock.open(open);
    setOpenMode(d->sock.openMode() | QIODevice::Unbuffered);
    return ret;
}


bool KTcpSocket::waitForBytesWritten(int msecs)
{
    return d->sock.waitForBytesWritten(msecs);
}


bool KTcpSocket::waitForReadyRead(int msecs)
{
    return d->sock.waitForReadyRead(msecs);
}


qint64 KTcpSocket::readData(char *data, qint64 maxSize)
{
    return d->sock.read(data, maxSize);
}


qint64 KTcpSocket::writeData(const char *data, qint64 maxSize)
{
    return d->sock.write(data, maxSize);
}

////////////////////////////// public methods from QAbstractSocket

void KTcpSocket::abort()
{
    d->sock.abort();
}


void KTcpSocket::connectToHost(const QString &hostName, quint16 port, ProxyPolicy policy)
{
    if (policy == AutoProxy) {
        //###
    }
    d->sock.connectToHost(hostName, port);
    // there are enough layers of buffers between us and the network, and there is a quirk
    // in QIODevice that can make it try to readData() twice per read() call if buffered and
    // reaData() does not deliver enough data the first time. like when the other side is
    // simply not sending any more data...
    // this can *apparently* lead to long delays sometimes which stalls applications.
    // do not want.
    setOpenMode(d->sock.openMode() | QIODevice::Unbuffered);
}


void KTcpSocket::connectToHost(const QHostAddress &hostAddress, quint16 port, ProxyPolicy policy)
{
    if (policy == AutoProxy) {
        //###
    }
    d->sock.connectToHost(hostAddress, port);
    setOpenMode(d->sock.openMode() | QIODevice::Unbuffered);
}


void KTcpSocket::connectToHost(const KUrl &url, ProxyPolicy policy)
{
    if (policy == AutoProxy) {
        //###
    }
    d->sock.connectToHost(url.host(), url.port());
    setOpenMode(d->sock.openMode() | QIODevice::Unbuffered);
}


void KTcpSocket::disconnectFromHost()
{
    d->sock.disconnectFromHost();
    setOpenMode(d->sock.openMode() | QIODevice::Unbuffered);
}


KTcpSocket::Error KTcpSocket::error() const
{
    return d->errorFromAbsSocket(d->sock.error());
}


QList<KSslError> KTcpSocket::sslErrors() const
{
    //### pretty slow; also consider throwing out duplicate error codes. We may get
    //    duplicates even though there were none in the original list because KSslError
    //    has a smallest common denominator range of SSL error codes.
    QList<KSslError> ret;
    foreach (const QSslError &e, d->sock.sslErrors())
        ret.append(KSslError(e));
    return ret;
}


bool KTcpSocket::flush()
{
    return d->sock.flush();
}


bool KTcpSocket::isValid() const
{
    return d->sock.isValid();
}


QHostAddress KTcpSocket::localAddress() const
{
    return d->sock.localAddress();
}


QHostAddress KTcpSocket::peerAddress() const
{
    return d->sock.peerAddress();
}


QString KTcpSocket::peerName() const
{
    return d->sock.peerName();
}


quint16 KTcpSocket::peerPort() const
{
    return d->sock.peerPort();
}


#ifndef QT_NO_NETWORKPROXY
QNetworkProxy KTcpSocket::proxy() const
{
    return d->sock.proxy();
}
#endif

qint64 KTcpSocket::readBufferSize() const
{
    return d->sock.readBufferSize();
}


#ifndef QT_NO_NETWORKPROXY
void KTcpSocket::setProxy(const QNetworkProxy &proxy)
{
    d->sock.setProxy(proxy);
}
#endif

void KTcpSocket::setReadBufferSize(qint64 size)
{
    d->sock.setReadBufferSize(size);
}


KTcpSocket::State KTcpSocket::state() const
{
    return d->state(d->sock.state());
}


bool KTcpSocket::waitForConnected(int msecs)
{
    bool ret = d->sock.waitForConnected(msecs);
    if (!ret)
        setErrorString(d->sock.errorString());
    setOpenMode(d->sock.openMode() | QIODevice::Unbuffered);
    return ret;
}


bool KTcpSocket::waitForDisconnected(int msecs)
{
    bool ret = d->sock.waitForDisconnected(msecs);
    if (!ret)
        setErrorString(d->sock.errorString());
    setOpenMode(d->sock.openMode() | QIODevice::Unbuffered);
    return ret;
}

////////////////////////////// public methods from QSslSocket

void KTcpSocket::addCaCertificate(const QSslCertificate &certificate)
{
    d->maybeLoadCertificates();
    d->sock.addCaCertificate(certificate);
}


/*
bool KTcpSocket::addCaCertificates(const QString &path, QSsl::EncodingFormat format,
                                   QRegExp::PatternSyntax syntax)
{
    d->maybeLoadCertificates();
    return d->sock.addCaCertificates(path, format, syntax);
}
*/


void KTcpSocket::addCaCertificates(const QList<QSslCertificate> &certificates)
{
    d->maybeLoadCertificates();
    d->sock.addCaCertificates(certificates);
}


QList<QSslCertificate> KTcpSocket::caCertificates() const
{
    d->maybeLoadCertificates();
    return d->sock.caCertificates();
}


QList<KSslCipher> KTcpSocket::ciphers() const
{
    return d->ciphers;
}


void KTcpSocket::connectToHostEncrypted(const QString &hostName, quint16 port, OpenMode openMode)
{
    d->maybeLoadCertificates();
    d->sock.setProtocol(qSslProtocolFromK(d->advertisedSslVersion));
    d->sock.connectToHostEncrypted(hostName, port, openMode);
    setOpenMode(d->sock.openMode() | QIODevice::Unbuffered);
}


QSslCertificate KTcpSocket::localCertificate() const
{
    return d->sock.localCertificate();
}


QList<QSslCertificate> KTcpSocket::peerCertificateChain() const
{
    return d->sock.peerCertificateChain();
}


KSslKey KTcpSocket::privateKey() const
{
    return KSslKey(d->sock.privateKey());
}


KSslCipher KTcpSocket::sessionCipher() const
{
    return KSslCipher(d->sock.sessionCipher());
}


void KTcpSocket::setCaCertificates(const QList<QSslCertificate> &certificates)
{
    d->sock.setCaCertificates(certificates);
    d->certificatesLoaded = true;
}


void KTcpSocket::setCiphers(const QList<KSslCipher> &ciphers)
{
    d->ciphers = ciphers;
    QList<QSslCipher> cl;
    foreach (const KSslCipher &c, d->ciphers) {
        cl.append(d->ccc.converted(c));
    }
    d->sock.setCiphers(cl);
}


void KTcpSocket::setLocalCertificate(const QSslCertificate &certificate)
{
    d->sock.setLocalCertificate(certificate);
}


void KTcpSocket::setLocalCertificate(const QString &fileName, QSsl::EncodingFormat format)
{
    d->sock.setLocalCertificate(fileName, format);
}


void KTcpSocket::setVerificationPeerName(const QString& hostName)
{
#if QT_VERSION >= 0x040800
    d->sock.setPeerVerifyName(hostName);
#else
    Q_UNUSED(hostName);
#endif
}


void KTcpSocket::setPrivateKey(const KSslKey &key)
{
    // We cannot map KSslKey::Algorithm:Dh to anything in QSsl::KeyAlgorithm.
    if (key.algorithm() == KSslKey::Dh)
        return;

    QSslKey _key(key.toDer(),
        (key.algorithm() == KSslKey::Rsa) ? QSsl::Rsa : QSsl::Dsa,
        QSsl::Der,
        (key.secrecy() == KSslKey::PrivateKey) ? QSsl::PrivateKey : QSsl::PublicKey);

    d->sock.setPrivateKey(_key);
}


void KTcpSocket::setPrivateKey(const QString &fileName, KSslKey::Algorithm algorithm,
                               QSsl::EncodingFormat format, const QByteArray &passPhrase)
{
    // We cannot map KSslKey::Algorithm:Dh to anything in QSsl::KeyAlgorithm.
    if (algorithm == KSslKey::Dh)
        return;

    d->sock.setPrivateKey(fileName,
        (algorithm == KSslKey::Rsa) ? QSsl::Rsa : QSsl::Dsa,
        format,
        passPhrase);
}


bool KTcpSocket::waitForEncrypted(int msecs)
{
    return d->sock.waitForEncrypted(msecs);
}


KTcpSocket::EncryptionMode KTcpSocket::encryptionMode() const
{
    return d->encryptionMode(d->sock.mode());
}

QVariant KTcpSocket::socketOption(QAbstractSocket::SocketOption options) const
{
    return d->sock.socketOption(options);
}

void KTcpSocket::setSocketOption(QAbstractSocket::SocketOption options, const QVariant &value)
{
    d->sock.setSocketOption(options, value);
}

QSslConfiguration KTcpSocket::sslConfiguration() const
{
    return d->sock.sslConfiguration();
}

void KTcpSocket::setSslConfiguration (const QSslConfiguration& configuration)
{
    d->sock.setSslConfiguration(configuration);
}

//slot
void KTcpSocket::ignoreSslErrors()
{
    d->sock.ignoreSslErrors();
}


//slot
void KTcpSocket::startClientEncryption()
{
    d->maybeLoadCertificates();
    d->sock.setProtocol(qSslProtocolFromK(d->advertisedSslVersion));
    d->sock.startClientEncryption();
}


//debugging H4X
void KTcpSocket::showSslErrors()
{
	foreach (const QSslError &e, d->sock.sslErrors())
		kDebug(7029) << e.errorString();
}


void KTcpSocket::setAdvertisedSslVersion(KTcpSocket::SslVersion version)
{
    d->advertisedSslVersion = version;
}


KTcpSocket::SslVersion KTcpSocket::advertisedSslVersion() const
{
    return d->advertisedSslVersion;
}


KTcpSocket::SslVersion KTcpSocket::negotiatedSslVersion() const
{
    if (!d->sock.isEncrypted()) {
        return UnknownSslVersion;
    }
    return kSslVersionFromQ(d->sock.protocol());
}


QString KTcpSocket::negotiatedSslVersionName() const
{
    if (!d->sock.isEncrypted()) {
        return QString();
    }
    return d->sock.sessionCipher().protocolString();
}


////////////////////////////// KSslKey

class KSslKeyPrivate
{
public:
    KSslKey::Algorithm convertAlgorithm(QSsl::KeyAlgorithm a)
    {
        switch(a) {
        case QSsl::Dsa:
            return KSslKey::Dsa;
        default:
            return KSslKey::Rsa;
        }
    }

    KSslKey::Algorithm algorithm;
    KSslKey::KeySecrecy secrecy;
    bool isExportable;
    QByteArray der;
};


KSslKey::KSslKey()
 : d(new KSslKeyPrivate)
{
    d->algorithm = Rsa;
    d->secrecy = PublicKey;
    d->isExportable = true;
}


KSslKey::KSslKey(const KSslKey &other)
 : d(new KSslKeyPrivate)
{
    *d = *other.d;
}


KSslKey::KSslKey(const QSslKey &qsk)
 : d(new KSslKeyPrivate)
{
    d->algorithm = d->convertAlgorithm(qsk.algorithm());
    d->secrecy = (qsk.type() == QSsl::PrivateKey) ? PrivateKey : PublicKey;
    d->isExportable = true;
    d->der = qsk.toDer();
}


KSslKey::~KSslKey()
{
    delete d;
}


KSslKey &KSslKey::operator=(const KSslKey &other)
{
    *d = *other.d;
    return *this;
}


KSslKey::Algorithm KSslKey::algorithm() const
{
    return d->algorithm;
}


bool KSslKey::isExportable() const
{
    return d->isExportable;
}


KSslKey::KeySecrecy KSslKey::secrecy() const
{
    return d->secrecy;
}


QByteArray KSslKey::toDer() const
{
    return d->der;
}

////////////////////////////// KSslCipher

//nice-to-have: make implicitly shared
class KSslCipherPrivate
{
public:

    QString authenticationMethod;
    QString encryptionMethod;
    QString keyExchangeMethod;
    QString name;
    bool isNull;
    int supportedBits;
    int usedBits;
};


KSslCipher::KSslCipher()
 : d(new KSslCipherPrivate)
{
    d->isNull = true;
    d->supportedBits = 0;
    d->usedBits = 0;
}


KSslCipher::KSslCipher(const KSslCipher &other)
 : d(new KSslCipherPrivate)
{
    *d = *other.d;
}


KSslCipher::KSslCipher(const QSslCipher &qsc)
 : d(new KSslCipherPrivate)
{
    d->authenticationMethod = qsc.authenticationMethod();
    d->encryptionMethod = qsc.encryptionMethod();
    //Qt likes to append the number of bits (usedBits?) to the algorithm,
    //for example "AES(256)". We only want the pure algorithm name, though.
    int parenIdx = d->encryptionMethod.indexOf(QLatin1Char('('));
    if (parenIdx > 0)
        d->encryptionMethod.truncate(parenIdx);
    d->keyExchangeMethod = qsc.keyExchangeMethod();
    d->name = qsc.name();
    d->isNull = qsc.isNull();
    d->supportedBits = qsc.supportedBits();
    d->usedBits = qsc.usedBits();
}


KSslCipher::~KSslCipher()
{
    delete d;
}


KSslCipher &KSslCipher::operator=(const KSslCipher &other)
{
    *d = *other.d;
    return *this;
}


bool KSslCipher::isNull() const
{
    return d->isNull;
}


QString KSslCipher::authenticationMethod() const
{
    return d->authenticationMethod;
}


QString KSslCipher::encryptionMethod() const
{
    return d->encryptionMethod;
}


QString KSslCipher::keyExchangeMethod() const
{
    return d->keyExchangeMethod;
}


QString KSslCipher::digestMethod() const
{
    //### This is not really backend neutral. It works for OpenSSL and
    //    for RFC compliant names, though.
    if (d->name.endsWith(QLatin1String("SHA")))
        return QString::fromLatin1("SHA-1");
    else if (d->name.endsWith(QLatin1String("MD5")))
        return QString::fromLatin1("MD5");
    else
        return QString::fromLatin1(""); // ## probably QString() is enough
}


QString KSslCipher::name() const
{
    return d->name;
}


int KSslCipher::supportedBits() const
{
    return d->supportedBits;
}


int KSslCipher::usedBits() const
{
    return d->usedBits;
}


//static
QList<KSslCipher> KSslCipher::supportedCiphers()
{
    QList<KSslCipher> ret;
    QList<QSslCipher> candidates = QSslSocket::supportedCiphers();
    foreach(const QSslCipher &c, candidates) {
        ret.append(KSslCipher(c));
    }
    return ret;
}


KSslErrorUiData::KSslErrorUiData()
 : d(new Private())
{
    d->usedBits = 0;
    d->bits = 0;
}


KSslErrorUiData::KSslErrorUiData(const KTcpSocket *socket)
 : d(new Private())
{
    d->certificateChain = socket->peerCertificateChain();
    d->sslErrors = socket->sslErrors();
    d->ip = socket->peerAddress().toString();
    d->host = socket->peerName();
    d->sslProtocol = socket->negotiatedSslVersionName();
    d->cipher = socket->sessionCipher().name();
    d->usedBits = socket->sessionCipher().usedBits();
    d->bits = socket->sessionCipher().supportedBits();
}

KSslErrorUiData::KSslErrorUiData(const QSslSocket *socket)
 : d(new Private())
{
    d->certificateChain = socket->peerCertificateChain();

    // See KTcpSocket::sslErrors()
    foreach (const QSslError &e, socket->sslErrors())
        d->sslErrors.append(KSslError(e));

    d->ip = socket->peerAddress().toString();
    d->host = socket->peerName();
    if (socket->isEncrypted()) {
        d->sslProtocol = socket->sessionCipher().protocolString();
    }
    d->cipher = socket->sessionCipher().name();
    d->usedBits = socket->sessionCipher().usedBits();
    d->bits = socket->sessionCipher().supportedBits();
}


KSslErrorUiData::KSslErrorUiData(const KSslErrorUiData &other)
 : d(new Private(*other.d))
{}

KSslErrorUiData::~KSslErrorUiData()
{
    delete d;
}

KSslErrorUiData &KSslErrorUiData::operator=(const KSslErrorUiData &other)
{
    *d = *other.d;
    return *this;
}


#include "../../ktcpsocket.moc"