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