diff options
Diffstat (limited to 'src/network/socket/qlocalsocket_unix.cpp')
-rw-r--r-- | src/network/socket/qlocalsocket_unix.cpp | 216 |
1 files changed, 141 insertions, 75 deletions
diff --git a/src/network/socket/qlocalsocket_unix.cpp b/src/network/socket/qlocalsocket_unix.cpp index 6fd17a6213..af0dc988af 100644 --- a/src/network/socket/qlocalsocket_unix.cpp +++ b/src/network/socket/qlocalsocket_unix.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtNetwork module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qlocalsocket.h" #include "qlocalsocket_p.h" @@ -49,22 +13,51 @@ #include <errno.h> #include <qdir.h> +#include <qdeadlinetimer.h> #include <qdebug.h> -#include <qelapsedtimer.h> +#include <qstringconverter.h> #ifdef Q_OS_VXWORKS # include <selectLib.h> #endif +using namespace std::chrono_literals; + #define QT_CONNECT_TIMEOUT 30000 QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + +namespace { +// determine the full server path +static QString pathNameForConnection(const QString &connectingName, + QLocalSocket::SocketOptions options) +{ + if (options.testFlag(QLocalSocket::AbstractNamespaceOption) + || connectingName.startsWith(u'/')) { + return connectingName; + } + + return QDir::tempPath() + u'/' + connectingName; +} + +static QLocalSocket::SocketOptions optionsForPlatform(QLocalSocket::SocketOptions srcOptions) +{ + // For OS that does not support abstract namespace the AbstractNamespaceOption + // option is cleared. + if (!PlatformSupportsAbstractNamespace) + return QLocalSocket::NoOptions; + return srcOptions; +} +} + QLocalSocketPrivate::QLocalSocketPrivate() : QIODevicePrivate(), delayConnect(nullptr), connectTimer(nullptr), connectingSocket(-1), - state(QLocalSocket::UnconnectedState) + state(QLocalSocket::UnconnectedState), + socketOptions(QLocalSocket::NoOptions) { } @@ -72,7 +65,6 @@ void QLocalSocketPrivate::init() { Q_Q(QLocalSocket); // QIODevice signals - q->connect(&unixSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose())); q->connect(&unixSocket, SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64))); q->connect(&unixSocket, SIGNAL(readyRead()), q, SIGNAL(readyRead())); @@ -90,7 +82,7 @@ void QLocalSocketPrivate::init() void QLocalSocketPrivate::_q_errorOccurred(QAbstractSocket::SocketError socketError) { Q_Q(QLocalSocket); - QString function = QLatin1String("QLocalSocket"); + QString function = "QLocalSocket"_L1; QLocalSocket::LocalSocketError error = (QLocalSocket::LocalSocketError)socketError; QString errorString = generateErrorString(error, function); q->setErrorString(errorString); @@ -220,7 +212,7 @@ void QLocalSocket::connectToServer(OpenMode openMode) { Q_D(QLocalSocket); if (state() == ConnectedState || state() == ConnectingState) { - QString errorString = d->generateErrorString(QLocalSocket::OperationError, QLatin1String("QLocalSocket::connectToserver")); + QString errorString = d->generateErrorString(QLocalSocket::OperationError, "QLocalSocket::connectToserver"_L1); setErrorString(errorString); emit errorOccurred(QLocalSocket::OperationError); return; @@ -232,15 +224,13 @@ void QLocalSocket::connectToServer(OpenMode openMode) emit stateChanged(d->state); if (d->serverName.isEmpty()) { - d->setErrorAndEmit(ServerNotFoundError, - QLatin1String("QLocalSocket::connectToServer")); + d->setErrorAndEmit(ServerNotFoundError, "QLocalSocket::connectToServer"_L1); return; } // create the socket if (-1 == (d->connectingSocket = qt_safe_socket(PF_UNIX, SOCK_STREAM, 0, O_NONBLOCK))) { - d->setErrorAndEmit(UnsupportedSocketOperationError, - QLatin1String("QLocalSocket::connectToServer")); + d->setErrorAndEmit(UnsupportedSocketOperationError, "QLocalSocket::connectToServer"_L1); return; } @@ -261,28 +251,34 @@ void QLocalSocket::connectToServer(OpenMode openMode) void QLocalSocketPrivate::_q_connectToSocket() { Q_Q(QLocalSocket); - QString connectingPathName; - - // determine the full server path - if (connectingName.startsWith(QLatin1Char('/'))) { - connectingPathName = connectingName; - } else { - connectingPathName = QDir::tempPath(); - connectingPathName += QLatin1Char('/') + connectingName; - } + QLocalSocket::SocketOptions options = optionsForPlatform(socketOptions); + const QString connectingPathName = pathNameForConnection(connectingName, options); const QByteArray encodedConnectingPathName = QFile::encodeName(connectingPathName); - struct sockaddr_un name; - name.sun_family = PF_UNIX; - if (sizeof(name.sun_path) < (uint)encodedConnectingPathName.size() + 1) { - QString function = QLatin1String("QLocalSocket::connectToServer"); + struct ::sockaddr_un addr; + addr.sun_family = PF_UNIX; + memset(addr.sun_path, 0, sizeof(addr.sun_path)); + + // for abstract socket add 2 to length, to take into account trailing AND leading null + constexpr unsigned int extraCharacters = PlatformSupportsAbstractNamespace ? 2 : 1; + + if (sizeof(addr.sun_path) < static_cast<size_t>(encodedConnectingPathName.size() + extraCharacters)) { + QString function = "QLocalSocket::connectToServer"_L1; setErrorAndEmit(QLocalSocket::ServerNotFoundError, function); return; } - ::memcpy(name.sun_path, encodedConnectingPathName.constData(), - encodedConnectingPathName.size() + 1); - if (-1 == qt_safe_connect(connectingSocket, (struct sockaddr *)&name, sizeof(name))) { - QString function = QLatin1String("QLocalSocket::connectToServer"); + + QT_SOCKLEN_T addrSize = sizeof(::sockaddr_un); + if (options.testFlag(QLocalSocket::AbstractNamespaceOption)) { + ::memcpy(addr.sun_path + 1, encodedConnectingPathName.constData(), + encodedConnectingPathName.size() + 1); + addrSize = offsetof(::sockaddr_un, sun_path) + encodedConnectingPathName.size() + 1; + } else { + ::memcpy(addr.sun_path, encodedConnectingPathName.constData(), + encodedConnectingPathName.size() + 1); + } + if (-1 == qt_safe_connect(connectingSocket, (struct sockaddr *)&addr, addrSize)) { + QString function = "QLocalSocket::connectToServer"_L1; switch (errno) { case EINVAL: @@ -327,10 +323,10 @@ void QLocalSocketPrivate::_q_connectToSocket() fullServerName = connectingPathName; if (unixSocket.setSocketDescriptor(connectingSocket, QAbstractSocket::ConnectedState, connectingOpenMode)) { - q->QIODevice::open(connectingOpenMode | QIODevice::Unbuffered); + q->QIODevice::open(connectingOpenMode); q->emit connected(); } else { - QString function = QLatin1String("QLocalSocket::connectToServer"); + QString function = "QLocalSocket::connectToServer"_L1; setErrorAndEmit(QLocalSocket::UnknownSocketError, function); } connectingSocket = -1; @@ -359,10 +355,69 @@ bool QLocalSocket::setSocketDescriptor(qintptr socketDescriptor, } QIODevice::open(openMode); d->state = socketState; + d->describeSocket(socketDescriptor); return d->unixSocket.setSocketDescriptor(socketDescriptor, newSocketState, openMode); } +void QLocalSocketPrivate::describeSocket(qintptr socketDescriptor) +{ + bool abstractAddress = false; + + struct ::sockaddr_un addr; + QT_SOCKLEN_T len = sizeof(addr); + memset(&addr, 0, sizeof(addr)); + const int getpeernameStatus = ::getpeername(socketDescriptor, (sockaddr *)&addr, &len); + if (getpeernameStatus != 0 || len == offsetof(sockaddr_un, sun_path)) { + // this is the case when we call it from QLocalServer, then there is no peername + len = sizeof(addr); + if (::getsockname(socketDescriptor, (sockaddr *)&addr, &len) != 0) + return; + } + if (parseSockaddr(addr, static_cast<uint>(len), fullServerName, serverName, abstractAddress)) { + QLocalSocket::SocketOptions options = socketOptions.value(); + socketOptions = options.setFlag(QLocalSocket::AbstractNamespaceOption, abstractAddress); + } +} + +bool QLocalSocketPrivate::parseSockaddr(const struct ::sockaddr_un &addr, + uint len, + QString &fullServerName, + QString &serverName, + bool &abstractNamespace) +{ + if (len <= offsetof(::sockaddr_un, sun_path)) + return false; + len -= offsetof(::sockaddr_un, sun_path); + // check for abstract socket address + abstractNamespace = PlatformSupportsAbstractNamespace + && (addr.sun_family == PF_UNIX && addr.sun_path[0] == 0); + QStringDecoder toUtf16(QStringDecoder::System, QStringDecoder::Flag::Stateless); + // An abstract socket address can be arbitrary binary. To properly handle such a case, + // we'd have to add new access functions for this very specific case. Instead, we just + // attempt to decode it according to OS text encoding. If it fails we ignore the result. + QByteArrayView textData(addr.sun_path + (abstractNamespace ? 1 : 0), + len - (abstractNamespace ? 1 : 0)); + QString name = toUtf16(textData); + if (!name.isEmpty() && !toUtf16.hasError()) { + //conversion encodes the trailing zeros. So, in case of non-abstract namespace we + //chop them off as \0 character is not allowed in filenames + if (!abstractNamespace && (name.at(name.size() - 1) == QChar::fromLatin1('\0'))) { + int truncPos = name.size() - 1; + while (truncPos > 0 && name.at(truncPos - 1) == QChar::fromLatin1('\0')) + truncPos--; + name.truncate(truncPos); + } + fullServerName = name; + serverName = abstractNamespace + ? name + : fullServerName.mid(fullServerName.lastIndexOf(u'/') + 1); + if (serverName.isEmpty()) + serverName = fullServerName; + } + return true; +} + void QLocalSocketPrivate::_q_abortConnectionAttempt() { Q_Q(QLocalSocket); @@ -393,6 +448,16 @@ qint64 QLocalSocket::readData(char *data, qint64 c) return d->unixSocket.read(data, c); } +qint64 QLocalSocket::readLineData(char *data, qint64 maxSize) +{ + if (!maxSize) + return 0; + + // QIODevice::readLine() reserves space for the trailing '\0' byte, + // so we must read 'maxSize + 1' bytes. + return d_func()->unixSocket.readLine(data, maxSize + 1); +} + qint64 QLocalSocket::skipData(qint64 maxSize) { return d_func()->unixSocket.skip(maxSize); @@ -408,6 +473,7 @@ void QLocalSocket::abort() { Q_D(QLocalSocket); d->unixSocket.abort(); + close(); } qint64 QLocalSocket::bytesAvailable() const @@ -431,6 +497,8 @@ bool QLocalSocket::canReadLine() const void QLocalSocket::close() { Q_D(QLocalSocket); + + QIODevice::close(); d->unixSocket.close(); d->cancelDelayedConnect(); if (d->connectingSocket != -1) @@ -440,7 +508,6 @@ void QLocalSocket::close() d->connectingOpenMode = { }; d->serverName.clear(); d->fullServerName.clear(); - QIODevice::close(); } bool QLocalSocket::waitForBytesWritten(int msecs) @@ -519,21 +586,20 @@ bool QLocalSocket::waitForConnected(int msec) if (state() != ConnectingState) return (state() == ConnectedState); - QElapsedTimer timer; - timer.start(); - pollfd pfd = qt_make_pollfd(d->connectingSocket, POLLIN); - do { - const int timeout = (msec > 0) ? qMax(msec - timer.elapsed(), Q_INT64_C(0)) : msec; - const int result = qt_poll_msecs(&pfd, 1, timeout); + QDeadlineTimer deadline{msec}; + auto remainingTime = deadline.remainingTimeAsDuration(); + do { + const int result = qt_safe_poll(&pfd, 1, deadline); if (result == -1) d->setErrorAndEmit(QLocalSocket::UnknownSocketError, - QLatin1String("QLocalSocket::waitForConnected")); + "QLocalSocket::waitForConnected"_L1); else if (result > 0) d->_q_connectToSocket(); - } while (state() == ConnectingState && !timer.hasExpired(msec)); + } while (state() == ConnectingState + && (remainingTime = deadline.remainingTimeAsDuration()) > 0ns); return (state() == ConnectedState); } |