Qt 4.8
qabstractsocket.cpp
Go to the documentation of this file.
1 /****************************************************************************
2 **
3 ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41 
42 //#define QABSTRACTSOCKET_DEBUG
43 
402 #include "qabstractsocket.h"
403 #include "qabstractsocket_p.h"
404 
405 #include "private/qhostinfo_p.h"
406 #include "private/qnetworksession_p.h"
407 
409 #include <qhostaddress.h>
410 #include <qhostinfo.h>
411 #include <qmetaobject.h>
412 #include <qpointer.h>
413 #include <qtimer.h>
414 #include <qelapsedtimer.h>
415 #include <qscopedvaluerollback.h>
416 
417 #ifndef QT_NO_OPENSSL
418 #include <QtNetwork/qsslsocket.h>
419 #endif
420 
421 #include <private/qthread_p.h>
422 
423 #ifdef QABSTRACTSOCKET_DEBUG
424 #include <qdebug.h>
425 #endif
426 
427 #include <time.h>
428 
429 #define Q_CHECK_SOCKETENGINE(returnValue) do { \
430  if (!d->socketEngine) { \
431  return returnValue; \
432  } } while (0)
433 
434 #ifndef QABSTRACTSOCKET_BUFFERSIZE
435 #define QABSTRACTSOCKET_BUFFERSIZE 32768
436 #endif
437 #define QT_CONNECT_TIMEOUT 30000
438 #define QT_TRANSFER_TIMEOUT 120000
439 
441 
442 #if defined QABSTRACTSOCKET_DEBUG
444 #include <qstring.h>
445 #include <ctype.h>
447 
448 /*
449  Returns a human readable representation of the first \a len
450  characters in \a data.
451 */
452 static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
453 {
454  if (!data) return "(null)";
455  QByteArray out;
456  for (int i = 0; i < len; ++i) {
457  char c = data[i];
458  if (isprint(int(uchar(c)))) {
459  out += c;
460  } else switch (c) {
461  case '\n': out += "\\n"; break;
462  case '\r': out += "\\r"; break;
463  case '\t': out += "\\t"; break;
464  default:
465  QString tmp;
466  tmp.sprintf("\\%o", c);
467  out += tmp.toLatin1();
468  }
469  }
470 
471  if (len < maxLength)
472  out += "...";
473 
474  return out;
475 }
476 #endif
477 
479 {
480  switch (error) {
487  return true;
488  default:
489  return false;
490  }
491 }
492 
501  : readSocketNotifierCalled(false),
502  readSocketNotifierState(false),
503  readSocketNotifierStateSet(false),
504  emittedReadyRead(false),
505  emittedBytesWritten(false),
506  abortCalled(false),
507  closeCalled(false),
508  pendingClose(false),
509  port(0),
510  localPort(0),
511  peerPort(0),
512  socketEngine(0),
513  cachedSocketDescriptor(-1),
514  readBufferMaxSize(0),
515  readBuffer(QABSTRACTSOCKET_BUFFERSIZE),
516  writeBuffer(QABSTRACTSOCKET_BUFFERSIZE),
517  isBuffered(false),
518  blockingTimeout(30000),
519  connectTimer(0),
520  disconnectTimer(0),
521  connectTimeElapsed(0),
522  hostLookupId(-1),
523  socketType(QAbstractSocket::UnknownSocketType),
524  state(QAbstractSocket::UnconnectedState),
525  socketError(QAbstractSocket::UnknownSocketError)
526 {
527 }
528 
538 {
539 }
540 
550 {
551 #if defined (QABSTRACTSOCKET_DEBUG)
552  qDebug("QAbstractSocketPrivate::resetSocketLayer()");
553 #endif
554 
555  if (socketEngine) {
556  socketEngine->close();
558  delete socketEngine;
559  socketEngine = 0;
561  }
562  if (connectTimer)
563  connectTimer->stop();
564  if (disconnectTimer)
566 }
567 
578 {
579 #ifdef QT_NO_NETWORKPROXY
580  // this is here to avoid a duplication of the call to createSocketEngine below
581  static const QNetworkProxy &proxyInUse = *(QNetworkProxy *)0;
582 #endif
583 
585 #if defined (QABSTRACTSOCKET_DEBUG)
586  QString typeStr;
587  if (q->socketType() == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
588  else if (q->socketType() == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
589  else typeStr = QLatin1String("UnknownSocketType");
590  QString protocolStr;
591  if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
592  else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
593  else protocolStr = QLatin1String("UnknownNetworkLayerProtocol");
594 #endif
595 
598  if (!socketEngine) {
600  q->setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
601  return false;
602  }
603 #ifndef QT_NO_BEARERMANAGEMENT
604  //copy network session down to the socket engine (if it has been set)
605  socketEngine->setProperty("_q_networksession", q->property("_q_networksession"));
606 #endif
607 #ifndef QT_NO_NETWORKPROXY
608  //copy user agent to socket engine (if it has been set)
609  socketEngine->setProperty("_q_user-agent", q->property("_q_user-agent"));
610 #endif
611  if (!socketEngine->initialize(q->socketType(), protocol)) {
612 #if defined (QABSTRACTSOCKET_DEBUG)
613  qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) failed (%s)",
614  typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(),
616 #endif
618  q->setErrorString(socketEngine->errorString());
619  return false;
620  }
621 
623  socketEngine->setReceiver(this);
624 
625 #if defined (QABSTRACTSOCKET_DEBUG)
626  qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) success",
627  typeStr.toLatin1().constData(), protocolStr.toLatin1().constData());
628 #endif
629  return true;
630 }
631 
642 {
644 #if defined (QABSTRACTSOCKET_DEBUG)
645  qDebug("QAbstractSocketPrivate::canReadNotification()");
646 #endif
647 
648  // Prevent recursive calls
654  }
655  }
658 
659  if (!isBuffered)
661 
662  // If buffered, read data from the socket into the read buffer
663  qint64 newBytes = 0;
664  if (isBuffered) {
665  // Return if there is no space in the buffer
667 #if defined (QABSTRACTSOCKET_DEBUG)
668  qDebug("QAbstractSocketPrivate::canReadNotification() buffer is full");
669 #endif
670  return false;
671  }
672 
673  // If reading from the socket fails after getting a read
674  // notification, close the socket.
675  newBytes = readBuffer.size();
676  if (!readFromSocket()) {
677 #if defined (QABSTRACTSOCKET_DEBUG)
678  qDebug("QAbstractSocketPrivate::canReadNotification() disconnecting socket");
679 #endif
680  q->disconnectFromHost();
681  return false;
682  }
683  newBytes = readBuffer.size() - newBytes;
684 
685  // If read buffer is full, disable the read socket notifier.
688  }
689  }
690 
691  // only emit readyRead() when not recursing, and only if there is data available
692  bool hasData = newBytes > 0
693 #ifndef QT_NO_UDPSOCKET
695 #endif
697  ;
698 
699  if (!emittedReadyRead && hasData) {
701  emittedReadyRead = true;
702  emit q->readyRead();
703  }
704 
705  // If we were closed as a result of the readyRead() signal,
706  // return.
708 #if defined (QABSTRACTSOCKET_DEBUG)
709  qDebug("QAbstractSocketPrivate::canReadNotification() socket is closing - returning");
710 #endif
711  return true;
712  }
713 
714  if (!hasData && socketEngine)
716 
717  // reset the read socket notifier state if we reentered inside the
718  // readyRead() connected slot.
723  }
724  return true;
725 }
726 
736 {
737 #if defined (Q_OS_WIN)
740 #endif
741 
742 #if defined (QABSTRACTSOCKET_DEBUG)
743  qDebug("QAbstractSocketPrivate::canWriteNotification() flushing");
744 #endif
745  int tmp = writeBuffer.size();
746  flush();
747 
748  if (socketEngine) {
749 #if defined (Q_OS_WIN)
750  if (!writeBuffer.isEmpty())
752 #else
753  if (writeBuffer.isEmpty() && socketEngine->bytesToWrite() == 0)
755 #endif
756  }
757 
758  return (writeBuffer.size() < tmp);
759 }
760 
770 {
771  // If in connecting state, check if the connection has been
772  // established, otherwise flush pending data.
774 #if defined (QABSTRACTSOCKET_DEBUG)
775  qDebug("QAbstractSocketPrivate::connectionNotification() testing connection");
776 #endif
778  }
779 }
780 
795 {
798  && socketEngine->bytesToWrite() == 0)) {
799 #if defined (QABSTRACTSOCKET_DEBUG)
800  qDebug("QAbstractSocketPrivate::flush() nothing to do: valid ? %s, writeBuffer.isEmpty() ? %s",
801  socketEngine->isValid() ? "yes" : "no", writeBuffer.isEmpty() ? "yes" : "no");
802 #endif
803 
804  // this covers the case when the buffer was empty, but we had to wait for the socket engine to finish
806  q->disconnectFromHost();
807 
808  return false;
809  }
810 
811  int nextSize = writeBuffer.nextDataBlockSize();
812  const char *ptr = writeBuffer.readPointer();
813 
814  // Attempt to write it all in one chunk.
815  qint64 written = socketEngine->write(ptr, nextSize);
816  if (written < 0) {
818  q->setErrorString(socketEngine->errorString());
819 #if defined (QABSTRACTSOCKET_DEBUG)
820  qDebug() << "QAbstractSocketPrivate::flush() write error, aborting." << socketEngine->errorString();
821 #endif
822  emit q->error(socketError);
823  // an unexpected error so close the socket.
824  q->abort();
825  return false;
826  }
827 
828 #if defined (QABSTRACTSOCKET_DEBUG)
829  qDebug("QAbstractSocketPrivate::flush() %lld bytes written to the network",
830  written);
831 #endif
832 
833  // Remove what we wrote so far.
834  writeBuffer.free(written);
835  if (written > 0) {
836  // Don't emit bytesWritten() recursively.
837  if (!emittedBytesWritten) {
839  emittedBytesWritten = true;
840  emit q->bytesWritten(written);
841  }
842  }
843 
845  && !socketEngine->bytesToWrite())
848  q->disconnectFromHost();
849 
850  return true;
851 }
852 
853 #ifndef QT_NO_NETWORKPROXY
854 
862 {
863  QList<QNetworkProxy> proxies;
864 
866  // a non-default proxy was set with setProxy
867  proxies << proxy;
868  } else {
869  // try the application settings instead
870  QNetworkProxyQuery query(hostname, port, QString(),
874  proxies = QNetworkProxyFactory::proxyForQuery(query);
875  }
876 
877  // return the first that we can use
878  foreach (const QNetworkProxy &p, proxies) {
881  continue;
882 
885  continue;
886 
887  proxyInUse = p;
888  return;
889  }
890 
891  // no proxy found
892  // DefaultProxy here will raise an error
894 }
895 
906 {
909  return;
910 
911 #if defined(QABSTRACTSOCKET_DEBUG)
912  qDebug("QAbstractSocketPrivate::startConnectingByName(host == %s)", qPrintable(host));
913 #endif
914 
915  // ### Let the socket engine drive this?
917  emit q->stateChanged(state);
918 
919  connectTimeElapsed = 0;
920 
922  if (socketEngine->connectToHostByName(host, port) ||
925 
926  return;
927  }
928 
929  // failed to connect
931  q->setErrorString(socketEngine->errorString());
932  }
933 
935  emit q->error(socketError);
936  emit q->stateChanged(state);
937 }
938 
939 #endif
940 
952 {
955  return;
956 
957  if (hostLookupId != -1 && hostLookupId != hostInfo.lookupId()) {
958  qWarning("QAbstractSocketPrivate::_q_startConnecting() received hostInfo for wrong lookup ID %d expected %d", hostInfo.lookupId(), hostLookupId);
959  }
960 
961  addresses = hostInfo.addresses();
962 
963 #if defined(QABSTRACTSOCKET_DEBUG)
964  QString s = QLatin1String("{");
965  for (int i = 0; i < addresses.count(); ++i) {
966  if (i != 0) s += QLatin1String(", ");
967  s += addresses.at(i).toString();
968  }
969  s += QLatin1Char('}');
970  qDebug("QAbstractSocketPrivate::_q_startConnecting(hostInfo == %s)", s.toLatin1().constData());
971 #endif
972 
973  // Try all addresses twice.
974  addresses += addresses;
975 
976  // If there are no addresses in the host list, report this to the
977  // user.
978  if (addresses.isEmpty()) {
979 #if defined(QABSTRACTSOCKET_DEBUG)
980  qDebug("QAbstractSocketPrivate::_q_startConnecting(), host not found");
981 #endif
984  q->setErrorString(QAbstractSocket::tr("Host not found"));
985  emit q->stateChanged(state);
987  return;
988  }
989 
990  // Enter Connecting state (see also sn_write, which is called by
991  // the write socket notifier after connect())
993  emit q->stateChanged(state);
994 
995  // Report the successful host lookup
996  emit q->hostFound();
997 
998  // Reset the total time spent connecting.
999  connectTimeElapsed = 0;
1000 
1001  // The addresses returned by the lookup will be tested one after
1002  // another by _q_connectToNextAddress().
1004 }
1005 
1019 {
1021  do {
1022  // Check for more pending addresses
1023  if (addresses.isEmpty()) {
1024 #if defined(QABSTRACTSOCKET_DEBUG)
1025  qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), all addresses failed.");
1026 #endif
1028  if (socketEngine) {
1030 #ifdef Q_OS_AIX
1031  // On AIX, the second connect call will result in EINVAL and not
1032  // ECONNECTIONREFUSED; although the meaning is the same.
1034 #endif
1037  q->setErrorString(QAbstractSocket::tr("Connection refused"));
1038  } else {
1040  q->setErrorString(socketEngine->errorString());
1041  }
1042  } else {
1043 // socketError = QAbstractSocket::ConnectionRefusedError;
1044 // q->setErrorString(QAbstractSocket::tr("Connection refused"));
1045  }
1046  emit q->stateChanged(state);
1047  emit q->error(socketError);
1048  return;
1049  }
1050 
1051  // Pick the first host address candidate
1052  host = addresses.takeFirst();
1053 #if defined(QABSTRACTSOCKET_DEBUG)
1054  qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connecting to %s:%i, %d left to try",
1056 #endif
1057 
1058 #if defined(QT_NO_IPV6)
1060  // If we have no IPv6 support, then we will not be able to
1061  // connect. So we just pretend we didn't see this address.
1062 #if defined(QABSTRACTSOCKET_DEBUG)
1063  qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), skipping IPv6 entry");
1064 #endif
1065  continue;
1066  }
1067 #endif
1068 
1069  if (!initSocketLayer(host.protocol())) {
1070  // hope that the next address is better
1071 #if defined(QABSTRACTSOCKET_DEBUG)
1072  qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), failed to initialize sock layer");
1073 #endif
1074  continue;
1075  }
1076 
1077  // Tries to connect to the address. If it succeeds immediately
1078  // (localhost address on BSD or any UDP connect), emit
1079  // connected() and return.
1081  //_q_testConnection();
1083  return;
1084  }
1085 
1086  // cache the socket descriptor even if we're not fully connected yet
1088 
1089  // Check that we're in delayed connection state. If not, try
1090  // the next address
1092 #if defined(QABSTRACTSOCKET_DEBUG)
1093  qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connection failed (%s)",
1095 #endif
1096  continue;
1097  }
1098 
1099  // Start the connect timer.
1100  if (threadData->eventDispatcher) {
1101  if (!connectTimer) {
1102  connectTimer = new QTimer(q);
1103  QObject::connect(connectTimer, SIGNAL(timeout()),
1106  }
1108  }
1109 
1110  // Wait for a write notification that will eventually call
1111  // _q_testConnection().
1113  break;
1115 }
1116 
1126 {
1127  if (socketEngine) {
1128  if (threadData->eventDispatcher) {
1129  if (connectTimer)
1130  connectTimer->stop();
1131  }
1132 
1134  // Fetch the parameters if our connection is completed;
1135  // otherwise, fall out and try the next address.
1137  if (pendingClose) {
1138  q_func()->disconnectFromHost();
1139  pendingClose = false;
1140  }
1141  return;
1142  }
1143 
1144  // don't retry the other addresses if we had a proxy error
1146  addresses.clear();
1147  }
1148 
1149  if (threadData->eventDispatcher) {
1150  if (connectTimer)
1151  connectTimer->stop();
1152  }
1153 
1154 #if defined(QABSTRACTSOCKET_DEBUG)
1155  qDebug("QAbstractSocketPrivate::_q_testConnection() connection failed,"
1156  " checking for alternative addresses");
1157 #endif
1159 }
1160 
1172 {
1174 #if defined(QABSTRACTSOCKET_DEBUG)
1175  qDebug("QAbstractSocketPrivate::_q_abortConnectionAttempt() (timed out)");
1176 #endif
1177  if (socketEngine)
1179 
1180  connectTimer->stop();
1181 
1182  if (addresses.isEmpty()) {
1185  q->setErrorString(QAbstractSocket::tr("Connection timed out"));
1186  emit q->stateChanged(state);
1187  emit q->error(socketError);
1188  } else {
1190  }
1191 }
1192 
1194 {
1197  socketEngine->close();
1198  q->disconnectFromHost();
1199  }
1200 }
1201 
1211 {
1213  // Find how many bytes we can read from the socket layer.
1214  qint64 bytesToRead = socketEngine->bytesAvailable();
1215  if (bytesToRead == 0) {
1216  // Under heavy load, certain conditions can trigger read notifications
1217  // for socket notifiers on which there is no activity. If we continue
1218  // to read 0 bytes from the socket, we will trigger behavior similar
1219  // to that which signals a remote close. When we hit this condition,
1220  // we try to read 4k of data from the socket, which will give us either
1221  // an EAGAIN/EWOULDBLOCK if the connection is alive (i.e., the remote
1222  // host has _not_ disappeared).
1223  bytesToRead = 4096;
1224  }
1225  if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - readBuffer.size()))
1226  bytesToRead = readBufferMaxSize - readBuffer.size();
1227 
1228 #if defined(QABSTRACTSOCKET_DEBUG)
1229  qDebug("QAbstractSocketPrivate::readFromSocket() about to read %d bytes",
1230  int(bytesToRead));
1231 #endif
1232 
1233  // Read from the socket, store data in the read buffer.
1234  char *ptr = readBuffer.reserve(bytesToRead);
1235  qint64 readBytes = socketEngine->read(ptr, bytesToRead);
1236  if (readBytes == -2) {
1237  // No bytes currently available for reading.
1238  readBuffer.chop(bytesToRead);
1239  return true;
1240  }
1241  readBuffer.chop(int(bytesToRead - (readBytes < 0 ? qint64(0) : readBytes)));
1242 #if defined(QABSTRACTSOCKET_DEBUG)
1243  qDebug("QAbstractSocketPrivate::readFromSocket() got %d bytes, buffer size = %d",
1244  int(readBytes), readBuffer.size());
1245 #endif
1246 
1247  if (!socketEngine->isValid()) {
1249  q->setErrorString(socketEngine->errorString());
1250  emit q->error(socketError);
1251 #if defined(QABSTRACTSOCKET_DEBUG)
1252  qDebug("QAbstractSocketPrivate::readFromSocket() read failed: %s",
1253  q->errorString().toLatin1().constData());
1254 #endif
1255  resetSocketLayer();
1256  return false;
1257  }
1258 
1259  return true;
1260 }
1261 
1270 {
1272 
1273  peerName = hostName;
1274  if (socketEngine) {
1282  }
1283 
1285  emit q->stateChanged(state);
1286  emit q->connected();
1287 
1288 #if defined(QABSTRACTSOCKET_DEBUG)
1289  qDebug("QAbstractSocketPrivate::fetchConnectionParameters() connection to %s:%i established",
1291 #endif
1292 }
1293 
1294 
1296 {
1297  QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
1298  if (!socketEngine)
1299  return;
1300  socket->d_func()->prePauseReadSocketNotifierState = socketEngine->isReadNotificationEnabled();
1301  socket->d_func()->prePauseWriteSocketNotifierState = socketEngine->isWriteNotificationEnabled();
1302  socket->d_func()->prePauseExceptionSocketNotifierState = socketEngine->isExceptionNotificationEnabled();
1303  socketEngine->setReadNotificationEnabled(false);
1304  socketEngine->setWriteNotificationEnabled(false);
1305  socketEngine->setExceptionNotificationEnabled(false);
1306 }
1307 
1309 {
1310  QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
1311  if (!socketEngine)
1312  return;
1313  socketEngine->setReadNotificationEnabled(socket->d_func()->prePauseReadSocketNotifierState);
1314  socketEngine->setWriteNotificationEnabled(socket->d_func()->prePauseWriteSocketNotifierState);
1315  socketEngine->setExceptionNotificationEnabled(socket->d_func()->prePauseExceptionSocketNotifierState);
1316 }
1317 
1319 {
1320  return socket->d_func()->socketEngine;
1321 }
1322 
1323 
1334  : QIODevice(dd, parent)
1335 {
1337 #if defined(QABSTRACTSOCKET_DEBUG)
1338  qDebug("QAbstractSocket::QAbstractSocket(%sSocket, QAbstractSocketPrivate == %p, parent == %p)",
1339  socketType == TcpSocket ? "Tcp" : socketType == UdpSocket
1340  ? "Udp" : "Unknown", &dd, parent);
1341 #endif
1342  d->socketType = socketType;
1343 }
1344 
1352  : QIODevice(*new QAbstractSocketPrivate, parent)
1353 {
1355 #if defined(QABSTRACTSOCKET_DEBUG)
1356  qDebug("QAbstractSocket::QAbstractSocket(%p)", parent);
1357 #endif
1358  d->socketType = socketType;
1359 }
1360 
1365 {
1367 #if defined(QABSTRACTSOCKET_DEBUG)
1368  qDebug("QAbstractSocket::~QAbstractSocket()");
1369 #endif
1370  if (d->state != UnconnectedState)
1371  abort();
1372 }
1373 
1384 {
1385  return d_func()->socketEngine ? d_func()->socketEngine->isValid() : isOpen();
1386 }
1387 
1410  OpenMode openMode)
1411 {
1412  QMetaObject::invokeMethod(this, "connectToHostImplementation",
1414  Q_ARG(QString, hostName),
1415  Q_ARG(quint16, port),
1416  Q_ARG(OpenMode, openMode));
1417 }
1418 
1431  OpenMode openMode)
1432 {
1434 #if defined(QABSTRACTSOCKET_DEBUG)
1435  qDebug("QAbstractSocket::connectToHost(\"%s\", %i, %i)...", qPrintable(hostName), port,
1436  (int) openMode);
1437 #endif
1438 
1439  if (d->state == ConnectedState || d->state == ConnectingState
1440  || d->state == ClosingState || d->state == HostLookupState) {
1441  qWarning("QAbstractSocket::connectToHost() called when already looking up or connecting/connected to \"%s\"", qPrintable(hostName));
1442  return;
1443  }
1444 
1445  d->hostName = hostName;
1446  d->port = port;
1447  d->state = UnconnectedState;
1448  d->readBuffer.clear();
1449  d->writeBuffer.clear();
1450  d->abortCalled = false;
1451  d->closeCalled = false;
1452  d->pendingClose = false;
1453  d->localPort = 0;
1454  d->peerPort = 0;
1455  d->localAddress.clear();
1456  d->peerAddress.clear();
1457  d->peerName = hostName;
1458  if (d->hostLookupId != -1) {
1459  QHostInfo::abortHostLookup(d->hostLookupId);
1460  d->hostLookupId = -1;
1461  }
1462 
1463 #ifndef QT_NO_NETWORKPROXY
1464  // Get the proxy information
1465  d->resolveProxy(hostName, port);
1466  if (d->proxyInUse.type() == QNetworkProxy::DefaultProxy) {
1467  // failed to setup the proxy
1469  setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
1470  emit error(d->socketError);
1471  return;
1472  }
1473 #endif
1474 
1475  if (openMode & QIODevice::Unbuffered)
1476  d->isBuffered = false; // Unbuffered QTcpSocket
1477  else if (!d_func()->isBuffered)
1478  openMode |= QAbstractSocket::Unbuffered; // QUdpSocket
1479 
1480  QIODevice::open(openMode);
1481  d->state = HostLookupState;
1482  emit stateChanged(d->state);
1483 
1484  QHostAddress temp;
1485  if (temp.setAddress(hostName)) {
1486  QHostInfo info;
1487  info.setAddresses(QList<QHostAddress>() << temp);
1488  d->_q_startConnecting(info);
1489 #ifndef QT_NO_NETWORKPROXY
1490  } else if (d->proxyInUse.capabilities() & QNetworkProxy::HostNameLookupCapability) {
1491  // the proxy supports connection by name, so use it
1492  d->startConnectingByName(hostName);
1493  return;
1494 #endif
1495  } else {
1496  if (d->threadData->eventDispatcher) {
1497  // this internal API for QHostInfo either immediately gives us the desired
1498  // QHostInfo from cache or later calls the _q_startConnecting slot.
1499  bool immediateResultValid = false;
1500  QHostInfo hostInfo = qt_qhostinfo_lookup(hostName,
1501  this,
1502  SLOT(_q_startConnecting(QHostInfo)),
1503  &immediateResultValid,
1504  &d->hostLookupId);
1505  if (immediateResultValid) {
1506  d->hostLookupId = -1;
1507  d->_q_startConnecting(hostInfo);
1508  }
1509  }
1510  }
1511 
1512 #if defined(QABSTRACTSOCKET_DEBUG)
1513  qDebug("QAbstractSocket::connectToHost(\"%s\", %i) == %s%s", hostName.toLatin1().constData(), port,
1514  (d->state == ConnectedState) ? "true" : "false",
1515  (d->state == ConnectingState || d->state == HostLookupState)
1516  ? " (connection in progress)" : "");
1517 #endif
1518 }
1519 
1528  OpenMode openMode)
1529 {
1530 #if defined(QABSTRACTSOCKET_DEBUG)
1531  qDebug("QAbstractSocket::connectToHost([%s], %i, %i)...",
1532  address.toString().toLatin1().constData(), port, (int) openMode);
1533 #endif
1534  connectToHost(address.toString(), port, openMode);
1535 }
1536 
1545 {
1546  Q_D(const QAbstractSocket);
1547 #if defined(QABSTRACTSOCKET_DEBUG)
1548  qDebug("QAbstractSocket::bytesToWrite() == %i", d->writeBuffer.size());
1549 #endif
1550  return (qint64)d->writeBuffer.size();
1551 }
1552 
1559 {
1560  Q_D(const QAbstractSocket);
1561  qint64 available = QIODevice::bytesAvailable();
1562 
1563  available += (qint64) d->readBuffer.size();
1564 
1565  if (!d->isBuffered && d->socketEngine && d->socketEngine->isValid())
1566  available += d->socketEngine->bytesAvailable();
1567 
1568 #if defined(QABSTRACTSOCKET_DEBUG)
1569  qDebug("QAbstractSocket::bytesAvailable() == %llu", available);
1570 #endif
1571  return available;
1572 }
1573 
1581 {
1582  Q_D(const QAbstractSocket);
1583  return d->localPort;
1584 }
1585 
1597 {
1598  Q_D(const QAbstractSocket);
1599  return d->localAddress;
1600 }
1601 
1609 {
1610  Q_D(const QAbstractSocket);
1611  return d->peerPort;
1612 }
1613 
1621 {
1622  Q_D(const QAbstractSocket);
1623  return d->peerAddress;
1624 }
1625 
1633 {
1634  Q_D(const QAbstractSocket);
1635  return d->peerName.isEmpty() ? d->hostName : d->peerName;
1636 }
1637 
1645 {
1646  bool hasLine = d_func()->readBuffer.canReadLine();
1647 #if defined (QABSTRACTSOCKET_DEBUG)
1648  qDebug("QAbstractSocket::canReadLine() == %s, buffer size = %d, size = %d", hasLine ? "true" : "false",
1649  d_func()->readBuffer.size(), d_func()->buffer.size());
1650 #endif
1651  return hasLine || QIODevice::canReadLine();
1652 }
1653 
1667 {
1668  Q_D(const QAbstractSocket);
1669  return d->cachedSocketDescriptor;
1670 }
1671 
1685  OpenMode openMode)
1686 {
1688 #ifndef QT_NO_OPENSSL
1689  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
1690  return socket->setSocketDescriptor(socketDescriptor, socketState, openMode);
1691 #endif
1692 
1693  d->resetSocketLayer();
1694  d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, this);
1695  if (!d->socketEngine) {
1696  d->socketError = UnsupportedSocketOperationError;
1697  setErrorString(tr("Operation on socket is not supported"));
1698  return false;
1699  }
1700 #ifndef QT_NO_BEARERMANAGEMENT
1701  //copy network session down to the socket engine (if it has been set)
1702  d->socketEngine->setProperty("_q_networksession", property("_q_networksession"));
1703 #endif
1704  bool result = d->socketEngine->initialize(socketDescriptor, socketState);
1705  if (!result) {
1706  d->socketError = d->socketEngine->error();
1707  setErrorString(d->socketEngine->errorString());
1708  return false;
1709  }
1710 
1711  if (d->threadData->eventDispatcher)
1712  d->socketEngine->setReceiver(d);
1713 
1714  QIODevice::open(openMode);
1715 
1716  if (d->state != socketState) {
1717  d->state = socketState;
1718  emit stateChanged(d->state);
1719  }
1720 
1721  d->pendingClose = false;
1722  d->socketEngine->setReadNotificationEnabled(true);
1723  d->localPort = d->socketEngine->localPort();
1724  d->peerPort = d->socketEngine->peerPort();
1725  d->localAddress = d->socketEngine->localAddress();
1726  d->peerAddress = d->socketEngine->peerAddress();
1727  d->cachedSocketDescriptor = socketDescriptor;
1728 
1729  return true;
1730 }
1731 
1742 {
1743 #ifndef QT_NO_OPENSSL
1744  if (QSslSocket *sslSocket = qobject_cast<QSslSocket*>(this)) {
1745  sslSocket->setSocketOption(option, value);
1746  return;
1747  }
1748 #endif
1749 
1750  if (!d_func()->socketEngine)
1751  return;
1752 
1753  switch (option) {
1754  case LowDelayOption:
1755  d_func()->socketEngine->setOption(QAbstractSocketEngine::LowDelayOption, value.toInt());
1756  break;
1757 
1758  case KeepAliveOption:
1759  d_func()->socketEngine->setOption(QAbstractSocketEngine::KeepAliveOption, value.toInt());
1760  break;
1761 
1762  case MulticastTtlOption:
1763  d_func()->socketEngine->setOption(QAbstractSocketEngine::MulticastTtlOption, value.toInt());
1764  break;
1765 
1767  d_func()->socketEngine->setOption(QAbstractSocketEngine::MulticastLoopbackOption, value.toInt());
1768  break;
1769  }
1770 }
1771 
1782 {
1783 #ifndef QT_NO_OPENSSL
1784  if (QSslSocket *sslSocket = qobject_cast<QSslSocket*>(this)) {
1785  return sslSocket->socketOption(option);
1786  }
1787 #endif
1788 
1789  if (!d_func()->socketEngine)
1790  return QVariant();
1791 
1792  int ret = -1;
1793  switch (option) {
1794  case LowDelayOption:
1795  ret = d_func()->socketEngine->option(QAbstractSocketEngine::LowDelayOption);
1796  break;
1797 
1798  case KeepAliveOption:
1799  ret = d_func()->socketEngine->option(QAbstractSocketEngine::KeepAliveOption);
1800  break;
1801 
1802  case MulticastTtlOption:
1803  ret = d_func()->socketEngine->option(QAbstractSocketEngine::MulticastTtlOption);
1804  break;
1806  ret = d_func()->socketEngine->option(QAbstractSocketEngine::MulticastLoopbackOption);
1807  break;
1808  }
1809  if (ret == -1)
1810  return QVariant();
1811  else
1812  return QVariant(ret);
1813 }
1814 
1815 
1816 /*
1817  Returns the difference between msecs and elapsed. If msecs is -1,
1818  however, -1 is returned.
1819 */
1820 static int qt_timeout_value(int msecs, int elapsed)
1821 {
1822  if (msecs == -1)
1823  return -1;
1824 
1825  int timeout = msecs - elapsed;
1826  return timeout < 0 ? 0 : timeout;
1827 }
1828 
1852 {
1854 #if defined (QABSTRACTSOCKET_DEBUG)
1855  qDebug("QAbstractSocket::waitForConnected(%i)", msecs);
1856 #endif
1857 
1858  if (state() == ConnectedState) {
1859 #if defined (QABSTRACTSOCKET_DEBUG)
1860  qDebug("QAbstractSocket::waitForConnected(%i) already connected", msecs);
1861 #endif
1862  return true;
1863  }
1864 
1865 #ifndef QT_NO_OPENSSL
1866  // Manual polymorphism; this function is not virtual, but has an overload
1867  // in QSslSocket.
1868  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
1869  return socket->waitForConnected(msecs);
1870 #endif
1871 
1872  bool wasPendingClose = d->pendingClose;
1873  d->pendingClose = false;
1874  QElapsedTimer stopWatch;
1875  stopWatch.start();
1876 
1877  if (d->state == HostLookupState) {
1878 #if defined (QABSTRACTSOCKET_DEBUG)
1879  qDebug("QAbstractSocket::waitForConnected(%i) doing host name lookup", msecs);
1880 #endif
1881  QHostInfo::abortHostLookup(d->hostLookupId);
1882  d->hostLookupId = -1;
1883 #ifndef QT_NO_BEARERMANAGEMENT
1884  QSharedPointer<QNetworkSession> networkSession;
1885  QVariant v(property("_q_networksession"));
1886  if (v.isValid()) {
1887  networkSession = qvariant_cast< QSharedPointer<QNetworkSession> >(v);
1888  d->_q_startConnecting(QHostInfoPrivate::fromName(d->hostName, networkSession));
1889  } else
1890 #endif
1891  d->_q_startConnecting(QHostInfo::fromName(d->hostName));
1892  }
1893  if (state() == UnconnectedState)
1894  return false; // connect not im progress anymore!
1895 
1896  bool timedOut = true;
1897 #if defined (QABSTRACTSOCKET_DEBUG)
1898  int attempt = 1;
1899 #endif
1900  while (state() == ConnectingState && (msecs == -1 || stopWatch.elapsed() < msecs)) {
1901  int timeout = qt_timeout_value(msecs, stopWatch.elapsed());
1902  if (msecs != -1 && timeout > QT_CONNECT_TIMEOUT)
1903  timeout = QT_CONNECT_TIMEOUT;
1904 #if defined (QABSTRACTSOCKET_DEBUG)
1905  qDebug("QAbstractSocket::waitForConnected(%i) waiting %.2f secs for connection attempt #%i",
1906  msecs, timeout / 1000.0, attempt++);
1907 #endif
1908  timedOut = false;
1909 
1910  if (d->socketEngine && d->socketEngine->waitForWrite(timeout, &timedOut) && !timedOut) {
1911  d->_q_testConnection();
1912  } else {
1913  d->_q_connectToNextAddress();
1914  }
1915  }
1916 
1917  if ((timedOut && state() != ConnectedState) || state() == ConnectingState) {
1918  d->socketError = SocketTimeoutError;
1919  d->state = UnconnectedState;
1920  emit stateChanged(d->state);
1921  d->resetSocketLayer();
1922  setErrorString(tr("Socket operation timed out"));
1923  }
1924 
1925 #if defined (QABSTRACTSOCKET_DEBUG)
1926  qDebug("QAbstractSocket::waitForConnected(%i) == %s", msecs,
1927  state() == ConnectedState ? "true" : "false");
1928 #endif
1929  if (state() != ConnectedState)
1930  return false;
1931  if (wasPendingClose)
1933  return true;
1934 }
1935 
1949 {
1951 #if defined (QABSTRACTSOCKET_DEBUG)
1952  qDebug("QAbstractSocket::waitForReadyRead(%i)", msecs);
1953 #endif
1954 
1955  // require calling connectToHost() before waitForReadyRead()
1956  if (state() == UnconnectedState) {
1957  /* If all you have is a QIODevice pointer to an abstractsocket, you cannot check
1958  this, so you cannot avoid this warning. */
1959 // qWarning("QAbstractSocket::waitForReadyRead() is not allowed in UnconnectedState");
1960  return false;
1961  }
1962 
1963  QElapsedTimer stopWatch;
1964  stopWatch.start();
1965 
1966  // handle a socket in connecting state
1967  if (state() == HostLookupState || state() == ConnectingState) {
1968  if (!waitForConnected(msecs))
1969  return false;
1970  }
1971 
1972  Q_ASSERT(d->socketEngine);
1973  do {
1974  bool readyToRead = false;
1975  bool readyToWrite = false;
1976  if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
1977  qt_timeout_value(msecs, stopWatch.elapsed()))) {
1978  d->socketError = d->socketEngine->error();
1979  setErrorString(d->socketEngine->errorString());
1980 #if defined (QABSTRACTSOCKET_DEBUG)
1981  qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
1982  msecs, d->socketError, errorString().toLatin1().constData());
1983 #endif
1984  emit error(d->socketError);
1985  if (d->socketError != SocketTimeoutError)
1986  close();
1987  return false;
1988  }
1989 
1990  if (readyToRead) {
1991  if (d->canReadNotification())
1992  return true;
1993  }
1994 
1995  if (readyToWrite)
1996  d->canWriteNotification();
1997 
1998  if (state() != ConnectedState)
1999  return false;
2000  } while (msecs == -1 || qt_timeout_value(msecs, stopWatch.elapsed()) > 0);
2001  return false;
2002 }
2003 
2007 {
2009 #if defined (QABSTRACTSOCKET_DEBUG)
2010  qDebug("QAbstractSocket::waitForBytesWritten(%i)", msecs);
2011 #endif
2012 
2013  // require calling connectToHost() before waitForBytesWritten()
2014  if (state() == UnconnectedState) {
2015  qWarning("QAbstractSocket::waitForBytesWritten() is not allowed in UnconnectedState");
2016  return false;
2017  }
2018 
2019  if (d->writeBuffer.isEmpty())
2020  return false;
2021 
2022  QElapsedTimer stopWatch;
2023  stopWatch.start();
2024 
2025  // handle a socket in connecting state
2026  if (state() == HostLookupState || state() == ConnectingState) {
2027  if (!waitForConnected(msecs))
2028  return false;
2029  }
2030 
2031  forever {
2032  bool readyToRead = false;
2033  bool readyToWrite = false;
2034  if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
2035  qt_timeout_value(msecs, stopWatch.elapsed()))) {
2036  d->socketError = d->socketEngine->error();
2037  setErrorString(d->socketEngine->errorString());
2038 #if defined (QABSTRACTSOCKET_DEBUG)
2039  qDebug("QAbstractSocket::waitForBytesWritten(%i) failed (%i, %s)",
2040  msecs, d->socketError, errorString().toLatin1().constData());
2041 #endif
2042  emit error(d->socketError);
2043  if (d->socketError != SocketTimeoutError)
2044  close();
2045  return false;
2046  }
2047 
2048  if (readyToRead) {
2049 #if defined (QABSTRACTSOCKET_DEBUG)
2050  qDebug("QAbstractSocket::waitForBytesWritten calls canReadNotification");
2051 #endif
2052  if(!d->canReadNotification())
2053  return false;
2054  }
2055 
2056 
2057  if (readyToWrite) {
2058  if (d->canWriteNotification()) {
2059 #if defined (QABSTRACTSOCKET_DEBUG)
2060  qDebug("QAbstractSocket::waitForBytesWritten returns true");
2061 #endif
2062  return true;
2063  }
2064  }
2065 
2066  if (state() != ConnectedState)
2067  return false;
2068  }
2069  return false;
2070 }
2071 
2089 {
2091 #ifndef QT_NO_OPENSSL
2092  // Manual polymorphism; this function is not virtual, but has an overload
2093  // in QSslSocket.
2094  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
2095  return socket->waitForDisconnected(msecs);
2096 #endif
2097 
2098  // require calling connectToHost() before waitForDisconnected()
2099  if (state() == UnconnectedState) {
2100  qWarning("QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState");
2101  return false;
2102  }
2103 
2104  QElapsedTimer stopWatch;
2105  stopWatch.start();
2106 
2107  // handle a socket in connecting state
2108  if (state() == HostLookupState || state() == ConnectingState) {
2109  if (!waitForConnected(msecs))
2110  return false;
2111  if (state() == UnconnectedState)
2112  return true;
2113  }
2114 
2115  forever {
2116  bool readyToRead = false;
2117  bool readyToWrite = false;
2118  if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, state() == ConnectedState,
2119  !d->writeBuffer.isEmpty(),
2120  qt_timeout_value(msecs, stopWatch.elapsed()))) {
2121  d->socketError = d->socketEngine->error();
2122  setErrorString(d->socketEngine->errorString());
2123 #if defined (QABSTRACTSOCKET_DEBUG)
2124  qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
2125  msecs, d->socketError, errorString().toLatin1().constData());
2126 #endif
2127  emit error(d->socketError);
2128  if (d->socketError != SocketTimeoutError)
2129  close();
2130  return false;
2131  }
2132 
2133  if (readyToRead)
2134  d->canReadNotification();
2135  if (readyToWrite)
2136  d->canWriteNotification();
2137 
2138  if (state() == UnconnectedState)
2139  return true;
2140  }
2141  return false;
2142 }
2143 
2152 {
2154 #if defined (QABSTRACTSOCKET_DEBUG)
2155  qDebug("QAbstractSocket::abort()");
2156 #endif
2157  if (d->state == UnconnectedState)
2158  return;
2159 #ifndef QT_NO_OPENSSL
2160  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this)) {
2161  socket->abort();
2162  return;
2163  }
2164 #endif
2165  if (d->connectTimer) {
2166  d->connectTimer->stop();
2167  delete d->connectTimer;
2168  d->connectTimer = 0;
2169  }
2170 
2171  d->writeBuffer.clear();
2172  d->abortCalled = true;
2173  close();
2174 }
2175 
2179 {
2180  return true;
2181 }
2182 
2199 {
2200  return QIODevice::atEnd() && (!isOpen() || d_func()->readBuffer.isEmpty());
2201 }
2202 
2217 // Note! docs copied to QSslSocket::flush()
2219 {
2221 #ifndef QT_NO_OPENSSL
2222  // Manual polymorphism; flush() isn't virtual, but QSslSocket overloads
2223  // it.
2224  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
2225  return socket->flush();
2226 #endif
2227  Q_CHECK_SOCKETENGINE(false);
2228  return d->flush();
2229 }
2230 
2234 {
2236 
2237  // This is for a buffered QTcpSocket
2238  if (d->isBuffered && d->readBuffer.isEmpty())
2239  // if we're still connected, return 0 indicating there may be more data in the future
2240  // if we're not connected, return -1 indicating EOF
2241  return d->state == QAbstractSocket::ConnectedState ? qint64(0) : qint64(-1);
2242 
2243  // short cut for a char read if we have something in the buffer
2244  if (maxSize == 1 && !d->readBuffer.isEmpty()) {
2245  *data = d->readBuffer.getChar();
2246 #if defined (QABSTRACTSOCKET_DEBUG)
2247  qDebug("QAbstractSocket::readData(%p '%c (0x%.2x)', 1) == 1 [char buffer]",
2248  data, isprint(int(uchar(*data))) ? *data : '?', *data);
2249 #endif
2250  if (d->readBuffer.isEmpty() && d->socketEngine && d->socketEngine->isValid())
2251  d->socketEngine->setReadNotificationEnabled(true);
2252  return 1;
2253  }
2254 
2255  // Special case for an Unbuffered QTcpSocket
2256  // Re-filling the buffer.
2257  if (d->socketType == TcpSocket
2258  && !d->isBuffered
2259  && d->readBuffer.size() < maxSize
2260  && d->readBufferMaxSize > 0
2261  && maxSize < d->readBufferMaxSize
2262  && d->socketEngine
2263  && d->socketEngine->isValid()) {
2264  // Our buffer is empty and a read() was requested for a byte amount that is smaller
2265  // than the readBufferMaxSize. This means that we should fill our buffer since we want
2266  // such small reads come from the buffer and not always go to the costly socket engine read()
2267  qint64 bytesToRead = d->socketEngine->bytesAvailable();
2268  if (bytesToRead > 0) {
2269  char *ptr = d->readBuffer.reserve(bytesToRead);
2270  qint64 readBytes = d->socketEngine->read(ptr, bytesToRead);
2271  if (readBytes == -2) {
2272  // No bytes currently available for reading.
2273  d->readBuffer.chop(bytesToRead);
2274  } else {
2275  d->readBuffer.chop(int(bytesToRead - (readBytes < 0 ? qint64(0) : readBytes)));
2276  }
2277  }
2278  }
2279 
2280  // First try to satisfy the read from the buffer
2281  qint64 bytesToRead = qMin(qint64(d->readBuffer.size()), maxSize);
2282  qint64 readSoFar = 0;
2283  while (readSoFar < bytesToRead) {
2284  const char *ptr = d->readBuffer.readPointer();
2285  int bytesToReadFromThisBlock = qMin(int(bytesToRead - readSoFar),
2286  d->readBuffer.nextDataBlockSize());
2287  memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
2288  readSoFar += bytesToReadFromThisBlock;
2289  d->readBuffer.free(bytesToReadFromThisBlock);
2290  }
2291 
2292  if (d->socketEngine && !d->socketEngine->isReadNotificationEnabled() && d->socketEngine->isValid())
2293  d->socketEngine->setReadNotificationEnabled(true);
2294 
2295  if (readSoFar > 0) {
2296  // we read some data from buffer.
2297  // Just return, readyRead will be emitted again
2298 #if defined (QABSTRACTSOCKET_DEBUG)
2299  qDebug("QAbstractSocket::readData(%p '%c (0x%.2x)', %lli) == %lli [buffer]",
2300  data, isprint(int(uchar(*data))) ? *data : '?', *data, maxSize, readSoFar);
2301 #endif
2302 
2303  if (d->readBuffer.isEmpty() && d->socketEngine)
2304  d->socketEngine->setReadNotificationEnabled(true);
2305  return readSoFar;
2306  }
2307 
2308  // This code path is for Unbuffered QTcpSocket or for connected UDP
2309 
2310  if (!d->isBuffered) {
2311  if (!d->socketEngine)
2312  return -1; // no socket engine is probably EOF
2313  if (!d->socketEngine->isValid())
2314  return -1; // This is for unbuffered TCP when we already had been disconnected
2315  if (d->state != QAbstractSocket::ConnectedState)
2316  return -1; // This is for unbuffered TCP if we're not connected yet
2317  qint64 readBytes = d->socketEngine->read(data, maxSize);
2318  if (readBytes == -2) {
2319  // -2 from the engine means no bytes available (EAGAIN) so read more later
2320  return 0;
2321  } else if (readBytes < 0) {
2322  d->socketError = d->socketEngine->error();
2323  setErrorString(d->socketEngine->errorString());
2324  d->resetSocketLayer();
2326  } else if (!d->socketEngine->isReadNotificationEnabled()) {
2327  // Only do this when there was no error
2328  d->socketEngine->setReadNotificationEnabled(true);
2329  }
2330 
2331 #if defined (QABSTRACTSOCKET_DEBUG)
2332  qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [engine]",
2333  data, qt_prettyDebug(data, 32, readBytes).data(), maxSize,
2334  readBytes);
2335 #endif
2336  return readBytes;
2337  }
2338 
2339 
2340 #if defined (QABSTRACTSOCKET_DEBUG)
2341  qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [unreachable]",
2342  data, qt_prettyDebug(data, qMin<qint64>(32, readSoFar), readSoFar).data(),
2343  maxSize, readSoFar);
2344 #endif
2345  return readSoFar;
2346 }
2347 
2351 {
2352  return QIODevice::readLineData(data, maxlen);
2353 }
2354 
2358 {
2360  if (d->state == QAbstractSocket::UnconnectedState) {
2361  d->socketError = QAbstractSocket::UnknownSocketError;
2362  setErrorString(tr("Socket is not connected"));
2363  return -1;
2364  }
2365 
2366  if (!d->isBuffered && d->socketType == TcpSocket && d->writeBuffer.isEmpty()) {
2367  // This code is for the new Unbuffered QTcpSocket use case
2368  qint64 written = d->socketEngine->write(data, size);
2369  if (written < 0) {
2370  d->socketError = d->socketEngine->error();
2371  setErrorString(d->socketEngine->errorString());
2372  return written;
2373  } else if (written < size) {
2374  // Buffer what was not written yet
2375  char *ptr = d->writeBuffer.reserve(size - written);
2376  memcpy(ptr, data + written, size - written);
2377  if (d->socketEngine)
2378  d->socketEngine->setWriteNotificationEnabled(true);
2379  }
2380  return size; // size=actually written + what has been buffered
2381  } else if (!d->isBuffered && d->socketType != TcpSocket) {
2382  // This is for a QUdpSocket that was connect()ed
2383  qint64 written = d->socketEngine->write(data, size);
2384  if (written < 0) {
2385  d->socketError = d->socketEngine->error();
2386  setErrorString(d->socketEngine->errorString());
2387  } else if (!d->writeBuffer.isEmpty()) {
2388  d->socketEngine->setWriteNotificationEnabled(true);
2389  }
2390 
2391 #if defined (QABSTRACTSOCKET_DEBUG)
2392  qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2393  qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2394  size, written);
2395 #endif
2396  if (written >= 0)
2397  emit bytesWritten(written);
2398  return written;
2399  }
2400 
2401  // This is the code path for normal buffered QTcpSocket or
2402  // unbuffered QTcpSocket when there was already something in the
2403  // write buffer and therefore we could not do a direct engine write.
2404  // We just write to our write buffer and enable the write notifier
2405  // The write notifier then flush()es the buffer.
2406 
2407  char *ptr = d->writeBuffer.reserve(size);
2408  if (size == 1)
2409  *ptr = *data;
2410  else
2411  memcpy(ptr, data, size);
2412 
2413  qint64 written = size;
2414 
2415  if (d->socketEngine && !d->writeBuffer.isEmpty())
2416  d->socketEngine->setWriteNotificationEnabled(true);
2417 
2418 #if defined (QABSTRACTSOCKET_DEBUG)
2419  qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2420  qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2421  size, written);
2422 #endif
2423  return written;
2424 }
2425 
2445 {
2447  d->localPort = port;
2448 }
2449 
2470 {
2472  d->localAddress = address;
2473 }
2474 
2492 {
2494  d->peerPort = port;
2495 }
2496 
2514 {
2516  d->peerAddress = address;
2517 }
2518 
2535 {
2537  d->peerName = name;
2538 }
2539 
2551 {
2553 #if defined(QABSTRACTSOCKET_DEBUG)
2554  qDebug("QAbstractSocket::close()");
2555 #endif
2556  QIODevice::close();
2557  if (d->state != UnconnectedState) {
2558  d->closeCalled = true;
2560  }
2561 
2562  d->localPort = 0;
2563  d->peerPort = 0;
2564  d->localAddress.clear();
2565  d->peerAddress.clear();
2566  d->peerName.clear();
2567  d->cachedSocketDescriptor = -1;
2568 }
2569 
2579 {
2580  QMetaObject::invokeMethod(this, "disconnectFromHostImplementation",
2582 }
2583 
2593 {
2595 #if defined(QABSTRACTSOCKET_DEBUG)
2596  qDebug("QAbstractSocket::disconnectFromHost()");
2597 #endif
2598 
2599  if (d->state == UnconnectedState) {
2600 #if defined(QABSTRACTSOCKET_DEBUG)
2601  qDebug("QAbstractSocket::disconnectFromHost() was called on an unconnected socket");
2602 #endif
2603  return;
2604  }
2605 
2606  if (!d->abortCalled && (d->state == ConnectingState || d->state == HostLookupState)) {
2607 #if defined(QABSTRACTSOCKET_DEBUG)
2608  qDebug("QAbstractSocket::disconnectFromHost() but we're still connecting");
2609 #endif
2610  d->pendingClose = true;
2611  return;
2612  }
2613 
2614 #ifdef QT3_SUPPORT
2615  emit connectionClosed(); // compat signal
2616 #endif
2617 
2618  // Disable and delete read notification
2619  if (d->socketEngine)
2620  d->socketEngine->setReadNotificationEnabled(false);
2621 
2622  if (d->abortCalled) {
2623 #if defined(QABSTRACTSOCKET_DEBUG)
2624  qDebug("QAbstractSocket::disconnectFromHost() aborting immediately");
2625 #endif
2626  if (d->state == HostLookupState) {
2627  QHostInfo::abortHostLookup(d->hostLookupId);
2628  d->hostLookupId = -1;
2629  }
2630  } else {
2631  // Perhaps emit closing()
2632  if (d->state != ClosingState) {
2633  d->state = ClosingState;
2634 #if defined(QABSTRACTSOCKET_DEBUG)
2635  qDebug("QAbstractSocket::disconnectFromHost() emits stateChanged()(ClosingState)");
2636 #endif
2637  emit stateChanged(d->state);
2638  } else {
2639 #if defined(QABSTRACTSOCKET_DEBUG)
2640  qDebug("QAbstractSocket::disconnectFromHost() return from delayed close");
2641 #endif
2642  }
2643 
2644  // Wait for pending data to be written.
2645  if (d->socketEngine && d->socketEngine->isValid() && (d->writeBuffer.size() > 0
2646  || d->socketEngine->bytesToWrite() > 0)) {
2647  // hack: when we are waiting for the socket engine to write bytes (only
2648  // possible when using Socks5 or HTTP socket engine), then close
2649  // anyway after 2 seconds. This is to prevent a timeout on Mac, where we
2650  // sometimes just did not get the write notifier from the underlying
2651  // CFSocket and no progress was made.
2652  if (d->writeBuffer.size() == 0 && d->socketEngine->bytesToWrite() > 0) {
2653  if (!d->disconnectTimer) {
2654  d->disconnectTimer = new QTimer(this);
2655  connect(d->disconnectTimer, SIGNAL(timeout()), this,
2656  SLOT(_q_forceDisconnect()), Qt::DirectConnection);
2657  }
2658  if (!d->disconnectTimer->isActive())
2659  d->disconnectTimer->start(2000);
2660  }
2661  d->socketEngine->setWriteNotificationEnabled(true);
2662 
2663 #if defined(QABSTRACTSOCKET_DEBUG)
2664  qDebug("QAbstractSocket::disconnectFromHost() delaying disconnect");
2665 #endif
2666  return;
2667  } else {
2668 #if defined(QABSTRACTSOCKET_DEBUG)
2669  qDebug("QAbstractSocket::disconnectFromHost() disconnecting immediately");
2670 #endif
2671  }
2672  }
2673 
2674  SocketState previousState = d->state;
2675  d->resetSocketLayer();
2676  d->state = UnconnectedState;
2677  emit stateChanged(d->state);
2678  emit readChannelFinished(); // we got an EOF
2679 
2680 #ifdef QT3_SUPPORT
2681  emit delayedCloseFinished(); // compat signal
2682 #endif
2683  // only emit disconnected if we were connected before
2684  if (previousState == ConnectedState || previousState == ClosingState)
2685  emit disconnected();
2686 
2687  d->localPort = 0;
2688  d->peerPort = 0;
2689  d->localAddress.clear();
2690  d->peerAddress.clear();
2691 
2692 #if defined(QABSTRACTSOCKET_DEBUG)
2693  qDebug("QAbstractSocket::disconnectFromHost() disconnected!");
2694 #endif
2695 
2696  if (d->closeCalled) {
2697 #if defined(QABSTRACTSOCKET_DEBUG)
2698  qDebug("QAbstractSocket::disconnectFromHost() closed!");
2699 #endif
2700  d->readBuffer.clear();
2701  d->writeBuffer.clear();
2702  QIODevice::close();
2703  }
2704 }
2705 
2717 {
2718  return d_func()->readBufferMaxSize;
2719 }
2720 
2744 {
2746 
2747 #ifndef QT_NO_OPENSSL
2748  // Manual polymorphism; setReadBufferSize() isn't virtual, but QSslSocket overloads
2749  // it.
2750  if (QSslSocket *socket = qobject_cast<QSslSocket *>(this)) {
2751  socket->setReadBufferSize(size);
2752  return;
2753  }
2754 #endif
2755 
2756  if (d->readBufferMaxSize == size)
2757  return;
2758  d->readBufferMaxSize = size;
2759  if (!d->readSocketNotifierCalled && d->socketEngine) {
2760  // ensure that the read notification is enabled if we've now got
2761  // room in the read buffer
2762  // but only if we're not inside canReadNotification -- that will take care on its own
2763  if ((size == 0 || d->readBuffer.size() < size) && d->state == QAbstractSocket::ConnectedState) // Do not change the notifier unless we are connected.
2764  d->socketEngine->setReadNotificationEnabled(true);
2765  }
2766 }
2767 
2774 {
2775  return d_func()->state;
2776 }
2777 
2784 {
2785  d_func()->state = state;
2786 }
2787 
2794 {
2795  return d_func()->socketType;
2796 }
2797 
2804 {
2805  return d_func()->socketError;
2806 }
2807 
2814 {
2815  d_func()->socketError = socketError;
2816 }
2817 
2818 #ifndef QT_NO_NETWORKPROXY
2819 
2841 void QAbstractSocket::setProxy(const QNetworkProxy &networkProxy)
2842 {
2844  d->proxy = networkProxy;
2845 }
2846 
2860 {
2861  Q_D(const QAbstractSocket);
2862  return d->proxy;
2863 }
2864 #endif // QT_NO_NETWORKPROXY
2865 
2866 #ifdef QT3_SUPPORT
2867 
2954 #endif // QT3_SUPPORT
2955 
2956 #ifndef QT_NO_DEBUG_STREAM
2958 {
2959  switch (error) {
2961  debug << "QAbstractSocket::ConnectionRefusedError";
2962  break;
2964  debug << "QAbstractSocket::RemoteHostClosedError";
2965  break;
2967  debug << "QAbstractSocket::HostNotFoundError";
2968  break;
2970  debug << "QAbstractSocket::SocketAccessError";
2971  break;
2973  debug << "QAbstractSocket::SocketResourceError";
2974  break;
2976  debug << "QAbstractSocket::SocketTimeoutError";
2977  break;
2979  debug << "QAbstractSocket::DatagramTooLargeError";
2980  break;
2982  debug << "QAbstractSocket::NetworkError";
2983  break;
2985  debug << "QAbstractSocket::AddressInUseError";
2986  break;
2988  debug << "QAbstractSocket::SocketAddressNotAvailableError";
2989  break;
2991  debug << "QAbstractSocket::UnsupportedSocketOperationError";
2992  break;
2994  debug << "QAbstractSocket::UnfinishedSocketOperationError";
2995  break;
2997  debug << "QAbstractSocket::ProxyAuthenticationRequiredError";
2998  break;
3000  debug << "QAbstractSocket::UnknownSocketError";
3001  break;
3003  debug << "QAbstractSocket::ProxyConnectionRefusedError";
3004  break;
3006  debug << "QAbstractSocket::ProxyConnectionClosedError";
3007  break;
3009  debug << "QAbstractSocket::ProxyConnectionTimeoutError";
3010  break;
3012  debug << "QAbstractSocket::ProxyNotFoundError";
3013  break;
3015  debug << "QAbstractSocket::ProxyProtocolError";
3016  break;
3017  default:
3018  debug << "QAbstractSocket::SocketError(" << int(error) << ')';
3019  break;
3020  }
3021  return debug;
3022 }
3023 
3025 {
3026  switch (state) {
3028  debug << "QAbstractSocket::UnconnectedState";
3029  break;
3031  debug << "QAbstractSocket::HostLookupState";
3032  break;
3034  debug << "QAbstractSocket::ConnectingState";
3035  break;
3037  debug << "QAbstractSocket::ConnectedState";
3038  break;
3040  debug << "QAbstractSocket::BoundState";
3041  break;
3043  debug << "QAbstractSocket::ListeningState";
3044  break;
3046  debug << "QAbstractSocket::ClosingState";
3047  break;
3048  default:
3049  debug << "QAbstractSocket::SocketState(" << int(state) << ')';
3050  break;
3051  }
3052  return debug;
3053 }
3054 #endif
3055 
3057 
3058 #include "moc_qabstractsocket.cpp"
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
QNetworkProxy::ProxyType type() const
Returns the proxy type for this instance.
virtual bool isReadNotificationEnabled() const =0
The QDebug class provides an output stream for debugging information.
Definition: qdebug.h:62
double d
Definition: qnumeric_p.h:62
virtual void setExceptionNotificationEnabled(bool enable)=0
int lookupId() const
Returns the ID of this lookup.
Definition: qhostinfo.cpp:433
virtual qint64 bytesToWrite() const =0
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
QString peerName() const
Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() ...
int socketDescriptor() const
Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise re...
QString & sprintf(const char *format,...)
Safely builds a formatted string from the format string cformat and an arbitrary list of arguments...
Definition: qstring.cpp:5567
static mach_timebase_info_data_t info
unsigned char c[8]
Definition: qnumeric_p.h:62
void setSocketError(SocketError socketError)
Sets the type of error that last occurred to socketError.
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
static double elapsed(qint64 after, qint64 before)
#define QT_END_NAMESPACE
This macro expands to.
Definition: qglobal.h:90
SocketType
This enum describes the transport layer protocol.
bool waitForBytesWritten(int msecs=30000)
Reimplemented Function
bool waitForReadyRead(int msecs=30000)
This function blocks until new data is available for reading and the QIODevice::readyRead() signal ha...
virtual int socketDescriptor() const =0
const QChar at(int i) const
Returns the character at the given index position in the string.
Definition: qstring.h:698
QHostAddress localAddress() const
Returns the host address of the local socket if available; otherwise returns QHostAddress::Null.
const char * readPointer() const
Definition: qringbuffer_p.h:73
virtual void close()
First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen.
Definition: qiodevice.cpp:590
bool waitForDisconnected(int msecs=30000)
Waits until the socket has disconnected, up to msecs milliseconds.
qint64 bytesAvailable() const
Returns the number of incoming bytes that are waiting to be read.
bool flush()
This function writes as much as possible from the internal write buffer to the underlying network soc...
QList< QHostAddress > addresses
virtual bool connectToHostByName(const QString &name, quint16 port)=0
Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketError error)
qint64 readData(char *data, qint64 maxlen)
Reimplemented Function
static QAbstractSocketEngine * createSocketEngine(QAbstractSocket::SocketType socketType, const QNetworkProxy &, QObject *parent)
void readChannelFinished()
This signal is emitted when the input (reading) stream is closed in this device.
#define QABSTRACTSOCKET_BUFFERSIZE
#define error(msg)
void connectToHost(const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
Attempts to make a connection to hostName on the given port.
int nextDataBlockSize() const
Definition: qringbuffer_p.h:69
void setPeerName(const QString &name)
Sets the host name of the remote peer to name.
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QNetworkProxy proxy() const
Returns the network proxy for this socket.
#define SLOT(a)
Definition: qobjectdefs.h:226
SocketOption
This enum represents the options that can be set on a socket.
QString errorString() const
Returns a human-readable description of the last device error that occurred.
Definition: qiodevice.cpp:1671
static void abortHostLookup(int lookupId)
Aborts the host lookup with the ID id, as returned by lookupHost().
Definition: qhostinfo.cpp:255
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
bool readFromSocket()
Reads data from the socket layer into the read buffer.
bool atEnd() const
Returns true if no more data is currently available for reading; otherwise returns false...
static void resumeSocketNotifiers(QAbstractSocket *)
bool setProperty(const char *name, const QVariant &value)
Sets the value of the object&#39;s name property to value.
Definition: qobject.cpp:3755
quint16 peerPort() const
Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0...
#define Q_ARG(type, data)
Definition: qobjectdefs.h:246
#define QT_END_INCLUDE_NAMESPACE
This macro is equivalent to QT_BEGIN_NAMESPACE.
Definition: qglobal.h:92
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
int count(const T &t) const
Returns the number of occurrences of value in the list.
Definition: qlist.h:891
void bytesWritten(qint64 bytes)
This signal is emitted every time a payload of data has been written to the device.
void connectToHostImplementation(const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
Contains the implementation of connectToHost().
void resetSocketLayer()
Resets the socket layer, clears the read and write buffers and deletes any socket notifiers...
NetworkLayerProtocol
This enum describes the network layer protocol values used in Qt.
bool isEmpty() const
void abort()
Aborts the current connection and resets the socket.
The QString class provides a Unicode character string.
Definition: qstring.h:83
virtual bool initialize(QAbstractSocket::SocketType type, QAbstractSocket::NetworkLayerProtocol protocol=QAbstractSocket::IPv4Protocol)=0
void setSocketState(SocketState state)
Sets the state of the socket to state.
qint64 readLineData(char *data, qint64 maxlen)
Reimplemented Function
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
void disconnected()
This signal is emitted when the socket has been disconnected.
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
SocketType socketType() const
Returns the socket type (TCP, UDP, or other).
static QList< QNetworkProxy > proxyForQuery(const QNetworkProxyQuery &query)
This function takes the query request, query, examines the details of the type of socket or request a...
virtual bool atEnd() const
Returns true if the current read and write position is at the end of the device (i.e.
Definition: qiodevice.cpp:711
qint64 readBufferSize() const
Returns the size of the internal read buffer.
QThreadData * threadData
Definition: qobject_p.h:195
QList< QHostAddress > addresses() const
Returns the list of IP addresses associated with hostName().
Definition: qhostinfo.cpp:372
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
void setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
Sets the given option to the value described by value.
virtual qint64 readLineData(char *data, qint64 maxlen)
Reads up to maxSize characters into data and returns the number of characters read.
Definition: qiodevice.cpp:1285
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
#define Q_Q(Class)
Definition: qglobal.h:2483
int toInt(bool *ok=0) const
Returns the variant as an int if the variant has type() Int , Bool , ByteArray , Char ...
Definition: qvariant.cpp:2625
SocketState
This enum describes the different states in which a socket can be.
Q_CORE_EXPORT void qDebug(const char *,...)
#define SIGNAL(a)
Definition: qobjectdefs.h:227
void startConnectingByName(const QString &host)
Starts the connection to host, like _q_startConnecting below, but without hostname resolution...
unsigned char uchar
Definition: qglobal.h:994
QAbstractSocket::SocketState state
virtual ~QAbstractSocketPrivate()
Destructs the QAbstractSocket.
The QNetworkProxy class provides a network layer proxy.
char * reserve(int bytes)
#define QT_BEGIN_NAMESPACE
This macro expands to.
Definition: qglobal.h:89
virtual bool isWriteNotificationEnabled() const =0
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
void _q_startConnecting(const QHostInfo &hostInfo)
Slot connected to QHostInfo::lookupHost() in connectToHost().
QHostAddress peerAddress() const
Capabilities capabilities() const
Returns the capabilities of this proxy server.
virtual void setWriteNotificationEnabled(bool enable)=0
T takeFirst()
Removes the first item in the list and returns it.
Definition: qlist.h:489
static bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
Creates a connection of the given type from the signal in the sender object to the method in the rece...
Definition: qobject.cpp:2580
void setAddresses(const QList< QHostAddress > &addresses)
Sets the list of addresses in this QHostInfo to addresses.
Definition: qhostinfo.cpp:382
const char * name
#define emit
Definition: qobjectdefs.h:76
bool setSocketDescriptor(int socketDescriptor, SocketState state=ConnectedState, OpenMode openMode=ReadWrite)
Initializes QAbstractSocket with the native socket descriptor socketDescriptor.
SocketError
This enum describes the socket errors that can occur.
bool isSequential() const
Reimplemented Function
bool waitForConnected(int msecs=30000)
Waits until the socket is connected, up to msecs milliseconds.
unsigned short quint16
Definition: qglobal.h:936
Q_CORE_EXPORT void qWarning(const char *,...)
QAbstractSocket::SocketError socketError
static const char * data(const QByteArray &arr)
QHostAddress localAddress() const
virtual ~QAbstractSocket()
Destroys the socket.
static QAbstractSocketEngine * getSocketEngine(QAbstractSocket *)
The QHostInfo class provides static functions for host name lookups.
Definition: qhostinfo.h:58
QString toString() const
Returns the address as a string.
static bool isProxyError(QAbstractSocket::SocketError error)
QVariant socketOption(QAbstractSocket::SocketOption option)
Returns the value of the option option.
const T * ptr(const T &t)
void setReadBufferSize(qint64 size)
Sets the size of QAbstractSocket&#39;s internal read buffer to be size bytes.
QByteArray toLatin1() const Q_REQUIRED_RESULT
Returns a Latin-1 representation of the string as a QByteArray.
Definition: qstring.cpp:3993
void clear()
Removes all items from the list.
Definition: qlist.h:764
__int64 qint64
Definition: qglobal.h:942
void _q_abortConnectionAttempt()
This function is called after a certain number of seconds has passed while waiting for a connection...
static QHostInfo fromName(const QString &hostName, QSharedPointer< QNetworkSession > networkSession)
Definition: qhostinfo.cpp:286
void close()
Closes the I/O device for the socket, disconnects the socket&#39;s connection with the host...
void setReceiver(QAbstractSocketEngineReceiver *receiver)
virtual qint64 write(const char *data, qint64 len)=0
#define QT_CONNECT_TIMEOUT
virtual bool hasPendingDatagrams() const =0
The QNetworkProxyQuery class is used to query the proxy settings for a socket.
Definition: qnetworkproxy.h:60
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
static bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *member)
Disconnects signal in object sender from method in object receiver.
Definition: qobject.cpp:2895
virtual bool isExceptionNotificationEnabled() const =0
void setLocalAddress(const QHostAddress &address)
Sets the address on the local side of a connection to address.
void setProxy(const QNetworkProxy &networkProxy)
Sets the explicit network proxy for this socket to networkProxy.
The QScopedValueRollback class resets a variable to its previous value on destruction.
static QHostInfo fromName(const QString &name)
Looks up the IP address(es) for the given host name.
Definition: qhostinfo.cpp:273
QAbstractSocket::NetworkLayerProtocol protocol() const
Returns the network layer protocol of the host address.
void free(int bytes)
void setAddress(quint32 ip4Addr)
Set the IPv4 address specified by ip4Addr.
void disconnectFromHostImplementation()
Contains the implementation of disconnectFromHost().
quint16 localPort() const
Returns the host port number (in native byte order) of the local socket if available; otherwise retur...
void chop(int bytes)
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
Definition: qiodevice.cpp:465
QAbstractSocket::SocketError error() const
void connectionNotification()
Slot connected to a notification of connection status change.
QObject * parent() const
Returns a pointer to the parent object.
Definition: qobject.h:273
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
#define Q_NETWORK_EXPORT
Definition: qglobal.h:1452
void _q_connectToNextAddress()
Called by a queued or direct connection from _q_startConnecting() or _q_testConnection(), this function takes the first address of the pending addresses list and tries to connect to it.
QAbstractSocketEngine * socketEngine
virtual qint64 bytesAvailable() const
Returns the number of bytes that are available for reading.
Definition: qiodevice.cpp:752
virtual void close()=0
void setLocalPort(quint16 port)
Sets the port on the local side of a connection to port.
qint64 bytesToWrite() const
Returns the number of bytes that are waiting to be written.
QAbstractSocket::SocketType socketType
T qvariant_cast(const QVariant &)
Definition: qvariant.h:571
QHostAddress peerAddress() const
Returns the address of the connected peer if the socket is in ConnectedState; otherwise returns QHost...
void fetchConnectionParameters()
Sets up the internal state after the connection has succeeded.
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
Definition: qiodevice.cpp:570
QVariant property(const char *name) const
Returns the value of the object&#39;s name property.
Definition: qobject.cpp:3807
void disconnectFromHost()
Attempts to close the socket.
bool flush()
Writes pending data in the write buffers to the socket.
QObject * parent
Definition: qobject.h:92
#define QT_BEGIN_INCLUDE_NAMESPACE
This macro is equivalent to QT_END_NAMESPACE.
Definition: qglobal.h:91
static int qt_timeout_value(int msecs, int elapsed)
#define Q_CHECK_SOCKETENGINE(returnValue)
void stateChanged(QAbstractSocket::SocketState)
This signal is emitted whenever QAbstractSocket&#39;s state changes.
void setPeerAddress(const QHostAddress &address)
Sets the address of the remote side of the connection to address.
static bool invokeMethod(QObject *obj, const char *member, Qt::ConnectionType, QGenericReturnArgument ret, QGenericArgument val0=QGenericArgument(0), QGenericArgument val1=QGenericArgument(), QGenericArgument val2=QGenericArgument(), QGenericArgument val3=QGenericArgument(), QGenericArgument val4=QGenericArgument(), QGenericArgument val5=QGenericArgument(), QGenericArgument val6=QGenericArgument(), QGenericArgument val7=QGenericArgument(), QGenericArgument val8=QGenericArgument(), QGenericArgument val9=QGenericArgument())
Invokes the member (a signal or a slot name) on the object obj.
bool initSocketLayer(QAbstractSocket::NetworkLayerProtocol protocol)
Initializes the socket layer to by of type type, using the network layer protocol protocol...
void resolveProxy(const QString &hostName, quint16 port)
Resolve the proxy to its final value.
virtual qint64 read(char *data, qint64 maxlen)=0
virtual bool isValid() const =0
QAbstractSocketPrivate()
Constructs a QAbstractSocketPrivate.
virtual bool canReadLine() const
Returns true if a complete line of data can be read from the device; otherwise returns false...
Definition: qiodevice.cpp:1330
The QHostAddress class provides an IP address.
Definition: qhostaddress.h:70
void _q_testConnection()
Tests if a connection has been established.
qint64 writeData(const char *data, qint64 len)
Reimplemented Function
The QTimer class provides repetitive and single-shot timers.
Definition: qtimer.h:56
QAbstractSocket::SocketState state() const
static void pauseSocketNotifiers(QAbstractSocket *)
SocketError error() const
Returns the type of error that last occurred.
bool isValid() const
Returns true if the storage type of this variant is not QVariant::Invalid; otherwise returns false...
Definition: qvariant.h:485
virtual void setReadNotificationEnabled(bool enable)=0
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66
void stop()
Stops the timer.
Definition: qtimer.cpp:284
bool canReadNotification()
Slot connected to the read socket notifier.
void start(int msec)
Starts or restarts the timer with a timeout interval of msec milliseconds.
Definition: qtimer.cpp:249
#define qPrintable(string)
Definition: qglobal.h:1750
virtual bool connectToHost(const QHostAddress &address, quint16 port)=0
bool canReadLine() const
Returns true if a line of data can be read from the socket; otherwise returns false.
bool canWriteNotification()
Slot connected to the write socket notifier.
The QAbstractSocket class provides the base functionality common to all socket types.
virtual qint64 bytesAvailable() const =0
void setPeerPort(quint16 port)
Sets the port of the remote side of the connection to port.
QAbstractEventDispatcher * eventDispatcher
Definition: qthread_p.h:264
void start()
Starts this timer.
QAbstractSocket(SocketType socketType, QObject *parent)
Creates a new abstract socket of type socketType.
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
SocketState state() const
Returns the state of the socket.
int size() const
QHostInfo qt_qhostinfo_lookup(const QString &name, QObject *receiver, const char *member, bool *valid, int *id)
Definition: qhostinfo.cpp:726
bool isValid() const
Returns true if the socket is valid and ready for use; otherwise returns false.
#define forever
This macro is provided for convenience for writing infinite loops.
Definition: qglobal.h:2452