1 | /**************************************************************************** |
2 | ** |
3 | ** Copyright (C) 2016 The Qt Company Ltd. |
4 | ** Copyright (C) 2014 BlackBerry Limited. All rights reserved. |
5 | ** Contact: https://www.qt.io/licensing/ |
6 | ** |
7 | ** This file is part of the QtNetwork module of the Qt Toolkit. |
8 | ** |
9 | ** $QT_BEGIN_LICENSE:LGPL$ |
10 | ** Commercial License Usage |
11 | ** Licensees holding valid commercial Qt licenses may use this file in |
12 | ** accordance with the commercial license agreement provided with the |
13 | ** Software or, alternatively, in accordance with the terms contained in |
14 | ** a written agreement between you and The Qt Company. For licensing terms |
15 | ** and conditions see https://www.qt.io/terms-conditions. For further |
16 | ** information use the contact form at https://www.qt.io/contact-us. |
17 | ** |
18 | ** GNU Lesser General Public License Usage |
19 | ** Alternatively, this file may be used under the terms of the GNU Lesser |
20 | ** General Public License version 3 as published by the Free Software |
21 | ** Foundation and appearing in the file LICENSE.LGPL3 included in the |
22 | ** packaging of this file. Please review the following information to |
23 | ** ensure the GNU Lesser General Public License version 3 requirements |
24 | ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. |
25 | ** |
26 | ** GNU General Public License Usage |
27 | ** Alternatively, this file may be used under the terms of the GNU |
28 | ** General Public License version 2.0 or (at your option) the GNU General |
29 | ** Public license version 3 or any later version approved by the KDE Free |
30 | ** Qt Foundation. The licenses are as published by the Free Software |
31 | ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 |
32 | ** included in the packaging of this file. Please review the following |
33 | ** information to ensure the GNU General Public License requirements will |
34 | ** be met: https://www.gnu.org/licenses/gpl-2.0.html and |
35 | ** https://www.gnu.org/licenses/gpl-3.0.html. |
36 | ** |
37 | ** $QT_END_LICENSE$ |
38 | ** |
39 | ****************************************************************************/ |
40 | |
41 | |
42 | //#define QSSLSOCKET_DEBUG |
43 | |
44 | /*! |
45 | \class QSslSocket |
46 | \brief The QSslSocket class provides an SSL encrypted socket for both |
47 | clients and servers. |
48 | \since 4.3 |
49 | |
50 | \reentrant |
51 | \ingroup network |
52 | \ingroup ssl |
53 | \inmodule QtNetwork |
54 | |
55 | QSslSocket establishes a secure, encrypted TCP connection you can |
56 | use for transmitting encrypted data. It can operate in both client |
57 | and server mode, and it supports modern SSL protocols, including |
58 | SSL 3 and TLS 1.2. By default, QSslSocket uses only SSL protocols |
59 | which are considered to be secure (QSsl::SecureProtocols), but you can |
60 | change the SSL protocol by calling setProtocol() as long as you do |
61 | it before the handshake has started. |
62 | |
63 | SSL encryption operates on top of the existing TCP stream after |
64 | the socket enters the ConnectedState. There are two simple ways to |
65 | establish a secure connection using QSslSocket: With an immediate |
66 | SSL handshake, or with a delayed SSL handshake occurring after the |
67 | connection has been established in unencrypted mode. |
68 | |
69 | The most common way to use QSslSocket is to construct an object |
70 | and start a secure connection by calling connectToHostEncrypted(). |
71 | This method starts an immediate SSL handshake once the connection |
72 | has been established. |
73 | |
74 | \snippet code/src_network_ssl_qsslsocket.cpp 0 |
75 | |
76 | As with a plain QTcpSocket, QSslSocket enters the HostLookupState, |
77 | ConnectingState, and finally the ConnectedState, if the connection |
78 | is successful. The handshake then starts automatically, and if it |
79 | succeeds, the encrypted() signal is emitted to indicate the socket |
80 | has entered the encrypted state and is ready for use. |
81 | |
82 | Note that data can be written to the socket immediately after the |
83 | return from connectToHostEncrypted() (i.e., before the encrypted() |
84 | signal is emitted). The data is queued in QSslSocket until after |
85 | the encrypted() signal is emitted. |
86 | |
87 | An example of using the delayed SSL handshake to secure an |
88 | existing connection is the case where an SSL server secures an |
89 | incoming connection. Suppose you create an SSL server class as a |
90 | subclass of QTcpServer. You would override |
91 | QTcpServer::incomingConnection() with something like the example |
92 | below, which first constructs an instance of QSslSocket and then |
93 | calls setSocketDescriptor() to set the new socket's descriptor to |
94 | the existing one passed in. It then initiates the SSL handshake |
95 | by calling startServerEncryption(). |
96 | |
97 | \snippet code/src_network_ssl_qsslsocket.cpp 1 |
98 | |
99 | If an error occurs, QSslSocket emits the sslErrors() signal. In this |
100 | case, if no action is taken to ignore the error(s), the connection |
101 | is dropped. To continue, despite the occurrence of an error, you |
102 | can call ignoreSslErrors(), either from within this slot after the |
103 | error occurs, or any time after construction of the QSslSocket and |
104 | before the connection is attempted. This will allow QSslSocket to |
105 | ignore the errors it encounters when establishing the identity of |
106 | the peer. Ignoring errors during an SSL handshake should be used |
107 | with caution, since a fundamental characteristic of secure |
108 | connections is that they should be established with a successful |
109 | handshake. |
110 | |
111 | Once encrypted, you use QSslSocket as a regular QTcpSocket. When |
112 | readyRead() is emitted, you can call read(), canReadLine() and |
113 | readLine(), or getChar() to read decrypted data from QSslSocket's |
114 | internal buffer, and you can call write() or putChar() to write |
115 | data back to the peer. QSslSocket will automatically encrypt the |
116 | written data for you, and emit encryptedBytesWritten() once |
117 | the data has been written to the peer. |
118 | |
119 | As a convenience, QSslSocket supports QTcpSocket's blocking |
120 | functions waitForConnected(), waitForReadyRead(), |
121 | waitForBytesWritten(), and waitForDisconnected(). It also provides |
122 | waitForEncrypted(), which will block the calling thread until an |
123 | encrypted connection has been established. |
124 | |
125 | \snippet code/src_network_ssl_qsslsocket.cpp 2 |
126 | |
127 | QSslSocket provides an extensive, easy-to-use API for handling |
128 | cryptographic ciphers, private keys, and local, peer, and |
129 | Certification Authority (CA) certificates. It also provides an API |
130 | for handling errors that occur during the handshake phase. |
131 | |
132 | The following features can also be customized: |
133 | |
134 | \list |
135 | \li The socket's cryptographic cipher suite can be customized before |
136 | the handshake phase with QSslConfiguration::setCiphers() |
137 | and QSslConfiguration::setDefaultCiphers(). |
138 | \li The socket's local certificate and private key can be customized |
139 | before the handshake phase with setLocalCertificate() and |
140 | setPrivateKey(). |
141 | \li The CA certificate database can be extended and customized with |
142 | QSslConfiguration::addCaCertificate(), |
143 | QSslConfiguration::addCaCertificates(). |
144 | \endlist |
145 | |
146 | To extend the list of \e default CA certificates used by the SSL sockets |
147 | during the SSL handshake you must update the default configuration, as |
148 | in the snippet below: |
149 | |
150 | \code |
151 | QList<QSslCertificate> certificates = getCertificates(); |
152 | QSslConfiguration configuration = QSslConfiguration::defaultConfiguration(); |
153 | configuration.addCaCertificates(certificates); |
154 | QSslConfiguration::setDefaultConfiguration(configuration); |
155 | \endcode |
156 | |
157 | \note If available, root certificates on Unix (excluding \macos) will be |
158 | loaded on demand from the standard certificate directories. If you do not |
159 | want to load root certificates on demand, you need to call either |
160 | QSslConfiguration::defaultConfiguration().setCaCertificates() before the first |
161 | SSL handshake is made in your application (for example, via passing |
162 | QSslSocket::systemCaCertificates() to it), or call |
163 | QSslConfiguration::defaultConfiguration()::setCaCertificates() on your QSslSocket instance |
164 | prior to the SSL handshake. |
165 | |
166 | For more information about ciphers and certificates, refer to QSslCipher and |
167 | QSslCertificate. |
168 | |
169 | This product includes software developed by the OpenSSL Project |
170 | for use in the OpenSSL Toolkit (\l{http://www.openssl.org/}). |
171 | |
172 | \note Be aware of the difference between the bytesWritten() signal and |
173 | the encryptedBytesWritten() signal. For a QTcpSocket, bytesWritten() |
174 | will get emitted as soon as data has been written to the TCP socket. |
175 | For a QSslSocket, bytesWritten() will get emitted when the data |
176 | is being encrypted and encryptedBytesWritten() |
177 | will get emitted as soon as data has been written to the TCP socket. |
178 | |
179 | \sa QSslCertificate, QSslCipher, QSslError |
180 | */ |
181 | |
182 | /*! |
183 | \enum QSslSocket::SslMode |
184 | |
185 | Describes the connection modes available for QSslSocket. |
186 | |
187 | \value UnencryptedMode The socket is unencrypted. Its |
188 | behavior is identical to QTcpSocket. |
189 | |
190 | \value SslClientMode The socket is a client-side SSL socket. |
191 | It is either already encrypted, or it is in the SSL handshake |
192 | phase (see QSslSocket::isEncrypted()). |
193 | |
194 | \value SslServerMode The socket is a server-side SSL socket. |
195 | It is either already encrypted, or it is in the SSL handshake |
196 | phase (see QSslSocket::isEncrypted()). |
197 | */ |
198 | |
199 | /*! |
200 | \enum QSslSocket::PeerVerifyMode |
201 | \since 4.4 |
202 | |
203 | Describes the peer verification modes for QSslSocket. The default mode is |
204 | AutoVerifyPeer, which selects an appropriate mode depending on the |
205 | socket's QSocket::SslMode. |
206 | |
207 | \value VerifyNone QSslSocket will not request a certificate from the |
208 | peer. You can set this mode if you are not interested in the identity of |
209 | the other side of the connection. The connection will still be encrypted, |
210 | and your socket will still send its local certificate to the peer if it's |
211 | requested. |
212 | |
213 | \value QueryPeer QSslSocket will request a certificate from the peer, but |
214 | does not require this certificate to be valid. This is useful when you |
215 | want to display peer certificate details to the user without affecting the |
216 | actual SSL handshake. This mode is the default for servers. |
217 | Note: In Schannel this value acts the same as VerifyNone. |
218 | |
219 | \value VerifyPeer QSslSocket will request a certificate from the peer |
220 | during the SSL handshake phase, and requires that this certificate is |
221 | valid. On failure, QSslSocket will emit the QSslSocket::sslErrors() |
222 | signal. This mode is the default for clients. |
223 | |
224 | \value AutoVerifyPeer QSslSocket will automatically use QueryPeer for |
225 | server sockets and VerifyPeer for client sockets. |
226 | |
227 | \sa QSslSocket::peerVerifyMode() |
228 | */ |
229 | |
230 | /*! |
231 | \fn void QSslSocket::encrypted() |
232 | |
233 | This signal is emitted when QSslSocket enters encrypted mode. After this |
234 | signal has been emitted, QSslSocket::isEncrypted() will return true, and |
235 | all further transmissions on the socket will be encrypted. |
236 | |
237 | \sa QSslSocket::connectToHostEncrypted(), QSslSocket::isEncrypted() |
238 | */ |
239 | |
240 | /*! |
241 | \fn void QSslSocket::modeChanged(QSslSocket::SslMode mode) |
242 | |
243 | This signal is emitted when QSslSocket changes from \l |
244 | QSslSocket::UnencryptedMode to either \l QSslSocket::SslClientMode or \l |
245 | QSslSocket::SslServerMode. \a mode is the new mode. |
246 | |
247 | \sa QSslSocket::mode() |
248 | */ |
249 | |
250 | /*! |
251 | \fn void QSslSocket::encryptedBytesWritten(qint64 written) |
252 | \since 4.4 |
253 | |
254 | This signal is emitted when QSslSocket writes its encrypted data to the |
255 | network. The \a written parameter contains the number of bytes that were |
256 | successfully written. |
257 | |
258 | \sa QIODevice::bytesWritten() |
259 | */ |
260 | |
261 | /*! |
262 | \fn void QSslSocket::peerVerifyError(const QSslError &error) |
263 | \since 4.4 |
264 | |
265 | QSslSocket can emit this signal several times during the SSL handshake, |
266 | before encryption has been established, to indicate that an error has |
267 | occurred while establishing the identity of the peer. The \a error is |
268 | usually an indication that QSslSocket is unable to securely identify the |
269 | peer. |
270 | |
271 | This signal provides you with an early indication when something's wrong. |
272 | By connecting to this signal, you can manually choose to tear down the |
273 | connection from inside the connected slot before the handshake has |
274 | completed. If no action is taken, QSslSocket will proceed to emitting |
275 | QSslSocket::sslErrors(). |
276 | |
277 | \sa sslErrors() |
278 | */ |
279 | |
280 | /*! |
281 | \fn void QSslSocket::sslErrors(const QList<QSslError> &errors); |
282 | |
283 | QSslSocket emits this signal after the SSL handshake to indicate that one |
284 | or more errors have occurred while establishing the identity of the |
285 | peer. The errors are usually an indication that QSslSocket is unable to |
286 | securely identify the peer. Unless any action is taken, the connection |
287 | will be dropped after this signal has been emitted. |
288 | |
289 | If you want to continue connecting despite the errors that have occurred, |
290 | you must call QSslSocket::ignoreSslErrors() from inside a slot connected to |
291 | this signal. If you need to access the error list at a later point, you |
292 | can call sslHandshakeErrors(). |
293 | |
294 | \a errors contains one or more errors that prevent QSslSocket from |
295 | verifying the identity of the peer. |
296 | |
297 | \note You cannot use Qt::QueuedConnection when connecting to this signal, |
298 | or calling QSslSocket::ignoreSslErrors() will have no effect. |
299 | |
300 | \sa peerVerifyError() |
301 | */ |
302 | |
303 | /*! |
304 | \fn void QSslSocket::preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator *authenticator) |
305 | \since 5.5 |
306 | |
307 | QSslSocket emits this signal when it negotiates a PSK ciphersuite, and |
308 | therefore a PSK authentication is then required. |
309 | |
310 | When using PSK, the client must send to the server a valid identity and a |
311 | valid pre shared key, in order for the SSL handshake to continue. |
312 | Applications can provide this information in a slot connected to this |
313 | signal, by filling in the passed \a authenticator object according to their |
314 | needs. |
315 | |
316 | \note Ignoring this signal, or failing to provide the required credentials, |
317 | will cause the handshake to fail, and therefore the connection to be aborted. |
318 | |
319 | \note The \a authenticator object is owned by the socket and must not be |
320 | deleted by the application. |
321 | |
322 | \sa QSslPreSharedKeyAuthenticator |
323 | */ |
324 | |
325 | /*! |
326 | \fn void QSslSocket::newSessionTicketReceived() |
327 | \since 5.15 |
328 | |
329 | If TLS 1.3 protocol was negotiated during a handshake, QSslSocket |
330 | emits this signal after receiving NewSessionTicket message. Session |
331 | and session ticket's lifetime hint are updated in the socket's |
332 | configuration. The session can be used for session resumption (and |
333 | a shortened handshake) in future TLS connections. |
334 | |
335 | \note This functionality enabled only with OpenSSL backend and requires |
336 | OpenSSL v 1.1.1 or above. |
337 | |
338 | \sa QSslSocket::sslConfiguration(), QSslConfiguration::sessionTicket(), QSslConfiguration::sessionTicketLifeTimeHint() |
339 | */ |
340 | |
341 | #include "qssl_p.h" |
342 | #include "qsslsocket.h" |
343 | #include "qsslcipher.h" |
344 | #include "qocspresponse.h" |
345 | #ifndef QT_NO_OPENSSL |
346 | #include "qsslsocket_openssl_p.h" |
347 | #endif |
348 | #ifdef Q_OS_WINRT |
349 | #include "qsslsocket_winrt_p.h" |
350 | #endif |
351 | #ifdef QT_SECURETRANSPORT |
352 | #include "qsslsocket_mac_p.h" |
353 | #endif |
354 | #if QT_CONFIG(schannel) |
355 | #include "qsslsocket_schannel_p.h" |
356 | #endif |
357 | #include "qsslconfiguration_p.h" |
358 | |
359 | #include <QtCore/qdebug.h> |
360 | #include <QtCore/qdir.h> |
361 | #include <QtCore/qmutex.h> |
362 | #include <QtCore/qurl.h> |
363 | #include <QtCore/qelapsedtimer.h> |
364 | #include <QtNetwork/qhostaddress.h> |
365 | #include <QtNetwork/qhostinfo.h> |
366 | |
367 | QT_BEGIN_NAMESPACE |
368 | |
369 | class QSslSocketGlobalData |
370 | { |
371 | public: |
372 | QSslSocketGlobalData() |
373 | : config(new QSslConfigurationPrivate), |
374 | dtlsConfig(new QSslConfigurationPrivate) |
375 | { |
376 | #if QT_CONFIG(dtls) |
377 | dtlsConfig->protocol = QSsl::DtlsV1_2OrLater; |
378 | #endif // dtls |
379 | } |
380 | |
381 | QMutex mutex; |
382 | QList<QSslCipher> supportedCiphers; |
383 | QVector<QSslEllipticCurve> supportedEllipticCurves; |
384 | QExplicitlySharedDataPointer<QSslConfigurationPrivate> config; |
385 | QExplicitlySharedDataPointer<QSslConfigurationPrivate> dtlsConfig; |
386 | }; |
387 | Q_GLOBAL_STATIC(QSslSocketGlobalData, globalData) |
388 | |
389 | /*! |
390 | Constructs a QSslSocket object. \a parent is passed to QObject's |
391 | constructor. The new socket's \l {QSslCipher} {cipher} suite is |
392 | set to the one returned by the static method defaultCiphers(). |
393 | */ |
394 | QSslSocket::QSslSocket(QObject *parent) |
395 | : QTcpSocket(*new QSslSocketBackendPrivate, parent) |
396 | { |
397 | Q_D(QSslSocket); |
398 | #ifdef QSSLSOCKET_DEBUG |
399 | qCDebug(lcSsl) << "QSslSocket::QSslSocket(" << parent << "), this =" << (void *)this; |
400 | #endif |
401 | d->q_ptr = this; |
402 | d->init(); |
403 | } |
404 | |
405 | /*! |
406 | Destroys the QSslSocket. |
407 | */ |
408 | QSslSocket::~QSslSocket() |
409 | { |
410 | Q_D(QSslSocket); |
411 | #ifdef QSSLSOCKET_DEBUG |
412 | qCDebug(lcSsl) << "QSslSocket::~QSslSocket(), this =" << (void *)this; |
413 | #endif |
414 | delete d->plainSocket; |
415 | d->plainSocket = nullptr; |
416 | } |
417 | |
418 | /*! |
419 | \reimp |
420 | |
421 | \since 5.0 |
422 | |
423 | Continues data transfer on the socket after it has been paused. If |
424 | "setPauseMode(QAbstractSocket::PauseOnSslErrors);" has been called on |
425 | this socket and a sslErrors() signal is received, calling this method |
426 | is necessary for the socket to continue. |
427 | |
428 | \sa QAbstractSocket::pauseMode(), QAbstractSocket::setPauseMode() |
429 | */ |
430 | void QSslSocket::resume() |
431 | { |
432 | Q_D(QSslSocket); |
433 | if (!d->paused) |
434 | return; |
435 | // continuing might emit signals, rather do this through the event loop |
436 | QMetaObject::invokeMethod(obj: this, member: "_q_resumeImplementation" , type: Qt::QueuedConnection); |
437 | } |
438 | |
439 | /*! |
440 | Starts an encrypted connection to the device \a hostName on \a |
441 | port, using \a mode as the \l OpenMode. This is equivalent to |
442 | calling connectToHost() to establish the connection, followed by a |
443 | call to startClientEncryption(). The \a protocol parameter can be |
444 | used to specify which network protocol to use (eg. IPv4 or IPv6). |
445 | |
446 | QSslSocket first enters the HostLookupState. Then, after entering |
447 | either the event loop or one of the waitFor...() functions, it |
448 | enters the ConnectingState, emits connected(), and then initiates |
449 | the SSL client handshake. At each state change, QSslSocket emits |
450 | signal stateChanged(). |
451 | |
452 | After initiating the SSL client handshake, if the identity of the |
453 | peer can't be established, signal sslErrors() is emitted. If you |
454 | want to ignore the errors and continue connecting, you must call |
455 | ignoreSslErrors(), either from inside a slot function connected to |
456 | the sslErrors() signal, or prior to entering encrypted mode. If |
457 | ignoreSslErrors() is not called, the connection is dropped, signal |
458 | disconnected() is emitted, and QSslSocket returns to the |
459 | UnconnectedState. |
460 | |
461 | If the SSL handshake is successful, QSslSocket emits encrypted(). |
462 | |
463 | \snippet code/src_network_ssl_qsslsocket.cpp 3 |
464 | |
465 | \note The example above shows that text can be written to |
466 | the socket immediately after requesting the encrypted connection, |
467 | before the encrypted() signal has been emitted. In such cases, the |
468 | text is queued in the object and written to the socket \e after |
469 | the connection is established and the encrypted() signal has been |
470 | emitted. |
471 | |
472 | The default for \a mode is \l ReadWrite. |
473 | |
474 | If you want to create a QSslSocket on the server side of a connection, you |
475 | should instead call startServerEncryption() upon receiving the incoming |
476 | connection through QTcpServer. |
477 | |
478 | \sa connectToHost(), startClientEncryption(), waitForConnected(), waitForEncrypted() |
479 | */ |
480 | void QSslSocket::connectToHostEncrypted(const QString &hostName, quint16 port, OpenMode mode, NetworkLayerProtocol protocol) |
481 | { |
482 | Q_D(QSslSocket); |
483 | if (d->state == ConnectedState || d->state == ConnectingState) { |
484 | qCWarning(lcSsl, |
485 | "QSslSocket::connectToHostEncrypted() called when already connecting/connected" ); |
486 | return; |
487 | } |
488 | |
489 | if (!supportsSsl()) { |
490 | qCWarning(lcSsl, "QSslSocket::connectToHostEncrypted: TLS initialization failed" ); |
491 | d->setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError, errorString: tr(s: "TLS initialization failed" )); |
492 | return; |
493 | } |
494 | |
495 | if (!d->verifyProtocolSupported(where: "QSslSocket::connectToHostEncrypted:" )) |
496 | return; |
497 | |
498 | d->init(); |
499 | d->autoStartHandshake = true; |
500 | d->initialized = true; |
501 | |
502 | // Note: When connecting to localhost, some platforms (e.g., HP-UX and some BSDs) |
503 | // establish the connection immediately (i.e., first attempt). |
504 | connectToHost(hostName, port, openMode: mode, protocol); |
505 | } |
506 | |
507 | /*! |
508 | \since 4.6 |
509 | \overload |
510 | |
511 | In addition to the original behaviour of connectToHostEncrypted, |
512 | this overloaded method enables the usage of a different hostname |
513 | (\a sslPeerName) for the certificate validation instead of |
514 | the one used for the TCP connection (\a hostName). |
515 | |
516 | \sa connectToHostEncrypted() |
517 | */ |
518 | void QSslSocket::connectToHostEncrypted(const QString &hostName, quint16 port, |
519 | const QString &sslPeerName, OpenMode mode, |
520 | NetworkLayerProtocol protocol) |
521 | { |
522 | Q_D(QSslSocket); |
523 | if (d->state == ConnectedState || d->state == ConnectingState) { |
524 | qCWarning(lcSsl, |
525 | "QSslSocket::connectToHostEncrypted() called when already connecting/connected" ); |
526 | return; |
527 | } |
528 | |
529 | if (!supportsSsl()) { |
530 | qCWarning(lcSsl, "QSslSocket::connectToHostEncrypted: TLS initialization failed" ); |
531 | d->setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError, errorString: tr(s: "TLS initialization failed" )); |
532 | return; |
533 | } |
534 | |
535 | d->init(); |
536 | d->autoStartHandshake = true; |
537 | d->initialized = true; |
538 | d->verificationPeerName = sslPeerName; |
539 | |
540 | // Note: When connecting to localhost, some platforms (e.g., HP-UX and some BSDs) |
541 | // establish the connection immediately (i.e., first attempt). |
542 | connectToHost(hostName, port, openMode: mode, protocol); |
543 | } |
544 | |
545 | /*! |
546 | Initializes QSslSocket with the native socket descriptor \a |
547 | socketDescriptor. Returns \c true if \a socketDescriptor is accepted |
548 | as a valid socket descriptor; otherwise returns \c false. |
549 | The socket is opened in the mode specified by \a openMode, and |
550 | enters the socket state specified by \a state. |
551 | |
552 | \note It is not possible to initialize two sockets with the same |
553 | native socket descriptor. |
554 | |
555 | \sa socketDescriptor() |
556 | */ |
557 | bool QSslSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState state, OpenMode openMode) |
558 | { |
559 | Q_D(QSslSocket); |
560 | #ifdef QSSLSOCKET_DEBUG |
561 | qCDebug(lcSsl) << "QSslSocket::setSocketDescriptor(" << socketDescriptor << ',' |
562 | << state << ',' << openMode << ')'; |
563 | #endif |
564 | if (!d->plainSocket) |
565 | d->createPlainSocket(openMode); |
566 | bool retVal = d->plainSocket->setSocketDescriptor(socketDescriptor, state, openMode); |
567 | d->cachedSocketDescriptor = d->plainSocket->socketDescriptor(); |
568 | d->setError(errorCode: d->plainSocket->error(), errorString: d->plainSocket->errorString()); |
569 | setSocketState(state); |
570 | setOpenMode(openMode); |
571 | setLocalPort(d->plainSocket->localPort()); |
572 | setLocalAddress(d->plainSocket->localAddress()); |
573 | setPeerPort(d->plainSocket->peerPort()); |
574 | setPeerAddress(d->plainSocket->peerAddress()); |
575 | setPeerName(d->plainSocket->peerName()); |
576 | d->readChannelCount = d->plainSocket->readChannelCount(); |
577 | d->writeChannelCount = d->plainSocket->writeChannelCount(); |
578 | return retVal; |
579 | } |
580 | |
581 | /*! |
582 | \since 4.6 |
583 | Sets the given \a option to the value described by \a value. |
584 | |
585 | \sa socketOption() |
586 | */ |
587 | void QSslSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value) |
588 | { |
589 | Q_D(QSslSocket); |
590 | if (d->plainSocket) |
591 | d->plainSocket->setSocketOption(option, value); |
592 | } |
593 | |
594 | /*! |
595 | \since 4.6 |
596 | Returns the value of the \a option option. |
597 | |
598 | \sa setSocketOption() |
599 | */ |
600 | QVariant QSslSocket::socketOption(QAbstractSocket::SocketOption option) |
601 | { |
602 | Q_D(QSslSocket); |
603 | if (d->plainSocket) |
604 | return d->plainSocket->socketOption(option); |
605 | else |
606 | return QVariant(); |
607 | } |
608 | |
609 | /*! |
610 | Returns the current mode for the socket; either UnencryptedMode, where |
611 | QSslSocket behaves identially to QTcpSocket, or one of SslClientMode or |
612 | SslServerMode, where the client is either negotiating or in encrypted |
613 | mode. |
614 | |
615 | When the mode changes, QSslSocket emits modeChanged() |
616 | |
617 | \sa SslMode |
618 | */ |
619 | QSslSocket::SslMode QSslSocket::mode() const |
620 | { |
621 | Q_D(const QSslSocket); |
622 | return d->mode; |
623 | } |
624 | |
625 | /*! |
626 | Returns \c true if the socket is encrypted; otherwise, false is returned. |
627 | |
628 | An encrypted socket encrypts all data that is written by calling write() |
629 | or putChar() before the data is written to the network, and decrypts all |
630 | incoming data as the data is received from the network, before you call |
631 | read(), readLine() or getChar(). |
632 | |
633 | QSslSocket emits encrypted() when it enters encrypted mode. |
634 | |
635 | You can call sessionCipher() to find which cryptographic cipher is used to |
636 | encrypt and decrypt your data. |
637 | |
638 | \sa mode() |
639 | */ |
640 | bool QSslSocket::isEncrypted() const |
641 | { |
642 | Q_D(const QSslSocket); |
643 | return d->connectionEncrypted; |
644 | } |
645 | |
646 | /*! |
647 | Returns the socket's SSL protocol. By default, \l QSsl::SecureProtocols is used. |
648 | |
649 | \sa setProtocol() |
650 | */ |
651 | QSsl::SslProtocol QSslSocket::protocol() const |
652 | { |
653 | Q_D(const QSslSocket); |
654 | return d->configuration.protocol; |
655 | } |
656 | |
657 | /*! |
658 | Sets the socket's SSL protocol to \a protocol. This will affect the next |
659 | initiated handshake; calling this function on an already-encrypted socket |
660 | will not affect the socket's protocol. |
661 | */ |
662 | void QSslSocket::setProtocol(QSsl::SslProtocol protocol) |
663 | { |
664 | Q_D(QSslSocket); |
665 | d->configuration.protocol = protocol; |
666 | } |
667 | |
668 | /*! |
669 | \since 4.4 |
670 | |
671 | Returns the socket's verify mode. This mode decides whether |
672 | QSslSocket should request a certificate from the peer (i.e., the client |
673 | requests a certificate from the server, or a server requesting a |
674 | certificate from the client), and whether it should require that this |
675 | certificate is valid. |
676 | |
677 | The default mode is AutoVerifyPeer, which tells QSslSocket to use |
678 | VerifyPeer for clients and QueryPeer for servers. |
679 | |
680 | \sa setPeerVerifyMode(), peerVerifyDepth(), mode() |
681 | */ |
682 | QSslSocket::PeerVerifyMode QSslSocket::peerVerifyMode() const |
683 | { |
684 | Q_D(const QSslSocket); |
685 | return d->configuration.peerVerifyMode; |
686 | } |
687 | |
688 | /*! |
689 | \since 4.4 |
690 | |
691 | Sets the socket's verify mode to \a mode. This mode decides whether |
692 | QSslSocket should request a certificate from the peer (i.e., the client |
693 | requests a certificate from the server, or a server requesting a |
694 | certificate from the client), and whether it should require that this |
695 | certificate is valid. |
696 | |
697 | The default mode is AutoVerifyPeer, which tells QSslSocket to use |
698 | VerifyPeer for clients and QueryPeer for servers. |
699 | |
700 | Setting this mode after encryption has started has no effect on the |
701 | current connection. |
702 | |
703 | \sa peerVerifyMode(), setPeerVerifyDepth(), mode() |
704 | */ |
705 | void QSslSocket::setPeerVerifyMode(QSslSocket::PeerVerifyMode mode) |
706 | { |
707 | Q_D(QSslSocket); |
708 | d->configuration.peerVerifyMode = mode; |
709 | } |
710 | |
711 | /*! |
712 | \since 4.4 |
713 | |
714 | Returns the maximum number of certificates in the peer's certificate chain |
715 | to be checked during the SSL handshake phase, or 0 (the default) if no |
716 | maximum depth has been set, indicating that the whole certificate chain |
717 | should be checked. |
718 | |
719 | The certificates are checked in issuing order, starting with the peer's |
720 | own certificate, then its issuer's certificate, and so on. |
721 | |
722 | \sa setPeerVerifyDepth(), peerVerifyMode() |
723 | */ |
724 | int QSslSocket::peerVerifyDepth() const |
725 | { |
726 | Q_D(const QSslSocket); |
727 | return d->configuration.peerVerifyDepth; |
728 | } |
729 | |
730 | /*! |
731 | \since 4.4 |
732 | |
733 | Sets the maximum number of certificates in the peer's certificate chain to |
734 | be checked during the SSL handshake phase, to \a depth. Setting a depth of |
735 | 0 means that no maximum depth is set, indicating that the whole |
736 | certificate chain should be checked. |
737 | |
738 | The certificates are checked in issuing order, starting with the peer's |
739 | own certificate, then its issuer's certificate, and so on. |
740 | |
741 | \sa peerVerifyDepth(), setPeerVerifyMode() |
742 | */ |
743 | void QSslSocket::setPeerVerifyDepth(int depth) |
744 | { |
745 | Q_D(QSslSocket); |
746 | if (depth < 0) { |
747 | qCWarning(lcSsl, "QSslSocket::setPeerVerifyDepth: cannot set negative depth of %d" , depth); |
748 | return; |
749 | } |
750 | d->configuration.peerVerifyDepth = depth; |
751 | } |
752 | |
753 | /*! |
754 | \since 4.8 |
755 | |
756 | Returns the different hostname for the certificate validation, as set by |
757 | setPeerVerifyName or by connectToHostEncrypted. |
758 | |
759 | \sa setPeerVerifyName(), connectToHostEncrypted() |
760 | */ |
761 | QString QSslSocket::peerVerifyName() const |
762 | { |
763 | Q_D(const QSslSocket); |
764 | return d->verificationPeerName; |
765 | } |
766 | |
767 | /*! |
768 | \since 4.8 |
769 | |
770 | Sets a different host name, given by \a hostName, for the certificate |
771 | validation instead of the one used for the TCP connection. |
772 | |
773 | \sa connectToHostEncrypted() |
774 | */ |
775 | void QSslSocket::setPeerVerifyName(const QString &hostName) |
776 | { |
777 | Q_D(QSslSocket); |
778 | d->verificationPeerName = hostName; |
779 | } |
780 | |
781 | /*! |
782 | \reimp |
783 | |
784 | Returns the number of decrypted bytes that are immediately available for |
785 | reading. |
786 | */ |
787 | qint64 QSslSocket::bytesAvailable() const |
788 | { |
789 | Q_D(const QSslSocket); |
790 | if (d->mode == UnencryptedMode) |
791 | return QAbstractSocket::bytesAvailable() + (d->plainSocket ? d->plainSocket->bytesAvailable() : 0); |
792 | return QAbstractSocket::bytesAvailable(); |
793 | } |
794 | |
795 | /*! |
796 | \reimp |
797 | |
798 | Returns the number of unencrypted bytes that are waiting to be encrypted |
799 | and written to the network. |
800 | */ |
801 | qint64 QSslSocket::bytesToWrite() const |
802 | { |
803 | Q_D(const QSslSocket); |
804 | if (d->mode == UnencryptedMode) |
805 | return d->plainSocket ? d->plainSocket->bytesToWrite() : 0; |
806 | return d->writeBuffer.size(); |
807 | } |
808 | |
809 | /*! |
810 | \since 4.4 |
811 | |
812 | Returns the number of encrypted bytes that are awaiting decryption. |
813 | Normally, this function will return 0 because QSslSocket decrypts its |
814 | incoming data as soon as it can. |
815 | */ |
816 | qint64 QSslSocket::encryptedBytesAvailable() const |
817 | { |
818 | Q_D(const QSslSocket); |
819 | if (d->mode == UnencryptedMode) |
820 | return 0; |
821 | return d->plainSocket->bytesAvailable(); |
822 | } |
823 | |
824 | /*! |
825 | \since 4.4 |
826 | |
827 | Returns the number of encrypted bytes that are waiting to be written to |
828 | the network. |
829 | */ |
830 | qint64 QSslSocket::encryptedBytesToWrite() const |
831 | { |
832 | Q_D(const QSslSocket); |
833 | if (d->mode == UnencryptedMode) |
834 | return 0; |
835 | return d->plainSocket->bytesToWrite(); |
836 | } |
837 | |
838 | /*! |
839 | \reimp |
840 | |
841 | Returns \c true if you can read one while line (terminated by a single ASCII |
842 | '\\n' character) of decrypted characters; otherwise, false is returned. |
843 | */ |
844 | bool QSslSocket::canReadLine() const |
845 | { |
846 | Q_D(const QSslSocket); |
847 | if (d->mode == UnencryptedMode) |
848 | return QAbstractSocket::canReadLine() || (d->plainSocket && d->plainSocket->canReadLine()); |
849 | return QAbstractSocket::canReadLine(); |
850 | } |
851 | |
852 | /*! |
853 | \reimp |
854 | */ |
855 | void QSslSocket::close() |
856 | { |
857 | #ifdef QSSLSOCKET_DEBUG |
858 | qCDebug(lcSsl) << "QSslSocket::close()" ; |
859 | #endif |
860 | Q_D(QSslSocket); |
861 | if (encryptedBytesToWrite() || !d->writeBuffer.isEmpty()) |
862 | flush(); |
863 | if (d->plainSocket) |
864 | d->plainSocket->close(); |
865 | QTcpSocket::close(); |
866 | |
867 | // must be cleared, reading/writing not possible on closed socket: |
868 | d->buffer.clear(); |
869 | d->writeBuffer.clear(); |
870 | } |
871 | |
872 | /*! |
873 | \reimp |
874 | */ |
875 | bool QSslSocket::atEnd() const |
876 | { |
877 | Q_D(const QSslSocket); |
878 | if (d->mode == UnencryptedMode) |
879 | return QAbstractSocket::atEnd() && (!d->plainSocket || d->plainSocket->atEnd()); |
880 | return QAbstractSocket::atEnd(); |
881 | } |
882 | |
883 | /*! |
884 | This function writes as much as possible from the internal write buffer to |
885 | the underlying network socket, without blocking. If any data was written, |
886 | this function returns \c true; otherwise false is returned. |
887 | |
888 | Call this function if you need QSslSocket to start sending buffered data |
889 | immediately. The number of bytes successfully written depends on the |
890 | operating system. In most cases, you do not need to call this function, |
891 | because QAbstractSocket will start sending data automatically once control |
892 | goes back to the event loop. In the absence of an event loop, call |
893 | waitForBytesWritten() instead. |
894 | |
895 | \sa write(), waitForBytesWritten() |
896 | */ |
897 | bool QSslSocket::flush() |
898 | { |
899 | return d_func()->flush(); |
900 | } |
901 | |
902 | /*! |
903 | \since 4.4 |
904 | |
905 | Sets the size of QSslSocket's internal read buffer to be \a size bytes. |
906 | */ |
907 | void QSslSocket::setReadBufferSize(qint64 size) |
908 | { |
909 | Q_D(QSslSocket); |
910 | d->readBufferMaxSize = size; |
911 | |
912 | if (d->plainSocket) |
913 | d->plainSocket->setReadBufferSize(size); |
914 | } |
915 | |
916 | /*! |
917 | Aborts the current connection and resets the socket. Unlike |
918 | disconnectFromHost(), this function immediately closes the socket, |
919 | clearing any pending data in the write buffer. |
920 | |
921 | \sa disconnectFromHost(), close() |
922 | */ |
923 | void QSslSocket::abort() |
924 | { |
925 | Q_D(QSslSocket); |
926 | #ifdef QSSLSOCKET_DEBUG |
927 | qCDebug(lcSsl) << "QSslSocket::abort()" ; |
928 | #endif |
929 | if (d->plainSocket) |
930 | d->plainSocket->abort(); |
931 | close(); |
932 | } |
933 | |
934 | /*! |
935 | \since 4.4 |
936 | |
937 | Returns the socket's SSL configuration state. The default SSL |
938 | configuration of a socket is to use the default ciphers, |
939 | default CA certificates, no local private key or certificate. |
940 | |
941 | The SSL configuration also contains fields that can change with |
942 | time without notice. |
943 | |
944 | \sa localCertificate(), peerCertificate(), peerCertificateChain(), |
945 | sessionCipher(), privateKey(), QSslConfiguration::ciphers(), |
946 | QSslConfiguration::caCertificates() |
947 | */ |
948 | QSslConfiguration QSslSocket::sslConfiguration() const |
949 | { |
950 | Q_D(const QSslSocket); |
951 | |
952 | // create a deep copy of our configuration |
953 | QSslConfigurationPrivate *copy = new QSslConfigurationPrivate(d->configuration); |
954 | copy->ref.storeRelaxed(newValue: 0); // the QSslConfiguration constructor refs up |
955 | copy->sessionCipher = d->sessionCipher(); |
956 | copy->sessionProtocol = d->sessionProtocol(); |
957 | |
958 | return QSslConfiguration(copy); |
959 | } |
960 | |
961 | /*! |
962 | \since 4.4 |
963 | |
964 | Sets the socket's SSL configuration to be the contents of \a configuration. |
965 | This function sets the local certificate, the ciphers, the private key and the CA |
966 | certificates to those stored in \a configuration. |
967 | |
968 | It is not possible to set the SSL-state related fields. |
969 | |
970 | \sa setLocalCertificate(), setPrivateKey(), QSslConfiguration::setCaCertificates(), |
971 | QSslConfiguration::setCiphers() |
972 | */ |
973 | void QSslSocket::setSslConfiguration(const QSslConfiguration &configuration) |
974 | { |
975 | Q_D(QSslSocket); |
976 | d->configuration.localCertificateChain = configuration.localCertificateChain(); |
977 | d->configuration.privateKey = configuration.privateKey(); |
978 | d->configuration.ciphers = configuration.ciphers(); |
979 | d->configuration.ellipticCurves = configuration.ellipticCurves(); |
980 | d->configuration.preSharedKeyIdentityHint = configuration.preSharedKeyIdentityHint(); |
981 | d->configuration.dhParams = configuration.diffieHellmanParameters(); |
982 | d->configuration.caCertificates = configuration.caCertificates(); |
983 | d->configuration.peerVerifyDepth = configuration.peerVerifyDepth(); |
984 | d->configuration.peerVerifyMode = configuration.peerVerifyMode(); |
985 | d->configuration.protocol = configuration.protocol(); |
986 | d->configuration.backendConfig = configuration.backendConfiguration(); |
987 | d->configuration.sslOptions = configuration.d->sslOptions; |
988 | d->configuration.sslSession = configuration.sessionTicket(); |
989 | d->configuration.sslSessionTicketLifeTimeHint = configuration.sessionTicketLifeTimeHint(); |
990 | d->configuration.nextAllowedProtocols = configuration.allowedNextProtocols(); |
991 | d->configuration.nextNegotiatedProtocol = configuration.nextNegotiatedProtocol(); |
992 | d->configuration.nextProtocolNegotiationStatus = configuration.nextProtocolNegotiationStatus(); |
993 | #if QT_CONFIG(ocsp) |
994 | d->configuration.ocspStaplingEnabled = configuration.ocspStaplingEnabled(); |
995 | #endif |
996 | |
997 | // if the CA certificates were set explicitly (either via |
998 | // QSslConfiguration::setCaCertificates() or QSslSocket::setCaCertificates(), |
999 | // we cannot load the certificates on demand |
1000 | if (!configuration.d->allowRootCertOnDemandLoading) { |
1001 | d->allowRootCertOnDemandLoading = false; |
1002 | d->configuration.allowRootCertOnDemandLoading = false; |
1003 | } |
1004 | } |
1005 | |
1006 | /*! |
1007 | Sets the certificate chain to be presented to the peer during the |
1008 | SSL handshake to be \a localChain. |
1009 | |
1010 | \sa QSslConfiguration::setLocalCertificateChain() |
1011 | \since 5.1 |
1012 | */ |
1013 | void QSslSocket::setLocalCertificateChain(const QList<QSslCertificate> &localChain) |
1014 | { |
1015 | Q_D(QSslSocket); |
1016 | d->configuration.localCertificateChain = localChain; |
1017 | } |
1018 | |
1019 | /*! |
1020 | Returns the socket's local \l {QSslCertificate} {certificate} chain, |
1021 | or an empty list if no local certificates have been assigned. |
1022 | |
1023 | \sa setLocalCertificateChain() |
1024 | \since 5.1 |
1025 | */ |
1026 | QList<QSslCertificate> QSslSocket::localCertificateChain() const |
1027 | { |
1028 | Q_D(const QSslSocket); |
1029 | return d->configuration.localCertificateChain; |
1030 | } |
1031 | |
1032 | /*! |
1033 | Sets the socket's local certificate to \a certificate. The local |
1034 | certificate is necessary if you need to confirm your identity to the |
1035 | peer. It is used together with the private key; if you set the local |
1036 | certificate, you must also set the private key. |
1037 | |
1038 | The local certificate and private key are always necessary for server |
1039 | sockets, but are also rarely used by client sockets if the server requires |
1040 | the client to authenticate. |
1041 | |
1042 | \note Secure Transport SSL backend on macOS may update the default keychain |
1043 | (the default is probably your login keychain) by importing your local certificates |
1044 | and keys. This can also result in system dialogs showing up and asking for |
1045 | permission when your application is using these private keys. If such behavior |
1046 | is undesired, set the QT_SSL_USE_TEMPORARY_KEYCHAIN environment variable to a |
1047 | non-zero value; this will prompt QSslSocket to use its own temporary keychain. |
1048 | |
1049 | \sa localCertificate(), setPrivateKey() |
1050 | */ |
1051 | void QSslSocket::setLocalCertificate(const QSslCertificate &certificate) |
1052 | { |
1053 | Q_D(QSslSocket); |
1054 | d->configuration.localCertificateChain = QList<QSslCertificate>(); |
1055 | d->configuration.localCertificateChain += certificate; |
1056 | } |
1057 | |
1058 | /*! |
1059 | \overload |
1060 | |
1061 | Sets the socket's local \l {QSslCertificate} {certificate} to the |
1062 | first one found in file \a path, which is parsed according to the |
1063 | specified \a format. |
1064 | */ |
1065 | void QSslSocket::setLocalCertificate(const QString &path, |
1066 | QSsl::EncodingFormat format) |
1067 | { |
1068 | QFile file(path); |
1069 | if (file.open(flags: QIODevice::ReadOnly | QIODevice::Text)) |
1070 | setLocalCertificate(QSslCertificate(file.readAll(), format)); |
1071 | |
1072 | } |
1073 | |
1074 | /*! |
1075 | Returns the socket's local \l {QSslCertificate} {certificate}, or |
1076 | an empty certificate if no local certificate has been assigned. |
1077 | |
1078 | \sa setLocalCertificate(), privateKey() |
1079 | */ |
1080 | QSslCertificate QSslSocket::localCertificate() const |
1081 | { |
1082 | Q_D(const QSslSocket); |
1083 | if (d->configuration.localCertificateChain.isEmpty()) |
1084 | return QSslCertificate(); |
1085 | return d->configuration.localCertificateChain[0]; |
1086 | } |
1087 | |
1088 | /*! |
1089 | Returns the peer's digital certificate (i.e., the immediate |
1090 | certificate of the host you are connected to), or a null |
1091 | certificate, if the peer has not assigned a certificate. |
1092 | |
1093 | The peer certificate is checked automatically during the |
1094 | handshake phase, so this function is normally used to fetch |
1095 | the certificate for display or for connection diagnostic |
1096 | purposes. It contains information about the peer, including |
1097 | its host name, the certificate issuer, and the peer's public |
1098 | key. |
1099 | |
1100 | Because the peer certificate is set during the handshake phase, it |
1101 | is safe to access the peer certificate from a slot connected to |
1102 | the sslErrors() signal or the encrypted() signal. |
1103 | |
1104 | If a null certificate is returned, it can mean the SSL handshake |
1105 | failed, or it can mean the host you are connected to doesn't have |
1106 | a certificate, or it can mean there is no connection. |
1107 | |
1108 | If you want to check the peer's complete chain of certificates, |
1109 | use peerCertificateChain() to get them all at once. |
1110 | |
1111 | \sa peerCertificateChain() |
1112 | */ |
1113 | QSslCertificate QSslSocket::peerCertificate() const |
1114 | { |
1115 | Q_D(const QSslSocket); |
1116 | return d->configuration.peerCertificate; |
1117 | } |
1118 | |
1119 | /*! |
1120 | Returns the peer's chain of digital certificates, or an empty list |
1121 | of certificates. |
1122 | |
1123 | Peer certificates are checked automatically during the handshake |
1124 | phase. This function is normally used to fetch certificates for |
1125 | display, or for performing connection diagnostics. Certificates |
1126 | contain information about the peer and the certificate issuers, |
1127 | including host name, issuer names, and issuer public keys. |
1128 | |
1129 | The peer certificates are set in QSslSocket during the handshake |
1130 | phase, so it is safe to call this function from a slot connected |
1131 | to the sslErrors() signal or the encrypted() signal. |
1132 | |
1133 | If an empty list is returned, it can mean the SSL handshake |
1134 | failed, or it can mean the host you are connected to doesn't have |
1135 | a certificate, or it can mean there is no connection. |
1136 | |
1137 | If you want to get only the peer's immediate certificate, use |
1138 | peerCertificate(). |
1139 | |
1140 | \sa peerCertificate() |
1141 | */ |
1142 | QList<QSslCertificate> QSslSocket::peerCertificateChain() const |
1143 | { |
1144 | Q_D(const QSslSocket); |
1145 | return d->configuration.peerCertificateChain; |
1146 | } |
1147 | |
1148 | /*! |
1149 | Returns the socket's cryptographic \l {QSslCipher} {cipher}, or a |
1150 | null cipher if the connection isn't encrypted. The socket's cipher |
1151 | for the session is set during the handshake phase. The cipher is |
1152 | used to encrypt and decrypt data transmitted through the socket. |
1153 | |
1154 | QSslSocket also provides functions for setting the ordered list of |
1155 | ciphers from which the handshake phase will eventually select the |
1156 | session cipher. This ordered list must be in place before the |
1157 | handshake phase begins. |
1158 | |
1159 | \sa QSslConfiguration::ciphers(), QSslConfiguration::setCiphers(), |
1160 | QSslConfiguration::setCiphers(), |
1161 | QSslConfiguration::ciphers(), |
1162 | QSslConfiguration::supportedCiphers() |
1163 | */ |
1164 | QSslCipher QSslSocket::sessionCipher() const |
1165 | { |
1166 | Q_D(const QSslSocket); |
1167 | return d->sessionCipher(); |
1168 | } |
1169 | |
1170 | /*! |
1171 | Returns the socket's SSL/TLS protocol or UnknownProtocol if the |
1172 | connection isn't encrypted. The socket's protocol for the session |
1173 | is set during the handshake phase. |
1174 | |
1175 | \sa protocol(), setProtocol() |
1176 | \since 5.4 |
1177 | */ |
1178 | QSsl::SslProtocol QSslSocket::sessionProtocol() const |
1179 | { |
1180 | Q_D(const QSslSocket); |
1181 | return d->sessionProtocol(); |
1182 | } |
1183 | |
1184 | /*! |
1185 | \since 5.13 |
1186 | |
1187 | This function returns Online Certificate Status Protocol responses that |
1188 | a server may send during a TLS handshake using OCSP stapling. The vector |
1189 | is empty if no definitive response or no response at all was received. |
1190 | |
1191 | \sa QSslConfiguration::setOcspStaplingEnabled() |
1192 | */ |
1193 | QVector<QOcspResponse> QSslSocket::ocspResponses() const |
1194 | { |
1195 | Q_D(const QSslSocket); |
1196 | return d->ocspResponses; |
1197 | } |
1198 | |
1199 | /*! |
1200 | Sets the socket's private \l {QSslKey} {key} to \a key. The |
1201 | private key and the local \l {QSslCertificate} {certificate} are |
1202 | used by clients and servers that must prove their identity to |
1203 | SSL peers. |
1204 | |
1205 | Both the key and the local certificate are required if you are |
1206 | creating an SSL server socket. If you are creating an SSL client |
1207 | socket, the key and local certificate are required if your client |
1208 | must identify itself to an SSL server. |
1209 | |
1210 | \sa privateKey(), setLocalCertificate() |
1211 | */ |
1212 | void QSslSocket::setPrivateKey(const QSslKey &key) |
1213 | { |
1214 | Q_D(QSslSocket); |
1215 | d->configuration.privateKey = key; |
1216 | } |
1217 | |
1218 | /*! |
1219 | \overload |
1220 | |
1221 | Reads the string in file \a fileName and decodes it using |
1222 | a specified \a algorithm and encoding \a format to construct |
1223 | an \l {QSslKey} {SSL key}. If the encoded key is encrypted, |
1224 | \a passPhrase is used to decrypt it. |
1225 | |
1226 | The socket's private key is set to the constructed key. The |
1227 | private key and the local \l {QSslCertificate} {certificate} are |
1228 | used by clients and servers that must prove their identity to SSL |
1229 | peers. |
1230 | |
1231 | Both the key and the local certificate are required if you are |
1232 | creating an SSL server socket. If you are creating an SSL client |
1233 | socket, the key and local certificate are required if your client |
1234 | must identify itself to an SSL server. |
1235 | |
1236 | \sa privateKey(), setLocalCertificate() |
1237 | */ |
1238 | void QSslSocket::setPrivateKey(const QString &fileName, QSsl::KeyAlgorithm algorithm, |
1239 | QSsl::EncodingFormat format, const QByteArray &passPhrase) |
1240 | { |
1241 | QFile file(fileName); |
1242 | if (!file.open(flags: QIODevice::ReadOnly)) { |
1243 | qCWarning(lcSsl, "QSslSocket::setPrivateKey: Couldn't open file for reading" ); |
1244 | return; |
1245 | } |
1246 | |
1247 | QSslKey key(file.readAll(), algorithm, format, QSsl::PrivateKey, passPhrase); |
1248 | if (key.isNull()) { |
1249 | qCWarning(lcSsl, "QSslSocket::setPrivateKey: " |
1250 | "The specified file does not contain a valid key" ); |
1251 | return; |
1252 | } |
1253 | |
1254 | Q_D(QSslSocket); |
1255 | d->configuration.privateKey = key; |
1256 | } |
1257 | |
1258 | /*! |
1259 | Returns this socket's private key. |
1260 | |
1261 | \sa setPrivateKey(), localCertificate() |
1262 | */ |
1263 | QSslKey QSslSocket::privateKey() const |
1264 | { |
1265 | Q_D(const QSslSocket); |
1266 | return d->configuration.privateKey; |
1267 | } |
1268 | |
1269 | #if QT_DEPRECATED_SINCE(5, 5) |
1270 | /*! |
1271 | \deprecated |
1272 | |
1273 | Use QSslConfiguration::ciphers() instead. |
1274 | |
1275 | Returns this socket's current cryptographic cipher suite. This |
1276 | list is used during the socket's handshake phase for choosing a |
1277 | session cipher. The returned list of ciphers is ordered by |
1278 | descending preference. (i.e., the first cipher in the list is the |
1279 | most preferred cipher). The session cipher will be the first one |
1280 | in the list that is also supported by the peer. |
1281 | |
1282 | By default, the handshake phase can choose any of the ciphers |
1283 | supported by this system's SSL libraries, which may vary from |
1284 | system to system. The list of ciphers supported by this system's |
1285 | SSL libraries is returned by supportedCiphers(). You can restrict |
1286 | the list of ciphers used for choosing the session cipher for this |
1287 | socket by calling setCiphers() with a subset of the supported |
1288 | ciphers. You can revert to using the entire set by calling |
1289 | setCiphers() with the list returned by supportedCiphers(). |
1290 | |
1291 | You can restrict the list of ciphers used for choosing the session |
1292 | cipher for \e all sockets by calling setDefaultCiphers() with a |
1293 | subset of the supported ciphers. You can revert to using the |
1294 | entire set by calling setCiphers() with the list returned by |
1295 | supportedCiphers(). |
1296 | |
1297 | \sa setCiphers(), defaultCiphers(), setDefaultCiphers(), supportedCiphers() |
1298 | */ |
1299 | QList<QSslCipher> QSslSocket::ciphers() const |
1300 | { |
1301 | Q_D(const QSslSocket); |
1302 | return d->configuration.ciphers; |
1303 | } |
1304 | |
1305 | /*! |
1306 | \deprecated |
1307 | |
1308 | USe QSslConfiguration::setCiphers() instead. |
1309 | |
1310 | Sets the cryptographic cipher suite for this socket to \a ciphers, |
1311 | which must contain a subset of the ciphers in the list returned by |
1312 | supportedCiphers(). |
1313 | |
1314 | Restricting the cipher suite must be done before the handshake |
1315 | phase, where the session cipher is chosen. |
1316 | |
1317 | \sa ciphers(), setDefaultCiphers(), supportedCiphers() |
1318 | */ |
1319 | void QSslSocket::setCiphers(const QList<QSslCipher> &ciphers) |
1320 | { |
1321 | Q_D(QSslSocket); |
1322 | d->configuration.ciphers = ciphers; |
1323 | } |
1324 | |
1325 | /*! |
1326 | \deprecated |
1327 | |
1328 | Use QSslConfiguration::setCiphers() instead. |
1329 | |
1330 | Sets the cryptographic cipher suite for this socket to \a ciphers, which |
1331 | is a colon-separated list of cipher suite names. The ciphers are listed in |
1332 | order of preference, starting with the most preferred cipher. For example: |
1333 | |
1334 | \snippet code/src_network_ssl_qsslsocket.cpp 4 |
1335 | |
1336 | Each cipher name in \a ciphers must be the name of a cipher in the |
1337 | list returned by supportedCiphers(). Restricting the cipher suite |
1338 | must be done before the handshake phase, where the session cipher |
1339 | is chosen. |
1340 | |
1341 | \sa ciphers(), setDefaultCiphers(), supportedCiphers() |
1342 | */ |
1343 | void QSslSocket::setCiphers(const QString &ciphers) |
1344 | { |
1345 | Q_D(QSslSocket); |
1346 | d->configuration.ciphers.clear(); |
1347 | const auto cipherNames = ciphers.split(sep: QLatin1Char(':'), behavior: Qt::SkipEmptyParts); |
1348 | for (const QString &cipherName : cipherNames) { |
1349 | QSslCipher cipher(cipherName); |
1350 | if (!cipher.isNull()) |
1351 | d->configuration.ciphers << cipher; |
1352 | } |
1353 | } |
1354 | |
1355 | /*! |
1356 | \deprecated |
1357 | |
1358 | Use QSslConfiguration::setCiphers() on the default QSslConfiguration instead. |
1359 | |
1360 | Sets the default cryptographic cipher suite for all sockets in |
1361 | this application to \a ciphers, which must contain a subset of the |
1362 | ciphers in the list returned by supportedCiphers(). |
1363 | |
1364 | Restricting the default cipher suite only affects SSL sockets |
1365 | that perform their handshake phase after the default cipher |
1366 | suite has been changed. |
1367 | |
1368 | \sa setCiphers(), defaultCiphers(), supportedCiphers() |
1369 | */ |
1370 | void QSslSocket::setDefaultCiphers(const QList<QSslCipher> &ciphers) |
1371 | { |
1372 | QSslSocketPrivate::setDefaultCiphers(ciphers); |
1373 | } |
1374 | |
1375 | /*! |
1376 | \deprecated |
1377 | |
1378 | Use QSslConfiguration::ciphers() on the default QSslConfiguration instead. |
1379 | |
1380 | Returns the default cryptographic cipher suite for all sockets in |
1381 | this application. This list is used during the socket's handshake |
1382 | phase when negotiating with the peer to choose a session cipher. |
1383 | The list is ordered by preference (i.e., the first cipher in the |
1384 | list is the most preferred cipher). |
1385 | |
1386 | By default, the handshake phase can choose any of the ciphers |
1387 | supported by this system's SSL libraries, which may vary from |
1388 | system to system. The list of ciphers supported by this system's |
1389 | SSL libraries is returned by supportedCiphers(). |
1390 | |
1391 | \sa supportedCiphers() |
1392 | */ |
1393 | QList<QSslCipher> QSslSocket::defaultCiphers() |
1394 | { |
1395 | return QSslSocketPrivate::defaultCiphers(); |
1396 | } |
1397 | |
1398 | /*! |
1399 | \deprecated |
1400 | |
1401 | Use QSslConfiguration::supportedCiphers() instead. |
1402 | |
1403 | Returns the list of cryptographic ciphers supported by this |
1404 | system. This list is set by the system's SSL libraries and may |
1405 | vary from system to system. |
1406 | |
1407 | \sa defaultCiphers(), ciphers(), setCiphers() |
1408 | */ |
1409 | QList<QSslCipher> QSslSocket::supportedCiphers() |
1410 | { |
1411 | return QSslSocketPrivate::supportedCiphers(); |
1412 | } |
1413 | #endif // #if QT_DEPRECATED_SINCE(5, 5) |
1414 | |
1415 | /*! |
1416 | \deprecated |
1417 | |
1418 | Use QSslConfiguration::addCaCertificates() instead. |
1419 | |
1420 | Searches all files in the \a path for certificates encoded in the |
1421 | specified \a format and adds them to this socket's CA certificate |
1422 | database. \a path must be a file or a pattern matching one or more |
1423 | files, as specified by \a syntax. Returns \c true if one or more |
1424 | certificates are added to the socket's CA certificate database; |
1425 | otherwise returns \c false. |
1426 | |
1427 | The CA certificate database is used by the socket during the |
1428 | handshake phase to validate the peer's certificate. |
1429 | |
1430 | For more precise control, use addCaCertificate(). |
1431 | |
1432 | \sa addCaCertificate(), QSslCertificate::fromPath() |
1433 | */ |
1434 | bool QSslSocket::addCaCertificates(const QString &path, QSsl::EncodingFormat format, |
1435 | QRegExp::PatternSyntax syntax) |
1436 | { |
1437 | Q_D(QSslSocket); |
1438 | QT_WARNING_PUSH |
1439 | QT_WARNING_DISABLE_DEPRECATED |
1440 | QList<QSslCertificate> certs = QSslCertificate::fromPath(path, format, syntax); |
1441 | QT_WARNING_POP |
1442 | if (certs.isEmpty()) |
1443 | return false; |
1444 | |
1445 | d->configuration.caCertificates += certs; |
1446 | return true; |
1447 | } |
1448 | |
1449 | /*! |
1450 | \deprecated |
1451 | |
1452 | Use QSslConfiguration::addCaCertificate() instead. |
1453 | |
1454 | Adds the \a certificate to this socket's CA certificate database. |
1455 | The CA certificate database is used by the socket during the |
1456 | handshake phase to validate the peer's certificate. |
1457 | |
1458 | To add multiple certificates, use addCaCertificates(). |
1459 | |
1460 | \sa QSslConfiguration::caCertificates(), |
1461 | QSslConfiguration::setCaCertificates() |
1462 | */ |
1463 | void QSslSocket::addCaCertificate(const QSslCertificate &certificate) |
1464 | { |
1465 | Q_D(QSslSocket); |
1466 | d->configuration.caCertificates += certificate; |
1467 | } |
1468 | |
1469 | /*! |
1470 | \deprecated |
1471 | |
1472 | Use QSslConfiguration::addCaCertificates() instead. |
1473 | |
1474 | Adds the \a certificates to this socket's CA certificate database. |
1475 | The CA certificate database is used by the socket during the |
1476 | handshake phase to validate the peer's certificate. |
1477 | |
1478 | For more precise control, use addCaCertificate(). |
1479 | |
1480 | \sa QSslConfiguration::caCertificates(), addDefaultCaCertificate() |
1481 | */ |
1482 | void QSslSocket::addCaCertificates(const QList<QSslCertificate> &certificates) |
1483 | { |
1484 | Q_D(QSslSocket); |
1485 | d->configuration.caCertificates += certificates; |
1486 | } |
1487 | |
1488 | #if QT_DEPRECATED_SINCE(5, 5) |
1489 | /*! |
1490 | \deprecated |
1491 | |
1492 | Use QSslConfiguration::setCaCertificates() instead. |
1493 | |
1494 | Sets this socket's CA certificate database to be \a certificates. |
1495 | The certificate database must be set prior to the SSL handshake. |
1496 | The CA certificate database is used by the socket during the |
1497 | handshake phase to validate the peer's certificate. |
1498 | |
1499 | The CA certificate database can be reset to the current default CA |
1500 | certificate database by calling this function with the list of CA |
1501 | certificates returned by defaultCaCertificates(). |
1502 | |
1503 | \sa defaultCaCertificates() |
1504 | */ |
1505 | void QSslSocket::setCaCertificates(const QList<QSslCertificate> &certificates) |
1506 | { |
1507 | Q_D(QSslSocket); |
1508 | d->configuration.caCertificates = certificates; |
1509 | d->allowRootCertOnDemandLoading = false; |
1510 | } |
1511 | |
1512 | /*! |
1513 | \deprecated |
1514 | |
1515 | Use QSslConfiguration::caCertificates() instead. |
1516 | |
1517 | Returns this socket's CA certificate database. The CA certificate |
1518 | database is used by the socket during the handshake phase to |
1519 | validate the peer's certificate. It can be moodified prior to the |
1520 | handshake with addCaCertificate(), addCaCertificates(), and |
1521 | setCaCertificates(). |
1522 | |
1523 | \note On Unix, this method may return an empty list if the root |
1524 | certificates are loaded on demand. |
1525 | |
1526 | \sa addCaCertificate(), addCaCertificates(), setCaCertificates() |
1527 | */ |
1528 | QList<QSslCertificate> QSslSocket::caCertificates() const |
1529 | { |
1530 | Q_D(const QSslSocket); |
1531 | return d->configuration.caCertificates; |
1532 | } |
1533 | #endif // #if QT_DEPRECATED_SINCE(5, 5) |
1534 | |
1535 | /*! |
1536 | \deprecated |
1537 | |
1538 | Use QSslConfiguration::addCaCertificates() on the default QSslConfiguration instead. |
1539 | |
1540 | Searches all files in the \a path for certificates with the |
1541 | specified \a encoding and adds them to the default CA certificate |
1542 | database. \a path can be an explicit file, or it can contain |
1543 | wildcards in the format specified by \a syntax. Returns \c true if |
1544 | any CA certificates are added to the default database. |
1545 | |
1546 | Each SSL socket's CA certificate database is initialized to the |
1547 | default CA certificate database. |
1548 | |
1549 | \sa QSslConfiguration::caCertificates(), QSslConfiguration::addCaCertificates(), |
1550 | QSslConfiguration::addCaCertificate() |
1551 | */ |
1552 | bool QSslSocket::addDefaultCaCertificates(const QString &path, QSsl::EncodingFormat encoding, |
1553 | QRegExp::PatternSyntax syntax) |
1554 | { |
1555 | return QSslSocketPrivate::addDefaultCaCertificates(path, format: encoding, syntax); |
1556 | } |
1557 | |
1558 | /*! |
1559 | \deprecated |
1560 | |
1561 | Use QSslConfiguration::addCaCertificate() on the default QSslConfiguration instead. |
1562 | |
1563 | Adds \a certificate to the default CA certificate database. Each |
1564 | SSL socket's CA certificate database is initialized to the default |
1565 | CA certificate database. |
1566 | |
1567 | \sa QSslConfiguration::addCaCertificates() |
1568 | */ |
1569 | void QSslSocket::addDefaultCaCertificate(const QSslCertificate &certificate) |
1570 | { |
1571 | QSslSocketPrivate::addDefaultCaCertificate(cert: certificate); |
1572 | } |
1573 | |
1574 | /*! |
1575 | \deprecated |
1576 | |
1577 | Use QSslConfiguration::addCaCertificates() on the default QSslConfiguration instead. |
1578 | |
1579 | Adds \a certificates to the default CA certificate database. Each |
1580 | SSL socket's CA certificate database is initialized to the default |
1581 | CA certificate database. |
1582 | |
1583 | \sa QSslConfiguration::caCertificates(), QSslConfiguration::addCaCertificates() |
1584 | */ |
1585 | void QSslSocket::addDefaultCaCertificates(const QList<QSslCertificate> &certificates) |
1586 | { |
1587 | QSslSocketPrivate::addDefaultCaCertificates(certs: certificates); |
1588 | } |
1589 | |
1590 | #if QT_DEPRECATED_SINCE(5, 5) |
1591 | /*! |
1592 | \deprecated |
1593 | |
1594 | Use QSslConfiguration::setCaCertificates() on the default QSslConfiguration instead. |
1595 | |
1596 | Sets the default CA certificate database to \a certificates. The |
1597 | default CA certificate database is originally set to your system's |
1598 | default CA certificate database. You can override the default CA |
1599 | certificate database with your own CA certificate database using |
1600 | this function. |
1601 | |
1602 | Each SSL socket's CA certificate database is initialized to the |
1603 | default CA certificate database. |
1604 | |
1605 | \sa addDefaultCaCertificate() |
1606 | */ |
1607 | void QSslSocket::setDefaultCaCertificates(const QList<QSslCertificate> &certificates) |
1608 | { |
1609 | QSslSocketPrivate::setDefaultCaCertificates(certificates); |
1610 | } |
1611 | |
1612 | /*! |
1613 | \deprecated |
1614 | |
1615 | Use QSslConfiguration::caCertificates() on the default QSslConfiguration instead. |
1616 | |
1617 | Returns the current default CA certificate database. This database |
1618 | is originally set to your system's default CA certificate database. |
1619 | If no system default database is found, an empty database will be |
1620 | returned. You can override the default CA certificate database |
1621 | with your own CA certificate database using setDefaultCaCertificates(). |
1622 | |
1623 | Each SSL socket's CA certificate database is initialized to the |
1624 | default CA certificate database. |
1625 | |
1626 | \note On Unix, this method may return an empty list if the root |
1627 | certificates are loaded on demand. |
1628 | |
1629 | \sa caCertificates() |
1630 | */ |
1631 | QList<QSslCertificate> QSslSocket::defaultCaCertificates() |
1632 | { |
1633 | return QSslSocketPrivate::defaultCaCertificates(); |
1634 | } |
1635 | |
1636 | /*! |
1637 | \deprecated |
1638 | |
1639 | Use QSslConfiguration::systemDefaultCaCertificates instead. |
1640 | |
1641 | This function provides the CA certificate database |
1642 | provided by the operating system. The CA certificate database |
1643 | returned by this function is used to initialize the database |
1644 | returned by defaultCaCertificates(). You can replace that database |
1645 | with your own with setDefaultCaCertificates(). |
1646 | |
1647 | \note: On OS X, only certificates that are either trusted for all |
1648 | purposes or trusted for the purpose of SSL in the keychain will be |
1649 | returned. |
1650 | |
1651 | \sa caCertificates(), defaultCaCertificates(), setDefaultCaCertificates() |
1652 | */ |
1653 | QList<QSslCertificate> QSslSocket::systemCaCertificates() |
1654 | { |
1655 | // we are calling ensureInitialized() in the method below |
1656 | return QSslSocketPrivate::systemCaCertificates(); |
1657 | } |
1658 | #endif // #if QT_DEPRECATED_SINCE(5, 5) |
1659 | |
1660 | /*! |
1661 | Waits until the socket is connected, or \a msecs milliseconds, |
1662 | whichever happens first. If the connection has been established, |
1663 | this function returns \c true; otherwise it returns \c false. |
1664 | |
1665 | \sa QAbstractSocket::waitForConnected() |
1666 | */ |
1667 | bool QSslSocket::waitForConnected(int msecs) |
1668 | { |
1669 | Q_D(QSslSocket); |
1670 | if (!d->plainSocket) |
1671 | return false; |
1672 | bool retVal = d->plainSocket->waitForConnected(msecs); |
1673 | if (!retVal) { |
1674 | setSocketState(d->plainSocket->state()); |
1675 | d->setError(errorCode: d->plainSocket->error(), errorString: d->plainSocket->errorString()); |
1676 | } |
1677 | return retVal; |
1678 | } |
1679 | |
1680 | /*! |
1681 | Waits until the socket has completed the SSL handshake and has |
1682 | emitted encrypted(), or \a msecs milliseconds, whichever comes |
1683 | first. If encrypted() has been emitted, this function returns |
1684 | true; otherwise (e.g., the socket is disconnected, or the SSL |
1685 | handshake fails), false is returned. |
1686 | |
1687 | The following example waits up to one second for the socket to be |
1688 | encrypted: |
1689 | |
1690 | \snippet code/src_network_ssl_qsslsocket.cpp 5 |
1691 | |
1692 | If msecs is -1, this function will not time out. |
1693 | |
1694 | \sa startClientEncryption(), startServerEncryption(), encrypted(), isEncrypted() |
1695 | */ |
1696 | bool QSslSocket::waitForEncrypted(int msecs) |
1697 | { |
1698 | Q_D(QSslSocket); |
1699 | if (!d->plainSocket || d->connectionEncrypted) |
1700 | return false; |
1701 | if (d->mode == UnencryptedMode && !d->autoStartHandshake) |
1702 | return false; |
1703 | if (!d->verifyProtocolSupported(where: "QSslSocket::waitForEncrypted:" )) |
1704 | return false; |
1705 | |
1706 | QElapsedTimer stopWatch; |
1707 | stopWatch.start(); |
1708 | |
1709 | if (d->plainSocket->state() != QAbstractSocket::ConnectedState) { |
1710 | // Wait until we've entered connected state. |
1711 | if (!d->plainSocket->waitForConnected(msecs)) |
1712 | return false; |
1713 | } |
1714 | |
1715 | while (!d->connectionEncrypted) { |
1716 | // Start the handshake, if this hasn't been started yet. |
1717 | if (d->mode == UnencryptedMode) |
1718 | startClientEncryption(); |
1719 | // Loop, waiting until the connection has been encrypted or an error |
1720 | // occurs. |
1721 | if (!d->plainSocket->waitForReadyRead(msecs: qt_subtract_from_timeout(timeout: msecs, elapsed: stopWatch.elapsed()))) |
1722 | return false; |
1723 | } |
1724 | return d->connectionEncrypted; |
1725 | } |
1726 | |
1727 | /*! |
1728 | \reimp |
1729 | */ |
1730 | bool QSslSocket::waitForReadyRead(int msecs) |
1731 | { |
1732 | Q_D(QSslSocket); |
1733 | if (!d->plainSocket) |
1734 | return false; |
1735 | if (d->mode == UnencryptedMode && !d->autoStartHandshake) |
1736 | return d->plainSocket->waitForReadyRead(msecs); |
1737 | |
1738 | // This function must return true if and only if readyRead() *was* emitted. |
1739 | // So we initialize "readyReadEmitted" to false and check if it was set to true. |
1740 | // waitForReadyRead() could be called recursively, so we can't use the same variable |
1741 | // (the inner waitForReadyRead() may fail, but the outer one still succeeded) |
1742 | bool readyReadEmitted = false; |
1743 | bool *previousReadyReadEmittedPointer = d->readyReadEmittedPointer; |
1744 | d->readyReadEmittedPointer = &readyReadEmitted; |
1745 | |
1746 | QElapsedTimer stopWatch; |
1747 | stopWatch.start(); |
1748 | |
1749 | if (!d->connectionEncrypted) { |
1750 | // Wait until we've entered encrypted mode, or until a failure occurs. |
1751 | if (!waitForEncrypted(msecs)) { |
1752 | d->readyReadEmittedPointer = previousReadyReadEmittedPointer; |
1753 | return false; |
1754 | } |
1755 | } |
1756 | |
1757 | if (!d->writeBuffer.isEmpty()) { |
1758 | // empty our cleartext write buffer first |
1759 | d->transmit(); |
1760 | } |
1761 | |
1762 | // test readyReadEmitted first because either operation above |
1763 | // (waitForEncrypted or transmit) may have set it |
1764 | while (!readyReadEmitted && |
1765 | d->plainSocket->waitForReadyRead(msecs: qt_subtract_from_timeout(timeout: msecs, elapsed: stopWatch.elapsed()))) { |
1766 | } |
1767 | |
1768 | d->readyReadEmittedPointer = previousReadyReadEmittedPointer; |
1769 | return readyReadEmitted; |
1770 | } |
1771 | |
1772 | /*! |
1773 | \reimp |
1774 | */ |
1775 | bool QSslSocket::waitForBytesWritten(int msecs) |
1776 | { |
1777 | Q_D(QSslSocket); |
1778 | if (!d->plainSocket) |
1779 | return false; |
1780 | if (d->mode == UnencryptedMode) |
1781 | return d->plainSocket->waitForBytesWritten(msecs); |
1782 | |
1783 | QElapsedTimer stopWatch; |
1784 | stopWatch.start(); |
1785 | |
1786 | if (!d->connectionEncrypted) { |
1787 | // Wait until we've entered encrypted mode, or until a failure occurs. |
1788 | if (!waitForEncrypted(msecs)) |
1789 | return false; |
1790 | } |
1791 | if (!d->writeBuffer.isEmpty()) { |
1792 | // empty our cleartext write buffer first |
1793 | d->transmit(); |
1794 | } |
1795 | |
1796 | return d->plainSocket->waitForBytesWritten(msecs: qt_subtract_from_timeout(timeout: msecs, elapsed: stopWatch.elapsed())); |
1797 | } |
1798 | |
1799 | /*! |
1800 | Waits until the socket has disconnected or \a msecs milliseconds, |
1801 | whichever comes first. If the connection has been disconnected, |
1802 | this function returns \c true; otherwise it returns \c false. |
1803 | |
1804 | \sa QAbstractSocket::waitForDisconnected() |
1805 | */ |
1806 | bool QSslSocket::waitForDisconnected(int msecs) |
1807 | { |
1808 | Q_D(QSslSocket); |
1809 | |
1810 | // require calling connectToHost() before waitForDisconnected() |
1811 | if (state() == UnconnectedState) { |
1812 | qCWarning(lcSsl, "QSslSocket::waitForDisconnected() is not allowed in UnconnectedState" ); |
1813 | return false; |
1814 | } |
1815 | |
1816 | if (!d->plainSocket) |
1817 | return false; |
1818 | // Forward to the plain socket unless the connection is secure. |
1819 | if (d->mode == UnencryptedMode && !d->autoStartHandshake) |
1820 | return d->plainSocket->waitForDisconnected(msecs); |
1821 | |
1822 | QElapsedTimer stopWatch; |
1823 | stopWatch.start(); |
1824 | |
1825 | if (!d->connectionEncrypted) { |
1826 | // Wait until we've entered encrypted mode, or until a failure occurs. |
1827 | if (!waitForEncrypted(msecs)) |
1828 | return false; |
1829 | } |
1830 | // We are delaying the disconnect, if the write buffer is not empty. |
1831 | // So, start the transmission. |
1832 | if (!d->writeBuffer.isEmpty()) |
1833 | d->transmit(); |
1834 | |
1835 | // At this point, the socket might be disconnected, if disconnectFromHost() |
1836 | // was called just after the connectToHostEncrypted() call. Also, we can |
1837 | // lose the connection as a result of the transmit() call. |
1838 | if (state() == UnconnectedState) |
1839 | return true; |
1840 | |
1841 | bool retVal = d->plainSocket->waitForDisconnected(msecs: qt_subtract_from_timeout(timeout: msecs, elapsed: stopWatch.elapsed())); |
1842 | if (!retVal) { |
1843 | setSocketState(d->plainSocket->state()); |
1844 | d->setError(errorCode: d->plainSocket->error(), errorString: d->plainSocket->errorString()); |
1845 | } |
1846 | return retVal; |
1847 | } |
1848 | |
1849 | #if QT_DEPRECATED_SINCE(5, 15) |
1850 | /*! |
1851 | \deprecated |
1852 | |
1853 | Use sslHandshakeErrors() instead. |
1854 | |
1855 | Returns a list of the last SSL errors that occurred. This is the |
1856 | same list as QSslSocket passes via the sslErrors() signal. If the |
1857 | connection has been encrypted with no errors, this function will |
1858 | return an empty list. |
1859 | |
1860 | \sa connectToHostEncrypted(), sslHandshakeErrors() |
1861 | */ |
1862 | QList<QSslError> QSslSocket::sslErrors() const |
1863 | { |
1864 | return sslHandshakeErrors(); |
1865 | } |
1866 | #endif // QT_DEPRECATED_SINCE(5, 15) |
1867 | |
1868 | /*! |
1869 | \since 5.15 |
1870 | |
1871 | Returns a list of the last SSL errors that occurred. This is the |
1872 | same list as QSslSocket passes via the sslErrors() signal. If the |
1873 | connection has been encrypted with no errors, this function will |
1874 | return an empty list. |
1875 | |
1876 | \sa connectToHostEncrypted() |
1877 | */ |
1878 | QList<QSslError> QSslSocket::sslHandshakeErrors() const |
1879 | { |
1880 | Q_D(const QSslSocket); |
1881 | return d->sslErrors; |
1882 | } |
1883 | |
1884 | /*! |
1885 | Returns \c true if this platform supports SSL; otherwise, returns |
1886 | false. If the platform doesn't support SSL, the socket will fail |
1887 | in the connection phase. |
1888 | */ |
1889 | bool QSslSocket::supportsSsl() |
1890 | { |
1891 | return QSslSocketPrivate::supportsSsl(); |
1892 | } |
1893 | |
1894 | /*! |
1895 | \since 5.0 |
1896 | Returns the version number of the SSL library in use. Note that |
1897 | this is the version of the library in use at run-time not compile |
1898 | time. If no SSL support is available then this will return an |
1899 | undefined value. |
1900 | */ |
1901 | long QSslSocket::sslLibraryVersionNumber() |
1902 | { |
1903 | return QSslSocketPrivate::sslLibraryVersionNumber(); |
1904 | } |
1905 | |
1906 | /*! |
1907 | \since 5.0 |
1908 | Returns the version string of the SSL library in use. Note that |
1909 | this is the version of the library in use at run-time not compile |
1910 | time. If no SSL support is available then this will return an empty value. |
1911 | */ |
1912 | QString QSslSocket::sslLibraryVersionString() |
1913 | { |
1914 | return QSslSocketPrivate::sslLibraryVersionString(); |
1915 | } |
1916 | |
1917 | /*! |
1918 | \since 5.4 |
1919 | Returns the version number of the SSL library in use at compile |
1920 | time. If no SSL support is available then this will return an |
1921 | undefined value. |
1922 | |
1923 | \sa sslLibraryVersionNumber() |
1924 | */ |
1925 | long QSslSocket::sslLibraryBuildVersionNumber() |
1926 | { |
1927 | return QSslSocketPrivate::sslLibraryBuildVersionNumber(); |
1928 | } |
1929 | |
1930 | /*! |
1931 | \since 5.4 |
1932 | Returns the version string of the SSL library in use at compile |
1933 | time. If no SSL support is available then this will return an |
1934 | empty value. |
1935 | |
1936 | \sa sslLibraryVersionString() |
1937 | */ |
1938 | QString QSslSocket::sslLibraryBuildVersionString() |
1939 | { |
1940 | return QSslSocketPrivate::sslLibraryBuildVersionString(); |
1941 | } |
1942 | |
1943 | /*! |
1944 | Starts a delayed SSL handshake for a client connection. This |
1945 | function can be called when the socket is in the \l ConnectedState |
1946 | but still in the \l UnencryptedMode. If it is not yet connected, |
1947 | or if it is already encrypted, this function has no effect. |
1948 | |
1949 | Clients that implement STARTTLS functionality often make use of |
1950 | delayed SSL handshakes. Most other clients can avoid calling this |
1951 | function directly by using connectToHostEncrypted() instead, which |
1952 | automatically performs the handshake. |
1953 | |
1954 | \sa connectToHostEncrypted(), startServerEncryption() |
1955 | */ |
1956 | void QSslSocket::startClientEncryption() |
1957 | { |
1958 | Q_D(QSslSocket); |
1959 | if (d->mode != UnencryptedMode) { |
1960 | qCWarning(lcSsl, |
1961 | "QSslSocket::startClientEncryption: cannot start handshake on non-plain connection" ); |
1962 | return; |
1963 | } |
1964 | if (state() != ConnectedState) { |
1965 | qCWarning(lcSsl, |
1966 | "QSslSocket::startClientEncryption: cannot start handshake when not connected" ); |
1967 | return; |
1968 | } |
1969 | |
1970 | if (!supportsSsl()) { |
1971 | qCWarning(lcSsl, "QSslSocket::startClientEncryption: TLS initialization failed" ); |
1972 | d->setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError, errorString: tr(s: "TLS initialization failed" )); |
1973 | return; |
1974 | } |
1975 | |
1976 | if (!d->verifyProtocolSupported(where: "QSslSocket::startClientEncryption:" )) |
1977 | return; |
1978 | |
1979 | #ifdef QSSLSOCKET_DEBUG |
1980 | qCDebug(lcSsl) << "QSslSocket::startClientEncryption()" ; |
1981 | #endif |
1982 | d->mode = SslClientMode; |
1983 | emit modeChanged(newMode: d->mode); |
1984 | d->startClientEncryption(); |
1985 | } |
1986 | |
1987 | /*! |
1988 | Starts a delayed SSL handshake for a server connection. This |
1989 | function can be called when the socket is in the \l ConnectedState |
1990 | but still in \l UnencryptedMode. If it is not connected or it is |
1991 | already encrypted, the function has no effect. |
1992 | |
1993 | For server sockets, calling this function is the only way to |
1994 | initiate the SSL handshake. Most servers will call this function |
1995 | immediately upon receiving a connection, or as a result of having |
1996 | received a protocol-specific command to enter SSL mode (e.g, the |
1997 | server may respond to receiving the string "STARTTLS\\r\\n" by |
1998 | calling this function). |
1999 | |
2000 | The most common way to implement an SSL server is to create a |
2001 | subclass of QTcpServer and reimplement |
2002 | QTcpServer::incomingConnection(). The returned socket descriptor |
2003 | is then passed to QSslSocket::setSocketDescriptor(). |
2004 | |
2005 | \sa connectToHostEncrypted(), startClientEncryption() |
2006 | */ |
2007 | void QSslSocket::startServerEncryption() |
2008 | { |
2009 | Q_D(QSslSocket); |
2010 | if (d->mode != UnencryptedMode) { |
2011 | qCWarning(lcSsl, "QSslSocket::startServerEncryption: cannot start handshake on non-plain connection" ); |
2012 | return; |
2013 | } |
2014 | #ifdef QSSLSOCKET_DEBUG |
2015 | qCDebug(lcSsl) << "QSslSocket::startServerEncryption()" ; |
2016 | #endif |
2017 | if (!supportsSsl()) { |
2018 | qCWarning(lcSsl, "QSslSocket::startServerEncryption: TLS initialization failed" ); |
2019 | d->setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError, errorString: tr(s: "TLS initialization failed" )); |
2020 | return; |
2021 | } |
2022 | if (!d->verifyProtocolSupported(where: "QSslSocket::startServerEncryption" )) |
2023 | return; |
2024 | |
2025 | d->mode = SslServerMode; |
2026 | emit modeChanged(newMode: d->mode); |
2027 | d->startServerEncryption(); |
2028 | } |
2029 | |
2030 | /*! |
2031 | This slot tells QSslSocket to ignore errors during QSslSocket's |
2032 | handshake phase and continue connecting. If you want to continue |
2033 | with the connection even if errors occur during the handshake |
2034 | phase, then you must call this slot, either from a slot connected |
2035 | to sslErrors(), or before the handshake phase. If you don't call |
2036 | this slot, either in response to errors or before the handshake, |
2037 | the connection will be dropped after the sslErrors() signal has |
2038 | been emitted. |
2039 | |
2040 | If there are no errors during the SSL handshake phase (i.e., the |
2041 | identity of the peer is established with no problems), QSslSocket |
2042 | will not emit the sslErrors() signal, and it is unnecessary to |
2043 | call this function. |
2044 | |
2045 | \warning Be sure to always let the user inspect the errors |
2046 | reported by the sslErrors() signal, and only call this method |
2047 | upon confirmation from the user that proceeding is ok. |
2048 | If there are unexpected errors, the connection should be aborted. |
2049 | Calling this method without inspecting the actual errors will |
2050 | most likely pose a security risk for your application. Use it |
2051 | with great care! |
2052 | |
2053 | \sa sslErrors() |
2054 | */ |
2055 | void QSslSocket::ignoreSslErrors() |
2056 | { |
2057 | Q_D(QSslSocket); |
2058 | d->ignoreAllSslErrors = true; |
2059 | } |
2060 | |
2061 | /*! |
2062 | \overload |
2063 | \since 4.6 |
2064 | |
2065 | This method tells QSslSocket to ignore only the errors given in \a |
2066 | errors. |
2067 | |
2068 | \note Because most SSL errors are associated with a certificate, for most |
2069 | of them you must set the expected certificate this SSL error is related to. |
2070 | If, for instance, you want to connect to a server that uses |
2071 | a self-signed certificate, consider the following snippet: |
2072 | |
2073 | \snippet code/src_network_ssl_qsslsocket.cpp 6 |
2074 | |
2075 | Multiple calls to this function will replace the list of errors that |
2076 | were passed in previous calls. |
2077 | You can clear the list of errors you want to ignore by calling this |
2078 | function with an empty list. |
2079 | |
2080 | \sa sslErrors(), sslHandshakeErrors() |
2081 | */ |
2082 | void QSslSocket::ignoreSslErrors(const QList<QSslError> &errors) |
2083 | { |
2084 | Q_D(QSslSocket); |
2085 | d->ignoreErrorsList = errors; |
2086 | } |
2087 | |
2088 | /*! |
2089 | \internal |
2090 | */ |
2091 | void QSslSocket::connectToHost(const QString &hostName, quint16 port, OpenMode openMode, NetworkLayerProtocol protocol) |
2092 | { |
2093 | Q_D(QSslSocket); |
2094 | d->preferredNetworkLayerProtocol = protocol; |
2095 | if (!d->initialized) |
2096 | d->init(); |
2097 | d->initialized = false; |
2098 | |
2099 | #ifdef QSSLSOCKET_DEBUG |
2100 | qCDebug(lcSsl) << "QSslSocket::connectToHost(" |
2101 | << hostName << ',' << port << ',' << openMode << ')'; |
2102 | #endif |
2103 | if (!d->plainSocket) { |
2104 | #ifdef QSSLSOCKET_DEBUG |
2105 | qCDebug(lcSsl) << "\tcreating internal plain socket" ; |
2106 | #endif |
2107 | d->createPlainSocket(openMode); |
2108 | } |
2109 | #ifndef QT_NO_NETWORKPROXY |
2110 | d->plainSocket->setProtocolTag(d->protocolTag); |
2111 | d->plainSocket->setProxy(proxy()); |
2112 | #endif |
2113 | QIODevice::open(mode: openMode); |
2114 | d->readChannelCount = d->writeChannelCount = 0; |
2115 | d->plainSocket->connectToHost(hostName, port, mode: openMode, protocol: d->preferredNetworkLayerProtocol); |
2116 | d->cachedSocketDescriptor = d->plainSocket->socketDescriptor(); |
2117 | } |
2118 | |
2119 | /*! |
2120 | \internal |
2121 | */ |
2122 | void QSslSocket::disconnectFromHost() |
2123 | { |
2124 | Q_D(QSslSocket); |
2125 | #ifdef QSSLSOCKET_DEBUG |
2126 | qCDebug(lcSsl) << "QSslSocket::disconnectFromHost()" ; |
2127 | #endif |
2128 | if (!d->plainSocket) |
2129 | return; |
2130 | if (d->state == UnconnectedState) |
2131 | return; |
2132 | if (d->mode == UnencryptedMode && !d->autoStartHandshake) { |
2133 | d->plainSocket->disconnectFromHost(); |
2134 | return; |
2135 | } |
2136 | if (d->state <= ConnectingState) { |
2137 | d->pendingClose = true; |
2138 | return; |
2139 | } |
2140 | |
2141 | // Perhaps emit closing() |
2142 | if (d->state != ClosingState) { |
2143 | d->state = ClosingState; |
2144 | emit stateChanged(d->state); |
2145 | } |
2146 | |
2147 | if (!d->writeBuffer.isEmpty()) { |
2148 | d->pendingClose = true; |
2149 | return; |
2150 | } |
2151 | |
2152 | if (d->mode == UnencryptedMode) { |
2153 | d->plainSocket->disconnectFromHost(); |
2154 | } else { |
2155 | d->disconnectFromHost(); |
2156 | } |
2157 | } |
2158 | |
2159 | /*! |
2160 | \reimp |
2161 | */ |
2162 | qint64 QSslSocket::readData(char *data, qint64 maxlen) |
2163 | { |
2164 | Q_D(QSslSocket); |
2165 | qint64 readBytes = 0; |
2166 | |
2167 | if (d->mode == UnencryptedMode && !d->autoStartHandshake) { |
2168 | readBytes = d->plainSocket->read(data, maxlen); |
2169 | #ifdef QSSLSOCKET_DEBUG |
2170 | qCDebug(lcSsl) << "QSslSocket::readData(" << (void *)data << ',' << maxlen << ") ==" |
2171 | << readBytes; |
2172 | #endif |
2173 | } else { |
2174 | // possibly trigger another transmit() to decrypt more data from the socket |
2175 | if (d->plainSocket->bytesAvailable() || d->hasUndecryptedData()) |
2176 | QMetaObject::invokeMethod(obj: this, member: "_q_flushReadBuffer" , type: Qt::QueuedConnection); |
2177 | else if (d->state != QAbstractSocket::ConnectedState) |
2178 | return maxlen ? qint64(-1) : qint64(0); |
2179 | } |
2180 | |
2181 | return readBytes; |
2182 | } |
2183 | |
2184 | /*! |
2185 | \reimp |
2186 | */ |
2187 | qint64 QSslSocket::writeData(const char *data, qint64 len) |
2188 | { |
2189 | Q_D(QSslSocket); |
2190 | #ifdef QSSLSOCKET_DEBUG |
2191 | qCDebug(lcSsl) << "QSslSocket::writeData(" << (void *)data << ',' << len << ')'; |
2192 | #endif |
2193 | if (d->mode == UnencryptedMode && !d->autoStartHandshake) |
2194 | return d->plainSocket->write(data, len); |
2195 | |
2196 | d->writeBuffer.append(data, size: len); |
2197 | |
2198 | // make sure we flush to the plain socket's buffer |
2199 | if (!d->flushTriggered) { |
2200 | d->flushTriggered = true; |
2201 | QMetaObject::invokeMethod(obj: this, member: "_q_flushWriteBuffer" , type: Qt::QueuedConnection); |
2202 | } |
2203 | |
2204 | return len; |
2205 | } |
2206 | |
2207 | /*! |
2208 | \internal |
2209 | */ |
2210 | QSslSocketPrivate::QSslSocketPrivate() |
2211 | : initialized(false) |
2212 | , mode(QSslSocket::UnencryptedMode) |
2213 | , autoStartHandshake(false) |
2214 | , connectionEncrypted(false) |
2215 | , shutdown(false) |
2216 | , ignoreAllSslErrors(false) |
2217 | , readyReadEmittedPointer(nullptr) |
2218 | , allowRootCertOnDemandLoading(true) |
2219 | , plainSocket(nullptr) |
2220 | , paused(false) |
2221 | , flushTriggered(false) |
2222 | { |
2223 | QSslConfigurationPrivate::deepCopyDefaultConfiguration(config: &configuration); |
2224 | } |
2225 | |
2226 | /*! |
2227 | \internal |
2228 | */ |
2229 | QSslSocketPrivate::~QSslSocketPrivate() |
2230 | { |
2231 | } |
2232 | |
2233 | /*! |
2234 | \internal |
2235 | */ |
2236 | void QSslSocketPrivate::init() |
2237 | { |
2238 | mode = QSslSocket::UnencryptedMode; |
2239 | autoStartHandshake = false; |
2240 | connectionEncrypted = false; |
2241 | ignoreAllSslErrors = false; |
2242 | shutdown = false; |
2243 | pendingClose = false; |
2244 | flushTriggered = false; |
2245 | ocspResponses.clear(); |
2246 | systemOrSslErrorDetected = false; |
2247 | // we don't want to clear the ignoreErrorsList, so |
2248 | // that it is possible setting it before connecting |
2249 | // ignoreErrorsList.clear(); |
2250 | |
2251 | buffer.clear(); |
2252 | writeBuffer.clear(); |
2253 | configuration.peerCertificate.clear(); |
2254 | configuration.peerCertificateChain.clear(); |
2255 | fetchAuthorityInformation = false; |
2256 | } |
2257 | |
2258 | /*! |
2259 | \internal |
2260 | */ |
2261 | bool QSslSocketPrivate::verifyProtocolSupported(const char *where) |
2262 | { |
2263 | if (configuration.protocol == QSsl::SslV2 || configuration.protocol == QSsl::SslV3) { |
2264 | qCWarning(lcSsl) << where << "Attempted to use an unsupported protocol." ; |
2265 | setErrorAndEmit(errorCode: QAbstractSocket::SslInvalidUserDataError, |
2266 | errorString: QSslSocket::tr(s: "Attempted to use an unsupported protocol." )); |
2267 | return false; |
2268 | } |
2269 | return true; |
2270 | } |
2271 | |
2272 | /*! |
2273 | \internal |
2274 | */ |
2275 | QList<QSslCipher> QSslSocketPrivate::defaultCiphers() |
2276 | { |
2277 | QSslSocketPrivate::ensureInitialized(); |
2278 | QMutexLocker locker(&globalData()->mutex); |
2279 | return globalData()->config->ciphers; |
2280 | } |
2281 | |
2282 | /*! |
2283 | \internal |
2284 | */ |
2285 | QList<QSslCipher> QSslSocketPrivate::supportedCiphers() |
2286 | { |
2287 | QSslSocketPrivate::ensureInitialized(); |
2288 | QMutexLocker locker(&globalData()->mutex); |
2289 | return globalData()->supportedCiphers; |
2290 | } |
2291 | |
2292 | /*! |
2293 | \internal |
2294 | */ |
2295 | void QSslSocketPrivate::setDefaultCiphers(const QList<QSslCipher> &ciphers) |
2296 | { |
2297 | QMutexLocker locker(&globalData()->mutex); |
2298 | globalData()->config.detach(); |
2299 | globalData()->config->ciphers = ciphers; |
2300 | } |
2301 | |
2302 | /*! |
2303 | \internal |
2304 | */ |
2305 | void QSslSocketPrivate::setDefaultSupportedCiphers(const QList<QSslCipher> &ciphers) |
2306 | { |
2307 | QMutexLocker locker(&globalData()->mutex); |
2308 | globalData()->config.detach(); |
2309 | globalData()->supportedCiphers = ciphers; |
2310 | } |
2311 | |
2312 | /*! |
2313 | \internal |
2314 | */ |
2315 | void q_setDefaultDtlsCiphers(const QList<QSslCipher> &ciphers) |
2316 | { |
2317 | QMutexLocker locker(&globalData()->mutex); |
2318 | globalData()->dtlsConfig.detach(); |
2319 | globalData()->dtlsConfig->ciphers = ciphers; |
2320 | } |
2321 | |
2322 | /*! |
2323 | \internal |
2324 | */ |
2325 | QList<QSslCipher> q_getDefaultDtlsCiphers() |
2326 | { |
2327 | QSslSocketPrivate::ensureInitialized(); |
2328 | QMutexLocker locker(&globalData()->mutex); |
2329 | return globalData()->dtlsConfig->ciphers; |
2330 | } |
2331 | |
2332 | /*! |
2333 | \internal |
2334 | */ |
2335 | QVector<QSslEllipticCurve> QSslSocketPrivate::supportedEllipticCurves() |
2336 | { |
2337 | QSslSocketPrivate::ensureInitialized(); |
2338 | const QMutexLocker locker(&globalData()->mutex); |
2339 | return globalData()->supportedEllipticCurves; |
2340 | } |
2341 | |
2342 | /*! |
2343 | \internal |
2344 | */ |
2345 | void QSslSocketPrivate::setDefaultSupportedEllipticCurves(const QVector<QSslEllipticCurve> &curves) |
2346 | { |
2347 | const QMutexLocker locker(&globalData()->mutex); |
2348 | globalData()->config.detach(); |
2349 | globalData()->dtlsConfig.detach(); |
2350 | globalData()->supportedEllipticCurves = curves; |
2351 | } |
2352 | |
2353 | /*! |
2354 | \internal |
2355 | */ |
2356 | QList<QSslCertificate> QSslSocketPrivate::defaultCaCertificates() |
2357 | { |
2358 | QSslSocketPrivate::ensureInitialized(); |
2359 | QMutexLocker locker(&globalData()->mutex); |
2360 | return globalData()->config->caCertificates; |
2361 | } |
2362 | |
2363 | /*! |
2364 | \internal |
2365 | */ |
2366 | void QSslSocketPrivate::setDefaultCaCertificates(const QList<QSslCertificate> &certs) |
2367 | { |
2368 | QSslSocketPrivate::ensureInitialized(); |
2369 | QMutexLocker locker(&globalData()->mutex); |
2370 | globalData()->config.detach(); |
2371 | globalData()->config->caCertificates = certs; |
2372 | globalData()->dtlsConfig.detach(); |
2373 | globalData()->dtlsConfig->caCertificates = certs; |
2374 | // when the certificates are set explicitly, we do not want to |
2375 | // load the system certificates on demand |
2376 | s_loadRootCertsOnDemand = false; |
2377 | } |
2378 | |
2379 | /*! |
2380 | \internal |
2381 | */ |
2382 | bool QSslSocketPrivate::addDefaultCaCertificates(const QString &path, QSsl::EncodingFormat format, |
2383 | QRegExp::PatternSyntax syntax) |
2384 | { |
2385 | QSslSocketPrivate::ensureInitialized(); |
2386 | QT_WARNING_PUSH |
2387 | QT_WARNING_DISABLE_DEPRECATED |
2388 | QList<QSslCertificate> certs = QSslCertificate::fromPath(path, format, syntax); |
2389 | QT_WARNING_POP |
2390 | if (certs.isEmpty()) |
2391 | return false; |
2392 | |
2393 | QMutexLocker locker(&globalData()->mutex); |
2394 | globalData()->config.detach(); |
2395 | globalData()->config->caCertificates += certs; |
2396 | globalData()->dtlsConfig.detach(); |
2397 | globalData()->dtlsConfig->caCertificates += certs; |
2398 | return true; |
2399 | } |
2400 | |
2401 | /*! |
2402 | \internal |
2403 | */ |
2404 | void QSslSocketPrivate::addDefaultCaCertificate(const QSslCertificate &cert) |
2405 | { |
2406 | QSslSocketPrivate::ensureInitialized(); |
2407 | QMutexLocker locker(&globalData()->mutex); |
2408 | if (globalData()->config->caCertificates.contains(t: cert)) |
2409 | return; |
2410 | globalData()->config.detach(); |
2411 | globalData()->config->caCertificates += cert; |
2412 | globalData()->dtlsConfig.detach(); |
2413 | globalData()->dtlsConfig->caCertificates += cert; |
2414 | } |
2415 | |
2416 | /*! |
2417 | \internal |
2418 | */ |
2419 | void QSslSocketPrivate::addDefaultCaCertificates(const QList<QSslCertificate> &certs) |
2420 | { |
2421 | QSslSocketPrivate::ensureInitialized(); |
2422 | QMutexLocker locker(&globalData()->mutex); |
2423 | globalData()->config.detach(); |
2424 | globalData()->config->caCertificates += certs; |
2425 | globalData()->dtlsConfig.detach(); |
2426 | globalData()->dtlsConfig->caCertificates += certs; |
2427 | } |
2428 | |
2429 | /*! |
2430 | \internal |
2431 | */ |
2432 | QSslConfiguration QSslConfigurationPrivate::defaultConfiguration() |
2433 | { |
2434 | QSslSocketPrivate::ensureInitialized(); |
2435 | QMutexLocker locker(&globalData()->mutex); |
2436 | return QSslConfiguration(globalData()->config.data()); |
2437 | } |
2438 | |
2439 | /*! |
2440 | \internal |
2441 | */ |
2442 | void QSslConfigurationPrivate::setDefaultConfiguration(const QSslConfiguration &configuration) |
2443 | { |
2444 | QSslSocketPrivate::ensureInitialized(); |
2445 | QMutexLocker locker(&globalData()->mutex); |
2446 | if (globalData()->config == configuration.d) |
2447 | return; // nothing to do |
2448 | |
2449 | globalData()->config = const_cast<QSslConfigurationPrivate*>(configuration.d.constData()); |
2450 | } |
2451 | |
2452 | /*! |
2453 | \internal |
2454 | */ |
2455 | void QSslConfigurationPrivate::deepCopyDefaultConfiguration(QSslConfigurationPrivate *ptr) |
2456 | { |
2457 | QSslSocketPrivate::ensureInitialized(); |
2458 | QMutexLocker locker(&globalData()->mutex); |
2459 | const QSslConfigurationPrivate *global = globalData()->config.constData(); |
2460 | |
2461 | if (!global) |
2462 | return; |
2463 | |
2464 | ptr->ref.storeRelaxed(newValue: 1); |
2465 | ptr->peerCertificate = global->peerCertificate; |
2466 | ptr->peerCertificateChain = global->peerCertificateChain; |
2467 | ptr->localCertificateChain = global->localCertificateChain; |
2468 | ptr->privateKey = global->privateKey; |
2469 | ptr->sessionCipher = global->sessionCipher; |
2470 | ptr->sessionProtocol = global->sessionProtocol; |
2471 | ptr->ciphers = global->ciphers; |
2472 | ptr->caCertificates = global->caCertificates; |
2473 | ptr->protocol = global->protocol; |
2474 | ptr->peerVerifyMode = global->peerVerifyMode; |
2475 | ptr->peerVerifyDepth = global->peerVerifyDepth; |
2476 | ptr->sslOptions = global->sslOptions; |
2477 | ptr->ellipticCurves = global->ellipticCurves; |
2478 | ptr->backendConfig = global->backendConfig; |
2479 | #if QT_CONFIG(dtls) |
2480 | ptr->dtlsCookieEnabled = global->dtlsCookieEnabled; |
2481 | #endif |
2482 | #if QT_CONFIG(ocsp) |
2483 | ptr->ocspStaplingEnabled = global->ocspStaplingEnabled; |
2484 | #endif |
2485 | } |
2486 | |
2487 | /*! |
2488 | \internal |
2489 | */ |
2490 | QSslConfiguration QSslConfigurationPrivate::defaultDtlsConfiguration() |
2491 | { |
2492 | QSslSocketPrivate::ensureInitialized(); |
2493 | QMutexLocker locker(&globalData()->mutex); |
2494 | |
2495 | return QSslConfiguration(globalData()->dtlsConfig.data()); |
2496 | } |
2497 | |
2498 | /*! |
2499 | \internal |
2500 | */ |
2501 | void QSslConfigurationPrivate::setDefaultDtlsConfiguration(const QSslConfiguration &configuration) |
2502 | { |
2503 | QSslSocketPrivate::ensureInitialized(); |
2504 | QMutexLocker locker(&globalData()->mutex); |
2505 | if (globalData()->dtlsConfig == configuration.d) |
2506 | return; // nothing to do |
2507 | |
2508 | globalData()->dtlsConfig = const_cast<QSslConfigurationPrivate*>(configuration.d.constData()); |
2509 | } |
2510 | |
2511 | /*! |
2512 | \internal |
2513 | */ |
2514 | void QSslSocketPrivate::createPlainSocket(QIODevice::OpenMode openMode) |
2515 | { |
2516 | Q_Q(QSslSocket); |
2517 | q->setOpenMode(openMode); // <- from QIODevice |
2518 | q->setSocketState(QAbstractSocket::UnconnectedState); |
2519 | q->setSocketError(QAbstractSocket::UnknownSocketError); |
2520 | q->setLocalPort(0); |
2521 | q->setLocalAddress(QHostAddress()); |
2522 | q->setPeerPort(0); |
2523 | q->setPeerAddress(QHostAddress()); |
2524 | q->setPeerName(QString()); |
2525 | |
2526 | plainSocket = new QTcpSocket(q); |
2527 | #ifndef QT_NO_BEARERMANAGEMENT // ### Qt6: Remove section |
2528 | //copy network session down to the plain socket (if it has been set) |
2529 | plainSocket->setProperty(name: "_q_networksession" , value: q->property(name: "_q_networksession" )); |
2530 | #endif |
2531 | q->connect(sender: plainSocket, SIGNAL(connected()), |
2532 | receiver: q, SLOT(_q_connectedSlot()), |
2533 | Qt::DirectConnection); |
2534 | q->connect(sender: plainSocket, SIGNAL(hostFound()), |
2535 | receiver: q, SLOT(_q_hostFoundSlot()), |
2536 | Qt::DirectConnection); |
2537 | q->connect(sender: plainSocket, SIGNAL(disconnected()), |
2538 | receiver: q, SLOT(_q_disconnectedSlot()), |
2539 | Qt::DirectConnection); |
2540 | q->connect(sender: plainSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), |
2541 | receiver: q, SLOT(_q_stateChangedSlot(QAbstractSocket::SocketState)), |
2542 | Qt::DirectConnection); |
2543 | q->connect(sender: plainSocket, SIGNAL(errorOccurred(QAbstractSocket::SocketError)), |
2544 | receiver: q, SLOT(_q_errorSlot(QAbstractSocket::SocketError)), |
2545 | Qt::DirectConnection); |
2546 | q->connect(sender: plainSocket, SIGNAL(readyRead()), |
2547 | receiver: q, SLOT(_q_readyReadSlot()), |
2548 | Qt::DirectConnection); |
2549 | q->connect(sender: plainSocket, SIGNAL(channelReadyRead(int)), |
2550 | receiver: q, SLOT(_q_channelReadyReadSlot(int)), |
2551 | Qt::DirectConnection); |
2552 | q->connect(sender: plainSocket, SIGNAL(bytesWritten(qint64)), |
2553 | receiver: q, SLOT(_q_bytesWrittenSlot(qint64)), |
2554 | Qt::DirectConnection); |
2555 | q->connect(sender: plainSocket, SIGNAL(channelBytesWritten(int,qint64)), |
2556 | receiver: q, SLOT(_q_channelBytesWrittenSlot(int,qint64)), |
2557 | Qt::DirectConnection); |
2558 | q->connect(sender: plainSocket, SIGNAL(readChannelFinished()), |
2559 | receiver: q, SLOT(_q_readChannelFinishedSlot()), |
2560 | Qt::DirectConnection); |
2561 | #ifndef QT_NO_NETWORKPROXY |
2562 | q->connect(sender: plainSocket, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
2563 | receiver: q, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
2564 | #endif |
2565 | |
2566 | buffer.clear(); |
2567 | writeBuffer.clear(); |
2568 | connectionEncrypted = false; |
2569 | configuration.peerCertificate.clear(); |
2570 | configuration.peerCertificateChain.clear(); |
2571 | mode = QSslSocket::UnencryptedMode; |
2572 | q->setReadBufferSize(readBufferMaxSize); |
2573 | } |
2574 | |
2575 | void QSslSocketPrivate::pauseSocketNotifiers(QSslSocket *socket) |
2576 | { |
2577 | if (!socket->d_func()->plainSocket) |
2578 | return; |
2579 | QAbstractSocketPrivate::pauseSocketNotifiers(socket->d_func()->plainSocket); |
2580 | } |
2581 | |
2582 | void QSslSocketPrivate::resumeSocketNotifiers(QSslSocket *socket) |
2583 | { |
2584 | if (!socket->d_func()->plainSocket) |
2585 | return; |
2586 | QAbstractSocketPrivate::resumeSocketNotifiers(socket->d_func()->plainSocket); |
2587 | } |
2588 | |
2589 | bool QSslSocketPrivate::isPaused() const |
2590 | { |
2591 | return paused; |
2592 | } |
2593 | |
2594 | bool QSslSocketPrivate::bind(const QHostAddress &address, quint16 port, QAbstractSocket::BindMode mode) |
2595 | { |
2596 | // this function is called from QAbstractSocket::bind |
2597 | if (!initialized) |
2598 | init(); |
2599 | initialized = false; |
2600 | |
2601 | #ifdef QSSLSOCKET_DEBUG |
2602 | qCDebug(lcSsl) << "QSslSocket::bind(" << address << ',' << port << ',' << mode << ')'; |
2603 | #endif |
2604 | if (!plainSocket) { |
2605 | #ifdef QSSLSOCKET_DEBUG |
2606 | qCDebug(lcSsl) << "\tcreating internal plain socket" ; |
2607 | #endif |
2608 | createPlainSocket(openMode: QIODevice::ReadWrite); |
2609 | } |
2610 | bool ret = plainSocket->bind(address, port, mode); |
2611 | localPort = plainSocket->localPort(); |
2612 | localAddress = plainSocket->localAddress(); |
2613 | cachedSocketDescriptor = plainSocket->socketDescriptor(); |
2614 | readChannelCount = writeChannelCount = 0; |
2615 | return ret; |
2616 | } |
2617 | |
2618 | /*! |
2619 | \internal |
2620 | */ |
2621 | void QSslSocketPrivate::_q_connectedSlot() |
2622 | { |
2623 | Q_Q(QSslSocket); |
2624 | q->setLocalPort(plainSocket->localPort()); |
2625 | q->setLocalAddress(plainSocket->localAddress()); |
2626 | q->setPeerPort(plainSocket->peerPort()); |
2627 | q->setPeerAddress(plainSocket->peerAddress()); |
2628 | q->setPeerName(plainSocket->peerName()); |
2629 | cachedSocketDescriptor = plainSocket->socketDescriptor(); |
2630 | readChannelCount = plainSocket->readChannelCount(); |
2631 | writeChannelCount = plainSocket->writeChannelCount(); |
2632 | |
2633 | #ifdef QSSLSOCKET_DEBUG |
2634 | qCDebug(lcSsl) << "QSslSocket::_q_connectedSlot()" ; |
2635 | qCDebug(lcSsl) << "\tstate =" << q->state(); |
2636 | qCDebug(lcSsl) << "\tpeer =" << q->peerName() << q->peerAddress() << q->peerPort(); |
2637 | qCDebug(lcSsl) << "\tlocal =" << QHostInfo::fromName(q->localAddress().toString()).hostName() |
2638 | << q->localAddress() << q->localPort(); |
2639 | #endif |
2640 | |
2641 | if (autoStartHandshake) |
2642 | q->startClientEncryption(); |
2643 | |
2644 | emit q->connected(); |
2645 | |
2646 | if (pendingClose && !autoStartHandshake) { |
2647 | pendingClose = false; |
2648 | q->disconnectFromHost(); |
2649 | } |
2650 | } |
2651 | |
2652 | /*! |
2653 | \internal |
2654 | */ |
2655 | void QSslSocketPrivate::_q_hostFoundSlot() |
2656 | { |
2657 | Q_Q(QSslSocket); |
2658 | #ifdef QSSLSOCKET_DEBUG |
2659 | qCDebug(lcSsl) << "QSslSocket::_q_hostFoundSlot()" ; |
2660 | qCDebug(lcSsl) << "\tstate =" << q->state(); |
2661 | #endif |
2662 | emit q->hostFound(); |
2663 | } |
2664 | |
2665 | /*! |
2666 | \internal |
2667 | */ |
2668 | void QSslSocketPrivate::_q_disconnectedSlot() |
2669 | { |
2670 | Q_Q(QSslSocket); |
2671 | #ifdef QSSLSOCKET_DEBUG |
2672 | qCDebug(lcSsl) << "QSslSocket::_q_disconnectedSlot()" ; |
2673 | qCDebug(lcSsl) << "\tstate =" << q->state(); |
2674 | #endif |
2675 | disconnected(); |
2676 | emit q->disconnected(); |
2677 | |
2678 | q->setLocalPort(0); |
2679 | q->setLocalAddress(QHostAddress()); |
2680 | q->setPeerPort(0); |
2681 | q->setPeerAddress(QHostAddress()); |
2682 | q->setPeerName(QString()); |
2683 | cachedSocketDescriptor = -1; |
2684 | } |
2685 | |
2686 | /*! |
2687 | \internal |
2688 | */ |
2689 | void QSslSocketPrivate::_q_stateChangedSlot(QAbstractSocket::SocketState state) |
2690 | { |
2691 | Q_Q(QSslSocket); |
2692 | #ifdef QSSLSOCKET_DEBUG |
2693 | qCDebug(lcSsl) << "QSslSocket::_q_stateChangedSlot(" << state << ')'; |
2694 | #endif |
2695 | q->setSocketState(state); |
2696 | emit q->stateChanged(state); |
2697 | } |
2698 | |
2699 | /*! |
2700 | \internal |
2701 | */ |
2702 | void QSslSocketPrivate::_q_errorSlot(QAbstractSocket::SocketError error) |
2703 | { |
2704 | Q_UNUSED(error) |
2705 | #ifdef QSSLSOCKET_DEBUG |
2706 | Q_Q(QSslSocket); |
2707 | qCDebug(lcSsl) << "QSslSocket::_q_errorSlot(" << error << ')'; |
2708 | qCDebug(lcSsl) << "\tstate =" << q->state(); |
2709 | qCDebug(lcSsl) << "\terrorString =" << q->errorString(); |
2710 | #endif |
2711 | // this moves encrypted bytes from plain socket into our buffer |
2712 | if (plainSocket->bytesAvailable() && mode != QSslSocket::UnencryptedMode) { |
2713 | qint64 tmpReadBufferMaxSize = readBufferMaxSize; |
2714 | readBufferMaxSize = 0; // reset temporarily so the plain sockets completely drained drained |
2715 | transmit(); |
2716 | readBufferMaxSize = tmpReadBufferMaxSize; |
2717 | } |
2718 | |
2719 | setErrorAndEmit(errorCode: plainSocket->error(), errorString: plainSocket->errorString()); |
2720 | } |
2721 | |
2722 | /*! |
2723 | \internal |
2724 | */ |
2725 | void QSslSocketPrivate::_q_readyReadSlot() |
2726 | { |
2727 | Q_Q(QSslSocket); |
2728 | #ifdef QSSLSOCKET_DEBUG |
2729 | qCDebug(lcSsl) << "QSslSocket::_q_readyReadSlot() -" << plainSocket->bytesAvailable() << "bytes available" ; |
2730 | #endif |
2731 | if (mode == QSslSocket::UnencryptedMode) { |
2732 | if (readyReadEmittedPointer) |
2733 | *readyReadEmittedPointer = true; |
2734 | emit q->readyRead(); |
2735 | return; |
2736 | } |
2737 | |
2738 | transmit(); |
2739 | } |
2740 | |
2741 | /*! |
2742 | \internal |
2743 | */ |
2744 | void QSslSocketPrivate::_q_channelReadyReadSlot(int channel) |
2745 | { |
2746 | Q_Q(QSslSocket); |
2747 | if (mode == QSslSocket::UnencryptedMode) |
2748 | emit q->channelReadyRead(channel); |
2749 | } |
2750 | |
2751 | /*! |
2752 | \internal |
2753 | */ |
2754 | void QSslSocketPrivate::_q_bytesWrittenSlot(qint64 written) |
2755 | { |
2756 | Q_Q(QSslSocket); |
2757 | #ifdef QSSLSOCKET_DEBUG |
2758 | qCDebug(lcSsl) << "QSslSocket::_q_bytesWrittenSlot(" << written << ')'; |
2759 | #endif |
2760 | |
2761 | if (mode == QSslSocket::UnencryptedMode) |
2762 | emit q->bytesWritten(bytes: written); |
2763 | else |
2764 | emit q->encryptedBytesWritten(totalBytes: written); |
2765 | if (state == QAbstractSocket::ClosingState && writeBuffer.isEmpty()) |
2766 | q->disconnectFromHost(); |
2767 | } |
2768 | |
2769 | /*! |
2770 | \internal |
2771 | */ |
2772 | void QSslSocketPrivate::_q_channelBytesWrittenSlot(int channel, qint64 written) |
2773 | { |
2774 | Q_Q(QSslSocket); |
2775 | if (mode == QSslSocket::UnencryptedMode) |
2776 | emit q->channelBytesWritten(channel, bytes: written); |
2777 | } |
2778 | |
2779 | /*! |
2780 | \internal |
2781 | */ |
2782 | void QSslSocketPrivate::_q_readChannelFinishedSlot() |
2783 | { |
2784 | Q_Q(QSslSocket); |
2785 | emit q->readChannelFinished(); |
2786 | } |
2787 | |
2788 | /*! |
2789 | \internal |
2790 | */ |
2791 | void QSslSocketPrivate::_q_flushWriteBuffer() |
2792 | { |
2793 | Q_Q(QSslSocket); |
2794 | |
2795 | // need to notice if knock-on effects of this flush (e.g. a readReady() via transmit()) |
2796 | // make another necessary, so clear flag before calling: |
2797 | flushTriggered = false; |
2798 | if (!writeBuffer.isEmpty()) |
2799 | q->flush(); |
2800 | } |
2801 | |
2802 | /*! |
2803 | \internal |
2804 | */ |
2805 | void QSslSocketPrivate::_q_flushReadBuffer() |
2806 | { |
2807 | // trigger a read from the plainSocket into SSL |
2808 | if (mode != QSslSocket::UnencryptedMode) |
2809 | transmit(); |
2810 | } |
2811 | |
2812 | /*! |
2813 | \internal |
2814 | */ |
2815 | void QSslSocketPrivate::_q_resumeImplementation() |
2816 | { |
2817 | if (plainSocket) |
2818 | plainSocket->resume(); |
2819 | paused = false; |
2820 | if (!connectionEncrypted) { |
2821 | if (verifyErrorsHaveBeenIgnored()) { |
2822 | continueHandshake(); |
2823 | } else { |
2824 | Q_ASSERT(!sslErrors.isEmpty()); |
2825 | setErrorAndEmit(errorCode: QAbstractSocket::SslHandshakeFailedError, errorString: sslErrors.constFirst().errorString()); |
2826 | plainSocket->disconnectFromHost(); |
2827 | return; |
2828 | } |
2829 | } |
2830 | transmit(); |
2831 | } |
2832 | |
2833 | /*! |
2834 | \internal |
2835 | */ |
2836 | bool QSslSocketPrivate::verifyErrorsHaveBeenIgnored() |
2837 | { |
2838 | bool doEmitSslError; |
2839 | if (!ignoreErrorsList.empty()) { |
2840 | // check whether the errors we got are all in the list of expected errors |
2841 | // (applies only if the method QSslSocket::ignoreSslErrors(const QList<QSslError> &errors) |
2842 | // was called) |
2843 | doEmitSslError = false; |
2844 | for (int a = 0; a < sslErrors.count(); a++) { |
2845 | if (!ignoreErrorsList.contains(t: sslErrors.at(i: a))) { |
2846 | doEmitSslError = true; |
2847 | break; |
2848 | } |
2849 | } |
2850 | } else { |
2851 | // if QSslSocket::ignoreSslErrors(const QList<QSslError> &errors) was not called and |
2852 | // we get an SSL error, emit a signal unless we ignored all errors (by calling |
2853 | // QSslSocket::ignoreSslErrors() ) |
2854 | doEmitSslError = !ignoreAllSslErrors; |
2855 | } |
2856 | return !doEmitSslError; |
2857 | } |
2858 | |
2859 | /*! |
2860 | \internal |
2861 | */ |
2862 | qint64 QSslSocketPrivate::peek(char *data, qint64 maxSize) |
2863 | { |
2864 | if (mode == QSslSocket::UnencryptedMode && !autoStartHandshake) { |
2865 | //unencrypted mode - do not use QIODevice::peek, as it reads ahead data from the plain socket |
2866 | //peek at data already in the QIODevice buffer (from a previous read) |
2867 | qint64 r = buffer.peek(data, maxLength: maxSize, pos: transactionPos); |
2868 | if (r == maxSize) |
2869 | return r; |
2870 | data += r; |
2871 | //peek at data in the plain socket |
2872 | if (plainSocket) { |
2873 | qint64 r2 = plainSocket->peek(data, maxlen: maxSize - r); |
2874 | if (r2 < 0) |
2875 | return (r > 0 ? r : r2); |
2876 | return r + r2; |
2877 | } else { |
2878 | return -1; |
2879 | } |
2880 | } else { |
2881 | //encrypted mode - the socket engine will read and decrypt data into the QIODevice buffer |
2882 | return QTcpSocketPrivate::peek(data, maxSize); |
2883 | } |
2884 | } |
2885 | |
2886 | /*! |
2887 | \internal |
2888 | */ |
2889 | QByteArray QSslSocketPrivate::peek(qint64 maxSize) |
2890 | { |
2891 | if (mode == QSslSocket::UnencryptedMode && !autoStartHandshake) { |
2892 | //unencrypted mode - do not use QIODevice::peek, as it reads ahead data from the plain socket |
2893 | //peek at data already in the QIODevice buffer (from a previous read) |
2894 | QByteArray ret; |
2895 | ret.reserve(asize: maxSize); |
2896 | ret.resize(size: buffer.peek(data: ret.data(), maxLength: maxSize, pos: transactionPos)); |
2897 | if (ret.length() == maxSize) |
2898 | return ret; |
2899 | //peek at data in the plain socket |
2900 | if (plainSocket) |
2901 | return ret + plainSocket->peek(maxlen: maxSize - ret.length()); |
2902 | else |
2903 | return QByteArray(); |
2904 | } else { |
2905 | //encrypted mode - the socket engine will read and decrypt data into the QIODevice buffer |
2906 | return QTcpSocketPrivate::peek(maxSize); |
2907 | } |
2908 | } |
2909 | |
2910 | /*! |
2911 | \internal |
2912 | */ |
2913 | qint64 QSslSocketPrivate::skip(qint64 maxSize) |
2914 | { |
2915 | if (mode == QSslSocket::UnencryptedMode && !autoStartHandshake) |
2916 | return plainSocket->skip(maxSize); |
2917 | |
2918 | // In encrypted mode, the SSL backend writes decrypted data directly into the |
2919 | // QIODevice's read buffer. As this buffer is always emptied by the caller, |
2920 | // we need to wait for more incoming data. |
2921 | return (state == QAbstractSocket::ConnectedState) ? Q_INT64_C(0) : Q_INT64_C(-1); |
2922 | } |
2923 | |
2924 | /*! |
2925 | \internal |
2926 | */ |
2927 | bool QSslSocketPrivate::flush() |
2928 | { |
2929 | #ifdef QSSLSOCKET_DEBUG |
2930 | qCDebug(lcSsl) << "QSslSocketPrivate::flush()" ; |
2931 | #endif |
2932 | if (mode != QSslSocket::UnencryptedMode) { |
2933 | // encrypt any unencrypted bytes in our buffer |
2934 | transmit(); |
2935 | } |
2936 | |
2937 | return plainSocket && plainSocket->flush(); |
2938 | } |
2939 | |
2940 | /*! |
2941 | \internal |
2942 | */ |
2943 | bool QSslSocketPrivate::rootCertOnDemandLoadingSupported() |
2944 | { |
2945 | return s_loadRootCertsOnDemand; |
2946 | } |
2947 | |
2948 | /*! |
2949 | \internal |
2950 | */ |
2951 | QList<QByteArray> QSslSocketPrivate::unixRootCertDirectories() |
2952 | { |
2953 | return QList<QByteArray>() << "/etc/ssl/certs/" // (K)ubuntu, OpenSUSE, Mandriva ... |
2954 | << "/usr/lib/ssl/certs/" // Gentoo, Mandrake |
2955 | << "/usr/share/ssl/" // Centos, Redhat, SuSE |
2956 | << "/usr/local/ssl/" // Normal OpenSSL Tarball |
2957 | << "/var/ssl/certs/" // AIX |
2958 | << "/usr/local/ssl/certs/" // Solaris |
2959 | << "/etc/openssl/certs/" // BlackBerry |
2960 | << "/opt/openssl/certs/" // HP-UX |
2961 | << "/etc/ssl/" ; // OpenBSD |
2962 | } |
2963 | |
2964 | /*! |
2965 | \internal |
2966 | */ |
2967 | void QSslSocketPrivate::checkSettingSslContext(QSslSocket* socket, QSharedPointer<QSslContext> sslContext) |
2968 | { |
2969 | if (socket->d_func()->sslContextPointer.isNull()) |
2970 | socket->d_func()->sslContextPointer = sslContext; |
2971 | } |
2972 | |
2973 | /*! |
2974 | \internal |
2975 | */ |
2976 | QSharedPointer<QSslContext> QSslSocketPrivate::sslContext(QSslSocket *socket) |
2977 | { |
2978 | return (socket) ? socket->d_func()->sslContextPointer : QSharedPointer<QSslContext>(); |
2979 | } |
2980 | |
2981 | bool QSslSocketPrivate::isMatchingHostname(const QSslCertificate &cert, const QString &peerName) |
2982 | { |
2983 | QHostAddress hostAddress(peerName); |
2984 | if (!hostAddress.isNull()) { |
2985 | const auto subjectAlternativeNames = cert.subjectAlternativeNames(); |
2986 | const auto ipAddresses = subjectAlternativeNames.equal_range(akey: QSsl::AlternativeNameEntryType::IpAddressEntry); |
2987 | |
2988 | for (auto it = ipAddresses.first; it != ipAddresses.second; it++) { |
2989 | if (QHostAddress(*it).isEqual(address: hostAddress, mode: QHostAddress::StrictConversion)) |
2990 | return true; |
2991 | } |
2992 | } |
2993 | |
2994 | const QString lowerPeerName = QString::fromLatin1(str: QUrl::toAce(peerName)); |
2995 | const QStringList commonNames = cert.subjectInfo(info: QSslCertificate::CommonName); |
2996 | |
2997 | for (const QString &commonName : commonNames) { |
2998 | if (isMatchingHostname(cn: commonName, hostname: lowerPeerName)) |
2999 | return true; |
3000 | } |
3001 | |
3002 | const auto subjectAlternativeNames = cert.subjectAlternativeNames(); |
3003 | const auto altNames = subjectAlternativeNames.equal_range(akey: QSsl::DnsEntry); |
3004 | for (auto it = altNames.first; it != altNames.second; ++it) { |
3005 | if (isMatchingHostname(cn: *it, hostname: lowerPeerName)) |
3006 | return true; |
3007 | } |
3008 | |
3009 | return false; |
3010 | } |
3011 | |
3012 | /*! \internal |
3013 | Checks if the certificate's name \a cn matches the \a hostname. |
3014 | \a hostname must be normalized in ASCII-Compatible Encoding, but \a cn is not normalized |
3015 | */ |
3016 | bool QSslSocketPrivate::isMatchingHostname(const QString &cn, const QString &hostname) |
3017 | { |
3018 | int wildcard = cn.indexOf(c: QLatin1Char('*')); |
3019 | |
3020 | // Check this is a wildcard cert, if not then just compare the strings |
3021 | if (wildcard < 0) |
3022 | return QLatin1String(QUrl::toAce(cn)) == hostname; |
3023 | |
3024 | int firstCnDot = cn.indexOf(c: QLatin1Char('.')); |
3025 | int secondCnDot = cn.indexOf(c: QLatin1Char('.'), from: firstCnDot+1); |
3026 | |
3027 | // Check at least 3 components |
3028 | if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.length())) |
3029 | return false; |
3030 | |
3031 | // Check * is last character of 1st component (ie. there's a following .) |
3032 | if (wildcard+1 != firstCnDot) |
3033 | return false; |
3034 | |
3035 | // Check only one star |
3036 | if (cn.lastIndexOf(c: QLatin1Char('*')) != wildcard) |
3037 | return false; |
3038 | |
3039 | // Reject wildcard character embedded within the A-labels or U-labels of an internationalized |
3040 | // domain name (RFC6125 section 7.2) |
3041 | if (cn.startsWith(s: QLatin1String("xn--" ), cs: Qt::CaseInsensitive)) |
3042 | return false; |
3043 | |
3044 | // Check characters preceding * (if any) match |
3045 | if (wildcard && hostname.leftRef(n: wildcard).compare(s: cn.leftRef(n: wildcard), cs: Qt::CaseInsensitive) != 0) |
3046 | return false; |
3047 | |
3048 | // Check characters following first . match |
3049 | int hnDot = hostname.indexOf(c: QLatin1Char('.')); |
3050 | if (hostname.midRef(position: hnDot + 1) != cn.midRef(position: firstCnDot + 1) |
3051 | && hostname.midRef(position: hnDot + 1) != QLatin1String(QUrl::toAce(cn.mid(position: firstCnDot + 1)))) { |
3052 | return false; |
3053 | } |
3054 | |
3055 | // Check if the hostname is an IP address, if so then wildcards are not allowed |
3056 | QHostAddress addr(hostname); |
3057 | if (!addr.isNull()) |
3058 | return false; |
3059 | |
3060 | // Ok, I guess this was a wildcard CN and the hostname matches. |
3061 | return true; |
3062 | } |
3063 | |
3064 | QT_END_NAMESPACE |
3065 | |
3066 | #include "moc_qsslsocket.cpp" |
3067 | |