summaryrefslogtreecommitdiffstats
path: root/libkdegames/kgame/kmessageserver.cpp
blob: 105f35dac86874c681363667b643ccce6a3fca49 (plain)
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
/*
    This file is part of the KDE games library
    Copyright (C) 2001 Burkhard Lehner (Burkhard.Lehner@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 <tqiodevice.h>
#include <tqbuffer.h>
#include <tqptrlist.h>
#include <tqptrqueue.h>
#include <tqtimer.h>
#include <tqvaluelist.h>

#include <kdebug.h>

#include "kmessageio.h"
#include "kmessageserver.h"

// --------------- internal class KMessageServerSocket

KMessageServerSocket::KMessageServerSocket (Q_UINT16 port, TQObject *parent)
  : TQServerSocket (port, 0, parent)
{
}

KMessageServerSocket::~KMessageServerSocket ()
{
}

void KMessageServerSocket::newConnection (int socket)
{
  emit newClientConnected (new KMessageSocket (socket));
}

// ---------------- class for storing an incoming message

class MessageBuffer
{
  public:
    MessageBuffer (Q_UINT32 clientID, const TQByteArray &messageData)
      : id (clientID), data (messageData) { }
    ~MessageBuffer () {}
    Q_UINT32 id;
    TQByteArray data;
};

// ---------------- KMessageServer's private class

class KMessageServerPrivate
{
public:
  KMessageServerPrivate()
    : mMaxClients (-1), mGameId (1), mUniqueClientNumber (1), mAdminID (0), mServerSocket (0)
  {
    mClientList.setAutoDelete (true);
    mMessageQueue.setAutoDelete (true);
  }

  int mMaxClients;
  int mGameId;
  Q_UINT16 mCookie;
  Q_UINT32 mUniqueClientNumber;
  Q_UINT32 mAdminID;

  KMessageServerSocket* mServerSocket;

  TQPtrList <KMessageIO> mClientList;
  TQPtrQueue <MessageBuffer> mMessageQueue;
  TQTimer mTimer;
  bool mIsRecursive;
};


// ------------------ KMessageServer

KMessageServer::KMessageServer (Q_UINT16 cookie,TQObject* parent)
  : TQObject(parent, 0)
{
  d = new KMessageServerPrivate;
  d->mIsRecursive=false;
  d->mCookie=cookie;
  connect (&(d->mTimer), TQT_SIGNAL (timeout()),
           this, TQT_SLOT (processOneMessage()));
  kdDebug(11001) << "CREATE(KMessageServer="
		<< this
		<< ") cookie="
		<< d->mCookie
		<< " sizeof(this)="
		<< sizeof(KMessageServer)
		<< endl;
}

KMessageServer::~KMessageServer()
{
  kdDebug(11001) << k_funcinfo << "this=" << this << endl;
  Debug();
  stopNetwork();
  deleteClients();
  delete d;
  kdDebug(11001) << k_funcinfo << " done" << endl;
}

//------------------------------------- TCP/IP server stuff

bool KMessageServer::initNetwork (Q_UINT16 port)
{
  kdDebug(11001) << k_funcinfo << endl;

  if (d->mServerSocket)
  {
    kdDebug (11001) << k_funcinfo << ": We were already offering connections!" << endl;
    delete d->mServerSocket;
  }

  d->mServerSocket = new KMessageServerSocket (port);
  d->mIsRecursive = false;

  if (!d->mServerSocket || !d->mServerSocket->ok())
  {
    kdError(11001) << k_funcinfo << ": Serversocket::ok() == false" << endl;
    delete d->mServerSocket;
    d->mServerSocket=0;
    return false;
  }

  kdDebug (11001) << k_funcinfo << ": Now listening to port "
                  << d->mServerSocket->port() << endl;
  connect (d->mServerSocket, TQT_SIGNAL (newClientConnected (KMessageIO*)),
           this, TQT_SLOT (addClient (KMessageIO*)));
  return true;
}

Q_UINT16 KMessageServer::serverPort () const
{
  if (d->mServerSocket)
    return d->mServerSocket->port();
  else
    return 0;
}

void KMessageServer::stopNetwork()
{
  if (d->mServerSocket) 
  {
    delete d->mServerSocket;
    d->mServerSocket = 0;
  }
}

bool KMessageServer::isOfferingConnections() const
{
  return d->mServerSocket != 0;
}

//----------------------------------------------- adding / removing clients

void KMessageServer::addClient (KMessageIO* client)
{
  TQByteArray msg;

  // maximum number of clients reached?
  if (d->mMaxClients >= 0 && d->mMaxClients <= clientCount())
  {
    kdError (11001) << k_funcinfo << ": Maximum number of clients reached!" << endl;
    return;
  }

  // give it a unique ID
  client->setId (uniqueClientNumber());
  kdDebug (11001) << k_funcinfo << ": " << client->id() << endl;

  // connect its signals
  connect (client, TQT_SIGNAL (connectionBroken()),
           this, TQT_SLOT (removeBrokenClient()));
  connect (client, TQT_SIGNAL (received (const TQByteArray &)),
           this, TQT_SLOT (getReceivedMessage (const TQByteArray &)));

  // Tell everyone about the new guest
  // Note: The new client doesn't get this message!
  TQDataStream (msg, IO_WriteOnly) << Q_UINT32 (EVNT_CLIENT_CONNECTED) << client->id();
  broadcastMessage (msg);

  // add to our list
  d->mClientList.append (client);

  // tell it its ID
  TQDataStream (msg, IO_WriteOnly) << Q_UINT32 (ANS_CLIENT_ID) << client->id();
  client->send (msg);

  // Give it the complete list of client IDs
  TQDataStream (msg, IO_WriteOnly)  << Q_UINT32 (ANS_CLIENT_LIST) << clientIDs();
  client->send (msg);


  if (clientCount() == 1)
  {
    // if it is the first client, it becomes the admin
    setAdmin (client->id());
  }
  else
  {
    // otherwise tell it who is the admin
    TQDataStream (msg, IO_WriteOnly) << Q_UINT32 (ANS_ADMIN_ID) << adminID();
    client->send (msg);
  }

  emit clientConnected (client);
}

void KMessageServer::removeClient (KMessageIO* client, bool broken)
{
  Q_UINT32 clientID = client->id();
  if (!d->mClientList.removeRef (client))
  {
    kdError(11001) << k_funcinfo << ": Deleting client that wasn't added before!" << endl;
    return;
  }

  // tell everyone about the removed client
  TQByteArray msg;
  TQDataStream (msg, IO_WriteOnly) << Q_UINT32 (EVNT_CLIENT_DISCONNECTED) << client->id() << (Q_INT8)broken;
  broadcastMessage (msg);

  // If it was the admin, select a new admin.
  if (clientID == adminID())
  {
    if (!d->mClientList.isEmpty())
      setAdmin (d->mClientList.first()->id());
    else
      setAdmin (0);
  }
}

void KMessageServer::deleteClients()
{
  d->mClientList.clear();
  d->mAdminID = 0;
}

void KMessageServer::removeBrokenClient ()
{
  if (!sender()->inherits ("KMessageIO"))
  {
    kdError (11001) << k_funcinfo << ": sender of the signal was not a KMessageIO object!" << endl;
    return;
  }

  KMessageIO *client = (KMessageIO *) sender();

  emit connectionLost (client);
  removeClient (client, true);
}


void KMessageServer::setMaxClients(int c)
{
  d->mMaxClients = c;
}

int KMessageServer::maxClients() const
{
  return d->mMaxClients;
}

int KMessageServer::clientCount() const
{
  return d->mClientList.count();
}

TQValueList <Q_UINT32> KMessageServer::clientIDs () const
{
  TQValueList <Q_UINT32> list;
  for (TQPtrListIterator <KMessageIO> iter (d->mClientList); *iter; ++iter)
    list.append ((*iter)->id());
  return list;
}

KMessageIO* KMessageServer::findClient (Q_UINT32 no) const
{
  if (no == 0)
    no = d->mAdminID;

  TQPtrListIterator <KMessageIO> iter (d->mClientList);
  while (*iter)
  {
    if ((*iter)->id() == no)
      return (*iter);
    ++iter;
  }
  return 0;
}

Q_UINT32 KMessageServer::adminID () const
{
  return d->mAdminID;
}

void KMessageServer::setAdmin (Q_UINT32 adminID)
{
  // Trying to set the the client that is already admin => nothing to do
  if (adminID == d->mAdminID)
    return;

  if (adminID > 0 && findClient (adminID) == 0)
  {
    kdWarning (11001) << "Trying to set a new admin that doesn't exist!" << endl;
    return;
  }

  d->mAdminID = adminID;

  TQByteArray msg;
  TQDataStream (msg, IO_WriteOnly) << Q_UINT32 (ANS_ADMIN_ID) << adminID;

  // Tell everyone about the new master
  broadcastMessage (msg);
}


//------------------------------------------- ID stuff

Q_UINT32 KMessageServer::uniqueClientNumber() const
{
  return d->mUniqueClientNumber++;
}

// --------------------- Messages ---------------------------

void KMessageServer::broadcastMessage (const TQByteArray &msg)
{
  for (TQPtrListIterator <KMessageIO> iter (d->mClientList); *iter; ++iter)
    (*iter)->send (msg);
}

void KMessageServer::sendMessage (Q_UINT32 id, const TQByteArray &msg)
{
  KMessageIO *client = findClient (id);
  if (client)
    client->send (msg);
}

void KMessageServer::sendMessage (const TQValueList <Q_UINT32> &ids, const TQByteArray &msg)
{
  for (TQValueListConstIterator <Q_UINT32> iter = ids.begin(); iter != ids.end(); ++iter)
    sendMessage (*iter, msg);
}

void KMessageServer::getReceivedMessage (const TQByteArray &msg)
{
  if (!sender() || !sender()->inherits("KMessageIO"))
  {
    kdError (11001) << k_funcinfo << ": slot was not called from KMessageIO!" << endl;
    return;
  }
  //kdDebug(11001) << k_funcinfo << ": size=" << msg.size() << endl;
  KMessageIO *client = (KMessageIO *) sender();
  Q_UINT32 clientID = client->id();

  //TQByteArray *ta=new QByteArray;
  //ta->duplicate(msg);
  //d->mMessageQueue.enqueue (new MessageBuffer (clientID, *ta));

  
  d->mMessageQueue.enqueue (new MessageBuffer (clientID, msg));
  if (!d->mTimer.isActive())
    d->mTimer.start(0); // AB: should be , TRUE i guess
}

void KMessageServer::processOneMessage ()
{
  // This shouldn't happen, since the timer should be stopped before. But only to be sure!
  if (d->mMessageQueue.isEmpty())
  {
    d->mTimer.stop();
    return;
  }
  if (d->mIsRecursive)
  {
    return;
  }
  d->mIsRecursive = true;

  MessageBuffer *msg_buf = d->mMessageQueue.head();

  Q_UINT32 clientID = msg_buf->id;
  TQBuffer in_buffer (msg_buf->data);
  in_buffer.open (IO_ReadOnly);
  TQDataStream in_stream (&in_buffer);

  TQByteArray out_msg;
  TQBuffer out_buffer (out_msg);
  out_buffer.open (IO_WriteOnly);
  TQDataStream out_stream (&out_buffer);

  bool unknown = false;

  TQByteArray ttt=in_buffer.buffer();
  Q_UINT32 messageID;
  in_stream >> messageID;
  //kdDebug(11001) << k_funcinfo << ": got message with messageID=" << messageID << endl;
  switch (messageID)
  {
    case REQ_BROADCAST:
      out_stream << Q_UINT32 (MSG_BROADCAST) << clientID;
      // FIXME, compiler bug?
      // this should be okay, since TQBuffer is subclass of QIODevice! :
      // out_buffer.writeBlock (in_buffer.readAll());
      out_buffer.TQIODevice::writeBlock (in_buffer.readAll());
      broadcastMessage (out_msg);
      break;

    case REQ_FORWARD:
      {
        TQValueList <Q_UINT32> clients;
        in_stream >> clients;
        out_stream << Q_UINT32 (MSG_FORWARD) << clientID << clients;
        // see above!
        out_buffer.TQIODevice::writeBlock (in_buffer.readAll());
        sendMessage (clients, out_msg);
      }
      break;

    case REQ_CLIENT_ID:
      out_stream << Q_UINT32 (ANS_CLIENT_ID) << clientID;
      sendMessage (clientID, out_msg);
      break;

    case REQ_ADMIN_ID:
      out_stream << Q_UINT32 (ANS_ADMIN_ID) << d->mAdminID;
      sendMessage (clientID, out_msg);
      break;

    case REQ_ADMIN_CHANGE:
      if (clientID == d->mAdminID)
      {
        Q_UINT32 newAdmin;
        in_stream >> newAdmin;
        setAdmin (newAdmin);
      }
      break;

    case REQ_REMOVE_CLIENT:
      if (clientID == d->mAdminID)
      {
        TQValueList <Q_UINT32> client_list;
        in_stream >> client_list;
        for (TQValueListIterator <Q_UINT32> iter = client_list.begin(); iter != client_list.end(); ++iter)
        {
          KMessageIO *client = findClient (*iter);
          if (client)
            removeClient (client, false);
          else
            kdWarning (11001) << k_funcinfo << ": removing non-existing clientID" << endl;
        }
      }
      break;

    case REQ_MAX_NUM_CLIENTS:
      if (clientID == d->mAdminID)
      {
        Q_INT32 maximum_clients;
        in_stream >> maximum_clients;
        setMaxClients (maximum_clients);
      }
      break;

    case REQ_CLIENT_LIST:
      {
        out_stream << Q_UINT32 (ANS_CLIENT_LIST) << clientIDs();
        sendMessage (clientID, out_msg);
      }
      break;

    default:
      unknown = true;
  }

  // check if all the data has been used
  if (!unknown && !in_buffer.atEnd())
    kdWarning (11001) << k_funcinfo << ": Extra data received for message ID " << messageID << endl;

  emit messageReceived (msg_buf->data, clientID, unknown);

  if (unknown)
    kdWarning (11001) << k_funcinfo << ": received unknown message ID " << messageID << endl;

  // remove the message, since we are ready with it
  d->mMessageQueue.remove();
  if (d->mMessageQueue.isEmpty())
    d->mTimer.stop();
  d->mIsRecursive = false;
}

void KMessageServer::Debug()
{
   kdDebug(11001) << "------------------ KMESSAGESERVER -----------------------" << endl;
   kdDebug(11001) << "MaxClients :   " << maxClients() << endl;
   kdDebug(11001) << "NoOfClients :  " << clientCount() << endl;
   kdDebug(11001) << "---------------------------------------------------" << endl;
}

#include "kmessageserver.moc"