Happy new year 2015 !!!
[MUtilities.git] / src / IPCChannel.cpp
blob042d59a99c37abe7c47588fbace146e77bdaabe7
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2015 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
22 //MUtils
23 #include <MUtils/IPCChannel.h>
24 #include <MUtils/Exception.h>
26 //Internal
27 #include "3rd_party/adler32/include/adler32.h"
29 //Qt includes
30 #include <QRegExp>
31 #include <QSharedMemory>
32 #include <QSystemSemaphore>
33 #include <QMutex>
34 #include <QWriteLocker>
35 #include <QCryptographicHash>
37 //CRT
38 #include <cassert>
40 ///////////////////////////////////////////////////////////////////////////////
41 // UTILITIES
42 ///////////////////////////////////////////////////////////////////////////////
44 namespace MUtils
46 namespace Internal
48 static const quint32 ADLER_SEED = 0x5D90C356;
50 template<class T>
51 static inline void UPDATE_CHECKSUM(T &data)
53 data.checksum = Internal::adler32(ADLER_SEED, &data.payload, sizeof(data.payload));
56 template<class T>
57 static inline bool VERIFY_CHECKSUM(const T &data)
59 return (data.checksum == Internal::adler32(ADLER_SEED, &data.payload, sizeof(data.payload)));
64 ///////////////////////////////////////////////////////////////////////////////
65 // TYPES
66 ///////////////////////////////////////////////////////////////////////////////
68 namespace MUtils
70 namespace Internal
72 static const size_t HDR_LEN = 40;
73 static const size_t IPC_SLOTS = 128;
75 typedef struct
77 quint64 counter;
78 quint32 pos_wr;
79 quint32 pos_rd;
81 ipc_status_data_t;
83 typedef struct
85 ipc_status_data_t payload;
86 quint32 checksum;
88 ipc_status_t;
90 typedef struct
92 quint32 command_id;
93 quint32 flags;
94 char param[MUtils::IPCChannel::MAX_MESSAGE_LEN];
95 quint64 timestamp;
97 ipc_msg_data_t;
99 typedef struct
101 ipc_msg_data_t payload;
102 quint32 checksum;
104 ipc_msg_t;
106 typedef struct
108 char header[HDR_LEN];
109 ipc_status_t status;
110 ipc_msg_t data[IPC_SLOTS];
112 ipc_t;
116 ///////////////////////////////////////////////////////////////////////////////
117 // UTILITIES
118 ///////////////////////////////////////////////////////////////////////////////
120 static QScopedPointer<QRegExp> g_escape_regexp;
121 static QMutex g_escape_lock;
123 #define ESCAPE(STR) (QString((STR)).replace(*g_escape_regexp, QLatin1String("_")).toLower())
125 static QString MAKE_ID(const QString &applicationId, const unsigned int &appVersionNo, const QString &channelId, const QString &itemId)
127 QMutexLocker locker(&g_escape_lock);
129 if(g_escape_regexp.isNull())
131 g_escape_regexp.reset(new QRegExp(QLatin1String("[^A-Za-z0-9_\\-]")));
134 return QString("com.muldersoft.mutilities.ipc.%1.r%2.%3.%4").arg(ESCAPE(applicationId), QString::number(appVersionNo, 16).toUpper(), ESCAPE(channelId), ESCAPE(itemId));
137 ///////////////////////////////////////////////////////////////////////////////
138 // PRIVATE DATA
139 ///////////////////////////////////////////////////////////////////////////////
141 namespace MUtils
143 class IPCChannel_Private
145 friend class IPCChannel;
147 protected:
148 volatile bool initialized;
149 QScopedPointer<QSharedMemory> sharedmem;
150 QScopedPointer<QSystemSemaphore> semaphore_rd;
151 QScopedPointer<QSystemSemaphore> semaphore_wr;
152 QReadWriteLock lock;
156 ///////////////////////////////////////////////////////////////////////////////
157 // CONSTRUCTOR & DESTRUCTOR
158 ///////////////////////////////////////////////////////////////////////////////
160 MUtils::IPCChannel::IPCChannel(const QString &applicationId, const quint32 &appVersionNo, const QString &channelId)
162 p(new IPCChannel_Private()),
163 m_applicationId(applicationId),
164 m_channelId(channelId),
165 m_appVersionNo(appVersionNo),
166 m_headerStr(QCryptographicHash::hash(MAKE_ID(applicationId, appVersionNo, channelId, "header").toLatin1(), QCryptographicHash::Sha1).toHex())
168 p->initialized = false;
169 if(m_headerStr.length() != Internal::HDR_LEN)
171 MUTILS_THROW("Invalid header length has been detected!");
175 MUtils::IPCChannel::~IPCChannel(void)
177 if(p->initialized)
179 if(p->sharedmem->isAttached())
181 p->sharedmem->detach();
185 delete p;
188 ///////////////////////////////////////////////////////////////////////////////
189 // INITIALIZATION
190 ///////////////////////////////////////////////////////////////////////////////
192 int MUtils::IPCChannel::initialize(void)
194 QWriteLocker writeLock(&p->lock);
196 if(p->initialized)
198 return RET_ALREADY_INITIALIZED;
201 p->sharedmem. reset(new QSharedMemory (MAKE_ID(m_applicationId, m_appVersionNo, m_channelId, "sharedmem"), 0));
202 p->semaphore_rd.reset(new QSystemSemaphore(MAKE_ID(m_applicationId, m_appVersionNo, m_channelId, "semaph_rd"), 0));
203 p->semaphore_wr.reset(new QSystemSemaphore(MAKE_ID(m_applicationId, m_appVersionNo, m_channelId, "semaph_wr"), 0));
205 if(p->semaphore_rd->error() != QSystemSemaphore::NoError)
207 const QString errorMessage = p->semaphore_rd->errorString();
208 qWarning("Failed to create system smaphore: %s", MUTILS_UTF8(errorMessage));
209 return RET_FAILURE;
212 if(p->semaphore_wr->error() != QSystemSemaphore::NoError)
214 const QString errorMessage = p->semaphore_wr->errorString();
215 qWarning("Failed to create system smaphore: %s", MUTILS_UTF8(errorMessage));
216 return RET_FAILURE;
219 if(!p->sharedmem->create(sizeof(Internal::ipc_t)))
221 if(p->sharedmem->error() == QSharedMemory::AlreadyExists)
223 if(!p->sharedmem->attach())
225 const QString errorMessage = p->sharedmem->errorString();
226 qWarning("Failed to attach to shared memory: %s", MUTILS_UTF8(errorMessage));
227 return RET_FAILURE;
229 if(p->sharedmem->error() != QSharedMemory::NoError)
231 const QString errorMessage = p->sharedmem->errorString();
232 qWarning("Failed to attach to shared memory: %s", MUTILS_UTF8(errorMessage));
233 return RET_FAILURE;
235 if(p->sharedmem->size() < sizeof(Internal::ipc_t))
237 qWarning("Failed to attach to shared memory: Size verification has failed!");
238 return RET_FAILURE;
240 if(Internal::ipc_t *const ptr = reinterpret_cast<Internal::ipc_t*>(p->sharedmem->data()))
242 if(memcmp(&ptr->header[0], m_headerStr.constData(), Internal::HDR_LEN) != 0)
244 qWarning("Failed to attach to shared memory: Header verification has failed!");
245 return RET_FAILURE;
248 else
250 const QString errorMessage = p->sharedmem->errorString();
251 qWarning("Failed to access shared memory: %s", MUTILS_UTF8(errorMessage));
252 return RET_FAILURE;
254 p->initialized = true;
255 return RET_SUCCESS_SLAVE;
257 else
259 const QString errorMessage = p->sharedmem->errorString();
260 qWarning("Failed to create shared memory: %s", MUTILS_UTF8(errorMessage));
261 return RET_FAILURE;
265 if(p->sharedmem->error() != QSharedMemory::NoError)
267 const QString errorMessage = p->sharedmem->errorString();
268 qWarning("Failed to create shared memory: %s", MUTILS_UTF8(errorMessage));
269 return RET_FAILURE;
272 if(Internal::ipc_t *const ptr = reinterpret_cast<Internal::ipc_t*>(p->sharedmem->data()))
274 memset(ptr, 0, sizeof(Internal::ipc_t));
275 memcpy(&ptr->header[0], m_headerStr.constData(), Internal::HDR_LEN);
276 UPDATE_CHECKSUM(ptr->status);
278 else
280 const QString errorMessage = p->sharedmem->errorString();
281 qWarning("Failed to access shared memory: %s", MUTILS_UTF8(errorMessage));
282 return RET_FAILURE;
285 if(!p->semaphore_wr->release(Internal::IPC_SLOTS))
287 const QString errorMessage = p->semaphore_wr->errorString();
288 qWarning("Failed to release system semaphore: %s", MUTILS_UTF8(errorMessage));
289 return RET_FAILURE;
292 //qDebug("IPC KEY #1: %s", MUTILS_UTF8(p->sharedmem->key()));
293 //qDebug("IPC KEY #2: %s", MUTILS_UTF8(p->semaphore_rd->key()));
294 //qDebug("IPC KEY #3: %s", MUTILS_UTF8(p->semaphore_wr->key()));
296 p->initialized = true;
297 return RET_SUCCESS_MASTER;
300 ///////////////////////////////////////////////////////////////////////////////
301 // SEND MESSAGE
302 ///////////////////////////////////////////////////////////////////////////////
304 bool MUtils::IPCChannel::send(const quint32 &command, const quint32 &flags, const char *const message)
306 bool success = false;
307 QReadLocker readLock(&p->lock);
309 if(!p->initialized)
311 MUTILS_THROW("Shared memory for IPC not initialized yet.");
314 if(!p->semaphore_wr->acquire())
316 const QString errorMessage = p->semaphore_wr->errorString();
317 qWarning("Failed to acquire system semaphore: %s", MUTILS_UTF8(errorMessage));
318 return false;
321 if(!p->sharedmem->lock())
323 const QString errorMessage = p->sharedmem->errorString();
324 qWarning("Failed to lock shared memory: %s", MUTILS_UTF8(errorMessage));
325 return false;
328 if(Internal::ipc_t *const ptr = reinterpret_cast<Internal::ipc_t*>(p->sharedmem->data()))
330 if(VERIFY_CHECKSUM(ptr->status))
332 Internal::ipc_msg_t ipc_msg;
333 memset(&ipc_msg, 0, sizeof(Internal::ipc_msg_t));
335 ipc_msg.payload.command_id = command;
336 ipc_msg.payload.flags = flags;
337 if(message)
339 strncpy_s(ipc_msg.payload.param, MAX_MESSAGE_LEN, message, _TRUNCATE);
341 ipc_msg.payload.timestamp = ptr->status.payload.counter++;
342 UPDATE_CHECKSUM(ipc_msg);
344 memcpy(&ptr->data[ptr->status.payload.pos_wr], &ipc_msg, sizeof(Internal::ipc_msg_t));
345 ptr->status.payload.pos_wr = (ptr->status.payload.pos_wr + 1) % Internal::IPC_SLOTS;
346 UPDATE_CHECKSUM(ptr->status);
348 success = true;
350 else
352 qWarning("Corrupted IPC status detected -> skipping!");
355 else
357 qWarning("Shared memory pointer is NULL -> unable to write data!");
360 if(!p->sharedmem->unlock())
362 const QString errorMessage = p->sharedmem->errorString();
363 qFatal("Failed to unlock shared memory: %s", MUTILS_UTF8(errorMessage));
366 if(!p->semaphore_rd->release())
368 const QString errorMessage = p->semaphore_rd->errorString();
369 qWarning("Failed to release system semaphore: %s", MUTILS_UTF8(errorMessage));
372 return success;
375 ///////////////////////////////////////////////////////////////////////////////
376 // READ MESSAGE
377 ///////////////////////////////////////////////////////////////////////////////
379 bool MUtils::IPCChannel::read(quint32 &command, quint32 &flags, char *const message, const size_t &buffSize)
381 bool success = false;
382 QReadLocker readLock(&p->lock);
384 command = 0;
385 if(message && (buffSize > 0))
387 message[0] = '\0';
390 if(!p->initialized)
392 MUTILS_THROW("Shared memory for IPC not initialized yet.");
395 Internal::ipc_msg_t ipc_msg;
396 memset(&ipc_msg, 0, sizeof(Internal::ipc_msg_t));
398 if(!p->semaphore_rd->acquire())
400 const QString errorMessage = p->semaphore_rd->errorString();
401 qWarning("Failed to acquire system semaphore: %s", MUTILS_UTF8(errorMessage));
402 return false;
405 if(!p->sharedmem->lock())
407 const QString errorMessage = p->sharedmem->errorString();
408 qWarning("Failed to lock shared memory: %s", MUTILS_UTF8(errorMessage));
409 return false;
412 if(Internal::ipc_t *const ptr = reinterpret_cast<Internal::ipc_t*>(p->sharedmem->data()))
414 if(VERIFY_CHECKSUM(ptr->status))
416 memcpy(&ipc_msg, &ptr->data[ptr->status.payload.pos_rd], sizeof(Internal::ipc_msg_t));
417 ptr->status.payload.pos_rd = (ptr->status.payload.pos_rd + 1) % Internal::IPC_SLOTS;
418 UPDATE_CHECKSUM(ptr->status);
420 if(VERIFY_CHECKSUM(ipc_msg) || (ipc_msg.payload.timestamp < ptr->status.payload.counter))
422 command = ipc_msg.payload.command_id;
423 flags = ipc_msg.payload.flags;
424 strncpy_s(message, buffSize, ipc_msg.payload.param, _TRUNCATE);
425 success = true;
427 else
429 qWarning("Malformed or corrupted IPC message, will be ignored!");
432 else
434 qWarning("Corrupted IPC status detected -> skipping!");
437 else
439 qWarning("Shared memory pointer is NULL -> unable to read data!");
442 if(!p->sharedmem->unlock())
444 const QString errorMessage = p->sharedmem->errorString();
445 qFatal("Failed to unlock shared memory: %s", MUTILS_UTF8(errorMessage));
448 if(!p->semaphore_wr->release())
450 const QString errorMessage = p->semaphore_wr->errorString();
451 qWarning("Failed to release system semaphore: %s", MUTILS_UTF8(errorMessage));
454 return success;