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);
123 qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
124 QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
129 bool QtLocalPeer::sendMessage(const QString &message, int timeout)
136 for(int i = 0; i < 2; i++) {
137 // Try twice, in case the other instance is just starting up
138 socket.connectToServer(socketName);
139 connOk = socket.waitForConnected(timeout/2);
143 #if defined(Q_OS_WIN)
146 struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
147 nanosleep(&ts, NULL);
153 QByteArray uMsg(message.toUtf8());
154 QDataStream ds(&socket);
155 ds.writeBytes(uMsg.constData(), uMsg.size());
156 bool res = socket.waitForBytesWritten(timeout);
158 res &= socket.waitForReadyRead(timeout); // wait for ack
160 res &= (socket.read(qstrlen(ack)) == ack);
166 void QtLocalPeer::receiveConnection()
168 QLocalSocket* socket = server->nextPendingConnection();
172 while (socket->bytesAvailable() < (int)sizeof(quint32))
173 socket->waitForReadyRead();
174 QDataStream ds(socket);
178 uMsg.resize(remaining);
180 char* uMsgBuf = uMsg.data();
182 got = ds.readRawData(uMsgBuf, remaining);
185 } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
187 qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
191 QString message(QString::fromUtf8(uMsg));
192 socket->write(ack, qstrlen(ack));
193 socket->waitForBytesWritten(1000);
194 socket->waitForDisconnected(1000); // make sure client reads ack
196 emit messageReceived(message); //### (might take a long time to return)