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