modernize: Reformat ALL the source... again!
[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 (_syncSlave.contains(classname) && _syncSlave[classname].contains(oldname) && oldname != newname) {
376         SyncableObject* obj = _syncSlave[classname][newname] = _syncSlave[classname].take(oldname);
377         requestInit(obj);
378     }
379 }
380
381 const QMetaObject* SignalProxy::metaObject(const QObject* obj)
382 {
383     if (const auto* syncObject = qobject_cast<const SyncableObject*>(obj))
384         return syncObject->syncMetaObject();
385     else
386         return obj->metaObject();
387 }
388
389 SignalProxy::ExtendedMetaObject* SignalProxy::extendedMetaObject(const QMetaObject* meta) const
390 {
391     if (_extendedMetaObjects.contains(meta))
392         return _extendedMetaObjects[meta];
393     else
394         return nullptr;
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 bool SignalProxy::attachSignal(QObject* sender, const char* signal, const QByteArray& sigName)
406 {
407     const QMetaObject* meta = sender->metaObject();
408     QByteArray sig(meta->normalizedSignature(signal).mid(1));
409     int methodId = meta->indexOfMethod(sig.constData());
410     if (methodId == -1 || meta->method(methodId).methodType() != QMetaMethod::Signal) {
411         qWarning() << "SignalProxy::attachSignal(): No such signal" << signal;
412         return false;
413     }
414
415     createExtendedMetaObject(meta);
416     _signalRelay->attachSignal(sender, methodId, sigName);
417
418     disconnect(sender, &QObject::destroyed, this, &SignalProxy::detachObject);
419     connect(sender, &QObject::destroyed, this, &SignalProxy::detachObject);
420     return true;
421 }
422
423 bool SignalProxy::attachSlot(const QByteArray& sigName, QObject* recv, const char* slot)
424 {
425     const QMetaObject* meta = recv->metaObject();
426     int methodId = meta->indexOfMethod(meta->normalizedSignature(slot).mid(1));
427     if (methodId == -1 || meta->method(methodId).methodType() == QMetaMethod::Method) {
428         qWarning() << "SignalProxy::attachSlot(): No such slot" << slot;
429         return false;
430     }
431
432     createExtendedMetaObject(meta);
433
434     QByteArray funcName = QMetaObject::normalizedSignature(sigName.constData());
435     _attachedSlots.insert(funcName, qMakePair(recv, methodId));
436
437     disconnect(recv, &QObject::destroyed, this, &SignalProxy::detachObject);
438     connect(recv, &QObject::destroyed, this, &SignalProxy::detachObject);
439     return true;
440 }
441
442 void SignalProxy::synchronize(SyncableObject* obj)
443 {
444     createExtendedMetaObject(obj, true);
445
446     // attaching as slave to receive sync Calls
447     QByteArray className(obj->syncMetaObject()->className());
448     _syncSlave[className][obj->objectName()] = obj;
449
450     if (proxyMode() == Server) {
451         obj->setInitialized();
452         emit objectInitialized(obj);
453     }
454     else {
455         if (obj->isInitialized())
456             emit objectInitialized(obj);
457         else
458             requestInit(obj);
459     }
460
461     obj->synchronize(this);
462 }
463
464 void SignalProxy::detachObject(QObject* obj)
465 {
466     // Don't try to connect SignalProxy from itself on shutdown
467     if (obj != this) {
468         detachSignals(obj);
469         detachSlots(obj);
470     }
471 }
472
473 void SignalProxy::detachSignals(QObject* sender)
474 {
475     _signalRelay->detachSignal(sender);
476 }
477
478 void SignalProxy::detachSlots(QObject* receiver)
479 {
480     SlotHash::iterator slotIter = _attachedSlots.begin();
481     while (slotIter != _attachedSlots.end()) {
482         if (slotIter.value().first == receiver) {
483             slotIter = _attachedSlots.erase(slotIter);
484         }
485         else
486             ++slotIter;
487     }
488 }
489
490 void SignalProxy::stopSynchronize(SyncableObject* obj)
491 {
492     // we can't use a className here, since it might be effed up, if we receive the call as a result of a decon
493     // gladly the objectName() is still valid. So we have only to iterate over the classes not each instance! *sigh*
494     QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
495     while (classIter != _syncSlave.end()) {
496         if (classIter->contains(obj->objectName()) && classIter.value()[obj->objectName()] == obj) {
497             classIter->remove(obj->objectName());
498             break;
499         }
500         ++classIter;
501     }
502     obj->stopSynchronize(this);
503 }
504
505 template<class T>
506 void SignalProxy::dispatch(const T& protoMessage)
507 {
508     for (auto&& peer : _peerMap.values()) {
509         dispatch(peer, protoMessage);
510     }
511 }
512
513 template<class T>
514 void SignalProxy::dispatch(Peer* peer, const T& protoMessage)
515 {
516     _targetPeer = peer;
517
518     if (peer && peer->isOpen())
519         peer->dispatch(protoMessage);
520     else
521         QCoreApplication::postEvent(this, new ::RemovePeerEvent(peer));
522
523     _targetPeer = nullptr;
524 }
525
526 void SignalProxy::handle(Peer* peer, const SyncMessage& syncMessage)
527 {
528     if (!_syncSlave.contains(syncMessage.className) || !_syncSlave[syncMessage.className].contains(syncMessage.objectName)) {
529         qWarning() << QString("no registered receiver for sync call: %1::%2 (objectName=\"%3\"). Params are:")
530                           .arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
531                    << syncMessage.params;
532         return;
533     }
534
535     SyncableObject* receiver = _syncSlave[syncMessage.className][syncMessage.objectName];
536     ExtendedMetaObject* eMeta = extendedMetaObject(receiver);
537     if (!eMeta->slotMap().contains(syncMessage.slotName)) {
538         qWarning() << QString("no matching slot for sync call: %1::%2 (objectName=\"%3\"). Params are:")
539                           .arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
540                    << syncMessage.params;
541         return;
542     }
543
544     int slotId = eMeta->slotMap()[syncMessage.slotName];
545     if (proxyMode() != eMeta->receiverMode(slotId)) {
546         qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed. Wrong ProxyMode!", eMeta->methodName(slotId).constData());
547         return;
548     }
549
550     // We can no longer construct a QVariant from QMetaType::Void
551     QVariant returnValue;
552     int returnType = eMeta->returnType(slotId);
553     if (returnType != QMetaType::Void)
554         returnValue = QVariant(static_cast<QVariant::Type>(returnType));
555
556     if (!invokeSlot(receiver, slotId, syncMessage.params, returnValue, peer)) {
557         qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed ", eMeta->methodName(slotId).constData());
558         return;
559     }
560
561     if (returnValue.type() != QVariant::Invalid && eMeta->receiveMap().contains(slotId)) {
562         int receiverId = eMeta->receiveMap()[slotId];
563         QVariantList returnParams;
564         if (eMeta->argTypes(receiverId).count() > 1)
565             returnParams << syncMessage.params;
566         returnParams << returnValue;
567         _targetPeer = peer;
568         peer->dispatch(SyncMessage(syncMessage.className, syncMessage.objectName, eMeta->methodName(receiverId), returnParams));
569         _targetPeer = nullptr;
570     }
571
572     // send emit update signal
573     invokeSlot(receiver, eMeta->updatedRemotelyId());
574 }
575
576 void SignalProxy::handle(Peer* peer, const InitRequest& initRequest)
577 {
578     if (!_syncSlave.contains(initRequest.className)) {
579         qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Class:" << initRequest.className;
580         return;
581     }
582
583     if (!_syncSlave[initRequest.className].contains(initRequest.objectName)) {
584         qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Object:" << initRequest.className
585                    << initRequest.objectName;
586         return;
587     }
588
589     SyncableObject* obj = _syncSlave[initRequest.className][initRequest.objectName];
590     _targetPeer = peer;
591     peer->dispatch(InitData(initRequest.className, initRequest.objectName, initData(obj)));
592     _targetPeer = nullptr;
593 }
594
595 void SignalProxy::handle(Peer* peer, const InitData& initData)
596 {
597     Q_UNUSED(peer)
598
599     if (!_syncSlave.contains(initData.className)) {
600         qWarning() << "SignalProxy::handleInitData() received initData for unregistered Class:" << initData.className;
601         return;
602     }
603
604     if (!_syncSlave[initData.className].contains(initData.objectName)) {
605         qWarning() << "SignalProxy::handleInitData() received initData for unregistered Object:" << initData.className << initData.objectName;
606         return;
607     }
608
609     SyncableObject* obj = _syncSlave[initData.className][initData.objectName];
610     setInitData(obj, initData.initData);
611 }
612
613 void SignalProxy::handle(Peer* peer, const RpcCall& rpcCall)
614 {
615     QObject* receiver;
616     int methodId;
617     SlotHash::const_iterator slot = _attachedSlots.constFind(rpcCall.slotName);
618     while (slot != _attachedSlots.constEnd() && slot.key() == rpcCall.slotName) {
619         receiver = (*slot).first;
620         methodId = (*slot).second;
621         if (!invokeSlot(receiver, methodId, rpcCall.params, peer)) {
622             ExtendedMetaObject* eMeta = extendedMetaObject(receiver);
623             qWarning("SignalProxy::handleSignal(): invokeMethod for \"%s\" failed ", eMeta->methodName(methodId).constData());
624         }
625         ++slot;
626     }
627 }
628
629 bool SignalProxy::invokeSlot(QObject* receiver, int methodId, const QVariantList& params, QVariant& returnValue, Peer* peer)
630 {
631     ExtendedMetaObject* eMeta = extendedMetaObject(receiver);
632     const QList<int> args = eMeta->argTypes(methodId);
633     const int numArgs = params.count() < args.count() ? params.count() : args.count();
634
635     if (eMeta->minArgCount(methodId) > params.count()) {
636         qWarning() << "SignalProxy::invokeSlot(): not enough params to invoke" << eMeta->methodName(methodId);
637         return false;
638     }
639
640     void* _a[] = {nullptr,  // return type...
641                   nullptr,
642                   nullptr,
643                   nullptr,
644                   nullptr,
645                   nullptr,  // and 10 args - that's the max size qt can handle with signals and slots
646                   nullptr,
647                   nullptr,
648                   nullptr,
649                   nullptr,
650                   nullptr};
651
652     // check for argument compatibility and build params array
653     for (int i = 0; i < numArgs; i++) {
654         if (!params[i].isValid()) {
655             qWarning() << "SignalProxy::invokeSlot(): received invalid data for argument number" << i << "of method"
656                        << QString("%1::%2()")
657                               .arg(receiver->metaObject()->className())
658                               .arg(receiver->metaObject()->method(methodId).methodSignature().constData());
659             qWarning() << "                            - make sure all your data types are known by the Qt MetaSystem";
660             return false;
661         }
662         if (args[i] != QMetaType::type(params[i].typeName())) {
663             qWarning() << "SignalProxy::invokeSlot(): incompatible param types to invoke" << eMeta->methodName(methodId);
664             return false;
665         }
666
667         _a[i + 1] = const_cast<void*>(params[i].constData());
668     }
669
670     if (returnValue.type() != QVariant::Invalid)
671         _a[0] = const_cast<void*>(returnValue.constData());
672
673     Qt::ConnectionType type = QThread::currentThread() == receiver->thread() ? Qt::DirectConnection : Qt::QueuedConnection;
674
675     if (type == Qt::DirectConnection) {
676         _sourcePeer = peer;
677         auto result = receiver->qt_metacall(QMetaObject::InvokeMetaMethod, methodId, _a) < 0;
678         _sourcePeer = nullptr;
679         return result;
680     }
681     else {
682         qWarning() << "Queued Connections are not implemented yet";
683         // note to self: qmetaobject.cpp:990 ff
684         return false;
685     }
686 }
687
688 bool SignalProxy::invokeSlot(QObject* receiver, int methodId, const QVariantList& params, Peer* peer)
689 {
690     QVariant ret;
691     return invokeSlot(receiver, methodId, params, ret, peer);
692 }
693
694 void SignalProxy::requestInit(SyncableObject* obj)
695 {
696     if (proxyMode() == Server || obj->isInitialized())
697         return;
698
699     dispatch(InitRequest(obj->syncMetaObject()->className(), obj->objectName()));
700 }
701
702 QVariantMap SignalProxy::initData(SyncableObject* obj) const
703 {
704     return obj->toVariantMap();
705 }
706
707 void SignalProxy::setInitData(SyncableObject* obj, const QVariantMap& properties)
708 {
709     if (obj->isInitialized())
710         return;
711     obj->fromVariantMap(properties);
712     obj->setInitialized();
713     emit objectInitialized(obj);
714     invokeSlot(obj, extendedMetaObject(obj)->updatedRemotelyId());
715 }
716
717 void SignalProxy::customEvent(QEvent* event)
718 {
719     switch ((int)event->type()) {
720     case RemovePeerEvent: {
721         auto* e = static_cast<::RemovePeerEvent*>(event);
722         removePeer(e->peer);
723         event->accept();
724         break;
725     }
726
727     default:
728         qWarning() << Q_FUNC_INFO << "Received unknown custom event:" << event->type();
729         return;
730     }
731 }
732
733 void SignalProxy::sync_call__(const SyncableObject* obj, SignalProxy::ProxyMode modeType, const char* funcname, va_list ap)
734 {
735     // qDebug() << obj << modeType << "(" << _proxyMode << ")" << funcname;
736     if (modeType != _proxyMode)
737         return;
738
739     ExtendedMetaObject* eMeta = extendedMetaObject(obj);
740
741     QVariantList params;
742
743     const QList<int>& argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname)));
744
745     for (int i = 0; i < argTypes.size(); i++) {
746         if (argTypes[i] == 0) {
747             qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal"
748                        << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname);
749             qWarning() << "        - make sure all your data types are known by the Qt MetaSystem";
750             return;
751         }
752         params << QVariant(argTypes[i], va_arg(ap, void*));
753     }
754
755     if (_restrictMessageTarget) {
756         for (auto peer : _restrictedTargets) {
757             if (peer != nullptr)
758                 dispatch(peer, SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
759         }
760     }
761     else
762         dispatch(SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
763 }
764
765 void SignalProxy::disconnectDevice(QIODevice* dev, const QString& reason)
766 {
767     if (!reason.isEmpty())
768         qWarning() << qPrintable(reason);
769     auto* sock = qobject_cast<QAbstractSocket*>(dev);
770     if (sock)
771         qWarning() << qPrintable(tr("Disconnecting")) << qPrintable(sock->peerAddress().toString());
772     dev->close();
773 }
774
775 void SignalProxy::dumpProxyStats()
776 {
777     QString mode;
778     if (proxyMode() == Server)
779         mode = "Server";
780     else
781         mode = "Client";
782
783     int slaveCount = 0;
784     foreach (ObjectId oid, _syncSlave.values())
785         slaveCount += oid.count();
786
787     qDebug() << this;
788     qDebug() << "              Proxy Mode:" << mode;
789     qDebug() << "          attached Slots:" << _attachedSlots.count();
790     qDebug() << " number of synced Slaves:" << slaveCount;
791     qDebug() << "number of Classes cached:" << _extendedMetaObjects.count();
792 }
793
794 void SignalProxy::updateSecureState()
795 {
796     bool wasSecure = _secure;
797
798     _secure = !_peerMap.isEmpty();
799     for (auto peer : _peerMap.values()) {
800         _secure &= peer->isSecure();
801     }
802
803     if (wasSecure != _secure)
804         emit secureStateChanged(_secure);
805 }
806
807 QVariantList SignalProxy::peerData()
808 {
809     QVariantList result;
810     for (auto&& peer : _peerMap.values()) {
811         QVariantMap data;
812         data["id"] = peer->id();
813         data["clientVersion"] = peer->clientVersion();
814         // We explicitly rename this, as, due to the Debian reproducability changes, buildDate isn’t actually the build
815         // date anymore, but on newer clients the date of the last git commit
816         data["clientVersionDate"] = peer->buildDate();
817         data["remoteAddress"] = peer->address();
818         data["connectedSince"] = peer->connectedSince();
819         data["secure"] = peer->isSecure();
820         data["features"] = static_cast<quint32>(peer->features().toLegacyFeatures());
821         data["featureList"] = peer->features().toStringList();
822         result << data;
823     }
824     return result;
825 }
826
827 Peer* SignalProxy::peerById(int peerId)
828 {
829     // We use ::value() here instead of the [] operator because the latter has the side-effect
830     // of automatically inserting a null value with the passed key into the map.  See
831     // https://doc.qt.io/qt-5/qhash.html#operator-5b-5d and https://doc.qt.io/qt-5/qhash.html#value.
832     return _peerMap.value(peerId);
833 }
834
835 void SignalProxy::restrictTargetPeers(QSet<Peer*> peers, std::function<void()> closure)
836 {
837     auto previousRestrictMessageTarget = _restrictMessageTarget;
838     auto previousRestrictedTargets = _restrictedTargets;
839     _restrictMessageTarget = true;
840     _restrictedTargets = peers;
841
842     closure();
843
844     _restrictMessageTarget = previousRestrictMessageTarget;
845     _restrictedTargets = previousRestrictedTargets;
846 }
847
848 Peer* SignalProxy::sourcePeer()
849 {
850     return _sourcePeer;
851 }
852
853 void SignalProxy::setSourcePeer(Peer* sourcePeer)
854 {
855     _sourcePeer = sourcePeer;
856 }
857
858 Peer* SignalProxy::targetPeer()
859 {
860     return _targetPeer;
861 }
862
863 void SignalProxy::setTargetPeer(Peer* targetPeer)
864 {
865     _targetPeer = targetPeer;
866 }
867
868 // ==================================================
869 //  ExtendedMetaObject
870 // ==================================================
871 SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject* meta, bool checkConflicts)
872     : _meta(meta)
873     , _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()"))
874 {
875     for (int i = 0; i < _meta->methodCount(); i++) {
876         if (_meta->method(i).methodType() != QMetaMethod::Slot)
877             continue;
878
879         if (_meta->method(i).methodSignature().contains('*'))
880             continue;  // skip methods with ptr params
881
882         QByteArray method = methodName(_meta->method(i));
883         if (method.startsWith("init"))
884             continue;  // skip initializers
885
886         if (_methodIds.contains(method)) {
887             /* funny... moc creates for methods containing default parameters multiple metaMethod with separate methodIds.
888                we don't care... we just need the full fledged version
889              */
890             const QMetaMethod& current = _meta->method(_methodIds[method]);
891             const QMetaMethod& candidate = _meta->method(i);
892             if (current.parameterTypes().count() > candidate.parameterTypes().count()) {
893                 int minCount = candidate.parameterTypes().count();
894                 QList<QByteArray> commonParams = current.parameterTypes().mid(0, minCount);
895                 if (commonParams == candidate.parameterTypes())
896                     continue;  // we already got the full featured version
897             }
898             else {
899                 int minCount = current.parameterTypes().count();
900                 QList<QByteArray> commonParams = candidate.parameterTypes().mid(0, minCount);
901                 if (commonParams == current.parameterTypes()) {
902                     _methodIds[method] = i;  // use the new one
903                     continue;
904                 }
905             }
906             if (checkConflicts) {
907                 qWarning() << "class" << meta->className() << "contains overloaded methods which is currently not supported!";
908                 qWarning() << " - " << _meta->method(i).methodSignature() << "conflicts with"
909                            << _meta->method(_methodIds[method]).methodSignature();
910             }
911             continue;
912         }
913         _methodIds[method] = i;
914     }
915 }
916
917 const SignalProxy::ExtendedMetaObject::MethodDescriptor& SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId)
918 {
919     if (!_methods.contains(methodId)) {
920         _methods[methodId] = MethodDescriptor(_meta->method(methodId));
921     }
922     return _methods[methodId];
923 }
924
925 const QHash<int, int>& SignalProxy::ExtendedMetaObject::receiveMap()
926 {
927     if (_receiveMap.isEmpty()) {
928         QHash<int, int> receiveMap;
929
930         QMetaMethod requestSlot;
931         QByteArray returnTypeName;
932         QByteArray signature;
933         QByteArray methodName;
934         QByteArray params;
935         int paramsPos;
936         int receiverId;
937         const int methodCount = _meta->methodCount();
938         for (int i = 0; i < methodCount; i++) {
939             requestSlot = _meta->method(i);
940             if (requestSlot.methodType() != QMetaMethod::Slot)
941                 continue;
942
943             returnTypeName = requestSlot.typeName();
944             if (QMetaType::Void == (QMetaType::Type)returnType(i))
945                 continue;
946
947             signature = requestSlot.methodSignature();
948             if (!signature.startsWith("request"))
949                 continue;
950
951             paramsPos = signature.indexOf('(');
952             if (paramsPos == -1)
953                 continue;
954
955             methodName = signature.left(paramsPos);
956             params = signature.mid(paramsPos);
957
958             methodName = methodName.replace("request", "receive");
959             params = params.left(params.count() - 1) + ", " + returnTypeName + ")";
960
961             signature = QMetaObject::normalizedSignature(methodName + params);
962             receiverId = _meta->indexOfSlot(signature);
963
964             if (receiverId == -1) {
965                 signature = QMetaObject::normalizedSignature(methodName + "(" + returnTypeName + ")");
966                 receiverId = _meta->indexOfSlot(signature);
967             }
968
969             if (receiverId != -1) {
970                 receiveMap[i] = receiverId;
971             }
972         }
973         _receiveMap = receiveMap;
974     }
975     return _receiveMap;
976 }
977
978 QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod& method)
979 {
980     QByteArray sig(method.methodSignature());
981     return sig.left(sig.indexOf("("));
982 }
983
984 QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod& method)
985 {
986     QString methodname = QString(method.methodSignature()).section("(", 0, 0);
987
988     // determine where we have to chop:
989     int upperCharPos;
990     if (method.methodType() == QMetaMethod::Slot) {
991         // we take evertyhing from the first uppercase char if it's slot
992         upperCharPos = methodname.indexOf(QRegExp("[A-Z]"));
993         if (upperCharPos == -1)
994             return QString();
995         methodname = methodname.mid(upperCharPos);
996     }
997     else {
998         // and if it's a signal we discard everything from the last uppercase char
999         upperCharPos = methodname.lastIndexOf(QRegExp("[A-Z]"));
1000         if (upperCharPos == -1)
1001             return QString();
1002         methodname = methodname.left(upperCharPos);
1003     }
1004
1005     methodname[0] = methodname[0].toUpper();
1006
1007     return methodname;
1008 }
1009
1010 SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod& method)
1011     : _methodName(SignalProxy::ExtendedMetaObject::methodName(method))
1012     , _returnType(QMetaType::type(method.typeName()))
1013 {
1014     // determine argTypes
1015     QList<QByteArray> paramTypes = method.parameterTypes();
1016     QList<int> argTypes;
1017     for (int i = 0; i < paramTypes.count(); i++) {
1018         argTypes.append(QMetaType::type(paramTypes[i]));
1019     }
1020     _argTypes = argTypes;
1021
1022     // determine minArgCount
1023     QString signature(method.methodSignature());
1024     _minArgCount = method.parameterTypes().count() - signature.count("=");
1025
1026     _receiverMode = (_methodName.startsWith("request")) ? SignalProxy::Server : SignalProxy::Client;
1027 }