1 /****************************************************************************
2 **
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the Qt Solutions component.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
10 **
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
13 ** met:
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
19 ** distribution.
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.
23 **
24 **
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."
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40
41
42 #include "qtlocalpeer.h"
43 #include <QCoreApplication>
44 #include <QDataStream>
45 #include <QTime>
46
47 #include "../config.h"
48 #if defined(Q_OS_LINUX) && !defined(DISABLE_DBUS)
49 #define USE_DBUS
50 #endif
51
52 #if defined(Q_OS_WIN)
53 #include <QLibrary>
54 #include <qt_windows.h>
55 typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
56 static PProcessIdToSessionId pProcessIdToSessionId = 0;
57 #endif
58 #if defined(Q_OS_UNIX)
59 #include <sys/types.h>
60 #include <time.h>
61 #include <unistd.h>
62 #endif
63
64 namespace QtLP_Private {
65 #include "qtlockedfile.cpp"
66 #if defined(Q_OS_WIN)
67 #include "qtlockedfile_win.cpp"
68 #else
69 #include "qtlockedfile_unix.cpp"
70 #endif
71 }
72
73 #ifdef USE_DBUS
74 #include <QDBusConnection>
75 #include <QDBusConnectionInterface>
76 #include <QDBusAbstractAdaptor>
77
78 class QtSingleAppDBusInterface : public QDBusAbstractAdaptor
79 {
80 Q_OBJECT
81 Q_CLASSINFO("D-Bus Interface", "org.kde.QtSingleApplication")
82
83 public:
QtSingleAppDBusInterface(QObject * parent)84 explicit QtSingleAppDBusInterface(QObject *parent)
85 : QDBusAbstractAdaptor(parent)
86 {
87 }
88
89 public Q_SLOTS:
SendMessage(const QString & message)90 void SendMessage(const QString &message)
91 {
92 Q_EMIT messageReceived(message);
93 }
94
95 Q_SIGNALS:
96 void messageReceived(const QString &message);
97 };
98 #endif
99
100 const char* QtLocalPeer::ack = "ack";
101
QtLocalPeer(QObject * parent,const QString & appId)102 QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
103 : QObject(parent), id(appId)
104 {
105 QString prefix = id;
106 if (id.isEmpty()) {
107 id = QCoreApplication::applicationFilePath();
108 #if defined(Q_OS_WIN)
109 id = id.toLower();
110 #endif
111 prefix = id.section(QLatin1Char('/'), -1);
112 }
113 prefix.remove(QRegExp("[^a-zA-Z]"));
114 prefix.truncate(6);
115
116 QByteArray idc = id.toUtf8();
117 quint16 idNum = qChecksum(idc.constData(), idc.size());
118 socketName = QLatin1String("qtsingleapp-") + prefix
119 + QLatin1Char('-') + QString::number(idNum, 16);
120
121 #if defined(Q_OS_WIN)
122 if (!pProcessIdToSessionId) {
123 QLibrary lib("kernel32");
124 pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
125 }
126 if (pProcessIdToSessionId) {
127 DWORD sessionId = 0;
128 pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
129 socketName += QLatin1Char('-') + QString::number(sessionId, 16);
130 }
131 #else
132 socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
133 #endif
134
135 #ifdef USE_DBUS
136 if (!QDBusConnection::sessionBus().isConnected()) {
137 qCritical("Failed to connect to session bus!");
138 }
139 m_dbusRegistered = QDBusConnection::sessionBus().registerService(id);
140 if (m_dbusRegistered) {
141 QtSingleAppDBusInterface *iface = new QtSingleAppDBusInterface(this);
142 connect(iface, &QtSingleAppDBusInterface::messageReceived, this, &QtLocalPeer::messageReceived);
143 QDBusConnection::sessionBus().registerObject(QStringLiteral("/"), this);
144 }
145 #else
146 server = new QLocalServer(this);
147 QString lockName = QDir(QDir::tempPath()).absolutePath()
148 + QLatin1Char('/') + socketName
149 + QLatin1String("-lockfile");
150 lockFile.setFileName(lockName);
151 lockFile.open(QIODevice::ReadWrite);
152 #endif
153 }
154
155
156
isClient()157 bool QtLocalPeer::isClient()
158 {
159 #ifdef USE_DBUS
160 if (m_dbusRegistered) {
161 return false;
162 }
163 return QDBusConnection::sessionBus().interface()->isServiceRegistered(id).value();
164 #else
165 if (lockFile.isLocked())
166 return false;
167
168 if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))
169 return true;
170
171 bool res = server->listen(socketName);
172 #if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0))
173 // ### Workaround
174 if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {
175 QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);
176 res = server->listen(socketName);
177 }
178 #endif
179 if (!res)
180 qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
181 QObject::connect(server, &QLocalServer::newConnection, this, &QtLocalPeer::receiveConnection);
182 return false;
183 #endif
184 }
185
186
sendMessage(const QString & message,int timeout)187 bool QtLocalPeer::sendMessage(const QString &message, int timeout)
188 {
189 if (!isClient())
190 return false;
191
192 #ifdef USE_DBUS
193 QDBusMessage msg = QDBusMessage::createMethodCall(id, QStringLiteral("/"),
194 QStringLiteral("org.kde.QtSingleApplication"),
195 QStringLiteral("SendMessage"));
196 msg << message;
197 return QDBusConnection::sessionBus().call(msg, QDBus::Block, timeout).type() == QDBusMessage::ReplyMessage;
198 #else
199 QLocalSocket socket;
200 bool connOk = false;
201 for(int i = 0; i < 2; i++) {
202 // Try twice, in case the other instance is just starting up
203 socket.connectToServer(socketName);
204 connOk = socket.waitForConnected(timeout/2);
205 if (connOk || i)
206 break;
207 int ms = 250;
208 #if defined(Q_OS_WIN)
209 Sleep(DWORD(ms));
210 #else
211 struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
212 nanosleep(&ts, NULL);
213 #endif
214 }
215 if (!connOk)
216 return false;
217
218 QByteArray uMsg(message.toUtf8());
219 QDataStream ds(&socket);
220 ds.writeBytes(uMsg.constData(), uMsg.size());
221 bool res = socket.waitForBytesWritten(timeout);
222 if (res) {
223 res &= socket.waitForReadyRead(timeout); // wait for ack
224 if (res)
225 res &= (socket.read(qstrlen(ack)) == ack);
226 }
227 return res;
228 #endif
229 }
230
removeLockedFile()231 void QtLocalPeer::removeLockedFile()
232 {
233 #ifndef USE_DBUS
234 lockFile.remove();
235 #endif
236 }
237
receiveConnection()238 void QtLocalPeer::receiveConnection()
239 {
240 #ifndef USE_DBUS
241 QLocalSocket* socket = server->nextPendingConnection();
242 if (!socket)
243 return;
244
245 while (true) {
246 if (socket->state() == QLocalSocket::UnconnectedState) {
247 qWarning("QtLocalPeer: Peer disconnected");
248 delete socket;
249 return;
250 }
251 if (socket->bytesAvailable() >= qint64(sizeof(quint32)))
252 break;
253 socket->waitForReadyRead();
254 }
255
256 QDataStream ds(socket);
257 QByteArray uMsg;
258 quint32 remaining;
259 ds >> remaining;
260 uMsg.resize(remaining);
261 int got = 0;
262 char* uMsgBuf = uMsg.data();
263 do {
264 got = ds.readRawData(uMsgBuf, remaining);
265 remaining -= got;
266 uMsgBuf += got;
267 } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
268 if (got < 0) {
269 qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
270 delete socket;
271 return;
272 }
273 QString message(QString::fromUtf8(uMsg));
274 socket->write(ack, qstrlen(ack));
275 socket->waitForBytesWritten(1000);
276 socket->waitForDisconnected(1000); // make sure client reads ack
277 delete socket;
278 emit messageReceived(message); //### (might take a long time to return)
279 #endif
280 }
281
282 #include "qtlocalpeer.moc"
283