Imported Upstream version 0.9.0
[deb_shairplay.git] / AirTV-Qt / qtsingleapplication / src / qtlocalpeer.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 **
6 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 **
8 ** This file is part of a Qt Solutions component.
9 **
10 ** You may use this file under the terms of the BSD license as follows:
11 **
12 ** "Redistribution and use in source and binary forms, with or without
13 ** modification, are permitted provided that the following conditions are
14 ** met:
15 ** * Redistributions of source code must retain the above copyright
16 ** notice, this list of conditions and the following disclaimer.
17 ** * Redistributions in binary form must reproduce the above copyright
18 ** notice, this list of conditions and the following disclaimer in
19 ** the documentation and/or other materials provided with the
20 ** distribution.
21 ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
22 ** the names of its contributors may be used to endorse or promote
23 ** products derived from this software without specific prior written
24 ** permission.
25 **
26 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
37 **
38 ****************************************************************************/
39
40
41 #include "qtlocalpeer.h"
42 #include <QtCore/QCoreApplication>
43 #include <QtCore/QTime>
44 #include <unistd.h>
45
46 #if defined(Q_OS_WIN)
47 #include <QtCore/QLibrary>
48 #include <QtCore/qt_windows.h>
49 typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
50 static PProcessIdToSessionId pProcessIdToSessionId = 0;
51 #endif
52 #if defined(Q_OS_UNIX)
53 #include <time.h>
54 #endif
55
56 namespace QtLP_Private {
57 #include "qtlockedfile.cpp"
58 #if defined(Q_OS_WIN)
59 #include "qtlockedfile_win.cpp"
60 #else
61 #include "qtlockedfile_unix.cpp"
62 #endif
63 }
64
65 const char* QtLocalPeer::ack = "ack";
66
67 QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
68 : QObject(parent), id(appId)
69 {
70 QString prefix = id;
71 if (id.isEmpty()) {
72 id = QCoreApplication::applicationFilePath();
73 #if defined(Q_OS_WIN)
74 id = id.toLower();
75 #endif
76 prefix = id.section(QLatin1Char('/'), -1);
77 }
78 prefix.remove(QRegExp("[^a-zA-Z]"));
79 prefix.truncate(6);
80
81 QByteArray idc = id.toUtf8();
82 quint16 idNum = qChecksum(idc.constData(), idc.size());
83 socketName = QLatin1String("qtsingleapp-") + prefix
84 + QLatin1Char('-') + QString::number(idNum, 16);
85
86 #if defined(Q_OS_WIN)
87 if (!pProcessIdToSessionId) {
88 QLibrary lib("kernel32");
89 pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
90 }
91 if (pProcessIdToSessionId) {
92 DWORD sessionId = 0;
93 pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
94 socketName += QLatin1Char('-') + QString::number(sessionId, 16);
95 }
96 #else
97 socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
98 #endif
99
100 server = new QLocalServer(this);
101 QString lockName = QDir(QDir::tempPath()).absolutePath()
102 + QLatin1Char('/') + socketName
103 + QLatin1String("-lockfile");
104 lockFile.setFileName(lockName);
105 lockFile.open(QIODevice::ReadWrite);
106 }
107
108
109
110 bool QtLocalPeer::isClient()
111 {
112 if (lockFile.isLocked())
113 return false;
114
115 if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))
116 return true;
117
118 bool res = server->listen(socketName);
119 #if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0))
120 // ### Workaround
121 if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {
122 QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);
123 res = server->listen(socketName);
124 }
125 #endif
126 if (!res)
127 qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
128 QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
129 return false;
130 }
131
132
133 bool QtLocalPeer::sendMessage(const QString &message, int timeout)
134 {
135 if (!isClient())
136 return false;
137
138 QLocalSocket socket;
139 bool connOk = false;
140 for(int i = 0; i < 2; i++) {
141 // Try twice, in case the other instance is just starting up
142 socket.connectToServer(socketName);
143 connOk = socket.waitForConnected(timeout/2);
144 if (connOk || i)
145 break;
146 int ms = 250;
147 #if defined(Q_OS_WIN)
148 Sleep(DWORD(ms));
149 #else
150 struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
151 nanosleep(&ts, NULL);
152 #endif
153 }
154 if (!connOk)
155 return false;
156
157 QByteArray uMsg(message.toUtf8());
158 QDataStream ds(&socket);
159 ds.writeBytes(uMsg.constData(), uMsg.size());
160 bool res = socket.waitForBytesWritten(timeout);
161 if (res) {
162 res &= socket.waitForReadyRead(timeout); // wait for ack
163 if (res)
164 res &= (socket.read(qstrlen(ack)) == ack);
165 }
166 return res;
167 }
168
169
170 void QtLocalPeer::receiveConnection()
171 {
172 QLocalSocket* socket = server->nextPendingConnection();
173 if (!socket)
174 return;
175
176 while (socket->bytesAvailable() < (int)sizeof(quint32))
177 socket->waitForReadyRead();
178 QDataStream ds(socket);
179 QByteArray uMsg;
180 quint32 remaining;
181 ds >> remaining;
182 uMsg.resize(remaining);
183 int got = 0;
184 char* uMsgBuf = uMsg.data();
185 do {
186 got = ds.readRawData(uMsgBuf, remaining);
187 remaining -= got;
188 uMsgBuf += got;
189 } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
190 if (got < 0) {
191 qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
192 delete socket;
193 return;
194 }
195 QString message(QString::fromUtf8(uMsg));
196 socket->write(ack, qstrlen(ack));
197 socket->waitForBytesWritten(1000);
198 delete socket;
199 emit messageReceived(message); //### (might take a long time to return)
200 }