Minor cleanups
[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 (proxy()->_restrictMessageTarget) {
160                 for (auto peer : proxy()->_restrictedTargets) {
161                     if (peer != nullptr)
162                         proxy()->dispatch(peer, RpcCall(signal.signature, params));
163                 }
164             } else
165                 proxy()->dispatch(RpcCall(signal.signature, params));
166         }
167         _id -= _slots.count();
168     }
169     return _id;
170 }
171
172
173 // ==================================================
174 //  SignalProxy
175 // ==================================================
176
177 thread_local SignalProxy *SignalProxy::_current{nullptr};
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     _current = nullptr;
212 }
213
214
215 void SignalProxy::setProxyMode(ProxyMode mode)
216 {
217     if (!_peerMap.empty()) {
218         qWarning() << Q_FUNC_INFO << "Cannot change proxy mode while connected";
219         return;
220     }
221
222     _proxyMode = mode;
223     if (mode == Server)
224         initServer();
225     else
226         initClient();
227 }
228
229 void SignalProxy::init()
230 {
231     _heartBeatInterval = 0;
232     _maxHeartBeatCount = 0;
233     _signalRelay = new SignalRelay(this);
234     setHeartBeatInterval(30);
235     setMaxHeartBeatCount(2);
236     _secure = false;
237     _current = this;
238     updateSecureState();
239 }
240
241
242 void SignalProxy::initServer()
243 {
244 }
245
246
247 void SignalProxy::initClient()
248 {
249     attachSlot("__objectRenamed__", this, SLOT(objectRenamed(QByteArray,QString,QString)));
250 }
251
252
253 void SignalProxy::setHeartBeatInterval(int secs)
254 {
255     if (_heartBeatInterval != secs) {
256         _heartBeatInterval = secs;
257         emit heartBeatIntervalChanged(secs);
258     }
259 }
260
261
262 void SignalProxy::setMaxHeartBeatCount(int max)
263 {
264     if (_maxHeartBeatCount != max) {
265         _maxHeartBeatCount = max;
266         emit maxHeartBeatCountChanged(max);
267     }
268 }
269
270
271 bool SignalProxy::addPeer(Peer *peer)
272 {
273     if (!peer)
274         return false;
275
276     if (_peerMap.values().contains(peer))
277         return true;
278
279     if (!peer->isOpen()) {
280         qWarning("SignalProxy: peer needs to be open!");
281         return false;
282     }
283
284     if (proxyMode() == Client) {
285         if (!_peerMap.isEmpty()) {
286             qWarning("SignalProxy: only one peer allowed in client mode!");
287             return false;
288         }
289         connect(peer, SIGNAL(lagUpdated(int)), SIGNAL(lagUpdated(int)));
290     }
291
292     connect(peer, SIGNAL(disconnected()), SLOT(removePeerBySender()));
293     connect(peer, SIGNAL(secureStateChanged(bool)), SLOT(updateSecureState()));
294
295     if (!peer->parent())
296         peer->setParent(this);
297
298     if (peer->id() < 0) {
299         peer->setId(nextPeerId());
300         peer->setConnectedSince(QDateTime::currentDateTimeUtc());
301     }
302
303     _peerMap[peer->id()] = peer;
304
305     peer->setSignalProxy(this);
306
307     if (peerCount() == 1)
308         emit connected();
309
310     updateSecureState();
311     return true;
312 }
313
314
315 void SignalProxy::removeAllPeers()
316 {
317     Q_ASSERT(proxyMode() == Server || peerCount() <= 1);
318     // wee need to copy that list since we modify it in the loop
319     QList<Peer *> peers = _peerMap.values();
320     for (auto peer : peers) {
321         removePeer(peer);
322     }
323 }
324
325
326 void SignalProxy::removePeer(Peer *peer)
327 {
328     if (!peer) {
329         qWarning() << Q_FUNC_INFO << "Trying to remove a null peer!";
330         return;
331     }
332
333     if (_peerMap.isEmpty()) {
334         qWarning() << "SignalProxy::removePeer(): No peers in use!";
335         return;
336     }
337
338     if (!_peerMap.values().contains(peer)) {
339         qWarning() << "SignalProxy: unknown Peer" << peer;
340         return;
341     }
342
343     disconnect(peer, 0, this, 0);
344     peer->setSignalProxy(0);
345
346     _peerMap.remove(peer->id());
347     emit peerRemoved(peer);
348
349     if (peer->parent() == this)
350         peer->deleteLater();
351
352     updateSecureState();
353
354     if (_peerMap.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     for (auto&& peer : _peerMap.values()) {
522         dispatch(peer, protoMessage);
523     }
524 }
525
526
527 template<class T>
528 void SignalProxy::dispatch(Peer *peer, const T &protoMessage)
529 {
530     _targetPeer = peer;
531
532     if (peer && peer->isOpen())
533         peer->dispatch(protoMessage);
534     else
535         QCoreApplication::postEvent(this, new ::RemovePeerEvent(peer));
536
537     _targetPeer = nullptr;
538 }
539
540
541 void SignalProxy::handle(Peer *peer, const SyncMessage &syncMessage)
542 {
543     if (!_syncSlave.contains(syncMessage.className) || !_syncSlave[syncMessage.className].contains(syncMessage.objectName)) {
544         qWarning() << QString("no registered receiver for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
545                    << syncMessage.params;
546         return;
547     }
548
549     SyncableObject *receiver = _syncSlave[syncMessage.className][syncMessage.objectName];
550     ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
551     if (!eMeta->slotMap().contains(syncMessage.slotName)) {
552         qWarning() << QString("no matching slot for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
553                    << syncMessage.params;
554         return;
555     }
556
557     int slotId = eMeta->slotMap()[syncMessage.slotName];
558     if (proxyMode() != eMeta->receiverMode(slotId)) {
559         qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed. Wrong ProxyMode!", eMeta->methodName(slotId).constData());
560         return;
561     }
562
563     // We can no longer construct a QVariant from QMetaType::Void
564     QVariant returnValue;
565     int returnType = eMeta->returnType(slotId);
566     if (returnType != QMetaType::Void)
567         returnValue = QVariant(static_cast<QVariant::Type>(returnType));
568
569     if (!invokeSlot(receiver, slotId, syncMessage.params, returnValue, peer)) {
570         qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed ", eMeta->methodName(slotId).constData());
571         return;
572     }
573
574     if (returnValue.type() != QVariant::Invalid && eMeta->receiveMap().contains(slotId)) {
575         int receiverId = eMeta->receiveMap()[slotId];
576         QVariantList returnParams;
577         if (eMeta->argTypes(receiverId).count() > 1)
578             returnParams << syncMessage.params;
579         returnParams << returnValue;
580         _targetPeer = peer;
581         peer->dispatch(SyncMessage(syncMessage.className, syncMessage.objectName, eMeta->methodName(receiverId), returnParams));
582         _targetPeer = nullptr;
583     }
584
585     // send emit update signal
586     invokeSlot(receiver, eMeta->updatedRemotelyId());
587 }
588
589
590 void SignalProxy::handle(Peer *peer, const InitRequest &initRequest)
591 {
592    if (!_syncSlave.contains(initRequest.className)) {
593         qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Class:"
594                    << initRequest.className;
595         return;
596     }
597
598     if (!_syncSlave[initRequest.className].contains(initRequest.objectName)) {
599         qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Object:"
600                    << initRequest.className << initRequest.objectName;
601         return;
602     }
603
604     SyncableObject *obj = _syncSlave[initRequest.className][initRequest.objectName];
605     _targetPeer = peer;
606     peer->dispatch(InitData(initRequest.className, initRequest.objectName, initData(obj)));
607     _targetPeer = nullptr;
608 }
609
610
611 void SignalProxy::handle(Peer *peer, const InitData &initData)
612 {
613     Q_UNUSED(peer)
614
615     if (!_syncSlave.contains(initData.className)) {
616         qWarning() << "SignalProxy::handleInitData() received initData for unregistered Class:"
617                    << initData.className;
618         return;
619     }
620
621     if (!_syncSlave[initData.className].contains(initData.objectName)) {
622         qWarning() << "SignalProxy::handleInitData() received initData for unregistered Object:"
623                    << initData.className << initData.objectName;
624         return;
625     }
626
627     SyncableObject *obj = _syncSlave[initData.className][initData.objectName];
628     setInitData(obj, initData.initData);
629 }
630
631
632 void SignalProxy::handle(Peer *peer, const RpcCall &rpcCall)
633 {
634     QObject *receiver;
635     int methodId;
636     SlotHash::const_iterator slot = _attachedSlots.constFind(rpcCall.slotName);
637     while (slot != _attachedSlots.constEnd() && slot.key() == rpcCall.slotName) {
638         receiver = (*slot).first;
639         methodId = (*slot).second;
640         if (!invokeSlot(receiver, methodId, rpcCall.params, peer)) {
641             ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
642             qWarning("SignalProxy::handleSignal(): invokeMethod for \"%s\" failed ", eMeta->methodName(methodId).constData());
643         }
644         ++slot;
645     }
646 }
647
648
649 bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList &params, QVariant &returnValue, Peer *peer)
650 {
651     ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
652     const QList<int> args = eMeta->argTypes(methodId);
653     const int numArgs = params.count() < args.count()
654                         ? params.count()
655                         : args.count();
656
657     if (eMeta->minArgCount(methodId) > params.count()) {
658         qWarning() << "SignalProxy::invokeSlot(): not enough params to invoke" << eMeta->methodName(methodId);
659         return false;
660     }
661
662     void *_a[] = { 0,           // return type...
663                    0, 0, 0, 0, 0, // and 10 args - that's the max size qt can handle with signals and slots
664                    0, 0, 0, 0, 0 };
665
666     // check for argument compatibility and build params array
667     for (int i = 0; i < numArgs; i++) {
668         if (!params[i].isValid()) {
669 #if QT_VERSION >= 0x050000
670             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());
671 #else
672             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());
673 #endif
674             qWarning() << "                            - make sure all your data types are known by the Qt MetaSystem";
675             return false;
676         }
677         if (args[i] != QMetaType::type(params[i].typeName())) {
678             qWarning() << "SignalProxy::invokeSlot(): incompatible param types to invoke" << eMeta->methodName(methodId);
679             return false;
680         }
681
682         _a[i+1] = const_cast<void *>(params[i].constData());
683     }
684
685     if (returnValue.type() != QVariant::Invalid)
686         _a[0] = const_cast<void *>(returnValue.constData());
687
688     Qt::ConnectionType type = QThread::currentThread() == receiver->thread()
689                               ? Qt::DirectConnection
690                               : Qt::QueuedConnection;
691
692     if (type == Qt::DirectConnection) {
693         _sourcePeer = peer;
694         auto result = receiver->qt_metacall(QMetaObject::InvokeMetaMethod, methodId, _a) < 0;
695         _sourcePeer = nullptr;
696         return result;
697     } else {
698         qWarning() << "Queued Connections are not implemented yet";
699         // note to self: qmetaobject.cpp:990 ff
700         return false;
701     }
702 }
703
704
705 bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList &params, Peer *peer)
706 {
707     QVariant ret;
708     return invokeSlot(receiver, methodId, params, ret, peer);
709 }
710
711
712 void SignalProxy::requestInit(SyncableObject *obj)
713 {
714     if (proxyMode() == Server || obj->isInitialized())
715         return;
716
717     dispatch(InitRequest(obj->syncMetaObject()->className(), obj->objectName()));
718 }
719
720
721 QVariantMap SignalProxy::initData(SyncableObject *obj) const
722 {
723     return obj->toVariantMap();
724 }
725
726
727 void SignalProxy::setInitData(SyncableObject *obj, const QVariantMap &properties)
728 {
729     if (obj->isInitialized())
730         return;
731     obj->fromVariantMap(properties);
732     obj->setInitialized();
733     emit objectInitialized(obj);
734     invokeSlot(obj, extendedMetaObject(obj)->updatedRemotelyId());
735 }
736
737
738 void SignalProxy::customEvent(QEvent *event)
739 {
740     switch ((int)event->type()) {
741     case RemovePeerEvent: {
742         ::RemovePeerEvent *e = static_cast< ::RemovePeerEvent *>(event);
743         removePeer(e->peer);
744         event->accept();
745         break;
746     }
747
748     default:
749         qWarning() << Q_FUNC_INFO << "Received unknown custom event:" << event->type();
750         return;
751     }
752 }
753
754
755 void SignalProxy::sync_call__(const SyncableObject *obj, SignalProxy::ProxyMode modeType, const char *funcname, va_list ap)
756 {
757     // qDebug() << obj << modeType << "(" << _proxyMode << ")" << funcname;
758     if (modeType != _proxyMode)
759         return;
760
761     ExtendedMetaObject *eMeta = extendedMetaObject(obj);
762
763     QVariantList params;
764
765     const QList<int> &argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname)));
766
767     for (int i = 0; i < argTypes.size(); i++) {
768         if (argTypes[i] == 0) {
769             qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname);
770             qWarning() << "        - make sure all your data types are known by the Qt MetaSystem";
771             return;
772         }
773         params << QVariant(argTypes[i], va_arg(ap, void *));
774     }
775
776     if (_restrictMessageTarget) {
777         for (auto peer : _restrictedTargets) {
778             if (peer != nullptr)
779                 dispatch(peer, SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
780         }
781     } else
782         dispatch(SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
783 }
784
785
786 void SignalProxy::disconnectDevice(QIODevice *dev, const QString &reason)
787 {
788     if (!reason.isEmpty())
789         qWarning() << qPrintable(reason);
790     QAbstractSocket *sock  = qobject_cast<QAbstractSocket *>(dev);
791     if (sock)
792         qWarning() << qPrintable(tr("Disconnecting")) << qPrintable(sock->peerAddress().toString());
793     dev->close();
794 }
795
796
797 void SignalProxy::dumpProxyStats()
798 {
799     QString mode;
800     if (proxyMode() == Server)
801         mode = "Server";
802     else
803         mode = "Client";
804
805     int slaveCount = 0;
806     foreach(ObjectId oid, _syncSlave.values())
807     slaveCount += oid.count();
808
809     qDebug() << this;
810     qDebug() << "              Proxy Mode:" << mode;
811     qDebug() << "          attached Slots:" << _attachedSlots.count();
812     qDebug() << " number of synced Slaves:" << slaveCount;
813     qDebug() << "number of Classes cached:" << _extendedMetaObjects.count();
814 }
815
816
817 void SignalProxy::updateSecureState()
818 {
819     bool wasSecure = _secure;
820
821     _secure = !_peerMap.isEmpty();
822     for (auto peer :  _peerMap.values()) {
823         _secure &= peer->isSecure();
824     }
825
826     if (wasSecure != _secure)
827         emit secureStateChanged(_secure);
828 }
829
830 QVariantList SignalProxy::peerData() {
831     QVariantList result;
832     for (auto peer : _peerMap.values()) {
833         QVariantMap data;
834         data["id"] = peer->id();
835         data["clientVersion"] = peer->clientVersion();
836         // We explicitly rename this, as, due to the Debian reproducability changes, buildDate isn’t actually the build
837         // date anymore, but on newer clients the date of the last git commit
838         data["clientVersionDate"] = peer->buildDate();
839         data["remoteAddress"] = peer->address();
840         data["connectedSince"] = peer->connectedSince();
841         data["secure"] = peer->isSecure();
842         result << data;
843     }
844     return result;
845 }
846
847 Peer *SignalProxy::peerById(int peerId) {
848     return _peerMap[peerId];
849 }
850
851 void SignalProxy::restrictTargetPeers(QSet<Peer*> peers, std::function<void()> closure)
852 {
853     auto previousRestrictMessageTarget = _restrictMessageTarget;
854     auto previousRestrictedTargets = _restrictedTargets;
855     _restrictMessageTarget = true;
856     _restrictedTargets = peers;
857
858     closure();
859
860     _restrictMessageTarget = previousRestrictMessageTarget;
861     _restrictedTargets = previousRestrictedTargets;
862 }
863
864 Peer *SignalProxy::sourcePeer() {
865     return _sourcePeer;
866 }
867
868 void SignalProxy::setSourcePeer(Peer *sourcePeer) {
869     _sourcePeer = sourcePeer;
870 }
871
872 Peer *SignalProxy::targetPeer() {
873     return _targetPeer;
874 }
875
876 void SignalProxy::setTargetPeer(Peer *targetPeer) {
877     _targetPeer = targetPeer;
878 }
879
880 // ==================================================
881 //  ExtendedMetaObject
882 // ==================================================
883 SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
884     : _meta(meta),
885     _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()"))
886 {
887     for (int i = 0; i < _meta->methodCount(); i++) {
888         if (_meta->method(i).methodType() != QMetaMethod::Slot)
889             continue;
890
891 #if QT_VERSION >= 0x050000
892         if (_meta->method(i).methodSignature().contains('*'))
893 #else
894         if (QByteArray(_meta->method(i).signature()).contains('*'))
895 #endif
896             continue;  // skip methods with ptr params
897
898         QByteArray method = methodName(_meta->method(i));
899         if (method.startsWith("init"))
900             continue;  // skip initializers
901
902         if (_methodIds.contains(method)) {
903             /* funny... moc creates for methods containing default parameters multiple metaMethod with separate methodIds.
904                we don't care... we just need the full fledged version
905              */
906             const QMetaMethod &current = _meta->method(_methodIds[method]);
907             const QMetaMethod &candidate = _meta->method(i);
908             if (current.parameterTypes().count() > candidate.parameterTypes().count()) {
909                 int minCount = candidate.parameterTypes().count();
910                 QList<QByteArray> commonParams = current.parameterTypes().mid(0, minCount);
911                 if (commonParams == candidate.parameterTypes())
912                     continue;  // we already got the full featured version
913             }
914             else {
915                 int minCount = current.parameterTypes().count();
916                 QList<QByteArray> commonParams = candidate.parameterTypes().mid(0, minCount);
917                 if (commonParams == current.parameterTypes()) {
918                     _methodIds[method] = i; // use the new one
919                     continue;
920                 }
921             }
922             if (checkConflicts) {
923                 qWarning() << "class" << meta->className() << "contains overloaded methods which is currently not supported!";
924 #if QT_VERSION >= 0x050000
925                 qWarning() << " - " << _meta->method(i).methodSignature() << "conflicts with" << _meta->method(_methodIds[method]).methodSignature();
926 #else
927                 qWarning() << " - " << _meta->method(i).signature() << "conflicts with" << _meta->method(_methodIds[method]).signature();
928 #endif
929             }
930             continue;
931         }
932         _methodIds[method] = i;
933     }
934 }
935
936
937 const SignalProxy::ExtendedMetaObject::MethodDescriptor &SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId)
938 {
939     if (!_methods.contains(methodId)) {
940         _methods[methodId] = MethodDescriptor(_meta->method(methodId));
941     }
942     return _methods[methodId];
943 }
944
945
946 const QHash<int, int> &SignalProxy::ExtendedMetaObject::receiveMap()
947 {
948     if (_receiveMap.isEmpty()) {
949         QHash<int, int> receiveMap;
950
951         QMetaMethod requestSlot;
952         QByteArray returnTypeName;
953         QByteArray signature;
954         QByteArray methodName;
955         QByteArray params;
956         int paramsPos;
957         int receiverId;
958         const int methodCount = _meta->methodCount();
959         for (int i = 0; i < methodCount; i++) {
960             requestSlot = _meta->method(i);
961             if (requestSlot.methodType() != QMetaMethod::Slot)
962                 continue;
963
964             returnTypeName = requestSlot.typeName();
965             if (QMetaType::Void == (QMetaType::Type)returnType(i))
966                 continue;
967
968 #if QT_VERSION >= 0x050000
969             signature = requestSlot.methodSignature();
970 #else
971             signature = QByteArray(requestSlot.signature());
972 #endif
973             if (!signature.startsWith("request"))
974                 continue;
975
976             paramsPos = signature.indexOf('(');
977             if (paramsPos == -1)
978                 continue;
979
980             methodName = signature.left(paramsPos);
981             params = signature.mid(paramsPos);
982
983             methodName = methodName.replace("request", "receive");
984             params = params.left(params.count() - 1) + ", " + returnTypeName + ")";
985
986             signature = QMetaObject::normalizedSignature(methodName + params);
987             receiverId = _meta->indexOfSlot(signature);
988
989             if (receiverId == -1) {
990                 signature = QMetaObject::normalizedSignature(methodName + "(" + returnTypeName + ")");
991                 receiverId = _meta->indexOfSlot(signature);
992             }
993
994             if (receiverId != -1) {
995                 receiveMap[i] = receiverId;
996             }
997         }
998         _receiveMap = receiveMap;
999     }
1000     return _receiveMap;
1001 }
1002
1003
1004 QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod &method)
1005 {
1006 #if QT_VERSION >= 0x050000
1007     QByteArray sig(method.methodSignature());
1008 #else
1009     QByteArray sig(method.signature());
1010 #endif
1011     return sig.left(sig.indexOf("("));
1012 }
1013
1014
1015 QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod &method)
1016 {
1017 #if QT_VERSION >= 0x050000
1018     QString methodname = QString(method.methodSignature()).section("(", 0, 0);
1019 #else
1020     QString methodname = QString(method.signature()).section("(", 0, 0);
1021 #endif
1022
1023     // determine where we have to chop:
1024     int upperCharPos;
1025     if (method.methodType() == QMetaMethod::Slot) {
1026         // we take evertyhing from the first uppercase char if it's slot
1027         upperCharPos = methodname.indexOf(QRegExp("[A-Z]"));
1028         if (upperCharPos == -1)
1029             return QString();
1030         methodname = methodname.mid(upperCharPos);
1031     }
1032     else {
1033         // and if it's a signal we discard everything from the last uppercase char
1034         upperCharPos = methodname.lastIndexOf(QRegExp("[A-Z]"));
1035         if (upperCharPos == -1)
1036             return QString();
1037         methodname = methodname.left(upperCharPos);
1038     }
1039
1040     methodname[0] = methodname[0].toUpper();
1041
1042     return methodname;
1043 }
1044
1045
1046 SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod &method)
1047     : _methodName(SignalProxy::ExtendedMetaObject::methodName(method)),
1048     _returnType(QMetaType::type(method.typeName()))
1049 {
1050     // determine argTypes
1051     QList<QByteArray> paramTypes = method.parameterTypes();
1052     QList<int> argTypes;
1053     for (int i = 0; i < paramTypes.count(); i++) {
1054         argTypes.append(QMetaType::type(paramTypes[i]));
1055     }
1056     _argTypes = argTypes;
1057
1058     // determine minArgCount
1059 #if QT_VERSION >= 0x050000
1060     QString signature(method.methodSignature());
1061 #else
1062     QString signature(method.signature());
1063 #endif
1064     _minArgCount = method.parameterTypes().count() - signature.count("=");
1065
1066     _receiverMode = (_methodName.startsWith("request"))
1067                     ? SignalProxy::Server
1068                     : SignalProxy::Client;
1069 }