Implement peer-specific signal sending
[quassel.git] / src / common / signalproxy.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program 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         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include <QCoreApplication>
22 #include <QHostAddress>
23 #include <QMetaMethod>
24 #include <QMetaProperty>
25 #include <QThread>
26
27 #ifdef HAVE_SSL
28     #include <QSslSocket>
29 #endif
30
31 #include "signalproxy.h"
32
33 #include "peer.h"
34 #include "protocol.h"
35 #include "syncableobject.h"
36 #include "util.h"
37 #include "types.h"
38
39 using namespace Protocol;
40
41 class RemovePeerEvent : public QEvent
42 {
43 public:
44     RemovePeerEvent(Peer *peer) : QEvent(QEvent::Type(SignalProxy::RemovePeerEvent)), peer(peer) {}
45     Peer *peer;
46 };
47
48
49 // ==================================================
50 //  SignalRelay
51 // ==================================================
52 class SignalProxy::SignalRelay : public QObject
53 {
54 /* Q_OBJECT is not necessary or even allowed, because we implement
55    qt_metacall ourselves (and don't use any other features of the meta
56    object system)
57 */
58 public:
59     SignalRelay(SignalProxy *parent) : QObject(parent), _proxy(parent) {}
60     inline SignalProxy *proxy() const { return _proxy; }
61
62     int qt_metacall(QMetaObject::Call _c, int _id, void **_a);
63
64     void attachSignal(QObject *sender, int signalId, const QByteArray &funcName);
65     void detachSignal(QObject *sender, int signalId = -1);
66
67 private:
68     struct Signal {
69         QObject *sender;
70         int signalId;
71         QByteArray signature;
72         Signal(QObject *sender, int sigId, const QByteArray &signature) : sender(sender), signalId(sigId), signature(signature) {}
73         Signal() : sender(0), signalId(-1) {}
74     };
75
76     SignalProxy *_proxy;
77     QHash<int, Signal> _slots;
78 };
79
80
81 void SignalProxy::SignalRelay::attachSignal(QObject *sender, int signalId, const QByteArray &funcName)
82 {
83     // we ride without safetybelts here... all checking for valid method etc pp has to be done by the caller
84     // all connected methodIds are offset by the standard methodCount of QObject
85     int slotId;
86     for (int i = 0;; i++) {
87         if (!_slots.contains(i)) {
88             slotId = i;
89             break;
90         }
91     }
92
93     QByteArray fn;
94     if (!funcName.isEmpty()) {
95         fn = QMetaObject::normalizedSignature(funcName);
96     }
97     else {
98         fn = SIGNAL(fakeMethodSignature());
99 #if QT_VERSION >= 0x050000
100         fn = fn.replace("fakeMethodSignature()", sender->metaObject()->method(signalId).methodSignature());
101 #else
102         fn = fn.replace("fakeMethodSignature()", sender->metaObject()->method(signalId).signature());
103 #endif
104     }
105
106     _slots[slotId] = Signal(sender, signalId, fn);
107
108     QMetaObject::connect(sender, signalId, this, QObject::staticMetaObject.methodCount() + slotId);
109 }
110
111
112 void SignalProxy::SignalRelay::detachSignal(QObject *sender, int signalId)
113 {
114     QHash<int, Signal>::iterator slotIter = _slots.begin();
115     while (slotIter != _slots.end()) {
116         if (slotIter->sender == sender && (signalId == -1 || slotIter->signalId == signalId)) {
117             slotIter = _slots.erase(slotIter);
118             if (signalId != -1)
119                 break;
120         }
121         else {
122             ++slotIter;
123         }
124     }
125 }
126
127
128 int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
129 {
130     _id = QObject::qt_metacall(_c, _id, _a);
131     if (_id < 0)
132         return _id;
133
134     if (_c == QMetaObject::InvokeMetaMethod) {
135         if (_slots.contains(_id)) {
136             QObject *caller = sender();
137
138             SignalProxy::ExtendedMetaObject *eMeta = proxy()->extendedMetaObject(caller->metaObject());
139             Q_ASSERT(eMeta);
140
141             const Signal &signal = _slots[_id];
142
143             QVariantList params;
144
145             const QList<int> &argTypes = eMeta->argTypes(signal.signalId);
146             for (int i = 0; i < argTypes.size(); i++) {
147                 if (argTypes[i] == 0) {
148 #if QT_VERSION >= 0x050000
149                     qWarning() << "SignalRelay::qt_metacall(): received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(caller->metaObject()->className()).arg(caller->metaObject()->method(signal.signalId).methodSignature().constData());
150 #else
151                     qWarning() << "SignalRelay::qt_metacall(): received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(caller->metaObject()->className()).arg(caller->metaObject()->method(signal.signalId).signature());
152 #endif
153                     qWarning() << "                            - make sure all your data types are known by the Qt MetaSystem";
154                     return _id;
155                 }
156                 params << QVariant(argTypes[i], _a[i+1]);
157             }
158
159             if (argTypes.size() >= 1 && argTypes[0] == qMetaTypeId<PeerPtr>() && proxy()->proxyMode() == SignalProxy::Server) {
160                 Peer *peer = params[0].value<PeerPtr>();
161                 proxy()->dispatch(peer, RpcCall(signal.signature, params));
162             } else if (proxy()->_restrictMessageTarget) {
163                 for (auto peer : proxy()->_restrictedTargets) {
164                     if (peer != nullptr)
165                         proxy()->dispatch(peer, RpcCall(signal.signature, params));
166                 }
167             } else
168                 proxy()->dispatch(RpcCall(signal.signature, params));
169         }
170         _id -= _slots.count();
171     }
172     return _id;
173 }
174
175
176 // ==================================================
177 //  SignalProxy
178 // ==================================================
179 SignalProxy::SignalProxy(QObject *parent)
180     : QObject(parent)
181 {
182     setProxyMode(Client);
183     init();
184 }
185
186
187 SignalProxy::SignalProxy(ProxyMode mode, QObject *parent)
188     : QObject(parent)
189 {
190     setProxyMode(mode);
191     init();
192 }
193
194
195 SignalProxy::~SignalProxy()
196 {
197     QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
198     while (classIter != _syncSlave.end()) {
199         ObjectId::iterator objIter = classIter->begin();
200         while (objIter != classIter->end()) {
201             SyncableObject *obj = objIter.value();
202             objIter = classIter->erase(objIter);
203             obj->stopSynchronize(this);
204         }
205         ++classIter;
206     }
207     _syncSlave.clear();
208
209     removeAllPeers();
210 }
211
212
213 void SignalProxy::setProxyMode(ProxyMode mode)
214 {
215     if (_peers.count()) {
216         qWarning() << Q_FUNC_INFO << "Cannot change proxy mode while connected";
217         return;
218     }
219
220     _proxyMode = mode;
221     if (mode == Server)
222         initServer();
223     else
224         initClient();
225 }
226
227
228 void SignalProxy::init()
229 {
230     _heartBeatInterval = 0;
231     _maxHeartBeatCount = 0;
232     _signalRelay = new SignalRelay(this);
233     setHeartBeatInterval(30);
234     setMaxHeartBeatCount(2);
235     _secure = false;
236     updateSecureState();
237 }
238
239
240 void SignalProxy::initServer()
241 {
242 }
243
244
245 void SignalProxy::initClient()
246 {
247     attachSlot("__objectRenamed__", this, SLOT(objectRenamed(QByteArray,QString,QString)));
248 }
249
250
251 void SignalProxy::setHeartBeatInterval(int secs)
252 {
253     if (_heartBeatInterval != secs) {
254         _heartBeatInterval = secs;
255         emit heartBeatIntervalChanged(secs);
256     }
257 }
258
259
260 void SignalProxy::setMaxHeartBeatCount(int max)
261 {
262     if (_maxHeartBeatCount != max) {
263         _maxHeartBeatCount = max;
264         emit maxHeartBeatCountChanged(max);
265     }
266 }
267
268
269 bool SignalProxy::addPeer(Peer *peer)
270 {
271     if (!peer)
272         return false;
273
274     if (_peers.contains(peer))
275         return true;
276
277     if (!peer->isOpen()) {
278         qWarning("SignalProxy: peer needs to be open!");
279         return false;
280     }
281
282     if (proxyMode() == Client) {
283         if (!_peers.isEmpty()) {
284             qWarning("SignalProxy: only one peer allowed in client mode!");
285             return false;
286         }
287         connect(peer, SIGNAL(lagUpdated(int)), SIGNAL(lagUpdated(int)));
288     }
289
290     connect(peer, SIGNAL(disconnected()), SLOT(removePeerBySender()));
291     connect(peer, SIGNAL(secureStateChanged(bool)), SLOT(updateSecureState()));
292
293     if (!peer->parent())
294         peer->setParent(this);
295
296     if (peer->_id < 0) {
297         peer->_id = nextPeerId();
298         peer->_connectedSince = QDateTime::currentDateTimeUtc();
299     }
300
301     _peers.insert(peer);
302     _peerMap[peer->_id] = peer;
303
304     peer->setSignalProxy(this);
305
306     if (_peers.count() == 1)
307         emit connected();
308
309     updateSecureState();
310     return true;
311 }
312
313
314 void SignalProxy::removeAllPeers()
315 {
316     Q_ASSERT(proxyMode() == Server || _peers.count() <= 1);
317     // wee need to copy that list since we modify it in the loop
318     QSet<Peer *> peers = _peers;
319     foreach(Peer *peer, peers) {
320         removePeer(peer);
321     }
322 }
323
324
325 void SignalProxy::removePeer(Peer *peer)
326 {
327     if (!peer) {
328         qWarning() << Q_FUNC_INFO << "Trying to remove a null peer!";
329         return;
330     }
331
332     if (_peers.isEmpty()) {
333         qWarning() << "SignalProxy::removePeer(): No peers in use!";
334         return;
335     }
336
337     if (!_peers.contains(peer)) {
338         qWarning() << "SignalProxy: unknown Peer" << peer;
339         return;
340     }
341
342     disconnect(peer, 0, this, 0);
343     peer->setSignalProxy(0);
344
345     _peerMap.remove(peer->_id);
346     _peers.remove(peer);
347     emit peerRemoved(peer);
348
349     if (peer->parent() == this)
350         peer->deleteLater();
351
352     updateSecureState();
353
354     if (_peers.isEmpty())
355         emit disconnected();
356 }
357
358
359 void SignalProxy::removePeerBySender()
360 {
361     removePeer(qobject_cast<Peer *>(sender()));
362 }
363
364
365 void SignalProxy::renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname)
366 {
367     if (proxyMode() == Client)
368         return;
369
370     const QMetaObject *meta = obj->syncMetaObject();
371     const QByteArray className(meta->className());
372     objectRenamed(className, newname, oldname);
373
374     dispatch(RpcCall("__objectRenamed__", QVariantList() << className << newname << oldname));
375 }
376
377
378 void SignalProxy::objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname)
379 {
380     if (_syncSlave.contains(classname) && _syncSlave[classname].contains(oldname) && oldname != newname) {
381         SyncableObject *obj = _syncSlave[classname][newname] = _syncSlave[classname].take(oldname);
382         requestInit(obj);
383     }
384 }
385
386
387 const QMetaObject *SignalProxy::metaObject(const QObject *obj)
388 {
389     if (const SyncableObject *syncObject = qobject_cast<const SyncableObject *>(obj))
390         return syncObject->syncMetaObject();
391     else
392         return obj->metaObject();
393 }
394
395
396 SignalProxy::ExtendedMetaObject *SignalProxy::extendedMetaObject(const QMetaObject *meta) const
397 {
398     if (_extendedMetaObjects.contains(meta))
399         return _extendedMetaObjects[meta];
400     else
401         return 0;
402 }
403
404
405 SignalProxy::ExtendedMetaObject *SignalProxy::createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
406 {
407     if (!_extendedMetaObjects.contains(meta)) {
408         _extendedMetaObjects[meta] = new ExtendedMetaObject(meta, checkConflicts);
409     }
410     return _extendedMetaObjects[meta];
411 }
412
413
414 bool SignalProxy::attachSignal(QObject *sender, const char *signal, const QByteArray &sigName)
415 {
416     const QMetaObject *meta = sender->metaObject();
417     QByteArray sig(meta->normalizedSignature(signal).mid(1));
418     int methodId = meta->indexOfMethod(sig.constData());
419     if (methodId == -1 || meta->method(methodId).methodType() != QMetaMethod::Signal) {
420         qWarning() << "SignalProxy::attachSignal(): No such signal" << signal;
421         return false;
422     }
423
424     createExtendedMetaObject(meta);
425     _signalRelay->attachSignal(sender, methodId, sigName);
426
427     disconnect(sender, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
428     connect(sender, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
429     return true;
430 }
431
432
433 bool SignalProxy::attachSlot(const QByteArray &sigName, QObject *recv, const char *slot)
434 {
435     const QMetaObject *meta = recv->metaObject();
436     int methodId = meta->indexOfMethod(meta->normalizedSignature(slot).mid(1));
437     if (methodId == -1 || meta->method(methodId).methodType() == QMetaMethod::Method) {
438         qWarning() << "SignalProxy::attachSlot(): No such slot" << slot;
439         return false;
440     }
441
442     createExtendedMetaObject(meta);
443
444     QByteArray funcName = QMetaObject::normalizedSignature(sigName.constData());
445     _attachedSlots.insert(funcName, qMakePair(recv, methodId));
446
447     disconnect(recv, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
448     connect(recv, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
449     return true;
450 }
451
452
453 void SignalProxy::synchronize(SyncableObject *obj)
454 {
455     createExtendedMetaObject(obj, true);
456
457     // attaching as slave to receive sync Calls
458     QByteArray className(obj->syncMetaObject()->className());
459     _syncSlave[className][obj->objectName()] = obj;
460
461     if (proxyMode() == Server) {
462         obj->setInitialized();
463         emit objectInitialized(obj);
464     }
465     else {
466         if (obj->isInitialized())
467             emit objectInitialized(obj);
468         else
469             requestInit(obj);
470     }
471
472     obj->synchronize(this);
473 }
474
475
476 void SignalProxy::detachObject(QObject *obj)
477 {
478     detachSignals(obj);
479     detachSlots(obj);
480 }
481
482
483 void SignalProxy::detachSignals(QObject *sender)
484 {
485     _signalRelay->detachSignal(sender);
486 }
487
488
489 void SignalProxy::detachSlots(QObject *receiver)
490 {
491     SlotHash::iterator slotIter = _attachedSlots.begin();
492     while (slotIter != _attachedSlots.end()) {
493         if (slotIter.value().first == receiver) {
494             slotIter = _attachedSlots.erase(slotIter);
495         }
496         else
497             ++slotIter;
498     }
499 }
500
501
502 void SignalProxy::stopSynchronize(SyncableObject *obj)
503 {
504     // we can't use a className here, since it might be effed up, if we receive the call as a result of a decon
505     // gladly the objectName() is still valid. So we have only to iterate over the classes not each instance! *sigh*
506     QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
507     while (classIter != _syncSlave.end()) {
508         if (classIter->contains(obj->objectName()) && classIter.value()[obj->objectName()] == obj) {
509             classIter->remove(obj->objectName());
510             break;
511         }
512         ++classIter;
513     }
514     obj->stopSynchronize(this);
515 }
516
517
518 template<class T>
519 void SignalProxy::dispatch(const T &protoMessage)
520 {
521     foreach (Peer *peer, _peers) {
522         if (peer->isOpen())
523             peer->dispatch(protoMessage);
524         else
525             QCoreApplication::postEvent(this, new ::RemovePeerEvent(peer));
526     }
527 }
528
529
530 template<class T>
531 void SignalProxy::dispatch(Peer *peer, const T &protoMessage)
532 {
533     if (peer && peer->isOpen())
534         peer->dispatch(protoMessage);
535     else
536         QCoreApplication::postEvent(this, new ::RemovePeerEvent(peer));
537 }
538
539
540 void SignalProxy::handle(Peer *peer, const SyncMessage &syncMessage)
541 {
542     if (!_syncSlave.contains(syncMessage.className) || !_syncSlave[syncMessage.className].contains(syncMessage.objectName)) {
543         qWarning() << QString("no registered receiver for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
544                    << syncMessage.params;
545         return;
546     }
547
548     SyncableObject *receiver = _syncSlave[syncMessage.className][syncMessage.objectName];
549     ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
550     if (!eMeta->slotMap().contains(syncMessage.slotName)) {
551         qWarning() << QString("no matching slot for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
552                    << syncMessage.params;
553         return;
554     }
555
556     int slotId = eMeta->slotMap()[syncMessage.slotName];
557     if (proxyMode() != eMeta->receiverMode(slotId)) {
558         qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed. Wrong ProxyMode!", eMeta->methodName(slotId).constData());
559         return;
560     }
561
562     // We can no longer construct a QVariant from QMetaType::Void
563     QVariant returnValue;
564     int returnType = eMeta->returnType(slotId);
565     if (returnType != QMetaType::Void)
566         returnValue = QVariant(static_cast<QVariant::Type>(returnType));
567
568     if (!invokeSlot(receiver, slotId, syncMessage.params, returnValue, peer)) {
569         qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed ", eMeta->methodName(slotId).constData());
570         return;
571     }
572
573     if (returnValue.type() != QVariant::Invalid && eMeta->receiveMap().contains(slotId)) {
574         int receiverId = eMeta->receiveMap()[slotId];
575         QVariantList returnParams;
576         if (eMeta->argTypes(receiverId).count() > 1)
577             returnParams << syncMessage.params;
578         returnParams << returnValue;
579         peer->dispatch(SyncMessage(syncMessage.className, syncMessage.objectName, eMeta->methodName(receiverId), returnParams));
580     }
581
582     // send emit update signal
583     invokeSlot(receiver, eMeta->updatedRemotelyId());
584 }
585
586
587 void SignalProxy::handle(Peer *peer, const InitRequest &initRequest)
588 {
589    if (!_syncSlave.contains(initRequest.className)) {
590         qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Class:"
591                    << initRequest.className;
592         return;
593     }
594
595     if (!_syncSlave[initRequest.className].contains(initRequest.objectName)) {
596         qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Object:"
597                    << initRequest.className << initRequest.objectName;
598         return;
599     }
600
601     SyncableObject *obj = _syncSlave[initRequest.className][initRequest.objectName];
602     peer->dispatch(InitData(initRequest.className, initRequest.objectName, initData(obj)));
603 }
604
605
606 void SignalProxy::handle(Peer *peer, const InitData &initData)
607 {
608     Q_UNUSED(peer)
609
610     if (!_syncSlave.contains(initData.className)) {
611         qWarning() << "SignalProxy::handleInitData() received initData for unregistered Class:"
612                    << initData.className;
613         return;
614     }
615
616     if (!_syncSlave[initData.className].contains(initData.objectName)) {
617         qWarning() << "SignalProxy::handleInitData() received initData for unregistered Object:"
618                    << initData.className << initData.objectName;
619         return;
620     }
621
622     SyncableObject *obj = _syncSlave[initData.className][initData.objectName];
623     setInitData(obj, initData.initData);
624 }
625
626
627 void SignalProxy::handle(Peer *peer, const RpcCall &rpcCall)
628 {
629     QObject *receiver;
630     int methodId;
631     SlotHash::const_iterator slot = _attachedSlots.constFind(rpcCall.slotName);
632     while (slot != _attachedSlots.constEnd() && slot.key() == rpcCall.slotName) {
633         receiver = (*slot).first;
634         methodId = (*slot).second;
635         if (!invokeSlot(receiver, methodId, rpcCall.params, peer)) {
636             ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
637             qWarning("SignalProxy::handleSignal(): invokeMethod for \"%s\" failed ", eMeta->methodName(methodId).constData());
638         }
639         ++slot;
640     }
641 }
642
643
644 bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList &params, QVariant &returnValue, Peer *peer)
645 {
646     ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
647     const QList<int> args = eMeta->argTypes(methodId);
648     const int numArgs = params.count() < args.count()
649                         ? params.count()
650                         : args.count();
651
652     if (eMeta->minArgCount(methodId) > params.count()) {
653         qWarning() << "SignalProxy::invokeSlot(): not enough params to invoke" << eMeta->methodName(methodId);
654         return false;
655     }
656
657     void *_a[] = { 0,           // return type...
658                    0, 0, 0, 0, 0, // and 10 args - that's the max size qt can handle with signals and slots
659                    0, 0, 0, 0, 0 };
660
661     // check for argument compatibility and build params array
662     for (int i = 0; i < numArgs; i++) {
663         if (!params[i].isValid()) {
664 #if QT_VERSION >= 0x050000
665             qWarning() << "SignalProxy::invokeSlot(): received invalid data for argument number" << i << "of method" << QString("%1::%2()").arg(receiver->metaObject()->className()).arg(receiver->metaObject()->method(methodId).methodSignature().constData());
666 #else
667             qWarning() << "SignalProxy::invokeSlot(): received invalid data for argument number" << i << "of method" << QString("%1::%2()").arg(receiver->metaObject()->className()).arg(receiver->metaObject()->method(methodId).signature());
668 #endif
669             qWarning() << "                            - make sure all your data types are known by the Qt MetaSystem";
670             return false;
671         }
672         if (args[i] != QMetaType::type(params[i].typeName())) {
673             qWarning() << "SignalProxy::invokeSlot(): incompatible param types to invoke" << eMeta->methodName(methodId);
674             return false;
675         }
676         // if first arg is a PeerPtr, replace it by the address of the peer originally receiving the RpcCall
677         if (peer && i == 0 && args[0] == qMetaTypeId<PeerPtr>()) {
678             QVariant v = QVariant::fromValue<PeerPtr>(peer);
679             _a[1] = const_cast<void*>(v.constData());
680         } else
681             _a[i+1] = const_cast<void *>(params[i].constData());
682     }
683
684     if (returnValue.type() != QVariant::Invalid)
685         _a[0] = const_cast<void *>(returnValue.constData());
686
687     Qt::ConnectionType type = QThread::currentThread() == receiver->thread()
688                               ? Qt::DirectConnection
689                               : Qt::QueuedConnection;
690
691     if (type == Qt::DirectConnection) {
692         return receiver->qt_metacall(QMetaObject::InvokeMetaMethod, methodId, _a) < 0;
693     }
694     else {
695         qWarning() << "Queued Connections are not implemented yet";
696         // note to self: qmetaobject.cpp:990 ff
697         return false;
698     }
699 }
700
701
702 bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList &params, Peer *peer)
703 {
704     QVariant ret;
705     return invokeSlot(receiver, methodId, params, ret, peer);
706 }
707
708
709 void SignalProxy::requestInit(SyncableObject *obj)
710 {
711     if (proxyMode() == Server || obj->isInitialized())
712         return;
713
714     dispatch(InitRequest(obj->syncMetaObject()->className(), obj->objectName()));
715 }
716
717
718 QVariantMap SignalProxy::initData(SyncableObject *obj) const
719 {
720     return obj->toVariantMap();
721 }
722
723
724 void SignalProxy::setInitData(SyncableObject *obj, const QVariantMap &properties)
725 {
726     if (obj->isInitialized())
727         return;
728     obj->fromVariantMap(properties);
729     obj->setInitialized();
730     emit objectInitialized(obj);
731     invokeSlot(obj, extendedMetaObject(obj)->updatedRemotelyId());
732 }
733
734
735 void SignalProxy::customEvent(QEvent *event)
736 {
737     switch ((int)event->type()) {
738     case RemovePeerEvent: {
739         ::RemovePeerEvent *e = static_cast< ::RemovePeerEvent *>(event);
740         removePeer(e->peer);
741         event->accept();
742         break;
743     }
744
745     default:
746         qWarning() << Q_FUNC_INFO << "Received unknown custom event:" << event->type();
747         return;
748     }
749 }
750
751
752 void SignalProxy::sync_call__(const SyncableObject *obj, SignalProxy::ProxyMode modeType, const char *funcname, va_list ap)
753 {
754     // qDebug() << obj << modeType << "(" << _proxyMode << ")" << funcname;
755     if (modeType != _proxyMode)
756         return;
757
758     ExtendedMetaObject *eMeta = extendedMetaObject(obj);
759
760     QVariantList params;
761
762     const QList<int> &argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname)));
763
764     for (int i = 0; i < argTypes.size(); i++) {
765         if (argTypes[i] == 0) {
766             qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname);
767             qWarning() << "        - make sure all your data types are known by the Qt MetaSystem";
768             return;
769         }
770         params << QVariant(argTypes[i], va_arg(ap, void *));
771     }
772
773     if (argTypes.size() >= 1 && argTypes[0] == qMetaTypeId<PeerPtr>() && proxyMode() == SignalProxy::Server) {
774         Peer *peer = params[0].value<PeerPtr>();
775         dispatch(peer, SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
776     } else
777         dispatch(SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
778 }
779
780
781 void SignalProxy::disconnectDevice(QIODevice *dev, const QString &reason)
782 {
783     if (!reason.isEmpty())
784         qWarning() << qPrintable(reason);
785     QAbstractSocket *sock  = qobject_cast<QAbstractSocket *>(dev);
786     if (sock)
787         qWarning() << qPrintable(tr("Disconnecting")) << qPrintable(sock->peerAddress().toString());
788     dev->close();
789 }
790
791
792 void SignalProxy::dumpProxyStats()
793 {
794     QString mode;
795     if (proxyMode() == Server)
796         mode = "Server";
797     else
798         mode = "Client";
799
800     int slaveCount = 0;
801     foreach(ObjectId oid, _syncSlave.values())
802     slaveCount += oid.count();
803
804     qDebug() << this;
805     qDebug() << "              Proxy Mode:" << mode;
806     qDebug() << "          attached Slots:" << _attachedSlots.count();
807     qDebug() << " number of synced Slaves:" << slaveCount;
808     qDebug() << "number of Classes cached:" << _extendedMetaObjects.count();
809 }
810
811
812 void SignalProxy::updateSecureState()
813 {
814     bool wasSecure = _secure;
815
816     _secure = !_peers.isEmpty();
817     foreach (const Peer *peer,  _peers) {
818         _secure &= peer->isSecure();
819     }
820
821     if (wasSecure != _secure)
822         emit secureStateChanged(_secure);
823 }
824
825 QVariantList SignalProxy::peerData() {
826     QVariantList result;
827     for (auto peer : _peers) {
828         QVariantMap data;
829         data["id"] = peer->_id;
830         data["clientVersion"] = peer->_clientVersion;
831         data["clientVersionDate"] = peer->_buildDate;
832         data["remoteAddress"] = peer->address();
833         data["connectedSince"] = peer->_connectedSince;
834         data["secure"] = peer->isSecure();
835         result << data;
836     }
837     return result;
838 }
839
840 Peer *SignalProxy::peerById(int peerId) {
841     return _peerMap[peerId];
842 }
843
844 /**
845  * This method allows to send a signal only to a limited set of peers
846  * @param peerIds A list of peers that should receive it
847  * @param closure Code you want to execute within of that restricted environment
848  */
849 void SignalProxy::restrictTargetPeers(std::initializer_list<Peer *> peers, std::function<void()> closure)
850 {
851     auto previousRestrictMessageTarget = _restrictMessageTarget;
852     auto previousRestrictedTargets = _restrictedTargets;
853     _restrictMessageTarget = true;
854     _restrictedTargets = QSet<Peer*>(peers);
855
856     closure();
857
858     _restrictMessageTarget = previousRestrictMessageTarget;
859     _restrictedTargets = previousRestrictedTargets;
860 }
861
862 // ==================================================
863 //  ExtendedMetaObject
864 // ==================================================
865 SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
866     : _meta(meta),
867     _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()"))
868 {
869     for (int i = 0; i < _meta->methodCount(); i++) {
870         if (_meta->method(i).methodType() != QMetaMethod::Slot)
871             continue;
872
873 #if QT_VERSION >= 0x050000
874         if (_meta->method(i).methodSignature().contains('*'))
875 #else
876         if (QByteArray(_meta->method(i).signature()).contains('*'))
877 #endif
878             continue;  // skip methods with ptr params
879
880         QByteArray method = methodName(_meta->method(i));
881         if (method.startsWith("init"))
882             continue;  // skip initializers
883
884         if (_methodIds.contains(method)) {
885             /* funny... moc creates for methods containing default parameters multiple metaMethod with separate methodIds.
886                we don't care... we just need the full fledged version
887              */
888             const QMetaMethod &current = _meta->method(_methodIds[method]);
889             const QMetaMethod &candidate = _meta->method(i);
890             if (current.parameterTypes().count() > candidate.parameterTypes().count()) {
891                 int minCount = candidate.parameterTypes().count();
892                 QList<QByteArray> commonParams = current.parameterTypes().mid(0, minCount);
893                 if (commonParams == candidate.parameterTypes())
894                     continue;  // we already got the full featured version
895             }
896             else {
897                 int minCount = current.parameterTypes().count();
898                 QList<QByteArray> commonParams = candidate.parameterTypes().mid(0, minCount);
899                 if (commonParams == current.parameterTypes()) {
900                     _methodIds[method] = i; // use the new one
901                     continue;
902                 }
903             }
904             if (checkConflicts) {
905                 qWarning() << "class" << meta->className() << "contains overloaded methods which is currently not supported!";
906 #if QT_VERSION >= 0x050000
907                 qWarning() << " - " << _meta->method(i).methodSignature() << "conflicts with" << _meta->method(_methodIds[method]).methodSignature();
908 #else
909                 qWarning() << " - " << _meta->method(i).signature() << "conflicts with" << _meta->method(_methodIds[method]).signature();
910 #endif
911             }
912             continue;
913         }
914         _methodIds[method] = i;
915     }
916 }
917
918
919 const SignalProxy::ExtendedMetaObject::MethodDescriptor &SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId)
920 {
921     if (!_methods.contains(methodId)) {
922         _methods[methodId] = MethodDescriptor(_meta->method(methodId));
923     }
924     return _methods[methodId];
925 }
926
927
928 const QHash<int, int> &SignalProxy::ExtendedMetaObject::receiveMap()
929 {
930     if (_receiveMap.isEmpty()) {
931         QHash<int, int> receiveMap;
932
933         QMetaMethod requestSlot;
934         QByteArray returnTypeName;
935         QByteArray signature;
936         QByteArray methodName;
937         QByteArray params;
938         int paramsPos;
939         int receiverId;
940         const int methodCount = _meta->methodCount();
941         for (int i = 0; i < methodCount; i++) {
942             requestSlot = _meta->method(i);
943             if (requestSlot.methodType() != QMetaMethod::Slot)
944                 continue;
945
946             returnTypeName = requestSlot.typeName();
947             if (QMetaType::Void == (QMetaType::Type)returnType(i))
948                 continue;
949
950 #if QT_VERSION >= 0x050000
951             signature = requestSlot.methodSignature();
952 #else
953             signature = QByteArray(requestSlot.signature());
954 #endif
955             if (!signature.startsWith("request"))
956                 continue;
957
958             paramsPos = signature.indexOf('(');
959             if (paramsPos == -1)
960                 continue;
961
962             methodName = signature.left(paramsPos);
963             params = signature.mid(paramsPos);
964
965             methodName = methodName.replace("request", "receive");
966             params = params.left(params.count() - 1) + ", " + returnTypeName + ")";
967
968             signature = QMetaObject::normalizedSignature(methodName + params);
969             receiverId = _meta->indexOfSlot(signature);
970
971             if (receiverId == -1) {
972                 signature = QMetaObject::normalizedSignature(methodName + "(" + returnTypeName + ")");
973                 receiverId = _meta->indexOfSlot(signature);
974             }
975
976             if (receiverId != -1) {
977                 receiveMap[i] = receiverId;
978             }
979         }
980         _receiveMap = receiveMap;
981     }
982     return _receiveMap;
983 }
984
985
986 QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod &method)
987 {
988 #if QT_VERSION >= 0x050000
989     QByteArray sig(method.methodSignature());
990 #else
991     QByteArray sig(method.signature());
992 #endif
993     return sig.left(sig.indexOf("("));
994 }
995
996
997 QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod &method)
998 {
999 #if QT_VERSION >= 0x050000
1000     QString methodname = QString(method.methodSignature()).section("(", 0, 0);
1001 #else
1002     QString methodname = QString(method.signature()).section("(", 0, 0);
1003 #endif
1004
1005     // determine where we have to chop:
1006     int upperCharPos;
1007     if (method.methodType() == QMetaMethod::Slot) {
1008         // we take evertyhing from the first uppercase char if it's slot
1009         upperCharPos = methodname.indexOf(QRegExp("[A-Z]"));
1010         if (upperCharPos == -1)
1011             return QString();
1012         methodname = methodname.mid(upperCharPos);
1013     }
1014     else {
1015         // and if it's a signal we discard everything from the last uppercase char
1016         upperCharPos = methodname.lastIndexOf(QRegExp("[A-Z]"));
1017         if (upperCharPos == -1)
1018             return QString();
1019         methodname = methodname.left(upperCharPos);
1020     }
1021
1022     methodname[0] = methodname[0].toUpper();
1023
1024     return methodname;
1025 }
1026
1027
1028 SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod &method)
1029     : _methodName(SignalProxy::ExtendedMetaObject::methodName(method)),
1030     _returnType(QMetaType::type(method.typeName()))
1031 {
1032     // determine argTypes
1033     QList<QByteArray> paramTypes = method.parameterTypes();
1034     QList<int> argTypes;
1035     for (int i = 0; i < paramTypes.count(); i++) {
1036         argTypes.append(QMetaType::type(paramTypes[i]));
1037     }
1038     _argTypes = argTypes;
1039
1040     // determine minArgCount
1041 #if QT_VERSION >= 0x050000
1042     QString signature(method.methodSignature());
1043 #else
1044     QString signature(method.signature());
1045 #endif
1046     _minArgCount = method.parameterTypes().count() - signature.count("=");
1047
1048     _receiverMode = (_methodName.startsWith("request"))
1049                     ? SignalProxy::Server
1050                     : SignalProxy::Client;
1051 }