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