1 /****************************************************************************
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the Qt Solutions component.
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
14 ** * Redistributions of source code must retain the above copyright
15 ** notice, this list of conditions and the following disclaimer.
16 ** * Redistributions in binary form must reproduce the above copyright
17 ** notice, this list of conditions and the following disclaimer in
18 ** the documentation and/or other materials provided with the
20 ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
21 ** of its contributors may be used to endorse or promote products derived
22 ** from this software without specific prior written permission.
25 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
39 ****************************************************************************/
42 #include "qtlocalpeer.h"
43 #include <QCoreApplication>
45 #include <QDataStream>
49 #include <qt_windows.h>
50 typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
51 static PProcessIdToSessionId pProcessIdToSessionId = 0;
53 #if defined(Q_OS_UNIX)
54 #include <sys/types.h>
59 namespace QtLP_Private {
60 #include "qtlockedfile.cpp"
62 #include "qtlockedfile_win.cpp"
64 #include "qtlockedfile_unix.cpp"
68 const char* QtLocalPeer::ack = "ack";
70 QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
71 : QObject(parent), id(appId)
75 id = QCoreApplication::applicationFilePath();
79 prefix = id.section(QLatin1Char('/'), -1);
81 prefix.remove(QRegExp("[^a-zA-Z]"));
84 QByteArray idc = id.toUtf8();
85 quint16 idNum = qChecksum(idc.constData(), idc.size());
86 socketName = QLatin1String("qtsingleapp-") + prefix
87 + QLatin1Char('-') + QString::number(idNum, 16);
90 if (!pProcessIdToSessionId) {
91 QLibrary lib("kernel32");
92 pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
94 if (pProcessIdToSessionId) {
96 pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
97 socketName += QLatin1Char('-') + QString::number(sessionId, 16);
100 socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
103 server = new QLocalServer(this);
104 QString lockName = QDir(QDir::tempPath()).absolutePath()
105 + QLatin1Char('/') + socketName
106 + QLatin1String("-lockfile");
107 lockFile.setFileName(lockName);
108 lockFile.open(QIODevice::ReadWrite);
113 bool QtLocalPeer::isClient()
115 if (lockFile.isLocked())
118 if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))
121 bool res = server->listen(socketName);
122 #if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0))
124 if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {
125 QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);
126 res = server->listen(socketName);
130 qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
131 QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
136 bool QtLocalPeer::sendMessage(const QString &message, int timeout)
143 for(int i = 0; i < 2; i++) {
144 // Try twice, in case the other instance is just starting up
145 socket.connectToServer(socketName);
146 connOk = socket.waitForConnected(timeout/2);
150 #if defined(Q_OS_WIN)
153 struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
154 nanosleep(&ts, NULL);
160 QByteArray uMsg(message.toUtf8());
161 QDataStream ds(&socket);
162 ds.writeBytes(uMsg.constData(), uMsg.size());
163 bool res = socket.waitForBytesWritten(timeout);
165 res &= socket.waitForReadyRead(timeout); // wait for ack
167 res &= (socket.read(qstrlen(ack)) == ack);
173 void QtLocalPeer::receiveConnection()
175 QLocalSocket* socket = server->nextPendingConnection();
179 while (socket->bytesAvailable() < (int)sizeof(quint32))
180 socket->waitForReadyRead();
181 QDataStream ds(socket);
185 uMsg.resize(remaining);
187 char* uMsgBuf = uMsg.data();
189 got = ds.readRawData(uMsgBuf, remaining);
192 } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
194 qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
198 QString message(QString::fromUtf8(uMsg));
199 socket->write(ack, qstrlen(ack));
200 socket->waitForBytesWritten(1000);
201 socket->waitForDisconnected(1000); // make sure client reads ack
203 emit messageReceived(message); //### (might take a long time to return)