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