f0711f16dfda7585be4192bc4651c8d35839e335
[quassel.git] / src / common / signalproxy.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include <QCoreApplication>
22 #include <QHostAddress>
23 #include <QMetaMethod>
24 #include <QMetaProperty>
25 #include <QThread>
26
27 #ifdef HAVE_SSL
28     #include <QSslSocket>
29 #endif
30
31 #include "signalproxy.h"
32
33 #include "peer.h"
34 #include "protocol.h"
35 #include "syncableobject.h"
36 #include "util.h"
37 #include "types.h"
38
39 using namespace Protocol;
40
41 class RemovePeerEvent : public QEvent
42 {
43 public:
44     RemovePeerEvent(Peer *peer) : QEvent(QEvent::Type(SignalProxy::RemovePeerEvent)), peer(peer) {}
45     Peer *peer;
46 };
47
48
49 // ==================================================
50 //  SignalRelay
51 // ==================================================
52 class SignalProxy::SignalRelay : public QObject
53 {
54 /* Q_OBJECT is not necessary or even allowed, because we implement
55    qt_metacall ourselves (and don't use any other features of the meta
56    object system)
57 */
58 public:
59     SignalRelay(SignalProxy *parent) : QObject(parent), _proxy(parent) {}
60     inline SignalProxy *proxy() const { return _proxy; }
61
62     int qt_metacall(QMetaObject::Call _c, int _id, void **_a) override;
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(nullptr), signalId(-1) {}
74     };
75
76     SignalProxy *_proxy;
77     QHash<int, Signal> _slots;
78 };
79
80
81 void SignalProxy::SignalRelay::attachSignal(QObject *sender, int signalId, const QByteArray &funcName)
82 {
83     // we ride without safetybelts here... all checking for valid method etc pp has to be done by the caller
84     // all connected methodIds are offset by the standard methodCount of QObject
85     int slotId;
86     for (int i = 0;; i++) {
87         if (!_slots.contains(i)) {
88             slotId = i;
89             break;
90         }
91     }
92
93     QByteArray fn;
94     if (!funcName.isEmpty()) {
95         fn = QMetaObject::normalizedSignature(funcName);
96     }
97     else {
98         fn = SIGNAL(fakeMethodSignature());
99         fn = fn.replace("fakeMethodSignature()", sender->metaObject()->method(signalId).methodSignature());
100     }
101
102     _slots[slotId] = Signal(sender, signalId, fn);
103
104     QMetaObject::connect(sender, signalId, this, QObject::staticMetaObject.methodCount() + slotId);
105 }
106
107
108 void SignalProxy::SignalRelay::detachSignal(QObject *sender, int signalId)
109 {
110     QHash<int, Signal>::iterator slotIter = _slots.begin();
111     while (slotIter != _slots.end()) {
112         if (slotIter->sender == sender && (signalId == -1 || slotIter->signalId == signalId)) {
113             slotIter = _slots.erase(slotIter);
114             if (signalId != -1)
115                 break;
116         }
117         else {
118             ++slotIter;
119         }
120     }
121 }
122
123
124 int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
125 {
126     _id = QObject::qt_metacall(_c, _id, _a);
127     if (_id < 0)
128         return _id;
129
130     if (_c == QMetaObject::InvokeMetaMethod) {
131         if (_slots.contains(_id)) {
132             QObject *caller = sender();
133
134             SignalProxy::ExtendedMetaObject *eMeta = proxy()->extendedMetaObject(caller->metaObject());
135             Q_ASSERT(eMeta);
136
137             const Signal &signal = _slots[_id];
138
139             QVariantList params;
140
141             const QList<int> &argTypes = eMeta->argTypes(signal.signalId);
142             for (int i = 0; i < argTypes.size(); i++) {
143                 if (argTypes[i] == 0) {
144                     qWarning() << "SignalRelay::qt_metacall(): received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(caller->metaObject()->className()).arg(caller->metaObject()->method(signal.signalId).methodSignature().constData());
145                     qWarning() << "                            - make sure all your data types are known by the Qt MetaSystem";
146                     return _id;
147                 }
148                 params << QVariant(argTypes[i], _a[i+1]);
149             }
150
151             if (proxy()->_restrictMessageTarget) {
152                 for (auto peer : proxy()->_restrictedTargets) {
153                     if (peer != nullptr)
154                         proxy()->dispatch(peer, RpcCall(signal.signature, params));
155                 }
156             } else
157                 proxy()->dispatch(RpcCall(signal.signature, params));
158         }
159         _id -= _slots.count();
160     }
161     return _id;
162 }
163
164
165 // ==================================================
166 //  SignalProxy
167 // ==================================================
168
169 namespace {
170 thread_local SignalProxy *_current{nullptr};
171 }
172
173 SignalProxy::SignalProxy(QObject *parent)
174     : QObject(parent)
175 {
176     setProxyMode(Client);
177     init();
178 }
179
180
181 SignalProxy::SignalProxy(ProxyMode mode, QObject *parent)
182     : QObject(parent)
183 {
184     setProxyMode(mode);
185     init();
186 }
187
188
189 SignalProxy::~SignalProxy()
190 {
191     QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
192     while (classIter != _syncSlave.end()) {
193         ObjectId::iterator objIter = classIter->begin();
194         while (objIter != classIter->end()) {
195             SyncableObject *obj = objIter.value();
196             objIter = classIter->erase(objIter);
197             obj->stopSynchronize(this);
198         }
199         ++classIter;
200     }
201     _syncSlave.clear();
202
203     removeAllPeers();
204
205     _current = nullptr;
206 }
207
208
209 SignalProxy *SignalProxy::current()
210 {
211     return _current;
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, nullptr, this, nullptr);
344     peer->setSignalProxy(nullptr);
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 nullptr;
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[] = { nullptr,           // return type...
666                    nullptr, nullptr, nullptr, nullptr, nullptr, // and 10 args - that's the max size qt can handle with signals and slots
667                    nullptr, nullptr, nullptr, nullptr, nullptr };
668
669     // check for argument compatibility and build params array
670     for (int i = 0; i < numArgs; i++) {
671         if (!params[i].isValid()) {
672             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());
673             qWarning() << "                            - make sure all your data types are known by the Qt MetaSystem";
674             return false;
675         }
676         if (args[i] != QMetaType::type(params[i].typeName())) {
677             qWarning() << "SignalProxy::invokeSlot(): incompatible param types to invoke" << eMeta->methodName(methodId);
678             return false;
679         }
680
681         _a[i+1] = const_cast<void *>(params[i].constData());
682     }
683
684     if (returnValue.type() != QVariant::Invalid)
685         _a[0] = const_cast<void *>(returnValue.constData());
686
687     Qt::ConnectionType type = QThread::currentThread() == receiver->thread()
688                               ? Qt::DirectConnection
689                               : Qt::QueuedConnection;
690
691     if (type == Qt::DirectConnection) {
692         _sourcePeer = peer;
693         auto result = receiver->qt_metacall(QMetaObject::InvokeMetaMethod, methodId, _a) < 0;
694         _sourcePeer = nullptr;
695         return result;
696     } else {
697         qWarning() << "Queued Connections are not implemented yet";
698         // note to self: qmetaobject.cpp:990 ff
699         return false;
700     }
701 }
702
703
704 bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList &params, Peer *peer)
705 {
706     QVariant ret;
707     return invokeSlot(receiver, methodId, params, ret, peer);
708 }
709
710
711 void SignalProxy::requestInit(SyncableObject *obj)
712 {
713     if (proxyMode() == Server || obj->isInitialized())
714         return;
715
716     dispatch(InitRequest(obj->syncMetaObject()->className(), obj->objectName()));
717 }
718
719
720 QVariantMap SignalProxy::initData(SyncableObject *obj) const
721 {
722     return obj->toVariantMap();
723 }
724
725
726 void SignalProxy::setInitData(SyncableObject *obj, const QVariantMap &properties)
727 {
728     if (obj->isInitialized())
729         return;
730     obj->fromVariantMap(properties);
731     obj->setInitialized();
732     emit objectInitialized(obj);
733     invokeSlot(obj, extendedMetaObject(obj)->updatedRemotelyId());
734 }
735
736
737 void SignalProxy::customEvent(QEvent *event)
738 {
739     switch ((int)event->type()) {
740     case RemovePeerEvent: {
741         ::RemovePeerEvent *e = static_cast< ::RemovePeerEvent *>(event);
742         removePeer(e->peer);
743         event->accept();
744         break;
745     }
746
747     default:
748         qWarning() << Q_FUNC_INFO << "Received unknown custom event:" << event->type();
749         return;
750     }
751 }
752
753
754 void SignalProxy::sync_call__(const SyncableObject *obj, SignalProxy::ProxyMode modeType, const char *funcname, va_list ap)
755 {
756     // qDebug() << obj << modeType << "(" << _proxyMode << ")" << funcname;
757     if (modeType != _proxyMode)
758         return;
759
760     ExtendedMetaObject *eMeta = extendedMetaObject(obj);
761
762     QVariantList params;
763
764     const QList<int> &argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname)));
765
766     for (int i = 0; i < argTypes.size(); i++) {
767         if (argTypes[i] == 0) {
768             qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname);
769             qWarning() << "        - make sure all your data types are known by the Qt MetaSystem";
770             return;
771         }
772         params << QVariant(argTypes[i], va_arg(ap, void *));
773     }
774
775     if (_restrictMessageTarget) {
776         for (auto peer : _restrictedTargets) {
777             if (peer != nullptr)
778                 dispatch(peer, SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
779         }
780     } else
781         dispatch(SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
782 }
783
784
785 void SignalProxy::disconnectDevice(QIODevice *dev, const QString &reason)
786 {
787     if (!reason.isEmpty())
788         qWarning() << qPrintable(reason);
789     QAbstractSocket *sock  = qobject_cast<QAbstractSocket *>(dev);
790     if (sock)
791         qWarning() << qPrintable(tr("Disconnecting")) << qPrintable(sock->peerAddress().toString());
792     dev->close();
793 }
794
795
796 void SignalProxy::dumpProxyStats()
797 {
798     QString mode;
799     if (proxyMode() == Server)
800         mode = "Server";
801     else
802         mode = "Client";
803
804     int slaveCount = 0;
805     foreach(ObjectId oid, _syncSlave.values())
806     slaveCount += oid.count();
807
808     qDebug() << this;
809     qDebug() << "              Proxy Mode:" << mode;
810     qDebug() << "          attached Slots:" << _attachedSlots.count();
811     qDebug() << " number of synced Slaves:" << slaveCount;
812     qDebug() << "number of Classes cached:" << _extendedMetaObjects.count();
813 }
814
815
816 void SignalProxy::updateSecureState()
817 {
818     bool wasSecure = _secure;
819
820     _secure = !_peerMap.isEmpty();
821     for (auto peer :  _peerMap.values()) {
822         _secure &= peer->isSecure();
823     }
824
825     if (wasSecure != _secure)
826         emit secureStateChanged(_secure);
827 }
828
829 QVariantList SignalProxy::peerData() {
830     QVariantList result;
831     for (auto &&peer : _peerMap.values()) {
832         QVariantMap data;
833         data["id"] = peer->id();
834         data["clientVersion"] = peer->clientVersion();
835         // We explicitly rename this, as, due to the Debian reproducability changes, buildDate isn’t actually the build
836         // date anymore, but on newer clients the date of the last git commit
837         data["clientVersionDate"] = peer->buildDate();
838         data["remoteAddress"] = peer->address();
839         data["connectedSince"] = peer->connectedSince();
840         data["secure"] = peer->isSecure();
841         data["features"] = static_cast<quint32>(peer->features().toLegacyFeatures());
842         data["featureList"] = peer->features().toStringList();
843         result << data;
844     }
845     return result;
846 }
847
848 Peer *SignalProxy::peerById(int peerId) {
849     // We use ::value() here instead of the [] operator because the latter has the side-effect
850     // of automatically inserting a null value with the passed key into the map.  See
851     // https://doc.qt.io/qt-5/qhash.html#operator-5b-5d and https://doc.qt.io/qt-5/qhash.html#value.
852     return _peerMap.value(peerId);
853 }
854
855 void SignalProxy::restrictTargetPeers(QSet<Peer*> peers, std::function<void()> closure)
856 {
857     auto previousRestrictMessageTarget = _restrictMessageTarget;
858     auto previousRestrictedTargets = _restrictedTargets;
859     _restrictMessageTarget = true;
860     _restrictedTargets = peers;
861
862     closure();
863
864     _restrictMessageTarget = previousRestrictMessageTarget;
865     _restrictedTargets = previousRestrictedTargets;
866 }
867
868 Peer *SignalProxy::sourcePeer() {
869     return _sourcePeer;
870 }
871
872 void SignalProxy::setSourcePeer(Peer *sourcePeer) {
873     _sourcePeer = sourcePeer;
874 }
875
876 Peer *SignalProxy::targetPeer() {
877     return _targetPeer;
878 }
879
880 void SignalProxy::setTargetPeer(Peer *targetPeer) {
881     _targetPeer = targetPeer;
882 }
883
884 // ==================================================
885 //  ExtendedMetaObject
886 // ==================================================
887 SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
888     : _meta(meta),
889     _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()"))
890 {
891     for (int i = 0; i < _meta->methodCount(); i++) {
892         if (_meta->method(i).methodType() != QMetaMethod::Slot)
893             continue;
894
895         if (_meta->method(i).methodSignature().contains('*'))
896             continue;  // skip methods with ptr params
897
898         QByteArray method = methodName(_meta->method(i));
899         if (method.startsWith("init"))
900             continue;  // skip initializers
901
902         if (_methodIds.contains(method)) {
903             /* funny... moc creates for methods containing default parameters multiple metaMethod with separate methodIds.
904                we don't care... we just need the full fledged version
905              */
906             const QMetaMethod &current = _meta->method(_methodIds[method]);
907             const QMetaMethod &candidate = _meta->method(i);
908             if (current.parameterTypes().count() > candidate.parameterTypes().count()) {
909                 int minCount = candidate.parameterTypes().count();
910                 QList<QByteArray> commonParams = current.parameterTypes().mid(0, minCount);
911                 if (commonParams == candidate.parameterTypes())
912                     continue;  // we already got the full featured version
913             }
914             else {
915                 int minCount = current.parameterTypes().count();
916                 QList<QByteArray> commonParams = candidate.parameterTypes().mid(0, minCount);
917                 if (commonParams == current.parameterTypes()) {
918                     _methodIds[method] = i; // use the new one
919                     continue;
920                 }
921             }
922             if (checkConflicts) {
923                 qWarning() << "class" << meta->className() << "contains overloaded methods which is currently not supported!";
924                 qWarning() << " - " << _meta->method(i).methodSignature() << "conflicts with" << _meta->method(_methodIds[method]).methodSignature();
925             }
926             continue;
927         }
928         _methodIds[method] = i;
929     }
930 }
931
932
933 const SignalProxy::ExtendedMetaObject::MethodDescriptor &SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId)
934 {
935     if (!_methods.contains(methodId)) {
936         _methods[methodId] = MethodDescriptor(_meta->method(methodId));
937     }
938     return _methods[methodId];
939 }
940
941
942 const QHash<int, int> &SignalProxy::ExtendedMetaObject::receiveMap()
943 {
944     if (_receiveMap.isEmpty()) {
945         QHash<int, int> receiveMap;
946
947         QMetaMethod requestSlot;
948         QByteArray returnTypeName;
949         QByteArray signature;
950         QByteArray methodName;
951         QByteArray params;
952         int paramsPos;
953         int receiverId;
954         const int methodCount = _meta->methodCount();
955         for (int i = 0; i < methodCount; i++) {
956             requestSlot = _meta->method(i);
957             if (requestSlot.methodType() != QMetaMethod::Slot)
958                 continue;
959
960             returnTypeName = requestSlot.typeName();
961             if (QMetaType::Void == (QMetaType::Type)returnType(i))
962                 continue;
963
964             signature = requestSlot.methodSignature();
965             if (!signature.startsWith("request"))
966                 continue;
967
968             paramsPos = signature.indexOf('(');
969             if (paramsPos == -1)
970                 continue;
971
972             methodName = signature.left(paramsPos);
973             params = signature.mid(paramsPos);
974
975             methodName = methodName.replace("request", "receive");
976             params = params.left(params.count() - 1) + ", " + returnTypeName + ")";
977
978             signature = QMetaObject::normalizedSignature(methodName + params);
979             receiverId = _meta->indexOfSlot(signature);
980
981             if (receiverId == -1) {
982                 signature = QMetaObject::normalizedSignature(methodName + "(" + returnTypeName + ")");
983                 receiverId = _meta->indexOfSlot(signature);
984             }
985
986             if (receiverId != -1) {
987                 receiveMap[i] = receiverId;
988             }
989         }
990         _receiveMap = receiveMap;
991     }
992     return _receiveMap;
993 }
994
995
996 QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod &method)
997 {
998     QByteArray sig(method.methodSignature());
999     return sig.left(sig.indexOf("("));
1000 }
1001
1002
1003 QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod &method)
1004 {
1005     QString methodname = QString(method.methodSignature()).section("(", 0, 0);
1006
1007     // determine where we have to chop:
1008     int upperCharPos;
1009     if (method.methodType() == QMetaMethod::Slot) {
1010         // we take evertyhing from the first uppercase char if it's slot
1011         upperCharPos = methodname.indexOf(QRegExp("[A-Z]"));
1012         if (upperCharPos == -1)
1013             return QString();
1014         methodname = methodname.mid(upperCharPos);
1015     }
1016     else {
1017         // and if it's a signal we discard everything from the last uppercase char
1018         upperCharPos = methodname.lastIndexOf(QRegExp("[A-Z]"));
1019         if (upperCharPos == -1)
1020             return QString();
1021         methodname = methodname.left(upperCharPos);
1022     }
1023
1024     methodname[0] = methodname[0].toUpper();
1025
1026     return methodname;
1027 }
1028
1029
1030 SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod &method)
1031     : _methodName(SignalProxy::ExtendedMetaObject::methodName(method)),
1032     _returnType(QMetaType::type(method.typeName()))
1033 {
1034     // determine argTypes
1035     QList<QByteArray> paramTypes = method.parameterTypes();
1036     QList<int> argTypes;
1037     for (int i = 0; i < paramTypes.count(); i++) {
1038         argTypes.append(QMetaType::type(paramTypes[i]));
1039     }
1040     _argTypes = argTypes;
1041
1042     // determine minArgCount
1043     QString signature(method.methodSignature());
1044     _minArgCount = method.parameterTypes().count() - signature.count("=");
1045
1046     _receiverMode = (_methodName.startsWith("request"))
1047                     ? SignalProxy::Server
1048                     : SignalProxy::Client;
1049 }