]> git.sur5r.net Git - minitube/blob - src/qtsingleapplication/qtlocalpeer.cpp
Imported Upstream version 2.5.1
[minitube] / src / qtsingleapplication / qtlocalpeer.cpp
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 #if defined(Q_OS_WIN)
48 #include <QLibrary>
49 #include <qt_windows.h>
50 typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
51 static PProcessIdToSessionId pProcessIdToSessionId = 0;
52 #endif
53 #if defined(Q_OS_UNIX)
54 #include <sys/types.h>
55 #include <time.h>
56 #include <unistd.h>
57 #endif
58
59 namespace QtLP_Private {
60 #include "qtlockedfile.cpp"
61 #if defined(Q_OS_WIN)
62 #include "qtlockedfile_win.cpp"
63 #else
64 #include "qtlockedfile_unix.cpp"
65 #endif
66 }
67
68 const char* QtLocalPeer::ack = "ack";
69
70 QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
71     : QObject(parent), id(appId)
72 {
73     QString prefix = id;
74     if (id.isEmpty()) {
75         id = QCoreApplication::applicationFilePath();
76 #if defined(Q_OS_WIN)
77         id = id.toLower();
78 #endif
79         prefix = id.section(QLatin1Char('/'), -1);
80     }
81     prefix.remove(QRegExp("[^a-zA-Z]"));
82     prefix.truncate(6);
83
84     QByteArray idc = id.toUtf8();
85     quint16 idNum = qChecksum(idc.constData(), idc.size());
86     socketName = QLatin1String("qtsingleapp-") + prefix
87                  + QLatin1Char('-') + QString::number(idNum, 16);
88
89 #if defined(Q_OS_WIN)
90     if (!pProcessIdToSessionId) {
91         QLibrary lib("kernel32");
92         pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
93     }
94     if (pProcessIdToSessionId) {
95         DWORD sessionId = 0;
96         pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
97         socketName += QLatin1Char('-') + QString::number(sessionId, 16);
98     }
99 #else
100     socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
101 #endif
102
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);
109 }
110
111
112
113 bool QtLocalPeer::isClient()
114 {
115     if (lockFile.isLocked())
116         return false;
117
118     if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))
119         return true;
120
121     bool res = server->listen(socketName);
122 #if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0))
123     // ### Workaround
124     if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {
125         QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);
126         res = server->listen(socketName);
127     }
128 #endif
129     if (!res)
130         qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
131     QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
132     return false;
133 }
134
135
136 bool QtLocalPeer::sendMessage(const QString &message, int timeout)
137 {
138     if (!isClient())
139         return false;
140
141     QLocalSocket socket;
142     bool connOk = false;
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);
147         if (connOk || i)
148             break;
149         int ms = 250;
150 #if defined(Q_OS_WIN)
151         Sleep(DWORD(ms));
152 #else
153         struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
154         nanosleep(&ts, NULL);
155 #endif
156     }
157     if (!connOk)
158         return false;
159
160     QByteArray uMsg(message.toUtf8());
161     QDataStream ds(&socket);
162     ds.writeBytes(uMsg.constData(), uMsg.size());
163     bool res = socket.waitForBytesWritten(timeout);
164     if (res) {
165         res &= socket.waitForReadyRead(timeout);   // wait for ack
166         if (res)
167             res &= (socket.read(qstrlen(ack)) == ack);
168     }
169     return res;
170 }
171
172
173 void QtLocalPeer::receiveConnection()
174 {
175     QLocalSocket* socket = server->nextPendingConnection();
176     if (!socket)
177         return;
178
179     while (socket->bytesAvailable() < (int)sizeof(quint32))
180         socket->waitForReadyRead();
181     QDataStream ds(socket);
182     QByteArray uMsg;
183     quint32 remaining;
184     ds >> remaining;
185     uMsg.resize(remaining);
186     int got = 0;
187     char* uMsgBuf = uMsg.data();
188     do {
189         got = ds.readRawData(uMsgBuf, remaining);
190         remaining -= got;
191         uMsgBuf += got;
192     } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
193     if (got < 0) {
194         qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
195         delete socket;
196         return;
197     }
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
202     delete socket;
203     emit messageReceived(message); //### (might take a long time to return)
204 }