Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/proxy/src/lib/network/synchronizeable.cc @ 9581

Last change on this file since 9581 was 9581, checked in by patrick, 18 years ago

traced bug to the permissions system of the MASTER_SERVER permission level. try this

File size: 18.5 KB
RevLine 
[5523]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
[5547]11
[5523]12### File Specific:
[9406]13   main-programmer: Christoph Renner (rennerc@ee.ethz.ch)
14   co-programmer: Patrick Boenzli (patrick@orxonox.ethz.ch)
[5547]15*/
[5523]16
[6139]17#define DEBUG_MODULE_NETWORK
18
[6695]19#include "shared_network_data.h"
20#include "network_stream.h"
[5547]21#include "netdefs.h"
[7954]22#include "network_log.h"
[8068]23#include "network_game_manager.h"
[5529]24
[6695]25#include "state.h"
[5996]26
[6753]27#include <cassert>
[6695]28
29#include "synchronizeable.h"
30
[9406]31#include "converter.h"
[6695]32
33
[9406]34
[5547]35/**
[5807]36 *  default constructor
[5547]37 */
[5996]38Synchronizeable::Synchronizeable()
[5997]39{
[6341]40  this->setClassID(CL_SYNCHRONIZEABLE, "Synchronizeable");
[8068]41  this->owner = 0;
[9406]42//   this->setIsServer(SharedNetworkData::getInstance()->getHostID() == 0);
[6695]43  this->uniqueID = NET_UID_UNASSIGNED;
[6145]44  this->networkStream = NULL;
[6695]45  this->bSynchronize = false;
[9406]46
[6695]47  if( State::isOnline())
48  {
49    NetworkStream* nd = SharedNetworkData::getInstance()->getDefaultSyncStream();
50    assert(nd != NULL);
51    nd->connectSynchronizeable(*this);
52    this->setUniqueID(SharedNetworkData::getInstance()->getNewUniqueID());
53  }
[7954]54
55  /* make sure loadClassId is first synced var because this is read by networkStream */
56  assert( syncVarList.size() == 0 );
57  mLeafClassId = this->registerVarId( new SynchronizeableInt( (int*)&this->getLeafClassID(), (int*)&this->getLeafClassID(), "leafClassId" ) );
[9406]58
[7954]59  this->registerVar( new SynchronizeableInt( &this->owner, &this->owner, "owner" ) );
60  this->registerVar( new SynchronizeableString( &this->objectName, &this->objectName, "objectName" ) );
[5997]61}
62
[5523]63
[5996]64
[5547]65/**
[5807]66 *  default destructor deletes all unneded stuff
[5547]67 */
68Synchronizeable::~Synchronizeable()
[6139]69{
70  if ( this->networkStream )
[9110]71  {
[6139]72    this->networkStream->disconnectSynchronizeable(*this);
[9406]73
[9494]74    // remove the message manager only by the server
75    if ( (SharedNetworkData::getInstance()->isMasterServer() )
[9406]76           && this->beSynchronized() && this->getUniqueID() > 0 && !this->isA( CL_MESSAGE_MANAGER ) )
[9110]77      NetworkGameManager::getInstance()->removeSynchronizeable( this->getUniqueID() );
78  }
[9406]79
[8623]80  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
81  {
82    delete *it;
83  }
84  syncVarList.clear();
[9406]85
[8623]86  for ( UserStateHistory::iterator it = recvStates.begin(); it != recvStates.end(); it++ )
87  {
88    for ( StateHistory::iterator it2 = it->begin(); it2 != it->end(); it2++ )
89    {
90      if ( (*it2)->data )
91      {
92        delete [] (*it2)->data;
93        (*it2)->data = NULL;
94      }
95      delete *it2;
96    }
97
98  }
[9406]99
[8623]100  for ( UserStateHistory::iterator it = sentStates.begin(); it != sentStates.end(); it++ )
101  {
102    for ( StateHistory::iterator it2 = it->begin(); it2 != it->end(); it2++ )
103    {
104      if ( (*it2)->data )
105      {
106        delete [] (*it2)->data;
107        (*it2)->data = NULL;
108      }
109      delete *it2;
110    }
111  }
[6139]112}
[5523]113
114
[6695]115
[5547]116/**
[9406]117 * creates a diff image from two states
118 * @param userId: the userid of the user where the image will be sent to
119 * @param data: the binary data array to write to
120 * @param maxLength: maximal length of the data written (length of available space in the array)
121 * @param stateId: the state id that this diff will represent
122 * @param priorityTH: the priority threshold: all syncs below this threshold won't be synchronized
123 *
124 * @todo check for permissions
[5547]125 */
[7954]126int Synchronizeable::getStateDiff( int userId, byte* data, int maxLength, int stateId, int fromStateId, int priorityTH )
127{
128  //make sure this user has his history
129  if ( sentStates.size() <= userId )
130    sentStates.resize( userId+1 );
[5547]131
[7954]132  //calculate needed memory
133  int neededSize = 0;
[5997]134
[7954]135  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
[8147]136  {
137    //PRINTF(0)("SIZE = %d %s\n", (*it)->getSize(), (*it)->getName().c_str());
[7954]138    neededSize += (*it)->getSize();
[8147]139  }
[5997]140
[7954]141  if ( !( neededSize <= maxLength ) )
142  {
143    PRINTF(0)( "%d > %d\n", neededSize, maxLength );
144    assert(false);
145  }
146
147  //remove older states from history than fromStateId
148  StateHistory::iterator it = sentStates[userId].begin();
149
150  while ( it != sentStates[userId].end() && (*it)->stateId < fromStateId )
151    it++;
152
153  if ( it != sentStates[userId].begin() )
154  {
155    for ( StateHistory::iterator it2 = sentStates[userId].begin(); it2 != it; it2++ )
156    {
157      if ( (*it2)->data != NULL )
158      {
159        delete [] (*it2)->data;
160        (*it2)->data = NULL;
161      }
[9406]162
[8623]163      delete *it2;
[7954]164    }
165    sentStates[userId].erase( sentStates[userId].begin(), it );
166  }
167
168  //find state to create diff from
169  StateHistoryEntry * stateFrom = NULL;
170
171  it = sentStates[userId].begin();
172  while ( it != sentStates[userId].end() && (*it)->stateId != fromStateId )
173    it++;
174
175  if ( it == sentStates[userId].end() )
176  {
177    StateHistoryEntry * initialEntry = new StateHistoryEntry();
178
179    initialEntry->stateId = fromStateId;
180    initialEntry->dataLength = 0;
181    initialEntry->data = NULL;
182
183    stateFrom = initialEntry;
[9406]184
[8623]185    sentStates[userId].push_back( stateFrom );
[7954]186  }
187  else
188    stateFrom = (*it);
189
[8623]190  StateHistoryEntry * stateTo = new StateHistoryEntry;
[7954]191
[8623]192  sentStates[userId].push_back( stateTo );
[9406]193
[7954]194  stateTo->stateId = stateId;
195  stateTo->dataLength = neededSize;
196  stateTo->data = new byte[ neededSize ];
197
198  std::list<int>::iterator sizeIter = stateFrom->sizeList.begin();
199
200  int i = 0;
201  int n;
[9406]202
203  bool hasPermission = false;
[8623]204  bool sizeChanged = false;
[7954]205
206  // now do the actual synchronization: kick all variables to write into a common buffer
207  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
208  {
[9406]209    // DATA PERMISSIONS
210    // check if this synchronizeable has the permissions to write the data
211
212    // first check MASTER_SERVER permissions
213    if( SharedNetworkData::getInstance()->isMasterServer() && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
214      hasPermission = true;
215    // now check PROXY_SERVER permissions
[9494]216    else if( SharedNetworkData::getInstance()->isProxyServerActive() && (*it)->checkPermission( PERMISSION_PROXY_SERVER ))
[9406]217      hasPermission = true;
218    // now check OWNER permissions
219    else if( this->owner == SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
220      hasPermission = true;
221    // now check ALL permissions
222    else if( (*it)->checkPermission( PERMISSION_ALL ))
223      hasPermission = true;
224    // SPECIAL: get write permissions if i am master server and i am able to overwrite the client stuff
[9494]225#warning this could probably override also clients that are connected to another proxy: the master server overwrites it
[9406]226    else if( SharedNetworkData::getInstance()->isMasterServer() && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ))
227      hasPermission = true;
228    // SPECIAL: get write permissions if i am proxy server and i am able to overwrite the client stuff
[9494]229    else if( SharedNetworkData::getInstance()->isProxyServerActive() && this->networkStream->isUserClient(userId)
[9581]230             && (*it)->checkPermission( PERMISSION_MASTER_SERVER) )
231      hasPermission = true;
232    else if( SharedNetworkData::getInstance()->isProxyServerActive() && this->networkStream->isUserClient(userId)
[9494]233             && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ) )
[9406]234      hasPermission = true;
235    else
236      hasPermission = false;
237
238
239    if ( sizeIter == stateFrom->sizeList.end() || *sizeIter != (*it)->getSize() )
[8623]240      sizeChanged = true;
[9406]241
[8623]242    if ( ( hasPermission && (*it)->getPriority() >= priorityTH ) || sizeChanged )
[7954]243    {
244      n = (*it)->writeToBuf( stateTo->data+i, stateTo->dataLength - i );
[9579]245      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
[9406]246      //PRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
[7954]247      stateTo->sizeList.push_back( n );
[9406]248      // this is only for very hardcore debug sessions
249      // (*it)->debug();
[7954]250      i += n;
251    }
252    else
253    {
254      for ( int j = 0; j<(*sizeIter); j++ )
255      {
256        assert( i < stateFrom->dataLength );
257        stateTo->data[i] = stateFrom->data[i];
258        i++;
259      }
260      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), *sizeIter);
261      stateTo->sizeList.push_back( (*sizeIter) );
262    }
263
264    if ( sizeIter != stateFrom->sizeList.end() )
265      sizeIter++;
266  }
267
[8147]268  if ( i != neededSize )
269  {
[9406]270    PRINTF(0)("strange error: (%s) %d != %d\n", this->getClassCName(), i, neededSize);
[8147]271    assert(false);
272  }
[7954]273
274  //write diff to data
275  for ( i = 0; i<neededSize; i++ )
276  {
277    if ( i < stateFrom->dataLength )
278      data[i] = stateTo->data[i] - stateFrom->data[i];
279    else
280      data[i] = stateTo->data[i];
281  }
282
283  return neededSize;
284}
285
[5997]286/**
[7954]287 * sets a new state out of a diff created on another host
288 * @param userId hostId of user who send me that diff
289 * @param data pointer to diff
290 * @param length length of diff
291 * @param stateId id of current state
292 * @param fromStateId id of the base state id
293 * @return number bytes read
[9406]294 *
[7954]295 * @todo check for permissions
[5997]296 */
[7954]297int Synchronizeable::setStateDiff( int userId, byte* data, int length, int stateId, int fromStateId )
[5997]298{
[7954]299  //make sure this user has his history
300  if ( recvStates.size() <= userId )
301    recvStates.resize( userId+1 );
302
303  //create new state
304  StateHistoryEntry * stateTo = new StateHistoryEntry();
305  stateTo->stateId = stateId;
306  stateTo->dataLength = length;
307  stateTo->data = new byte[ length ];
308
309
310  //find state to apply diff to
311  StateHistoryEntry * stateFrom = NULL;
312
[9406]313  // search the state from wich the diff is made of
[7954]314  StateHistory::iterator it = recvStates[userId].begin();
315  while ( it != recvStates[userId].end() && (*it)->stateId != fromStateId )
316    it++;
317
[9406]318  // if this is the first state to receive
[7954]319  if ( it == recvStates[userId].end() )
320  {
321    StateHistoryEntry * initialEntry = new StateHistoryEntry();
322
323    initialEntry->stateId = fromStateId;
324    initialEntry->dataLength = 0;
325    initialEntry->data = NULL;
326
327    stateFrom = initialEntry;
[9406]328
[8623]329    recvStates[userId].push_back( stateFrom );
[7954]330  }
[5997]331  else
[7954]332    stateFrom = (*it);
[9406]333
334
335  // apply diff
[7954]336  for ( int i = 0; i<length; i++ )
337  {
338    if ( i < stateFrom->dataLength )
339      stateTo->data[i] = stateFrom->data[i] + data[i];
340    else
341      stateTo->data[i] = data[i];
342  }
[9406]343
[7954]344  //add state to state history
345  recvStates[userId].push_back( stateTo );
[9406]346
[7954]347  int i = 0;
348  int n = 0;
349  std::list<int> changes;
[9406]350  bool hasPermission = false;
351
352  // extract the new state for every client
[7954]353  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
354  {
[9406]355    // DATA PERMISSIONS
356    // check if this synchronizeable has the permissions to write the data
357
358    // first check MASTER_SERVER permissions
359    if(  this->networkStream->isUserMasterServer( userId ) && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
360      hasPermission = true;
361    // now check PROXY_SERVER permissions
[9494]362    else if( this->networkStream->isUserProxyServerActive( userId )  && (*it)->checkPermission( PERMISSION_MASTER_SERVER )
363             && SharedNetworkData::getInstance()->isClient())
[9406]364      hasPermission = true;
365    // now check OWNER permissions
366    else if( this->owner == userId && (*it)->checkPermission( PERMISSION_OWNER ))
367      hasPermission = true;
368    // now check ALL permissions
369    else if( (*it)->checkPermission( PERMISSION_ALL ))
370      hasPermission = true;
371    // SPECIAL: get write permissions if im sending to a master server that does not own this sync
372    else if( this->networkStream->isUserMasterServer( userId ) && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
373      hasPermission = true;
374    // SPECIAL: get write permissions if im sending to a proxy server that does not own this sync
[9494]375    else if( this->networkStream->isUserProxyServerActive( userId ) && SharedNetworkData::getInstance()->isClient()
376              && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
[9406]377      hasPermission = true;
378    else
379      hasPermission = false;
380
381
382
383    // if it has the permission to write do it
384    if( hasPermission)
[7954]385    {
386      n = (*it)->readFromBuf( stateTo->data + i, stateTo->dataLength - i );
387      i += n;
[9406]388      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
[9579]389      //PRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
[7954]390      //(*it)->debug();
391      if ( (*it)->getHasChanged() )
392      {
393        changes.push_back( (*it)->getVarId() );
394      }
395    }
396    else
397    {
[9494]398//       PRINTF(0)("DONT SET VAR BECAUSE OF PERMISSION: %s perm: %d %d %d - %d %d %d\n", (*it)->getName().c_str(), (*it)->checkPermission( PERMISSION_MASTER_SERVER ), (*it)->checkPermission( PERMISSION_OWNER ), (*it)->checkPermission( PERMISSION_ALL ), networkStream->isUserMasterServer( userId ), this->owner, userId );
[7954]399      n = (*it)->getSizeFromBuf( stateTo->data + i, stateTo->dataLength - i );
[9406]400      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
[7954]401      //(*it)->debug();
402      i += n;
403    }
404  }
405
406  this->varChangeHandler( changes );
[9406]407
[7954]408  return i;
[5997]409}
410
[7954]411 /**
412 * override this function to be notified on change
413 * of your registred variables.
414 * @param id id's which have changed
415 */
416void Synchronizeable::varChangeHandler( std::list<int> & id )
417{
418}
[6695]419
[5997]420/**
[7954]421 * registers a varable to be synchronized over network
422 * @param var see src/lib/network/synchronizeable_var/ for available classes
[5997]423 */
[7954]424void Synchronizeable::registerVar( SynchronizeableVar * var )
[5997]425{
[7954]426  syncVarList.push_back( var );
[5997]427}
428
429/**
[7954]430 * registers a varable to be synchronized over network
431 * return value is passed to varChangeHandler on change
432 * @param var see src/lib/network/synchronizeable_var/ for available classes
433 * @return handle passed to varChangeHandler on changes
[5997]434 */
[7954]435int Synchronizeable::registerVarId( SynchronizeableVar * var )
[5997]436{
[7954]437  syncVarList.push_back( var );
438  var->setWatched( true );
439  var->setVarId( syncVarList.size()-1 );
440  return syncVarList.size()-1;
[5997]441}
442
443/**
[7954]444 * removed user's states from memory
445 * @param userId user to clean
[5997]446 */
[7954]447void Synchronizeable::cleanUpUser( int userId )
[5997]448{
[8228]449  if ( recvStates.size() > userId )
[7954]450  {
[8228]451    for ( std::list<StateHistoryEntry*>::iterator it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
[7954]452    {
[8228]453      if ( (*it)->data )
[8623]454      {
[8228]455        delete [] (*it)->data;
[8623]456        (*it)->data = NULL;
457      }
[9406]458
[8228]459      delete *it;
[7954]460    }
[8228]461    recvStates[userId].clear();
[7954]462  }
[9406]463
[8228]464  if ( sentStates.size() > userId )
[7954]465  {
[9406]466
[8228]467    for ( std::list<StateHistoryEntry*>::iterator it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
[7954]468    {
[8228]469      if ( (*it)->data )
[8623]470      {
[8228]471        delete [] (*it)->data;
[8623]472        (*it)->data = NULL;
473      }
[9406]474
[8228]475      delete *it;
[7954]476    }
[8228]477    sentStates[userId].clear();
[7954]478  }
[5997]479}
[6139]480
[6341]481/**
[7954]482 * this function is called after recieving a state.
[9406]483 * @param userId
484 * @param stateId
485 * @param fromStateId
[6341]486 */
[7954]487void Synchronizeable::handleRecvState( int userId, int stateId, int fromStateId )
[6341]488{
[7954]489   //make sure this user has his history
490  if ( recvStates.size() <= userId )
491    recvStates.resize( userId+1 );
[9406]492
[7954]493  //remove old states
494  StateHistory::iterator it = recvStates[userId].begin();
495
496#if 0
497  while ( it != recvStates[userId].end() && (*it)->stateId < fromStateId )
498    it++;
499
500  if ( it != recvStates[userId].begin() )
501  {
502    for ( StateHistory::iterator it2 = recvStates[userId].begin(); it2 != it; it2++ )
503    {
504      if ( (*it2)->data != NULL )
505      {
506        delete [] (*it2)->data;
507        (*it2)->data = NULL;
508      }
509    }
510    recvStates[userId].erase( recvStates[userId].begin(), it );
511  }
512#endif
513
514  for ( it = recvStates[userId].begin(); it != recvStates[userId].end();  )
515  {
516    if ( (*it)->stateId < fromStateId )
517    {
518      StateHistory::iterator delIt = it;
519      it ++;
[9406]520
[7954]521      if ( (*delIt)->data )
[8623]522      {
[7954]523        delete [] (*delIt)->data;
[8623]524        (*delIt)->data = NULL;
525      }
526      delete *delIt;
[7954]527      recvStates[userId].erase( delIt );
[9406]528
[7954]529      continue;
530    }
531    it++;
532  }
[9406]533
[7954]534  StateHistory::iterator fromState = recvStates[userId].end();
535  StateHistory::iterator toState = recvStates[userId].end();
[9406]536
[7954]537  for ( it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
538  {
539    if ( (*it)->stateId == stateId )
540      toState = it;
541    if ( (*it)->stateId == fromStateId )
542      fromState = it;
[9406]543
[7954]544    if ( fromState != recvStates[userId].end() && toState != recvStates[userId].end() )
545      break;
546  }
[9406]547
[7954]548  // setStateDiff was not called and i know fromStateId
549  if ( fromState != recvStates[userId].end() && toState == recvStates[userId].end() )
550  {
551    StateHistoryEntry * entry = new StateHistoryEntry;
[9406]552
[7954]553    entry->dataLength = (*fromState)->dataLength;
554    if ( entry->dataLength > 0 )
555    {
556      entry->data = new byte[entry->dataLength];
[9406]557
[7954]558      assert( (*fromState)->data );
559      memcpy( entry->data, (*fromState)->data, entry->dataLength );
560    }
561    else
562      entry->data = NULL;
[9406]563
[7954]564    entry->sizeList = (*fromState)->sizeList;
565    entry->stateId = stateId;
[9406]566
[7954]567    recvStates[userId].push_back(entry);
568  }
[6341]569}
[6139]570
[6341]571/**
[7954]572 * this function is called after sending a state
[9406]573 * @param userId
574 * @param stateId
575 * @param fromStateId
[6341]576 */
[7954]577void Synchronizeable::handleSentState( int userId, int stateId, int fromStateId )
[6341]578{
[7954]579   //make sure this user has his history
580  if ( sentStates.size() <= userId )
581    sentStates.resize( userId+1 );
582
583   //remove old states
584  StateHistory::iterator it = sentStates[userId].begin();
585
586  for ( it = sentStates[userId].begin(); it != sentStates[userId].end();  )
587  {
588    if ( (*it)->stateId < fromStateId )
589    {
590      StateHistory::iterator delIt = it;
591      it ++;
[9406]592
[7954]593      if ( (*delIt)->data )
[8623]594      {
[7954]595        delete [] (*delIt)->data;
[8623]596        (*delIt)->data = NULL;
597      }
598      delete *delIt;
[7954]599      sentStates[userId].erase( delIt );
[9406]600
[7954]601      continue;
602    }
603    it++;
604  }
605
[9406]606
[7954]607  StateHistory::iterator fromState = sentStates[userId].end();
608  StateHistory::iterator toState = sentStates[userId].end();
[9406]609
[7954]610  for ( it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
611  {
612    if ( (*it)->stateId == stateId )
613      toState = it;
614    if ( (*it)->stateId == fromStateId )
615      fromState = it;
[9406]616
[7954]617    if ( fromState != sentStates[userId].end() && toState != sentStates[userId].end() )
618      break;
619  }
620
[9406]621
[7954]622  // getStateDiff was not called and i know fromStateId
623  if ( fromState != sentStates[userId].end() && toState == sentStates[userId].end() )
624  {
625    StateHistoryEntry * entry = new StateHistoryEntry;
[9406]626
[7954]627    entry->dataLength = (*fromState)->dataLength;
628    if ( entry->dataLength > 0 )
629    {
630      entry->data = new byte[entry->dataLength];
[9406]631
[7954]632      assert( (*fromState)->data );
633      memcpy( entry->data, (*fromState)->data, entry->dataLength );
634    }
635    else
636      entry->data = NULL;
[9406]637
[7954]638    entry->sizeList = (*fromState)->sizeList;
639    entry->stateId = stateId;
[9406]640
[7954]641    sentStates[userId].push_back(entry);
642  }
[9406]643
[6341]644}
[6139]645
[6341]646
647
Note: See TracBrowser for help on using the repository browser.