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