util/src/network/socket/qlocalsocket_win.cpp
changeset 7 f7bc934e204c
equal deleted inserted replaced
3:41300fa6a67c 7:f7bc934e204c
       
     1 /****************************************************************************
       
     2 **
       
     3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
       
     4 ** All rights reserved.
       
     5 ** Contact: Nokia Corporation (qt-info@nokia.com)
       
     6 **
       
     7 ** This file is part of the QtNetwork module of the Qt Toolkit.
       
     8 **
       
     9 ** $QT_BEGIN_LICENSE:LGPL$
       
    10 ** No Commercial Usage
       
    11 ** This file contains pre-release code and may not be distributed.
       
    12 ** You may use this file in accordance with the terms and conditions
       
    13 ** contained in the Technology Preview License Agreement accompanying
       
    14 ** this package.
       
    15 **
       
    16 ** GNU Lesser General Public License Usage
       
    17 ** Alternatively, this file may be used under the terms of the GNU Lesser
       
    18 ** General Public License version 2.1 as published by the Free Software
       
    19 ** Foundation and appearing in the file LICENSE.LGPL included in the
       
    20 ** packaging of this file.  Please review the following information to
       
    21 ** ensure the GNU Lesser General Public License version 2.1 requirements
       
    22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
       
    23 **
       
    24 ** In addition, as a special exception, Nokia gives you certain additional
       
    25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
       
    26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
       
    27 **
       
    28 ** If you have questions regarding the use of this file, please contact
       
    29 ** Nokia at qt-info@nokia.com.
       
    30 **
       
    31 **
       
    32 **
       
    33 **
       
    34 **
       
    35 **
       
    36 **
       
    37 **
       
    38 ** $QT_END_LICENSE$
       
    39 **
       
    40 ****************************************************************************/
       
    41 
       
    42 #include "qlocalsocket.h"
       
    43 #include "qlocalsocket_p.h"
       
    44 
       
    45 #include <private/qthread_p.h>
       
    46 #include <qcoreapplication.h>
       
    47 #include <qdebug.h>
       
    48 
       
    49 QT_BEGIN_NAMESPACE
       
    50 
       
    51 void QLocalSocketPrivate::init()
       
    52 {
       
    53     Q_Q(QLocalSocket);
       
    54     memset(&overlapped, 0, sizeof(overlapped));
       
    55     overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
       
    56     dataReadNotifier = new QWinEventNotifier(overlapped.hEvent, q);
       
    57     q->connect(dataReadNotifier, SIGNAL(activated(HANDLE)), q, SLOT(_q_notified()));
       
    58 }
       
    59 
       
    60 void QLocalSocketPrivate::setErrorString(const QString &function)
       
    61 {
       
    62     Q_Q(QLocalSocket);
       
    63     BOOL windowsError = GetLastError();
       
    64     QLocalSocket::LocalSocketState currentState = state;
       
    65 
       
    66     // If the connectToServer fails due to WaitNamedPipe() time-out, assume ConnectionError  
       
    67     if (state == QLocalSocket::ConnectingState && windowsError == ERROR_SEM_TIMEOUT)
       
    68         windowsError = ERROR_NO_DATA;
       
    69 
       
    70     switch (windowsError) {
       
    71     case ERROR_PIPE_NOT_CONNECTED:
       
    72     case ERROR_BROKEN_PIPE:
       
    73     case ERROR_NO_DATA:
       
    74         error = QLocalSocket::ConnectionError;
       
    75         errorString = QLocalSocket::tr("%1: Connection error").arg(function);
       
    76         state = QLocalSocket::UnconnectedState;
       
    77         break;
       
    78     case ERROR_FILE_NOT_FOUND:
       
    79         error = QLocalSocket::ServerNotFoundError;
       
    80         errorString = QLocalSocket::tr("%1: Invalid name").arg(function);
       
    81         state = QLocalSocket::UnconnectedState;
       
    82         break;
       
    83     default:
       
    84         error = QLocalSocket::UnknownSocketError;
       
    85         errorString = QLocalSocket::tr("%1: Unknown error %2").arg(function).arg(windowsError);
       
    86 #if defined QLOCALSOCKET_DEBUG
       
    87         qWarning() << "QLocalSocket error not handled:" << errorString;
       
    88 #endif
       
    89         state = QLocalSocket::UnconnectedState;
       
    90     }
       
    91 
       
    92     if (currentState != state) {
       
    93         q->emit stateChanged(state);
       
    94         if (state == QLocalSocket::UnconnectedState)
       
    95             q->emit disconnected();
       
    96     }
       
    97     emit q->error(error);
       
    98 }
       
    99 
       
   100 QLocalSocketPrivate::QLocalSocketPrivate() : QIODevicePrivate(),
       
   101        handle(INVALID_HANDLE_VALUE),
       
   102        pipeWriter(0),
       
   103        readBufferMaxSize(0),
       
   104        actualReadBufferSize(0),
       
   105        error(QLocalSocket::UnknownSocketError),
       
   106        readSequenceStarted(false),
       
   107        pendingReadyRead(false),
       
   108        pipeClosed(false),
       
   109        state(QLocalSocket::UnconnectedState)
       
   110 {
       
   111 }
       
   112 
       
   113 QLocalSocketPrivate::~QLocalSocketPrivate()
       
   114 {
       
   115     destroyPipeHandles();
       
   116     CloseHandle(overlapped.hEvent);
       
   117 }
       
   118 
       
   119 void QLocalSocketPrivate::destroyPipeHandles()
       
   120 {
       
   121     if (handle != INVALID_HANDLE_VALUE) {
       
   122         DisconnectNamedPipe(handle);
       
   123         CloseHandle(handle);
       
   124     }
       
   125 }
       
   126 
       
   127 void QLocalSocket::connectToServer(const QString &name, OpenMode openMode)
       
   128 {
       
   129     Q_D(QLocalSocket);
       
   130     if (state() == ConnectedState || state() == ConnectingState)
       
   131         return;
       
   132 
       
   133     d->error = QLocalSocket::UnknownSocketError;
       
   134     d->errorString = QString();
       
   135     d->state = ConnectingState;
       
   136     emit stateChanged(d->state);
       
   137     if (name.isEmpty()) {
       
   138         d->error = QLocalSocket::ServerNotFoundError;
       
   139         setErrorString(QLocalSocket::tr("%1: Invalid name").arg(QLatin1String("QLocalSocket::connectToServer")));
       
   140         d->state = UnconnectedState;
       
   141         emit error(d->error);
       
   142         emit stateChanged(d->state);
       
   143         return;
       
   144     }
       
   145 
       
   146     QString pipePath = QLatin1String("\\\\.\\pipe\\");
       
   147     if (name.startsWith(pipePath))
       
   148         d->fullServerName = name;
       
   149     else
       
   150         d->fullServerName = pipePath + name;
       
   151     // Try to open a named pipe
       
   152     HANDLE localSocket;
       
   153     forever {
       
   154         DWORD permissions = (openMode & QIODevice::ReadOnly) ? GENERIC_READ : 0;
       
   155         permissions |= (openMode & QIODevice::WriteOnly) ? GENERIC_WRITE : 0;
       
   156         localSocket = CreateFile((const wchar_t *)d->fullServerName.utf16(),   // pipe name
       
   157                                  permissions,
       
   158                                  0,              // no sharing
       
   159                                  NULL,           // default security attributes
       
   160                                  OPEN_EXISTING,  // opens existing pipe
       
   161                                  FILE_FLAG_OVERLAPPED,
       
   162                                  NULL);          // no template file
       
   163 
       
   164         if (localSocket != INVALID_HANDLE_VALUE)
       
   165             break;
       
   166         DWORD error = GetLastError();
       
   167         // It is really an error only if it is not ERROR_PIPE_BUSY
       
   168         if (ERROR_PIPE_BUSY != error) {
       
   169             break;
       
   170         }
       
   171 
       
   172         // All pipe instances are busy, so wait until connected or up to 5 seconds.
       
   173         if (!WaitNamedPipe((const wchar_t *)d->fullServerName.utf16(), 5000))
       
   174             break;
       
   175     }
       
   176 
       
   177     if (localSocket == INVALID_HANDLE_VALUE) {
       
   178         d->setErrorString(QLatin1String("QLocalSocket::connectToServer"));
       
   179         d->fullServerName = QString();
       
   180         return;
       
   181     }
       
   182 
       
   183     // we have a valid handle
       
   184     d->serverName = name;
       
   185     if (setSocketDescriptor((quintptr)localSocket, ConnectedState, openMode)) {
       
   186         d->handle = localSocket;
       
   187         emit connected();
       
   188     }
       
   189 }
       
   190 
       
   191 // This is reading from the buffer
       
   192 qint64 QLocalSocket::readData(char *data, qint64 maxSize)
       
   193 {
       
   194     Q_D(QLocalSocket);
       
   195 
       
   196     qint64 readSoFar;
       
   197     // If startAsyncRead() read data, copy it to its destination.
       
   198     if (maxSize == 1 && d->actualReadBufferSize > 0) {
       
   199         *data = d->readBuffer.getChar();
       
   200         d->actualReadBufferSize--;
       
   201         readSoFar = 1;
       
   202     } else {
       
   203         qint64 bytesToRead = qMin(qint64(d->actualReadBufferSize), maxSize);
       
   204         readSoFar = 0;
       
   205         while (readSoFar < bytesToRead) {
       
   206             const char *ptr = d->readBuffer.readPointer();
       
   207             int bytesToReadFromThisBlock = qMin(bytesToRead - readSoFar,
       
   208                                                 qint64(d->readBuffer.nextDataBlockSize()));
       
   209             memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
       
   210             readSoFar += bytesToReadFromThisBlock;
       
   211             d->readBuffer.free(bytesToReadFromThisBlock);
       
   212             d->actualReadBufferSize -= bytesToReadFromThisBlock;
       
   213         }
       
   214     }
       
   215 
       
   216     if (d->pipeClosed) {
       
   217         if (readSoFar == 0) {
       
   218             QTimer::singleShot(0, this, SLOT(_q_pipeClosed()));
       
   219             return -1;  // signal EOF
       
   220         }
       
   221     } else {
       
   222         if (!d->readSequenceStarted)
       
   223             d->startAsyncRead();
       
   224         d->checkReadyRead();
       
   225     }
       
   226 
       
   227     return readSoFar;
       
   228 }
       
   229 
       
   230 /*!
       
   231     \internal
       
   232     Schedules or cancels a readyRead() emission depending on actual data availability
       
   233  */
       
   234 void QLocalSocketPrivate::checkReadyRead()
       
   235 {
       
   236     if (actualReadBufferSize > 0) {
       
   237         if (!pendingReadyRead) {
       
   238             Q_Q(QLocalSocket);
       
   239             QTimer::singleShot(0, q, SLOT(_q_emitReadyRead()));
       
   240             pendingReadyRead = true;
       
   241         }
       
   242     } else {
       
   243         pendingReadyRead = false;
       
   244     }
       
   245 }
       
   246 
       
   247 /*!
       
   248     \internal
       
   249     Reads data from the socket into the readbuffer
       
   250  */
       
   251 void QLocalSocketPrivate::startAsyncRead()
       
   252 {
       
   253     do {
       
   254         DWORD bytesToRead = bytesAvailable();
       
   255         if (bytesToRead == 0) {
       
   256             // There are no bytes in the pipe but we need to
       
   257             // start the overlapped read with some buffer size.
       
   258             bytesToRead = initialReadBufferSize;
       
   259         }
       
   260 
       
   261         if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - readBuffer.size())) {
       
   262             bytesToRead = readBufferMaxSize - readBuffer.size();
       
   263             if (bytesToRead == 0) {
       
   264                 // Buffer is full. User must read data from the buffer
       
   265                 // before we can read more from the pipe.
       
   266                 return;
       
   267             }
       
   268         }
       
   269 
       
   270         char *ptr = readBuffer.reserve(bytesToRead);
       
   271 
       
   272         readSequenceStarted = true;
       
   273         if (ReadFile(handle, ptr, bytesToRead, NULL, &overlapped)) {
       
   274             completeAsyncRead();
       
   275         } else {
       
   276             switch (GetLastError()) {
       
   277                 case ERROR_IO_PENDING:
       
   278                     // This is not an error. We're getting notified, when data arrives.
       
   279                     return;
       
   280                 case ERROR_PIPE_NOT_CONNECTED:
       
   281                     {
       
   282                         // It may happen, that the other side closes the connection directly
       
   283                         // after writing data. Then we must set the appropriate socket state.
       
   284                         pipeClosed = true;
       
   285                         Q_Q(QLocalSocket);
       
   286                         emit q->readChannelFinished();
       
   287                         return;
       
   288                     }
       
   289                 default:
       
   290                     setErrorString(QLatin1String("QLocalSocketPrivate::startAsyncRead"));
       
   291                     return;
       
   292             }
       
   293         }
       
   294     } while (!readSequenceStarted);
       
   295 }
       
   296 
       
   297 /*!
       
   298     \internal
       
   299     Sets the correct size of the read buffer after a read operation.
       
   300     Returns false, if an error occured or the connection dropped.
       
   301  */
       
   302 bool QLocalSocketPrivate::completeAsyncRead()
       
   303 {
       
   304     ResetEvent(overlapped.hEvent);
       
   305     readSequenceStarted = false;
       
   306 
       
   307     DWORD bytesRead;
       
   308     if (!GetOverlappedResult(handle, &overlapped, &bytesRead, TRUE)) {
       
   309         if (GetLastError() != ERROR_PIPE_NOT_CONNECTED)
       
   310             setErrorString(QLatin1String("QLocalSocketPrivate::completeAsyncRead"));
       
   311         return false;
       
   312     }
       
   313 
       
   314     actualReadBufferSize += bytesRead;
       
   315     readBuffer.truncate(actualReadBufferSize);
       
   316     return true;
       
   317 }
       
   318 
       
   319 qint64 QLocalSocket::writeData(const char *data, qint64 maxSize)
       
   320 {
       
   321     Q_D(QLocalSocket);
       
   322     if (!d->pipeWriter) {
       
   323         d->pipeWriter = new QWindowsPipeWriter(d->handle, this);
       
   324         connect(d->pipeWriter, SIGNAL(canWrite()), this, SLOT(_q_canWrite()));
       
   325         connect(d->pipeWriter, SIGNAL(bytesWritten(qint64)), this, SIGNAL(bytesWritten(qint64)));
       
   326         d->pipeWriter->start();
       
   327     }
       
   328     return d->pipeWriter->write(data, maxSize);
       
   329 }
       
   330 
       
   331 void QLocalSocket::abort()
       
   332 {
       
   333     close();
       
   334 }
       
   335 
       
   336 /*!
       
   337     The number of bytes available from the pipe
       
   338   */
       
   339 DWORD QLocalSocketPrivate::bytesAvailable()
       
   340 {
       
   341     Q_Q(QLocalSocket);
       
   342     DWORD bytes;
       
   343     if (PeekNamedPipe(handle, NULL, 0, NULL, &bytes, NULL)) {
       
   344         return bytes;
       
   345     } else {
       
   346         if (!pipeClosed) {
       
   347             pipeClosed = true;
       
   348             emit q->readChannelFinished();
       
   349             QTimer::singleShot(0, q, SLOT(_q_pipeClosed()));
       
   350         }
       
   351     }
       
   352     return 0;
       
   353 }
       
   354 
       
   355 void QLocalSocketPrivate::_q_pipeClosed()
       
   356 {
       
   357     Q_Q(QLocalSocket);
       
   358     q->close();
       
   359 }
       
   360 
       
   361 qint64 QLocalSocket::bytesAvailable() const
       
   362 {
       
   363     Q_D(const QLocalSocket);
       
   364     qint64 available = QIODevice::bytesAvailable();
       
   365     available += (qint64) d->actualReadBufferSize;
       
   366     return available;
       
   367 }
       
   368 
       
   369 qint64 QLocalSocket::bytesToWrite() const
       
   370 {
       
   371     Q_D(const QLocalSocket);
       
   372     return (d->pipeWriter) ? d->pipeWriter->bytesToWrite() : 0;
       
   373 }
       
   374 
       
   375 bool QLocalSocket::canReadLine() const
       
   376 {
       
   377     Q_D(const QLocalSocket);
       
   378     if (state() != ConnectedState)
       
   379         return false;
       
   380     return (QIODevice::canReadLine()
       
   381             || d->readBuffer.indexOf('\n', d->actualReadBufferSize) != -1);
       
   382 }
       
   383 
       
   384 void QLocalSocket::close()
       
   385 {
       
   386     Q_D(QLocalSocket);
       
   387     if (state() == UnconnectedState)
       
   388         return;
       
   389 
       
   390     QIODevice::close();
       
   391     d->state = ClosingState;
       
   392     emit stateChanged(d->state);
       
   393     if (!d->pipeClosed)
       
   394         emit readChannelFinished();
       
   395     d->serverName = QString();
       
   396     d->fullServerName = QString();
       
   397 
       
   398     if (state() != UnconnectedState && bytesToWrite() > 0) {
       
   399         disconnectFromServer();
       
   400         return;
       
   401     }
       
   402     d->readSequenceStarted = false;
       
   403     d->pendingReadyRead = false;
       
   404     d->pipeClosed = false;
       
   405     d->destroyPipeHandles();
       
   406     d->handle = INVALID_HANDLE_VALUE;
       
   407     ResetEvent(d->overlapped.hEvent);
       
   408     d->state = UnconnectedState;
       
   409     emit stateChanged(d->state);
       
   410     emit disconnected();
       
   411     if (d->pipeWriter) {
       
   412         delete d->pipeWriter;
       
   413         d->pipeWriter = 0;
       
   414     }
       
   415 }
       
   416 
       
   417 bool QLocalSocket::flush()
       
   418 {
       
   419     Q_D(QLocalSocket);
       
   420     if (d->pipeWriter)
       
   421         return d->pipeWriter->waitForWrite(0);
       
   422     return false;
       
   423 }
       
   424 
       
   425 void QLocalSocket::disconnectFromServer()
       
   426 {
       
   427     Q_D(QLocalSocket);
       
   428     flush();
       
   429     if (d->pipeWriter && d->pipeWriter->bytesToWrite() != 0) {
       
   430         d->state = QLocalSocket::ClosingState;
       
   431         emit stateChanged(d->state);
       
   432     } else {
       
   433         close();
       
   434     }
       
   435 }
       
   436 
       
   437 QLocalSocket::LocalSocketError QLocalSocket::error() const
       
   438 {
       
   439     Q_D(const QLocalSocket);
       
   440     return d->error;
       
   441 }
       
   442 
       
   443 bool QLocalSocket::setSocketDescriptor(quintptr socketDescriptor,
       
   444               LocalSocketState socketState, OpenMode openMode)
       
   445 {
       
   446     Q_D(QLocalSocket);
       
   447     d->readBuffer.clear();
       
   448     d->actualReadBufferSize = 0;
       
   449     QIODevice::open(openMode);
       
   450     d->handle = (int*)socketDescriptor;
       
   451     d->state = socketState;
       
   452     emit stateChanged(d->state);
       
   453     if (d->state == ConnectedState && openMode.testFlag(QIODevice::ReadOnly)) {
       
   454         d->startAsyncRead();
       
   455         d->checkReadyRead();
       
   456     }
       
   457     return true;
       
   458 }
       
   459 
       
   460 void QLocalSocketPrivate::_q_canWrite()
       
   461 {
       
   462     Q_Q(QLocalSocket);
       
   463     if (state == QLocalSocket::ClosingState)
       
   464         q->close();
       
   465 }
       
   466 
       
   467 void QLocalSocketPrivate::_q_notified()
       
   468 {
       
   469     Q_Q(QLocalSocket);
       
   470     if (!completeAsyncRead()) {
       
   471         pipeClosed = true;
       
   472         emit q->readChannelFinished();
       
   473         return;
       
   474     }
       
   475     startAsyncRead();
       
   476     pendingReadyRead = false;
       
   477     emit q->readyRead();
       
   478 }
       
   479 
       
   480 void QLocalSocketPrivate::_q_emitReadyRead()
       
   481 {
       
   482     if (pendingReadyRead) {
       
   483         Q_Q(QLocalSocket);
       
   484         pendingReadyRead = false;
       
   485         emit q->readyRead();
       
   486     }
       
   487 }
       
   488 
       
   489 quintptr QLocalSocket::socketDescriptor() const
       
   490 {
       
   491     Q_D(const QLocalSocket);
       
   492     return (quintptr)d->handle;
       
   493 }
       
   494 
       
   495 qint64 QLocalSocket::readBufferSize() const
       
   496 {
       
   497     Q_D(const QLocalSocket);
       
   498     return d->readBufferMaxSize;
       
   499 }
       
   500 
       
   501 void QLocalSocket::setReadBufferSize(qint64 size)
       
   502 {
       
   503     Q_D(QLocalSocket);
       
   504     d->readBufferMaxSize = size;
       
   505 }
       
   506 
       
   507 bool QLocalSocket::waitForConnected(int msecs)
       
   508 {
       
   509     Q_UNUSED(msecs);
       
   510     return (state() == ConnectedState);
       
   511 }
       
   512 
       
   513 bool QLocalSocket::waitForDisconnected(int msecs)
       
   514 {
       
   515     Q_D(QLocalSocket);
       
   516     if (state() == UnconnectedState)
       
   517         return false;
       
   518     if (!openMode().testFlag(QIODevice::ReadOnly)) {
       
   519         qWarning("QLocalSocket::waitForDisconnected isn't supported for write only pipes.");
       
   520         return false;
       
   521     }
       
   522     QIncrementalSleepTimer timer(msecs);
       
   523     forever {
       
   524         d->bytesAvailable();    // to check if PeekNamedPipe fails
       
   525         if (d->pipeClosed)
       
   526             close();
       
   527         if (state() == UnconnectedState)
       
   528             return true;
       
   529         Sleep(timer.nextSleepTime());
       
   530         if (timer.hasTimedOut())
       
   531             break;
       
   532     }
       
   533 
       
   534     return false;
       
   535 }
       
   536 
       
   537 bool QLocalSocket::isValid() const
       
   538 {
       
   539     Q_D(const QLocalSocket);
       
   540     if (d->handle == INVALID_HANDLE_VALUE)
       
   541         return false;
       
   542 
       
   543     return PeekNamedPipe(d->handle, NULL, 0, NULL, NULL, NULL);
       
   544 }
       
   545 
       
   546 bool QLocalSocket::waitForReadyRead(int msecs)
       
   547 {
       
   548     Q_D(QLocalSocket);
       
   549 
       
   550     if (bytesAvailable() > 0)
       
   551         return true;
       
   552 
       
   553     if (d->state != QLocalSocket::ConnectedState)
       
   554         return false;
       
   555 
       
   556     Q_ASSERT(d->readSequenceStarted);
       
   557     DWORD result = WaitForSingleObject(d->overlapped.hEvent, msecs == -1 ? INFINITE : msecs);
       
   558     switch (result) {
       
   559         case WAIT_OBJECT_0:
       
   560             d->_q_notified();
       
   561             return true;
       
   562         case WAIT_TIMEOUT:
       
   563             return false;
       
   564     }
       
   565 
       
   566     qWarning("QLocalSocket::waitForReadyRead WaitForSingleObject failed with error code %d.", int(GetLastError()));
       
   567     return false;
       
   568 }
       
   569 
       
   570 bool QLocalSocket::waitForBytesWritten(int msecs)
       
   571 {
       
   572     Q_D(const QLocalSocket);
       
   573     if (!d->pipeWriter)
       
   574         return false;
       
   575 
       
   576     // Wait for the pipe writer to acknowledge that it has
       
   577     // written. This will succeed if either the pipe writer has
       
   578     // already written the data, or if it manages to write data
       
   579     // within the given timeout.
       
   580     return d->pipeWriter->waitForWrite(msecs);
       
   581 }
       
   582 
       
   583 QT_END_NAMESPACE