Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/network/message_manager.cc @ 9744

Last change on this file since 9744 was 9656, checked in by bensch, 18 years ago

orxonox/trunk: merged the proxy bache back with no conflicts

File size: 16.3 KB
RevLine 
[7631]1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Christoph Renner
[9656]13   co-programmer: Patrick Boenzli (patrick@orxonox.ethz.ch)
14
15     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
16     July 2006: some code rearangement and integration of the proxy server mechanism (boenzlip@ee.ethz.ch)
17     July 2006: message forwarding algorithms
[7631]18*/
19
20//#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_
21
22#include "message_manager.h"
23
[8228]24#include "network_stream.h"
[8708]25#include "shared_network_data.h"
[9406]26#include "converter.h"
27#include <cassert>
[8228]28
[7631]29
[9406]30
[7671]31MessageManager* MessageManager::singletonRef = NULL;
[7631]32
[7671]33
[7631]34/**
35 * standard constructor
36*/
37MessageManager::MessageManager ()
38{
39  this->setClassID( CL_MESSAGE_MANAGER, "MessageManager" );
[7681]40  newNumber = 1;
41  setSynchronized( true );
[7631]42}
43
44
45/**
46 * standard deconstructor
47*/
48MessageManager::~MessageManager ()
49{
[9656]50  for ( MessageQueue::iterator it = outgoingMessageQueue.begin(); it != outgoingMessageQueue.end(); it++ )
[7671]51  {
52    for ( std::list<NetworkMessage>::iterator it2 = it->second.messages.begin(); it2 != it->second.messages.end(); it2++ )
53    {
54      if ( it2->data )
55      {
[8623]56        delete [] it2->data;
[7671]57        it2->data = NULL;
58      }
59    }
[9406]60
[7671]61    it->second.messages.clear();
62    it->second.toAck.clear();
63  }
[9406]64
[9656]65  outgoingMessageQueue.clear();
[9406]66
[9059]67  this->messageHandlerMap.clear();
[9406]68
[9059]69  MessageManager::singletonRef = NULL;
[7631]70}
71
72/**
73 * get the diff to last acked state of userId
74 *
[7671]75 * this class does not use the normal SynchronizeableVars for zynchronisation. instead
76 * it defines its own protocol
[7631]77 *
78 * @param userId user to create diff for
79 * @param data buffer to copy diff in
80 * @param maxLength max bytes to copy into data
81 * @param stateId id of current state
82 * @param fromStateId the reference state for the delta state
83 * @param priorityTH tells getStateDiff to not send element with priority \< priorityTH
84 * @return n bytes copied into data
85 */
86int MessageManager::getStateDiff( int userId, byte * data, int maxLength, int stateId, int fromStateId, int priorityTH )
87{
[7671]88  int i = 0;
89  int n;
[9406]90
[9656]91  n = Converter::intToByteArray( outgoingMessageQueue[userId].toAck.size(), data + i, maxLength );
[7671]92  i += n;
93  assert( n == INTSIZE );
[9406]94
[9656]95  for ( std::list<int>::iterator it = outgoingMessageQueue[userId].toAck.begin(); it != outgoingMessageQueue[userId].toAck.end(); it++)
[7671]96  {
97    n = Converter::intToByteArray( *it, data + i, maxLength );
98    i += n;
99    assert( n == INTSIZE );
100  }
[9406]101
[9656]102  outgoingMessageQueue[userId].toAck.clear();
[9406]103
[9656]104  n = Converter::intToByteArray( outgoingMessageQueue[userId].messages.size(), data + i, maxLength );
[7671]105  i += n;
106  assert( n == INTSIZE );
[9406]107
[9656]108  // write the message down, a message has this structure:
109  //   | data_length | serial_number | message_type | source_id | dest_id | ...data... |
110  //      4byte        4byte            4byte         4byte      4byte     data_length
111  for ( std::list<NetworkMessage>::iterator it = outgoingMessageQueue[userId].messages.begin(); it != outgoingMessageQueue[userId].messages.end(); it++ )
[7671]112  {
[9656]113    // send data length
[7671]114    n = Converter::intToByteArray( it->length, data + i, maxLength );
115    i += n;
116    assert( n == INTSIZE );
[9406]117
[9656]118    // send serial number
[7671]119    n = Converter::intToByteArray( it->number, data + i, maxLength );
120    i += n;
121    assert( n == INTSIZE );
[9406]122
[9656]123    // send message type
124    n = Converter::intToByteArray( it->messageType, data + i, maxLength );
[7671]125    i += n;
126    assert( n == INTSIZE );
[9406]127
[9656]128    // send sender id
129    n = Converter::intToByteArray( it->senderId, data + i, maxLength );
130    i += n;
131    assert( n == INTSIZE );
132
133    // send destination id
134    n = Converter::intToByteArray( it->destinationId, data + i, maxLength );
135    i += n;
136    assert( n == INTSIZE );
137
138    // send receiver type
139    n = Converter::intToByteArray( it->recieverType, data + i, maxLength );
140    i += n;
141    assert( n == INTSIZE );
142
143    // and copy the data
[7671]144    assert( i + it->length <= maxLength );
145    memcpy( data + i, it->data, it->length );
146    i += it->length;
147  }
[9406]148
[7671]149  return i;
[7631]150}
151
152/**
153 * sets a new state out of a diff created on another host
154 * @param userId hostId of user who send me that diff
155 * @param data pointer to diff
156 * @param length length of diff
157 * @param stateId id of current state
158 * @param fromStateId id of the base state id
159 * @return number bytes read
160 * @todo check for permissions
161 */
162int MessageManager::setStateDiff( int userId, byte * data, int length, int stateId, int fromStateId )
163{
[7671]164  int i = 0;
165  int n;
[9406]166
[7671]167  int nAcks;
[9406]168
[9656]169
[7678]170  assert( i + INTSIZE <= length );
[7671]171  n = Converter::byteArrayToInt( data + i, &nAcks );
172  assert( n == INTSIZE );
173  i += n;
[9406]174
[7671]175  std::list<int> acks;
[9406]176
[7671]177  int number;
[9406]178
[7671]179  for ( int j = 0; j < nAcks; j++ )
180  {
[7678]181    assert( i + INTSIZE <= length );
[7671]182    n = Converter::byteArrayToInt( data + i, &number );
183    assert( n == INTSIZE );
184    i += n;
[9406]185
[7671]186    acks.push_back( number );
187  }
[9406]188
[7671]189  int nMessages;
[9406]190
[7678]191  assert( i + INTSIZE <= length );
[7671]192  n = Converter::byteArrayToInt( data + i, &nMessages );
193  assert( n == INTSIZE );
194  i += n;
[7678]195
[9656]196  int messageLength, messageType;
197  int senderId, destinationId, recieverType;
[9406]198
[9656]199  // now go through all newly received messages and assemble them
[7671]200  for ( int j = 0; j < nMessages; j++ )
201  {
[9656]202    // read the length
[7678]203    assert( i + INTSIZE <= length );
204    n = Converter::byteArrayToInt( data + i, &messageLength );
205    assert( n == INTSIZE );
206    i += n;
[9406]207
[9656]208    // read the serial number
[7678]209    assert( i + INTSIZE <= length );
210    n = Converter::byteArrayToInt( data + i, &number );
211    assert( n == INTSIZE );
212    i += n;
[9406]213
[9656]214    // read the message type
[7678]215    assert( i + INTSIZE <= length );
[9656]216    n = Converter::byteArrayToInt( data + i, &messageType );
[7678]217    assert( n == INTSIZE );
218    i += n;
[9406]219
[9656]220    // read the sender id
221    assert( i + INTSIZE <= length );
222    n = Converter::byteArrayToInt( data + i, &senderId );
223    assert( n == INTSIZE );
224    i += n;
225
226    //read the destination id
227    assert( i + INTSIZE <= length );
228    n = Converter::byteArrayToInt( data + i, &destinationId);
229    assert( n == INTSIZE );
230    i += n;
231
232    // read the receiver type
233    assert( i + INTSIZE <= length );
234    n = Converter::byteArrayToInt( data + i, &recieverType);
235    assert( n == INTSIZE );
236    i += n;
237
[7678]238    if ( number > 0 )
[9656]239      outgoingMessageQueue[userId].toAck.push_back( number );
[9406]240
[9656]241//     PRINTF(0)("got message with type: %i\n", messageType);
[7678]242    assert( i + messageLength <= length );
[9656]243    // make sure there is a message handler for this message type
244    assert( messageHandlerMap.find( (MessageType)messageType ) != messageHandlerMap.end());
245
246
247    if ( std::find( outgoingMessageQueue[userId].recievedMessages.begin(), outgoingMessageQueue[userId].recievedMessages.end(), number ) ==
248         outgoingMessageQueue[userId].recievedMessages.end() )
[7681]249    {
[9656]250
251      // find out if this message is addressed for this client too
252      if( recieverType == RT_ALL_BUT_ME  && SharedNetworkData::getInstance()->getHostID() != senderId ||
253          recieverType == RT_ALL_ME ||
254          recieverType == RT_NOT_USER && SharedNetworkData::getInstance()->getHostID() != destinationId ||
255          recieverType == RT_USER  && SharedNetworkData::getInstance()->getHostID() == destinationId ||
256          recieverType == RT_SERVER && SharedNetworkData::getInstance()->isMasterServer() ||
257          recieverType == RT_SERVER && SharedNetworkData::getInstance()->isProxyServerActive())
[7693]258      {
[9406]259
[9656]260        PRINTF(0)("<<< MessageManager: got msg with type: %i, from sender %i, to rec: %i\n", messageType, senderId, destinationId);
261      // call the handler function and handle errors
262        if ( !(*(messageHandlerMap[(MessageType)messageType].cb))( (MessageType)messageType, data + i, messageLength,
263                 messageHandlerMap[(MessageType)messageType].someData, senderId, destinationId ) )
264        {
265        // if the message is not handled correctly, bush it back to the incoming packets therefore trying it later
266          NetworkMessage msg;
[9406]267
[9656]268          msg.data = new byte[messageLength];
269          memcpy( msg.data, data + i, messageLength );
270          msg.length = messageLength;
271          msg.messageType = (MessageType)messageType;
272          msg.number = userId;
273          msg.senderId = senderId;
274          msg.recieverType = (RecieverType)recieverType;
275          msg.destinationId = destinationId;
276
277          incomingMessageQueue.push_back( msg );
278        }
[7693]279      }
[9656]280
281
282      // check if the message needs to be forwarded
283      if( recieverType == RT_ALL_BUT_ME ||
284          recieverType == RT_ALL_ME ||
285          recieverType == RT_NOT_USER ||
286          recieverType == RT_USER  && SharedNetworkData::getInstance()->getHostID() != destinationId ||
287          recieverType == RT_SERVER && SharedNetworkData::getInstance()->isProxyServerActive() )
288      {
289        // forwarding the messages but only if its a proxy
290        if( SharedNetworkData::getInstance()->isProxyServerActive())
291        {
292          PRINTF(0)("===========>> Forwarding Message msg with type: %i, from sender %i, to rec: %i\n", messageType, senderId, destinationId);
293          NetworkMessage msg;
294
295          msg.data = new byte[messageLength];
296          memcpy( msg.data, data + i, messageLength );
297          msg.length = messageLength;
298          msg.messageType = (MessageType)messageType;
299          msg.number = userId;
300          msg.senderId = senderId;
301          msg.destinationId = destinationId;
302          msg.recieverType = (RecieverType)recieverType;
303
304          this->sendMessage(msg.messageType, msg.data, msg.length, msg.recieverType, msg.senderId = senderId, msg.destinationId, MP_HIGHBANDWIDTH);
305        }
306      }
307
308      // save the serial number for ack signaling
309      outgoingMessageQueue[userId].recievedMessages.push_back( number );
[7681]310    }
[9656]311
[7678]312    i += messageLength;
[7671]313  }
[9406]314
315
[9656]316  //walk throu message queue and remove acked messages
317  for ( std::list<NetworkMessage>::iterator it = outgoingMessageQueue[userId].messages.begin(); it != outgoingMessageQueue[userId].messages.end();  )
[7693]318  {
[9656]319    if ( std::find( acks.begin(), acks.end(), it->number) != acks.end() )
[7693]320    {
321      std::list<NetworkMessage>::iterator delIt = it;
322      it++;
[9656]323      outgoingMessageQueue[userId].messages.erase( delIt );
[7693]324      continue;
325    }
326    it++;
327  }
[9406]328
[9656]329  //TODO find bether way. maybe with timestamp
330  if ( outgoingMessageQueue[userId].recievedMessages.size() > 1000 )
[7681]331  {
[9656]332    for ( int j = 0; j < (int)outgoingMessageQueue[userId].recievedMessages.size() - 1000; j++ )
333      outgoingMessageQueue[userId].recievedMessages.erase( outgoingMessageQueue[userId].recievedMessages.begin() );
334  }
335
336  return i;
337}
338
339
340
341
342/**
343 * processes the message manager data, specialy check for localy generated messages
344 */
345void MessageManager::processData()
346{
347  // now call the message handlers with the new message
348  for ( std::list<NetworkMessage>::iterator it = incomingMessageQueue.begin(); it != incomingMessageQueue.end();  )
349  {
350    PRINTF(0)("<<< MessageManager: got local msg with type: %i, from sender %i, to rec: %i\n", (*it).messageType, (*it).senderId, (*it).destinationId);
351
352    if ( (*(messageHandlerMap[it->messageType].cb))( it->messageType, it->data, it->length, messageHandlerMap[it->messageType].someData,
353                                                     /*it->number, */it->senderId, it->destinationId ) )
[7681]354    {
355      std::list<NetworkMessage>::iterator delIt = it;
[9656]356      if ( it->data )
357        delete it->data;
[7681]358      it++;
[9656]359      incomingMessageQueue.erase( delIt );
[7681]360      continue;
361    }
362    it++;
363  }
[9406]364
[7631]365}
366
[9656]367
368
369
[7631]370/**
371 * clean up memory reserved for user
372 * @param userId userid
373 */
374void MessageManager::cleanUpUser( int userId )
375{
[9656]376  if ( outgoingMessageQueue.find( userId ) == outgoingMessageQueue.end() )
[7678]377    return;
[9406]378
[9656]379  for ( std::list<NetworkMessage>::iterator it = outgoingMessageQueue[userId].messages.begin(); it != outgoingMessageQueue[userId].messages.end(); it++ )
[7678]380  {
381    if ( it->data )
382      delete it->data;
383    it->data = NULL;
384  }
[9406]385
[9656]386  outgoingMessageQueue[userId].toAck.clear();
[9406]387
[9656]388  outgoingMessageQueue.erase( userId );
[7631]389}
[7671]390
391/**
[9656]392 * registers function to handle messages with id messageType. someData is passed to callbackfuntion
393 * @param messageType message id to handle
[7671]394 * @param cb function pointer to callback function
395 * @param someData this pointer is passed to callback function without modification
396 * @return true on success
397 */
[9656]398bool MessageManager::registerMessageHandler( MessageType messageType, MessageCallback cb, void * someData )
[7671]399{
[7678]400  MessageHandler messageHandler;
[9406]401
[7678]402  messageHandler.cb = cb;
[9656]403  messageHandler.messageType = messageType;
[7678]404  messageHandler.someData = someData;
[9406]405
[9656]406  messageHandlerMap[messageType] = messageHandler;
[9406]407
[7678]408  return true;
[7671]409}
410
411/**
412 * initializes buffers for user
413 * @param userId userId
414 */
415void MessageManager::initUser( int userId )
416{
[7678]417  // just do something so map creates a new entry
[9656]418  outgoingMessageQueue[userId].toAck.clear();
419  //assert( outgoingMessageQueue[userId].messages.size() == 0 );
[7671]420}
[7681]421
[9656]422
423
[7681]424/**
425 * send a message to one or more clients
426 * recieverType:
427 *               RT_ALL send to all users. reciever is ignored
428 *               RT_USER send only to reciever
429 *               RT_NOT_USER send to all but reciever
430 *
[9656]431 * @param messageType message id
[7681]432 * @param data pointer to data
433 * @param dataLength length of data
[9656]434 * @param recieverType type of the receiver
435 * @param reciever the userId of the receiver if needed (depends on the ReceiverType)
[7681]436 */
[9656]437void MessageManager::sendMessage( MessageType messageType, byte * data, int dataLength, RecieverType recieverType, int reciever, MessagePriority messagePriority )
[7681]438{
[9656]439  this->sendMessage(messageType, data, dataLength, recieverType, SharedNetworkData::getInstance()->getHostID(), reciever, messagePriority);
440}
441
442
443/**
444 * send a message to one or more clients as a special client
445 * recieverType:
446 *               RT_ALL send to all users. reciever is ignored
447 *               RT_USER send only to reciever
448 *               RT_NOT_USER send to all but reciever
449 *
450 * @param messageType message id
451 * @param data pointer to data
452 * @param dataLength length of data
453 * @param recieverType type of the receiver
454 * @param sender the userId of the sender if there is need for shadowing it (eg. for msg forwarding)
455 * @param reciever the userId of the receiver if needed (depends on the ReceiverType)
456 */
457    void MessageManager::sendMessage( MessageType messageType, byte * data, int dataLength, RecieverType recieverType, int sender, int reciever, MessagePriority messagePriority )
458{
459  PRINTF(0)(" >>> MessageManager: sending msg with type: %i, recieverType: %i, reciever %i\n", messageType, recieverType, reciever);
460
461  // go through all outgoing message queues and add the message if its appropriate
462  for ( MessageQueue::iterator it = this->outgoingMessageQueue.begin(); it != this->outgoingMessageQueue.end(); it++ )
[7681]463  {
[9656]464
[9406]465    if (
[9656]466         recieverType == RT_ALL_ME      ||
467         recieverType == RT_ALL_BUT_ME  ||
468         recieverType == RT_USER        && it->first == reciever ||
469         recieverType == RT_USER        && reciever == NET_ID_MASTER_SERVER && !getNetworkStream()->isUserMasterServer( it->first ) ||  //(*)
470         recieverType == RT_NOT_USER    && it->first != reciever ||
471         recieverType == RT_SERVER      && getNetworkStream()->isUserMasterServer( it->first ) ||
472         recieverType == RT_SERVER      && getNetworkStream()->isUserProxyServerActive( it->first )
473       )// (*) special case: forward
[7681]474    {
475      NetworkMessage msg;
[8623]476
[7681]477      msg.data = new byte[dataLength];
478      memcpy( msg.data, data, dataLength );
479      msg.length = dataLength;
[9656]480      msg.messageType = messageType;
481      msg.number = this->newNumber++;
482      msg.senderId = sender;
483      msg.destinationId = reciever;
484      msg.recieverType = recieverType;
[7681]485      msg.priority = messagePriority;
[8623]486
[7681]487      it->second.messages.push_back( msg );
488    }
[9656]489
490
[7681]491  }
[9406]492
[9656]493
494  // if the message is also for myself, handle it here
495  if ( recieverType == RT_ALL_ME ||
496       recieverType == RT_USER   && reciever == SharedNetworkData::getInstance()->getHostID()
497     )
[8623]498  {
499    NetworkMessage msg;
500
501    msg.data = new byte[dataLength];
502    memcpy( msg.data, data, dataLength );
503    msg.length = dataLength;
[9656]504    msg.messageType = messageType;
[8708]505    msg.number = SharedNetworkData::getInstance()->getHostID();
[9656]506    msg.senderId = sender;
507    msg.destinationId = reciever;
508    msg.recieverType = recieverType;
[8623]509    msg.priority = messagePriority;
510
[9656]511    this->incomingMessageQueue.push_back( msg );
[8623]512  }
[7681]513}
514
515
Note: See TracBrowser for help on using the repository browser.