src/network/socket/qlocalsocket_win.cpp
changeset 0 1918ee327afb
child 3 41300fa6a67c
equal deleted inserted replaced
-1:000000000000 0:1918ee327afb
       
     1 /****************************************************************************
       
     2 **
       
     3 ** Copyright (C) 2009 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 void QLocalSocket::connectToServer(const QString &name, OpenMode openMode)
       
   114 {
       
   115     Q_D(QLocalSocket);
       
   116     if (state() == ConnectedState || state() == ConnectingState)
       
   117         return;
       
   118 
       
   119     d->error = QLocalSocket::UnknownSocketError;
       
   120     d->errorString = QString();
       
   121     d->state = ConnectingState;
       
   122     emit stateChanged(d->state);
       
   123     if (name.isEmpty()) {
       
   124         d->error = QLocalSocket::ServerNotFoundError;
       
   125         setErrorString(QLocalSocket::tr("%1: Invalid name").arg(QLatin1String("QLocalSocket::connectToServer")));
       
   126         d->state = UnconnectedState;
       
   127         emit error(d->error);
       
   128         emit stateChanged(d->state);
       
   129         return;
       
   130     }
       
   131 
       
   132     QString pipePath = QLatin1String("\\\\.\\pipe\\");
       
   133     if (name.startsWith(pipePath))
       
   134         d->fullServerName = name;
       
   135     else
       
   136         d->fullServerName = pipePath + name;
       
   137     // Try to open a named pipe
       
   138     HANDLE localSocket;
       
   139     forever {
       
   140         DWORD permissions = (openMode & QIODevice::ReadOnly) ? GENERIC_READ : 0;
       
   141         permissions |= (openMode & QIODevice::WriteOnly) ? GENERIC_WRITE : 0;
       
   142         localSocket = CreateFile((const wchar_t *)d->fullServerName.utf16(),   // pipe name
       
   143                                  permissions,
       
   144                                  0,              // no sharing
       
   145                                  NULL,           // default security attributes
       
   146                                  OPEN_EXISTING,  // opens existing pipe
       
   147                                  FILE_FLAG_OVERLAPPED,
       
   148                                  NULL);          // no template file
       
   149 
       
   150         if (localSocket != INVALID_HANDLE_VALUE)
       
   151             break;
       
   152         DWORD error = GetLastError();
       
   153         // It is really an error only if it is not ERROR_PIPE_BUSY
       
   154         if (ERROR_PIPE_BUSY != error) {
       
   155             break;
       
   156         }
       
   157 
       
   158         // All pipe instances are busy, so wait until connected or up to 5 seconds.
       
   159         if (!WaitNamedPipe((const wchar_t *)d->fullServerName.utf16(), 5000))
       
   160             break;
       
   161     }
       
   162 
       
   163     if (localSocket == INVALID_HANDLE_VALUE) {
       
   164         d->setErrorString(QLatin1String("QLocalSocket::connectToServer"));
       
   165         d->fullServerName = QString();
       
   166         return;
       
   167     }
       
   168 
       
   169     // we have a valid handle
       
   170     d->serverName = name;
       
   171     if (setSocketDescriptor((quintptr)localSocket, ConnectedState, openMode)) {
       
   172         d->handle = localSocket;
       
   173         emit connected();
       
   174     }
       
   175 }
       
   176 
       
   177 // This is reading from the buffer
       
   178 qint64 QLocalSocket::readData(char *data, qint64 maxSize)
       
   179 {
       
   180     Q_D(QLocalSocket);
       
   181 
       
   182     qint64 readSoFar;
       
   183     // If startAsyncRead() read data, copy it to its destination.
       
   184     if (maxSize == 1 && d->actualReadBufferSize > 0) {
       
   185         *data = d->readBuffer.getChar();
       
   186         d->actualReadBufferSize--;
       
   187         readSoFar = 1;
       
   188     } else {
       
   189         qint64 bytesToRead = qMin(qint64(d->actualReadBufferSize), maxSize);
       
   190         readSoFar = 0;
       
   191         while (readSoFar < bytesToRead) {
       
   192             const char *ptr = d->readBuffer.readPointer();
       
   193             int bytesToReadFromThisBlock = qMin(bytesToRead - readSoFar,
       
   194                                                 qint64(d->readBuffer.nextDataBlockSize()));
       
   195             memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
       
   196             readSoFar += bytesToReadFromThisBlock;
       
   197             d->readBuffer.free(bytesToReadFromThisBlock);
       
   198             d->actualReadBufferSize -= bytesToReadFromThisBlock;
       
   199         }
       
   200     }
       
   201 
       
   202     if (d->pipeClosed) {
       
   203         if (readSoFar == 0) {
       
   204             QTimer::singleShot(0, this, SLOT(_q_pipeClosed()));
       
   205             return -1;  // signal EOF
       
   206         }
       
   207     } else {
       
   208         if (!d->readSequenceStarted)
       
   209             d->startAsyncRead();
       
   210         d->checkReadyRead();
       
   211     }
       
   212 
       
   213     return readSoFar;
       
   214 }
       
   215 
       
   216 /*!
       
   217     \internal
       
   218     Schedules or cancels a readyRead() emission depending on actual data availability
       
   219  */
       
   220 void QLocalSocketPrivate::checkReadyRead()
       
   221 {
       
   222     if (actualReadBufferSize > 0) {
       
   223         if (!pendingReadyRead) {
       
   224             Q_Q(QLocalSocket);
       
   225             QTimer::singleShot(0, q, SLOT(_q_emitReadyRead()));
       
   226             pendingReadyRead = true;
       
   227         }
       
   228     } else {
       
   229         pendingReadyRead = false;
       
   230     }
       
   231 }
       
   232 
       
   233 /*!
       
   234     \internal
       
   235     Reads data from the socket into the readbuffer
       
   236  */
       
   237 void QLocalSocketPrivate::startAsyncRead()
       
   238 {
       
   239     do {
       
   240         DWORD bytesToRead = bytesAvailable();
       
   241         if (bytesToRead == 0) {
       
   242             // There are no bytes in the pipe but we need to
       
   243             // start the overlapped read with some buffer size.
       
   244             bytesToRead = initialReadBufferSize;
       
   245         }
       
   246 
       
   247         if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - readBuffer.size())) {
       
   248             bytesToRead = readBufferMaxSize - readBuffer.size();
       
   249             if (bytesToRead == 0) {
       
   250                 // Buffer is full. User must read data from the buffer
       
   251                 // before we can read more from the pipe.
       
   252                 return;
       
   253             }
       
   254         }
       
   255 
       
   256         char *ptr = readBuffer.reserve(bytesToRead);
       
   257 
       
   258         readSequenceStarted = true;
       
   259         if (ReadFile(handle, ptr, bytesToRead, NULL, &overlapped)) {
       
   260             completeAsyncRead();
       
   261         } else {
       
   262             switch (GetLastError()) {
       
   263                 case ERROR_IO_PENDING:
       
   264                     // This is not an error. We're getting notified, when data arrives.
       
   265                     return;
       
   266                 case ERROR_PIPE_NOT_CONNECTED:
       
   267                     {
       
   268                         // It may happen, that the other side closes the connection directly
       
   269                         // after writing data. Then we must set the appropriate socket state.
       
   270                         pipeClosed = true;
       
   271                         Q_Q(QLocalSocket);
       
   272                         emit q->readChannelFinished();
       
   273                         return;
       
   274                     }
       
   275                 default:
       
   276                     setErrorString(QLatin1String("QLocalSocketPrivate::startAsyncRead"));
       
   277                     return;
       
   278             }
       
   279         }
       
   280     } while (!readSequenceStarted);
       
   281 }
       
   282 
       
   283 /*!
       
   284     \internal
       
   285     Sets the correct size of the read buffer after a read operation.
       
   286     Returns false, if an error occured or the connection dropped.
       
   287  */
       
   288 bool QLocalSocketPrivate::completeAsyncRead()
       
   289 {
       
   290     ResetEvent(overlapped.hEvent);
       
   291     readSequenceStarted = false;
       
   292 
       
   293     DWORD bytesRead;
       
   294     if (!GetOverlappedResult(handle, &overlapped, &bytesRead, TRUE)) {
       
   295         if (GetLastError() != ERROR_PIPE_NOT_CONNECTED)
       
   296             setErrorString(QLatin1String("QLocalSocketPrivate::completeAsyncRead"));
       
   297         return false;
       
   298     }
       
   299 
       
   300     actualReadBufferSize += bytesRead;
       
   301     readBuffer.truncate(actualReadBufferSize);
       
   302     return true;
       
   303 }
       
   304 
       
   305 qint64 QLocalSocket::writeData(const char *data, qint64 maxSize)
       
   306 {
       
   307     Q_D(QLocalSocket);
       
   308     if (!d->pipeWriter) {
       
   309         d->pipeWriter = new QWindowsPipeWriter(d->handle, this);
       
   310         connect(d->pipeWriter, SIGNAL(canWrite()), this, SLOT(_q_canWrite()));
       
   311         connect(d->pipeWriter, SIGNAL(bytesWritten(qint64)), this, SIGNAL(bytesWritten(qint64)));
       
   312         d->pipeWriter->start();
       
   313     }
       
   314     return d->pipeWriter->write(data, maxSize);
       
   315 }
       
   316 
       
   317 void QLocalSocket::abort()
       
   318 {
       
   319     close();
       
   320 }
       
   321 
       
   322 /*!
       
   323     The number of bytes available from the pipe
       
   324   */
       
   325 DWORD QLocalSocketPrivate::bytesAvailable()
       
   326 {
       
   327     Q_Q(QLocalSocket);
       
   328     DWORD bytes;
       
   329     if (PeekNamedPipe(handle, NULL, 0, NULL, &bytes, NULL)) {
       
   330         return bytes;
       
   331     } else {
       
   332         if (!pipeClosed) {
       
   333             pipeClosed = true;
       
   334             emit q->readChannelFinished();
       
   335             QTimer::singleShot(0, q, SLOT(_q_pipeClosed()));
       
   336         }
       
   337     }
       
   338     return 0;
       
   339 }
       
   340 
       
   341 void QLocalSocketPrivate::_q_pipeClosed()
       
   342 {
       
   343     Q_Q(QLocalSocket);
       
   344     q->close();
       
   345 }
       
   346 
       
   347 qint64 QLocalSocket::bytesAvailable() const
       
   348 {
       
   349     Q_D(const QLocalSocket);
       
   350     qint64 available = QIODevice::bytesAvailable();
       
   351     available += (qint64) d->actualReadBufferSize;
       
   352     return available;
       
   353 }
       
   354 
       
   355 qint64 QLocalSocket::bytesToWrite() const
       
   356 {
       
   357     Q_D(const QLocalSocket);
       
   358     return (d->pipeWriter) ? d->pipeWriter->bytesToWrite() : 0;
       
   359 }
       
   360 
       
   361 bool QLocalSocket::canReadLine() const
       
   362 {
       
   363     Q_D(const QLocalSocket);
       
   364     if (state() != ConnectedState)
       
   365         return false;
       
   366     return (d->readBuffer.indexOf('\n') != -1 || QIODevice::canReadLine());
       
   367 }
       
   368 
       
   369 void QLocalSocket::close()
       
   370 {
       
   371     Q_D(QLocalSocket);
       
   372     if (state() == UnconnectedState)
       
   373         return;
       
   374 
       
   375     QIODevice::close();
       
   376     d->state = ClosingState;
       
   377     emit stateChanged(d->state);
       
   378     if (!d->pipeClosed)
       
   379         emit readChannelFinished();
       
   380     d->serverName = QString();
       
   381     d->fullServerName = QString();
       
   382 
       
   383     if (state() != UnconnectedState && bytesToWrite() > 0) {
       
   384         disconnectFromServer();
       
   385         return;
       
   386     }
       
   387     d->readSequenceStarted = false;
       
   388     d->pendingReadyRead = false;
       
   389     d->pipeClosed = false;
       
   390     DisconnectNamedPipe(d->handle);
       
   391     CloseHandle(d->handle);
       
   392     d->handle = INVALID_HANDLE_VALUE;
       
   393     ResetEvent(d->overlapped.hEvent);
       
   394     d->state = UnconnectedState;
       
   395     emit stateChanged(d->state);
       
   396     emit disconnected();
       
   397     if (d->pipeWriter) {
       
   398         delete d->pipeWriter;
       
   399         d->pipeWriter = 0;
       
   400     }
       
   401 }
       
   402 
       
   403 bool QLocalSocket::flush()
       
   404 {
       
   405     Q_D(QLocalSocket);
       
   406     if (d->pipeWriter)
       
   407         return d->pipeWriter->waitForWrite(0);
       
   408     return false;
       
   409 }
       
   410 
       
   411 void QLocalSocket::disconnectFromServer()
       
   412 {
       
   413     Q_D(QLocalSocket);
       
   414     flush();
       
   415     if (d->pipeWriter && d->pipeWriter->bytesToWrite() != 0) {
       
   416         d->state = QLocalSocket::ClosingState;
       
   417         emit stateChanged(d->state);
       
   418     } else {
       
   419         close();
       
   420     }
       
   421 }
       
   422 
       
   423 QLocalSocket::LocalSocketError QLocalSocket::error() const
       
   424 {
       
   425     Q_D(const QLocalSocket);
       
   426     return d->error;
       
   427 }
       
   428 
       
   429 bool QLocalSocket::setSocketDescriptor(quintptr socketDescriptor,
       
   430               LocalSocketState socketState, OpenMode openMode)
       
   431 {
       
   432     Q_D(QLocalSocket);
       
   433     d->readBuffer.clear();
       
   434     d->actualReadBufferSize = 0;
       
   435     QIODevice::open(openMode);
       
   436     d->handle = (int*)socketDescriptor;
       
   437     d->state = socketState;
       
   438     emit stateChanged(d->state);
       
   439     if (d->state == ConnectedState && openMode.testFlag(QIODevice::ReadOnly)) {
       
   440         d->startAsyncRead();
       
   441         d->checkReadyRead();
       
   442     }
       
   443     return true;
       
   444 }
       
   445 
       
   446 void QLocalSocketPrivate::_q_canWrite()
       
   447 {
       
   448     Q_Q(QLocalSocket);
       
   449     if (state == QLocalSocket::ClosingState)
       
   450         q->close();
       
   451 }
       
   452 
       
   453 void QLocalSocketPrivate::_q_notified()
       
   454 {
       
   455     Q_Q(QLocalSocket);
       
   456     if (!completeAsyncRead()) {
       
   457         pipeClosed = true;
       
   458         emit q->readChannelFinished();
       
   459         return;
       
   460     }
       
   461     startAsyncRead();
       
   462     pendingReadyRead = false;
       
   463     emit q->readyRead();
       
   464 }
       
   465 
       
   466 void QLocalSocketPrivate::_q_emitReadyRead()
       
   467 {
       
   468     if (pendingReadyRead) {
       
   469         Q_Q(QLocalSocket);
       
   470         pendingReadyRead = false;
       
   471         emit q->readyRead();
       
   472     }
       
   473 }
       
   474 
       
   475 quintptr QLocalSocket::socketDescriptor() const
       
   476 {
       
   477     Q_D(const QLocalSocket);
       
   478     return (quintptr)d->handle;
       
   479 }
       
   480 
       
   481 qint64 QLocalSocket::readBufferSize() const
       
   482 {
       
   483     Q_D(const QLocalSocket);
       
   484     return d->readBufferMaxSize;
       
   485 }
       
   486 
       
   487 void QLocalSocket::setReadBufferSize(qint64 size)
       
   488 {
       
   489     Q_D(QLocalSocket);
       
   490     d->readBufferMaxSize = size;
       
   491 }
       
   492 
       
   493 bool QLocalSocket::waitForConnected(int msecs)
       
   494 {
       
   495     Q_UNUSED(msecs);
       
   496     return (state() == ConnectedState);
       
   497 }
       
   498 
       
   499 bool QLocalSocket::waitForDisconnected(int msecs)
       
   500 {
       
   501     Q_D(QLocalSocket);
       
   502     if (state() == UnconnectedState)
       
   503         return false;
       
   504     if (!openMode().testFlag(QIODevice::ReadOnly)) {
       
   505         qWarning("QLocalSocket::waitForDisconnected isn't supported for write only pipes.");
       
   506         return false;
       
   507     }
       
   508     QIncrementalSleepTimer timer(msecs);
       
   509     forever {
       
   510         d->bytesAvailable();    // to check if PeekNamedPipe fails
       
   511         if (d->pipeClosed)
       
   512             close();
       
   513         if (state() == UnconnectedState)
       
   514             return true;
       
   515         Sleep(timer.nextSleepTime());
       
   516         if (timer.hasTimedOut())
       
   517             break;
       
   518     }
       
   519 
       
   520     return false;
       
   521 }
       
   522 
       
   523 bool QLocalSocket::isValid() const
       
   524 {
       
   525     Q_D(const QLocalSocket);
       
   526     return (d->handle != INVALID_HANDLE_VALUE);
       
   527 }
       
   528 
       
   529 bool QLocalSocket::waitForReadyRead(int msecs)
       
   530 {
       
   531     Q_D(QLocalSocket);
       
   532 
       
   533     if (bytesAvailable() > 0)
       
   534         return true;
       
   535 
       
   536     if (d->state != QLocalSocket::ConnectedState)
       
   537         return false;
       
   538 
       
   539     Q_ASSERT(d->readSequenceStarted);
       
   540     DWORD result = WaitForSingleObject(d->overlapped.hEvent, msecs == -1 ? INFINITE : msecs);
       
   541     switch (result) {
       
   542         case WAIT_OBJECT_0:
       
   543             d->_q_notified();
       
   544             return true;
       
   545         case WAIT_TIMEOUT:
       
   546             return false;
       
   547     }
       
   548 
       
   549     qWarning("QLocalSocket::waitForReadyRead WaitForSingleObject failed with error code %d.", int(GetLastError()));
       
   550     return false;
       
   551 }
       
   552 
       
   553 bool QLocalSocket::waitForBytesWritten(int msecs)
       
   554 {
       
   555     Q_D(const QLocalSocket);
       
   556     if (!d->pipeWriter)
       
   557         return false;
       
   558 
       
   559     // Wait for the pipe writer to acknowledge that it has
       
   560     // written. This will succeed if either the pipe writer has
       
   561     // already written the data, or if it manages to write data
       
   562     // within the given timeout.
       
   563     return d->pipeWriter->waitForWrite(msecs);
       
   564 }
       
   565 
       
   566 QT_END_NAMESPACE