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