~ubuntu-branches/ubuntu/trusty/quassel/trusty-proposed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
/***************************************************************************
 *   Copyright (C) 2005-2014 by the Quassel Project                        *
 *   devel@quassel-irc.org                                                 *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) version 3.                                           *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QCoreApplication>
#include <QHostAddress>
#include <QMetaMethod>
#include <QMetaProperty>
#include <QThread>

#ifdef HAVE_SSL
    #include <QSslSocket>
#endif

#include "signalproxy.h"

#include "peer.h"
#include "protocol.h"
#include "syncableobject.h"
#include "util.h"
#include "types.h"

using namespace Protocol;

class RemovePeerEvent : public QEvent
{
public:
    RemovePeerEvent(Peer *peer) : QEvent(QEvent::Type(SignalProxy::RemovePeerEvent)), peer(peer) {}
    Peer *peer;
};


// ==================================================
//  SignalRelay
// ==================================================
class SignalProxy::SignalRelay : public QObject
{
/* Q_OBJECT is not necessary or even allowed, because we implement
   qt_metacall ourselves (and don't use any other features of the meta
   object system)
*/
public:
    SignalRelay(SignalProxy *parent) : QObject(parent), _proxy(parent) {}
    inline SignalProxy *proxy() const { return _proxy; }

    int qt_metacall(QMetaObject::Call _c, int _id, void **_a);

    void attachSignal(QObject *sender, int signalId, const QByteArray &funcName);
    void detachSignal(QObject *sender, int signalId = -1);

private:
    struct Signal {
        QObject *sender;
        int signalId;
        QByteArray signature;
        Signal(QObject *sender, int sigId, const QByteArray &signature) : sender(sender), signalId(sigId), signature(signature) {}
        Signal() : sender(0), signalId(-1) {}
    };

    SignalProxy *_proxy;
    QHash<int, Signal> _slots;
};


void SignalProxy::SignalRelay::attachSignal(QObject *sender, int signalId, const QByteArray &funcName)
{
    // we ride without safetybelts here... all checking for valid method etc pp has to be done by the caller
    // all connected methodIds are offset by the standard methodCount of QObject
    int slotId;
    for (int i = 0;; i++) {
        if (!_slots.contains(i)) {
            slotId = i;
            break;
        }
    }

    QByteArray fn;
    if (!funcName.isEmpty()) {
        fn = QMetaObject::normalizedSignature(funcName);
    }
    else {
        fn = SIGNAL(fakeMethodSignature());
        fn = fn.replace("fakeMethodSignature()", sender->metaObject()->method(signalId).signature());
    }

    _slots[slotId] = Signal(sender, signalId, fn);

    QMetaObject::connect(sender, signalId, this, QObject::staticMetaObject.methodCount() + slotId);
}


void SignalProxy::SignalRelay::detachSignal(QObject *sender, int signalId)
{
    QHash<int, Signal>::iterator slotIter = _slots.begin();
    while (slotIter != _slots.end()) {
        if (slotIter->sender == sender && (signalId == -1 || slotIter->signalId == signalId)) {
            slotIter = _slots.erase(slotIter);
            if (signalId != -1)
                break;
        }
        else {
            slotIter++;
        }
    }
}


int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;

    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_slots.contains(_id)) {
            QObject *caller = sender();

            SignalProxy::ExtendedMetaObject *eMeta = proxy()->extendedMetaObject(caller->metaObject());
            Q_ASSERT(eMeta);

            const Signal &signal = _slots[_id];

            QVariantList params;

            const QList<int> &argTypes = eMeta->argTypes(signal.signalId);
            for (int i = 0; i < argTypes.size(); i++) {
                if (argTypes[i] == 0) {
                    qWarning() << "SignalRelay::qt_metacall(): received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(caller->metaObject()->className()).arg(caller->metaObject()->method(_id).signature());
                    qWarning() << "                            - make sure all your data types are known by the Qt MetaSystem";
                    return _id;
                }
                params << QVariant(argTypes[i], _a[i+1]);
            }

            if (argTypes.size() >= 1 && argTypes[0] == qMetaTypeId<PeerPtr>() && proxy()->proxyMode() == SignalProxy::Server) {
                Peer *peer = params[0].value<PeerPtr>();
                proxy()->dispatch(peer, RpcCall(signal.signature, params));
            } else
                proxy()->dispatch(RpcCall(signal.signature, params));
        }
        _id -= _slots.count();
    }
    return _id;
}


// ==================================================
//  SignalProxy
// ==================================================
SignalProxy::SignalProxy(QObject *parent)
    : QObject(parent)
{
    setProxyMode(Client);
    init();
}


SignalProxy::SignalProxy(ProxyMode mode, QObject *parent)
    : QObject(parent)
{
    setProxyMode(mode);
    init();
}


SignalProxy::~SignalProxy()
{
    QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
    while (classIter != _syncSlave.end()) {
        ObjectId::iterator objIter = classIter->begin();
        while (objIter != classIter->end()) {
            SyncableObject *obj = objIter.value();
            objIter = classIter->erase(objIter);
            obj->stopSynchronize(this);
        }
        classIter++;
    }
    _syncSlave.clear();

    removeAllPeers();
}


void SignalProxy::setProxyMode(ProxyMode mode)
{
    if (_peers.count()) {
        qWarning() << Q_FUNC_INFO << "Cannot change proxy mode while connected";
        return;
    }

    _proxyMode = mode;
    if (mode == Server)
        initServer();
    else
        initClient();
}


void SignalProxy::init()
{
    _heartBeatInterval = 0;
    _maxHeartBeatCount = 0;
    _signalRelay = new SignalRelay(this);
    setHeartBeatInterval(30);
    setMaxHeartBeatCount(2);
    _secure = false;
    updateSecureState();
}


void SignalProxy::initServer()
{
}


void SignalProxy::initClient()
{
    attachSlot("__objectRenamed__", this, SLOT(objectRenamed(QByteArray,QString,QString)));
}


void SignalProxy::setHeartBeatInterval(int secs)
{
    if (_heartBeatInterval != secs) {
        _heartBeatInterval = secs;
        emit heartBeatIntervalChanged(secs);
    }
}


void SignalProxy::setMaxHeartBeatCount(int max)
{
    if (_maxHeartBeatCount != max) {
        _maxHeartBeatCount = max;
        emit maxHeartBeatCountChanged(max);
    }
}


bool SignalProxy::addPeer(Peer *peer)
{
    if (!peer)
        return false;

    if (_peers.contains(peer))
        return true;

    if (!peer->isOpen()) {
        qWarning("SignalProxy: peer needs to be open!");
        return false;
    }

    if (proxyMode() == Client) {
        if (!_peers.isEmpty()) {
            qWarning("SignalProxy: only one peer allowed in client mode!");
            return false;
        }
        connect(peer, SIGNAL(lagUpdated(int)), SIGNAL(lagUpdated(int)));
    }

    connect(peer, SIGNAL(disconnected()), SLOT(removePeerBySender()));
    connect(peer, SIGNAL(secureStateChanged(bool)), SLOT(updateSecureState()));

    if (!peer->parent())
        peer->setParent(this);

    _peers.insert(peer);

    peer->setSignalProxy(this);

    if (_peers.count() == 1)
        emit connected();

    updateSecureState();
    return true;
}


void SignalProxy::removeAllPeers()
{
    Q_ASSERT(proxyMode() == Server || _peers.count() <= 1);
    // wee need to copy that list since we modify it in the loop
    QSet<Peer *> peers = _peers;
    foreach(Peer *peer, peers) {
        removePeer(peer);
    }
}


void SignalProxy::removePeer(Peer *peer)
{
    if (!peer) {
        qWarning() << Q_FUNC_INFO << "Trying to remove a null peer!";
        return;
    }

    if (_peers.isEmpty()) {
        qWarning() << "SignalProxy::removePeer(): No peers in use!";
        return;
    }

    if (!_peers.contains(peer)) {
        qWarning() << "SignalProxy: unknown Peer" << peer;
        return;
    }

    disconnect(peer, 0, this, 0);
    peer->setSignalProxy(0);

    _peers.remove(peer);
    emit peerRemoved(peer);

    if (peer->parent() == this)
        peer->deleteLater();

    updateSecureState();

    if (_peers.isEmpty())
        emit disconnected();
}


void SignalProxy::removePeerBySender()
{
    removePeer(qobject_cast<Peer *>(sender()));
}


void SignalProxy::renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname)
{
    if (proxyMode() == Client)
        return;

    const QMetaObject *meta = obj->syncMetaObject();
    const QByteArray className(meta->className());
    objectRenamed(className, newname, oldname);

    dispatch(RpcCall("__objectRenamed__", QVariantList() << className << newname << oldname));
}


void SignalProxy::objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname)
{
    if (_syncSlave.contains(classname) && _syncSlave[classname].contains(oldname) && oldname != newname) {
        SyncableObject *obj = _syncSlave[classname][newname] = _syncSlave[classname].take(oldname);
        requestInit(obj);
    }
}


const QMetaObject *SignalProxy::metaObject(const QObject *obj)
{
    if (const SyncableObject *syncObject = qobject_cast<const SyncableObject *>(obj))
        return syncObject->syncMetaObject();
    else
        return obj->metaObject();
}


SignalProxy::ExtendedMetaObject *SignalProxy::extendedMetaObject(const QMetaObject *meta) const
{
    if (_extendedMetaObjects.contains(meta))
        return _extendedMetaObjects[meta];
    else
        return 0;
}


SignalProxy::ExtendedMetaObject *SignalProxy::createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
{
    if (!_extendedMetaObjects.contains(meta)) {
        _extendedMetaObjects[meta] = new ExtendedMetaObject(meta, checkConflicts);
    }
    return _extendedMetaObjects[meta];
}


bool SignalProxy::attachSignal(QObject *sender, const char *signal, const QByteArray &sigName)
{
    const QMetaObject *meta = sender->metaObject();
    QByteArray sig(meta->normalizedSignature(signal).mid(1));
    int methodId = meta->indexOfMethod(sig.constData());
    if (methodId == -1 || meta->method(methodId).methodType() != QMetaMethod::Signal) {
        qWarning() << "SignalProxy::attachSignal(): No such signal" << signal;
        return false;
    }

    createExtendedMetaObject(meta);
    _signalRelay->attachSignal(sender, methodId, sigName);

    disconnect(sender, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
    connect(sender, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
    return true;
}


bool SignalProxy::attachSlot(const QByteArray &sigName, QObject *recv, const char *slot)
{
    const QMetaObject *meta = recv->metaObject();
    int methodId = meta->indexOfMethod(meta->normalizedSignature(slot).mid(1));
    if (methodId == -1 || meta->method(methodId).methodType() == QMetaMethod::Method) {
        qWarning() << "SignalProxy::attachSlot(): No such slot" << slot;
        return false;
    }

    createExtendedMetaObject(meta);

    QByteArray funcName = QMetaObject::normalizedSignature(sigName.constData());
    _attachedSlots.insert(funcName, qMakePair(recv, methodId));

    disconnect(recv, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
    connect(recv, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
    return true;
}


void SignalProxy::synchronize(SyncableObject *obj)
{
    createExtendedMetaObject(obj, true);

    // attaching as slave to receive sync Calls
    QByteArray className(obj->syncMetaObject()->className());
    _syncSlave[className][obj->objectName()] = obj;

    if (proxyMode() == Server) {
        obj->setInitialized();
        emit objectInitialized(obj);
    }
    else {
        if (obj->isInitialized())
            emit objectInitialized(obj);
        else
            requestInit(obj);
    }

    obj->synchronize(this);
}


void SignalProxy::detachObject(QObject *obj)
{
    detachSignals(obj);
    detachSlots(obj);
}


void SignalProxy::detachSignals(QObject *sender)
{
    _signalRelay->detachSignal(sender);
}


void SignalProxy::detachSlots(QObject *receiver)
{
    SlotHash::iterator slotIter = _attachedSlots.begin();
    while (slotIter != _attachedSlots.end()) {
        if (slotIter.value().first == receiver) {
            slotIter = _attachedSlots.erase(slotIter);
        }
        else
            slotIter++;
    }
}


void SignalProxy::stopSynchronize(SyncableObject *obj)
{
    // we can't use a className here, since it might be effed up, if we receive the call as a result of a decon
    // gladly the objectName() is still valid. So we have only to iterate over the classes not each instance! *sigh*
    QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
    while (classIter != _syncSlave.end()) {
        if (classIter->contains(obj->objectName()) && classIter.value()[obj->objectName()] == obj) {
            classIter->remove(obj->objectName());
            break;
        }
        classIter++;
    }
    obj->stopSynchronize(this);
}


template<class T>
void SignalProxy::dispatch(const T &protoMessage)
{
    foreach (Peer *peer, _peers) {
        if (peer->isOpen())
            peer->dispatch(protoMessage);
        else
            QCoreApplication::postEvent(this, new ::RemovePeerEvent(peer));
    }
}


template<class T>
void SignalProxy::dispatch(Peer *peer, const T &protoMessage)
{
    if (peer && peer->isOpen())
        peer->dispatch(protoMessage);
    else
        QCoreApplication::postEvent(this, new ::RemovePeerEvent(peer));
}


void SignalProxy::handle(Peer *peer, const SyncMessage &syncMessage)
{
    if (!_syncSlave.contains(syncMessage.className) || !_syncSlave[syncMessage.className].contains(syncMessage.objectName)) {
        qWarning() << QString("no registered receiver for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
                   << syncMessage.params;
        return;
    }

    SyncableObject *receiver = _syncSlave[syncMessage.className][syncMessage.objectName];
    ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
    if (!eMeta->slotMap().contains(syncMessage.slotName)) {
        qWarning() << QString("no matching slot for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
                   << syncMessage.params;
        return;
    }

    int slotId = eMeta->slotMap()[syncMessage.slotName];
    if (proxyMode() != eMeta->receiverMode(slotId)) {
        qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed. Wrong ProxyMode!", eMeta->methodName(slotId).constData());
        return;
    }

    QVariant returnValue((QVariant::Type)eMeta->returnType(slotId));
    if (!invokeSlot(receiver, slotId, syncMessage.params, returnValue, peer)) {
        qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed ", eMeta->methodName(slotId).constData());
        return;
    }

    if (returnValue.type() != QVariant::Invalid && eMeta->receiveMap().contains(slotId)) {
        int receiverId = eMeta->receiveMap()[slotId];
        QVariantList returnParams;
        if (eMeta->argTypes(receiverId).count() > 1)
            returnParams << syncMessage.params;
        returnParams << returnValue;
        peer->dispatch(SyncMessage(syncMessage.className, syncMessage.objectName, eMeta->methodName(receiverId), returnParams));
    }

    // send emit update signal
    invokeSlot(receiver, eMeta->updatedRemotelyId());
}


void SignalProxy::handle(Peer *peer, const InitRequest &initRequest)
{
   if (!_syncSlave.contains(initRequest.className)) {
        qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Class:"
                   << initRequest.className;
        return;
    }

    if (!_syncSlave[initRequest.className].contains(initRequest.objectName)) {
        qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Object:"
                   << initRequest.className << initRequest.objectName;
        return;
    }

    SyncableObject *obj = _syncSlave[initRequest.className][initRequest.objectName];
    peer->dispatch(InitData(initRequest.className, initRequest.objectName, initData(obj)));
}


void SignalProxy::handle(Peer *peer, const InitData &initData)
{
    Q_UNUSED(peer)

    if (!_syncSlave.contains(initData.className)) {
        qWarning() << "SignalProxy::handleInitData() received initData for unregistered Class:"
                   << initData.className;
        return;
    }

    if (!_syncSlave[initData.className].contains(initData.objectName)) {
        qWarning() << "SignalProxy::handleInitData() received initData for unregistered Object:"
                   << initData.className << initData.objectName;
        return;
    }

    SyncableObject *obj = _syncSlave[initData.className][initData.objectName];
    setInitData(obj, initData.initData);
}


void SignalProxy::handle(Peer *peer, const RpcCall &rpcCall)
{
    QObject *receiver;
    int methodId;
    SlotHash::const_iterator slot = _attachedSlots.constFind(rpcCall.slotName);
    while (slot != _attachedSlots.constEnd() && slot.key() == rpcCall.slotName) {
        receiver = (*slot).first;
        methodId = (*slot).second;
        if (!invokeSlot(receiver, methodId, rpcCall.params, peer)) {
            ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
            qWarning("SignalProxy::handleSignal(): invokeMethod for \"%s\" failed ", eMeta->methodName(methodId).constData());
        }
        ++slot;
    }
}


bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList &params, QVariant &returnValue, Peer *peer)
{
    ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
    const QList<int> args = eMeta->argTypes(methodId);
    const int numArgs = params.count() < args.count()
                        ? params.count()
                        : args.count();

    if (eMeta->minArgCount(methodId) > params.count()) {
        qWarning() << "SignalProxy::invokeSlot(): not enough params to invoke" << eMeta->methodName(methodId);
        return false;
    }

    void *_a[] = { 0,           // return type...
                   0, 0, 0, 0, 0, // and 10 args - that's the max size qt can handle with signals and slots
                   0, 0, 0, 0, 0 };

    // check for argument compatibility and build params array
    for (int i = 0; i < numArgs; i++) {
        if (!params[i].isValid()) {
            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());
            qWarning() << "                            - make sure all your data types are known by the Qt MetaSystem";
            return false;
        }
        if (args[i] != QMetaType::type(params[i].typeName())) {
            qWarning() << "SignalProxy::invokeSlot(): incompatible param types to invoke" << eMeta->methodName(methodId);
            return false;
        }
        // if first arg is a PeerPtr, replace it by the address of the peer originally receiving the RpcCall
        if (peer && i == 0 && args[0] == qMetaTypeId<PeerPtr>()) {
            QVariant v = QVariant::fromValue<PeerPtr>(peer);
            _a[1] = const_cast<void*>(v.constData());
        } else
            _a[i+1] = const_cast<void *>(params[i].constData());
    }

    if (returnValue.type() != QVariant::Invalid)
        _a[0] = const_cast<void *>(returnValue.constData());

    Qt::ConnectionType type = QThread::currentThread() == receiver->thread()
                              ? Qt::DirectConnection
                              : Qt::QueuedConnection;

    if (type == Qt::DirectConnection) {
        return receiver->qt_metacall(QMetaObject::InvokeMetaMethod, methodId, _a) < 0;
    }
    else {
        qWarning() << "Queued Connections are not implemented yet";
        // note to self: qmetaobject.cpp:990 ff
        return false;
    }
}


bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList &params, Peer *peer)
{
    QVariant ret;
    return invokeSlot(receiver, methodId, params, ret, peer);
}


void SignalProxy::requestInit(SyncableObject *obj)
{
    if (proxyMode() == Server || obj->isInitialized())
        return;

    dispatch(InitRequest(obj->syncMetaObject()->className(), obj->objectName()));
}


QVariantMap SignalProxy::initData(SyncableObject *obj) const
{
    return obj->toVariantMap();
}


void SignalProxy::setInitData(SyncableObject *obj, const QVariantMap &properties)
{
    if (obj->isInitialized())
        return;
    obj->fromVariantMap(properties);
    obj->setInitialized();
    emit objectInitialized(obj);
    invokeSlot(obj, extendedMetaObject(obj)->updatedRemotelyId());
}


void SignalProxy::customEvent(QEvent *event)
{
    switch ((int)event->type()) {
    case RemovePeerEvent: {
        ::RemovePeerEvent *e = static_cast< ::RemovePeerEvent *>(event);
        removePeer(e->peer);
        event->accept();
        break;
    }

    default:
        qWarning() << Q_FUNC_INFO << "Received unknown custom event:" << event->type();
        return;
    }
}


void SignalProxy::sync_call__(const SyncableObject *obj, SignalProxy::ProxyMode modeType, const char *funcname, va_list ap)
{
    // qDebug() << obj << modeType << "(" << _proxyMode << ")" << funcname;
    if (modeType != _proxyMode)
        return;

    ExtendedMetaObject *eMeta = extendedMetaObject(obj);

    QVariantList params;

    const QList<int> &argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname)));

    for (int i = 0; i < argTypes.size(); i++) {
        if (argTypes[i] == 0) {
            qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname);
            qWarning() << "        - make sure all your data types are known by the Qt MetaSystem";
            return;
        }
        params << QVariant(argTypes[i], va_arg(ap, void *));
    }

    if (argTypes.size() >= 1 && argTypes[0] == qMetaTypeId<PeerPtr>() && proxyMode() == SignalProxy::Server) {
        Peer *peer = params[0].value<PeerPtr>();
        dispatch(peer, SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
    } else
        dispatch(SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
}


void SignalProxy::disconnectDevice(QIODevice *dev, const QString &reason)
{
    if (!reason.isEmpty())
        qWarning() << qPrintable(reason);
    QAbstractSocket *sock  = qobject_cast<QAbstractSocket *>(dev);
    if (sock)
        qWarning() << qPrintable(tr("Disconnecting")) << qPrintable(sock->peerAddress().toString());
    dev->close();
}


void SignalProxy::dumpProxyStats()
{
    QString mode;
    if (proxyMode() == Server)
        mode = "Server";
    else
        mode = "Client";

    int slaveCount = 0;
    foreach(ObjectId oid, _syncSlave.values())
    slaveCount += oid.count();

    qDebug() << this;
    qDebug() << "              Proxy Mode:" << mode;
    qDebug() << "          attached Slots:" << _attachedSlots.count();
    qDebug() << " number of synced Slaves:" << slaveCount;
    qDebug() << "number of Classes cached:" << _extendedMetaObjects.count();
}


void SignalProxy::updateSecureState()
{
    bool wasSecure = _secure;

    _secure = !_peers.isEmpty();
    foreach (const Peer *peer,  _peers) {
        _secure &= peer->isSecure();
    }

    if (wasSecure != _secure)
        emit secureStateChanged(_secure);
}


// ==================================================
//  ExtendedMetaObject
// ==================================================
SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
    : _meta(meta),
    _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()"))
{
    for (int i = 0; i < _meta->methodCount(); i++) {
        if (_meta->method(i).methodType() != QMetaMethod::Slot)
            continue;

        if (QByteArray(_meta->method(i).signature()).contains('*'))
            continue;  // skip methods with ptr params

        QByteArray method = methodName(_meta->method(i));
        if (method.startsWith("init"))
            continue;  // skip initializers

        if (_methodIds.contains(method)) {
            /* funny... moc creates for methods containing default parameters multiple metaMethod with separate methodIds.
               we don't care... we just need the full fledged version
             */
            const QMetaMethod &current = _meta->method(_methodIds[method]);
            const QMetaMethod &candidate = _meta->method(i);
            if (current.parameterTypes().count() > candidate.parameterTypes().count()) {
                int minCount = candidate.parameterTypes().count();
                QList<QByteArray> commonParams = current.parameterTypes().mid(0, minCount);
                if (commonParams == candidate.parameterTypes())
                    continue;  // we already got the full featured version
            }
            else {
                int minCount = current.parameterTypes().count();
                QList<QByteArray> commonParams = candidate.parameterTypes().mid(0, minCount);
                if (commonParams == current.parameterTypes()) {
                    _methodIds[method] = i; // use the new one
                    continue;
                }
            }
            if (checkConflicts) {
                qWarning() << "class" << meta->className() << "contains overloaded methods which is currently not supported!";
                qWarning() << " - " << _meta->method(i).signature() << "conflicts with" << _meta->method(_methodIds[method]).signature();
            }
            continue;
        }
        _methodIds[method] = i;
    }
}


const SignalProxy::ExtendedMetaObject::MethodDescriptor &SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId)
{
    if (!_methods.contains(methodId)) {
        _methods[methodId] = MethodDescriptor(_meta->method(methodId));
    }
    return _methods[methodId];
}


const QHash<int, int> &SignalProxy::ExtendedMetaObject::receiveMap()
{
    if (_receiveMap.isEmpty()) {
        QHash<int, int> receiveMap;

        QMetaMethod requestSlot;
        QByteArray returnTypeName;
        QByteArray signature;
        QByteArray methodName;
        QByteArray params;
        int paramsPos;
        int receiverId;
        const int methodCount = _meta->methodCount();
        for (int i = 0; i < methodCount; i++) {
            requestSlot = _meta->method(i);
            if (requestSlot.methodType() != QMetaMethod::Slot)
                continue;

            returnTypeName = requestSlot.typeName();
            if (QMetaType::Void == (QMetaType::Type)returnType(i))
                continue;

            signature = QByteArray(requestSlot.signature());
            if (!signature.startsWith("request"))
                continue;

            paramsPos = signature.indexOf('(');
            if (paramsPos == -1)
                continue;

            methodName = signature.left(paramsPos);
            params = signature.mid(paramsPos);

            methodName = methodName.replace("request", "receive");
            params = params.left(params.count() - 1) + ", " + returnTypeName + ")";

            signature = QMetaObject::normalizedSignature(methodName + params);
            receiverId = _meta->indexOfSlot(signature);

            if (receiverId == -1) {
                signature = QMetaObject::normalizedSignature(methodName + "(" + returnTypeName + ")");
                receiverId = _meta->indexOfSlot(signature);
            }

            if (receiverId != -1) {
                receiveMap[i] = receiverId;
            }
        }
        _receiveMap = receiveMap;
    }
    return _receiveMap;
}


QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod &method)
{
    QByteArray sig(method.signature());
    return sig.left(sig.indexOf("("));
}


QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod &method)
{
    QString methodname = QString(method.signature()).section("(", 0, 0);

    // determine where we have to chop:
    int upperCharPos;
    if (method.methodType() == QMetaMethod::Slot) {
        // we take evertyhing from the first uppercase char if it's slot
        upperCharPos = methodname.indexOf(QRegExp("[A-Z]"));
        if (upperCharPos == -1)
            return QString();
        methodname = methodname.mid(upperCharPos);
    }
    else {
        // and if it's a signal we discard everything from the last uppercase char
        upperCharPos = methodname.lastIndexOf(QRegExp("[A-Z]"));
        if (upperCharPos == -1)
            return QString();
        methodname = methodname.left(upperCharPos);
    }

    methodname[0] = methodname[0].toUpper();

    return methodname;
}


SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod &method)
    : _methodName(SignalProxy::ExtendedMetaObject::methodName(method)),
    _returnType(QMetaType::type(method.typeName()))
{
    // determine argTypes
    QList<QByteArray> paramTypes = method.parameterTypes();
    QList<int> argTypes;
    for (int i = 0; i < paramTypes.count(); i++) {
        argTypes.append(QMetaType::type(paramTypes[i]));
    }
    _argTypes = argTypes;

    // determine minArgCount
    QString signature(method.signature());
    _minArgCount = method.parameterTypes().count() - signature.count("=");

    _receiverMode = (_methodName.startsWith("request"))
                    ? SignalProxy::Server
                    : SignalProxy::Client;
}