~neon/libkdegames/master

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
/*
    This file is part of the KDE games library
    Copyright (C) 2001 Martin Heni (kde at heni-online.de)
    Copyright (C) 2001 Andreas Beckermann (b_mann@gmx.de)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 as published by the Free Software Foundation.

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "kgamenetwork.h"

#include "kgamemessage.h"
#include "kgameerror.h"

#include "kmessageserver.h"
#include "kmessageclient.h"
#include "kmessageio.h"
#include <dnssd/publicservice.h>

#include <qbuffer.h>
//Added by qt3to4:
#include <QList>

class KGameNetworkPrivate
{
public:
        KGameNetworkPrivate()
        {
                mMessageClient = nullptr;
                mMessageServer = nullptr;
                mDisconnectId = 0;
		mService = nullptr;
        }

public:
        KMessageClient* mMessageClient;
        KMessageServer* mMessageServer;
        quint32 mDisconnectId;  // Stores gameId() over a disconnect process
	KDNSSD::PublicService* mService;
	QString mType;
	QString mName;

        int mCookie;
};

// ------------------- NETWORK GAME ------------------------
KGameNetwork::KGameNetwork(int c, QObject* parent) 
    : QObject(parent),
      d( new KGameNetworkPrivate )
{
 d->mCookie = (qint16)c;

 // Init the game as a local game, i.e.
 // create your own KMessageServer and a KMessageClient connected to it.
 setMaster();

 qCDebug(GAMES_PRIVATE_KGAME) << "this=" << this <<", cookie=" << cookie() << "sizeof(this)="<<sizeof(KGameNetwork);
}

KGameNetwork::~KGameNetwork()
{
 qCDebug(GAMES_PRIVATE_KGAME) << "this=" << this;
// Debug();
 delete d->mService;
 delete d;
}

// ----------------------------- status methods
bool KGameNetwork::isNetwork() const
{ return isOfferingConnections() || d->mMessageClient->isNetwork();}

quint32 KGameNetwork::gameId() const
{
  //return d->mMessageClient->id() ;
  // Return stored id in the case of disconnect. In any other
  // case the disconnect id is 0
  if (d->mMessageClient->id()!=0 ) {
    return d->mMessageClient->id() ;
  } else {
    return d->mDisconnectId;
  }
}

int KGameNetwork::cookie() const
{ return d->mCookie; }

bool KGameNetwork::isMaster() const
{ return (d->mMessageServer != nullptr); }

bool KGameNetwork::isAdmin() const
{ return (d->mMessageClient->isAdmin()); }

KMessageClient* KGameNetwork::messageClient() const
{ return d->mMessageClient; }

KMessageServer* KGameNetwork::messageServer() const
{ return d->mMessageServer; }

// ----------------------- network init
void KGameNetwork::setMaster()
{
 if (!d->mMessageServer) {
   d->mMessageServer = new KMessageServer (cookie(), this);
 } else {
   qCWarning(GAMES_PRIVATE_KGAME) << "Server already running!!";
 }
 if (!d->mMessageClient) {
   d->mMessageClient = new KMessageClient (this);
   connect(d->mMessageClient, &KMessageClient::broadcastReceived, this, &KGameNetwork::receiveNetworkTransmission);
   connect(d->mMessageClient, &KMessageClient::connectionBroken, this, &KGameNetwork::signalConnectionBroken);
   connect(d->mMessageClient, &KMessageClient::aboutToDisconnect, this, &KGameNetwork::aboutToLoseConnection);
   connect(d->mMessageClient, &KMessageClient::connectionBroken, this, &KGameNetwork::slotResetConnection);

   connect(d->mMessageClient, &KMessageClient::adminStatusChanged, this, &KGameNetwork::slotAdminStatusChanged);
   connect(d->mMessageClient, &KMessageClient::eventClientConnected, this, &KGameNetwork::signalClientConnected);
   connect(d->mMessageClient, &KMessageClient::eventClientDisconnected, this, &KGameNetwork::signalClientDisconnected);

   // broacast and direct messages are treated equally on receive.
   connect (d->mMessageClient, &KMessageClient::forwardReceived,
            d->mMessageClient, &KMessageClient::broadcastReceived);

 } else {
   // should be no problem but still has to be tested
   qCDebug(GAMES_PRIVATE_KGAME) << "Client already exists!";
 }
 d->mMessageClient->setServer(d->mMessageServer);
}

void KGameNetwork::setDiscoveryInfo(const QString& type, const QString& name)
{
 qCDebug(GAMES_PRIVATE_KGAME) << type << ":" << name;
 d->mType = type;
 d->mName = name;
 tryPublish();
}

void KGameNetwork::tryPublish()
{
 if (d->mType.isNull() || !isOfferingConnections()) return;
 if (!d->mService) d->mService = new KDNSSD::PublicService(d->mName,d->mType,port());
 else {
   if (d->mType!=d->mService->type()) d->mService->setType(d->mType);
   if (d->mName!=d->mService->serviceName()) d->mService->setServiceName(d->mName);
   }
 if (!d->mService->isPublished()) d->mService->publishAsync();
}

void KGameNetwork::tryStopPublishing()
{
 if (d->mService) d->mService->stop();
}

bool KGameNetwork::offerConnections(quint16 port)
{
 qCDebug(GAMES_PRIVATE_KGAME) << "on port" << port;
 if (!isMaster()) {
   setMaster();
 }

 // Make sure this is 0
 d->mDisconnectId = 0;

 // FIXME: This debug message can be removed when the program is working correct.
 if (d->mMessageServer && d->mMessageServer->isOfferingConnections()) {
   qCDebug(GAMES_PRIVATE_KGAME) << "Already running as server! Changing the port now!";
 }

 tryStopPublishing();
 qCDebug(GAMES_PRIVATE_KGAME) << "before Server->initNetwork";
 if (!d->mMessageServer->initNetwork (port)) {
   qCCritical(GAMES_PRIVATE_KGAME) << "Unable to bind to port" << port << "!";
   // no need to delete - we just cannot listen to the port
//   delete d->mMessageServer;
//   d->mMessageServer = 0;
//   d->mMessageClient->setServer((KMessageServer*)0);
   return false;
 }
 qCDebug(GAMES_PRIVATE_KGAME) << "after Server->initNetwork";
 tryPublish();
 return true;
}

bool KGameNetwork::connectToServer (const QString& host, quint16 port)
{
 if (host.isEmpty()) {
   qCCritical(GAMES_PRIVATE_KGAME) << "No hostname given";
   return false;
 }
 if (connectToServer(new KMessageSocket (host, port)))
 {
  qCDebug(GAMES_PRIVATE_KGAME) << "connected to" << host << ":" << port;
  return true;
 }
 else
 {
   return false;
 }
}

bool KGameNetwork::connectToServer (KMessageIO *connection)
{
  // Make sure this is 0
  d->mDisconnectId = 0;
  
  // if (!d->mMessageServer) {
 //   // FIXME: What shall we do here? Probably must stop a running game.
 //   qCWarning(GAMES_PRIVATE_KGAME) << "We are already connected to another server!";
 /// }
 
 if (d->mMessageServer) {
   // FIXME: What shall we do here? Probably must stop a running game.
   qCWarning(GAMES_PRIVATE_KGAME) << "we are server but we are trying to connect to another server! "
   << "make sure that all clients connect to that server! "
   << "quitting the local server now...";
   stopServerConnection();
   d->mMessageClient->setServer((KMessageIO*)nullptr);
   delete d->mMessageServer;
   d->mMessageServer = nullptr;
 }
 
 qCDebug(GAMES_PRIVATE_KGAME) << "    about to set server";
 d->mMessageClient->setServer(connection);
 Q_EMIT signalAdminStatusChanged(false); // as we delete the connection above isAdmin() is always false now!
 
 // OK: We say that we already have connected, but this isn't so yet!
 // If the connection cannot be established, it will look as being disconnected
 // again ("slotConnectionLost" is called).
 // Shall we differ between these?
 qCDebug(GAMES_PRIVATE_KGAME) << "connected";
 return true;
}

quint16 KGameNetwork::port() const
{
 if (isNetwork()) {
   if (isOfferingConnections()) {
     return d->mMessageServer->serverPort();
   } else {
     return d->mMessageClient->peerPort();
   }
 }
 return 0;
}

QString KGameNetwork::hostName() const
{
 return d->mMessageClient->peerName();
}

bool KGameNetwork::stopServerConnection()
{
 // We still are the Master, we just don't accept further connections!
 tryStopPublishing();
 if (d->mMessageServer) {
   d->mMessageServer->stopNetwork();
   return true;
 }
 return false;
}

bool KGameNetwork::isOfferingConnections() const
{ return (d->mMessageServer && d->mMessageServer->isOfferingConnections()); }

void KGameNetwork::disconnect()
{
 // TODO MH
 qCDebug(GAMES_PRIVATE_KGAME) ;
 stopServerConnection();
 if (d->mMessageServer) {
    QList <quint32> list=d->mMessageServer->clientIDs();
    QList<quint32>::Iterator it;
    for( it = list.begin(); it != list.end(); ++it )
    {
      qCDebug(GAMES_PRIVATE_KGAME) << "Client id=" << (*it);
      KMessageIO *client=d->mMessageServer->findClient(*it);
      if (!client)
      {
        continue;
      }
      qCDebug(GAMES_PRIVATE_KGAME) << "   rtti=" << client->rtti();
      if (client->rtti()==2)
      {
        qCDebug(GAMES_PRIVATE_KGAME) << "DIRECT IO";
      }
      else
      {
        d->mMessageServer->removeClient(client,false);
      }
    }
 }
 else
 {
   qCDebug(GAMES_PRIVATE_KGAME) << "before client->disconnect() id="<<gameId();
   //d->mMessageClient->setServer((KMessageIO*)0);
   qCDebug(GAMES_PRIVATE_KGAME) << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++";
   d->mMessageClient->disconnect();

   qCDebug(GAMES_PRIVATE_KGAME) << "++++++--------------------------------------------+++++";
 }
 //setMaster();
 /*
 if (d->mMessageServer) {
  //delete d->mMessageServer;
  //d->mMessageServer=0;
  server=true;
  qCDebug(GAMES_PRIVATE_KGAME) << "  server true";
  d->mMessageServer->deleteClients();
  qCDebug(GAMES_PRIVATE_KGAME) << "  server deleteClients";
 }
 */
 qCDebug(GAMES_PRIVATE_KGAME) << "DONE";
}

void KGameNetwork::aboutToLoseConnection(quint32 clientID)
{
  qCDebug(GAMES_PRIVATE_KGAME) << "Storing client id of connection "<<clientID;
  d->mDisconnectId = clientID;
}

void KGameNetwork::slotResetConnection()
{
  qCDebug(GAMES_PRIVATE_KGAME) << "Resseting client disconnect id";
  d->mDisconnectId = 0;
}

void KGameNetwork::electAdmin(quint32 clientID)
{
 if (!isAdmin()) {
	qCWarning(GAMES_PRIVATE_KGAME) << "only ADMIN is allowed to call this!";
	return;
 }
 QByteArray buffer;
 QDataStream stream(&buffer,QIODevice::WriteOnly);
 stream << static_cast<quint32>( KMessageServer::REQ_ADMIN_CHANGE );
 stream << clientID;
 d->mMessageClient->sendServerMessage(buffer);
}

void KGameNetwork::setMaxClients(int max)
{
 if (!isAdmin()) {
	qCWarning(GAMES_PRIVATE_KGAME) << "only ADMIN is allowed to call this!";
	return;
 }
 QByteArray buffer;
 QDataStream stream(&buffer,QIODevice::WriteOnly);
 stream << static_cast<quint32>( KMessageServer::REQ_MAX_NUM_CLIENTS );
 stream << (qint32)max;
 d->mMessageClient->sendServerMessage(buffer);
}

void KGameNetwork::lock()
{
 if (messageClient()) {
   messageClient()->lock();
 }
}

void KGameNetwork::unlock()
{
 if (messageClient()) {
   messageClient()->unlock();
 }
}

// --------------------- send messages ---------------------------

bool KGameNetwork::sendSystemMessage(int data, int msgid, quint32 receiver, quint32 sender)
{
 QByteArray buffer;
 QDataStream stream(&buffer,QIODevice::WriteOnly);
 stream << data;
 return sendSystemMessage(buffer,msgid,receiver,sender);
}

bool KGameNetwork::sendSystemMessage(const QString &msg, int msgid, quint32 receiver, quint32 sender)
{
 QByteArray buffer;
 QDataStream stream(&buffer, QIODevice::WriteOnly);
 stream << msg;
 return sendSystemMessage(buffer, msgid, receiver, sender);
}

bool KGameNetwork::sendSystemMessage(const QDataStream &msg, int msgid, quint32 receiver, quint32 sender)
{ return sendSystemMessage(((QBuffer*)msg.device())->buffer(), msgid, receiver, sender); }

bool KGameNetwork::sendSystemMessage(const QByteArray& data, int msgid, quint32 receiver, quint32 sender)
{
 QByteArray buffer;
 QDataStream stream(&buffer,QIODevice::WriteOnly);
 if (!sender) {
   sender = gameId();
 }

 quint32 receiverClient = KGameMessage::rawGameId(receiver); // KGame::gameId()
 int receiverPlayer = KGameMessage::rawPlayerId(receiver); // KPlayer::id()

 KGameMessage::createHeader(stream, sender, receiver, msgid);
 stream.writeRawData(data.data(), data.size());

 /*
 qCDebug(GAMES_PRIVATE_KGAME) << "transmitGameClientMessage msgid=" << msgid << "recv="
                << receiver << "sender=" << sender << "Buffersize="
                << buffer.size();
  */

 if (!d->mMessageClient) {
   // No client created, this should never happen!
   // Having a local game means we have our own
   // KMessageServer and we are the only client.
   qCWarning(GAMES_PRIVATE_KGAME) << "We don't have a client! Should never happen!";
   return false;
 }

 if (receiverClient == 0 || receiverPlayer != 0)
 {
   // if receiverClient == 0 this is a broadcast message. if it is != 0 but
   // receiverPlayer is also != 0 we have to send broadcast anyway, because the
   // KPlayer object on all clients needs to receive the message.
   d->mMessageClient->sendBroadcast(buffer);
 }
 else
 {
   d->mMessageClient->sendForward(buffer, receiverClient);
 }
 return true;
}

bool KGameNetwork::sendMessage(int data, int msgid, quint32 receiver, quint32 sender)
{ return sendSystemMessage(data,msgid+KGameMessage::IdUser,receiver,sender); }

bool KGameNetwork::sendMessage(const QString &msg, int msgid, quint32 receiver, quint32 sender)
{ return sendSystemMessage(msg,msgid+KGameMessage::IdUser,receiver,sender); }

bool KGameNetwork::sendMessage(const QDataStream &msg, int msgid, quint32 receiver, quint32 sender)
{ return sendSystemMessage(msg, msgid+KGameMessage::IdUser, receiver, sender); }

bool KGameNetwork::sendMessage(const QByteArray &msg, int msgid, quint32 receiver, quint32 sender)
{ return sendSystemMessage(msg, msgid+KGameMessage::IdUser, receiver, sender); }

void KGameNetwork::sendError(int error,const QByteArray& message, quint32 receiver, quint32 sender)
{
 QByteArray buffer;
 QDataStream stream(&buffer,QIODevice::WriteOnly);
 stream << (qint32) error;
 stream.writeRawData(message.data(), message.size());
 sendSystemMessage(stream,KGameMessage::IdError,receiver,sender);
}


// ----------------- receive messages from the network
void KGameNetwork::receiveNetworkTransmission(const QByteArray& receiveBuffer, quint32 clientID)
{
 QDataStream stream(receiveBuffer);
 int msgid;
 quint32 sender; // the id of the KGame/KPlayer who sent the message
 quint32 receiver; // the id of the KGame/KPlayer the message is for 
 KGameMessage::extractHeader(stream, sender, receiver, msgid);
// qCDebug(GAMES_PRIVATE_KGAME) << "id=" << msgid << "sender=" << sender << "recv=" << receiver;

 // No broadcast : receiver==0
 // No player isPlayer(receiver)
 // Different game gameId()!=receiver
 if (receiver &&  receiver!=gameId() && !KGameMessage::isPlayer(receiver) )
 {
   // receiver=0 is broadcast or player message
   qCDebug(GAMES_PRIVATE_KGAME) << "Message not meant for us "
            << gameId() << "!=" << receiver << "rawid="
            << KGameMessage::rawGameId(receiver);
   return;
 }
 else if (msgid==KGameMessage::IdError)
 {
   QString text;
   qint32 error;
   stream >> error;
   qCDebug(GAMES_PRIVATE_KGAME) << "Got IdError" << error;
   text = KGameError::errorText(error, stream);
   qCDebug(GAMES_PRIVATE_KGAME) << "Error text:" << text.toLatin1();
   Q_EMIT signalNetworkErrorMessage((int)error,text);
 }
 else
 {
   networkTransmission(stream, msgid, receiver, sender, clientID);
 }
}

// -------------- slots for the signals of the client
void KGameNetwork::slotAdminStatusChanged(bool isAdmin)
{
 Q_EMIT signalAdminStatusChanged(isAdmin);

// TODO: I'm pretty sure there are a lot of things that should be done here...
}

void KGameNetwork::Debug()
{
 qCDebug(GAMES_PRIVATE_KGAME) << "------------------- KNETWORKGAME -------------------------";
 qCDebug(GAMES_PRIVATE_KGAME) << "gameId         " << gameId();
 qCDebug(GAMES_PRIVATE_KGAME) << "gameMaster     " << isMaster();
 qCDebug(GAMES_PRIVATE_KGAME) << "gameAdmin      " << isAdmin();
 qCDebug(GAMES_PRIVATE_KGAME) << "---------------------------------------------------";
}

/*
 * vim: et sw=2
 */