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
Line 
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
12### File Specific:
13   main-programmer: Christoph Renner (rennerc@ee.ethz.ch)
14   co-programmer: Patrick Boenzli (patrick@orxonox.ethz.ch)
15*/
16
17#define DEBUG_MODULE_NETWORK
18
19#include "shared_network_data.h"
20#include "network_stream.h"
21#include "netdefs.h"
22#include "network_log.h"
23#include "network_game_manager.h"
24
25#include "state.h"
26
27#include <cassert>
28
29#include "synchronizeable.h"
30
31#include "converter.h"
32
33
34
35/**
36 *  default constructor
37 */
38Synchronizeable::Synchronizeable()
39{
40  this->setClassID(CL_SYNCHRONIZEABLE, "Synchronizeable");
41  this->owner = 0;
42//   this->setIsServer(SharedNetworkData::getInstance()->getHostID() == 0);
43  this->uniqueID = NET_UID_UNASSIGNED;
44  this->networkStream = NULL;
45  this->bSynchronize = false;
46
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  }
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" ) );
58
59  this->registerVar( new SynchronizeableInt( &this->owner, &this->owner, "owner" ) );
60  this->registerVar( new SynchronizeableString( &this->objectName, &this->objectName, "objectName" ) );
61}
62
63
64
65/**
66 *  default destructor deletes all unneded stuff
67 */
68Synchronizeable::~Synchronizeable()
69{
70  if ( this->networkStream )
71  {
72    this->networkStream->disconnectSynchronizeable(*this);
73
74    // remove the message manager only by the server
75    if ( (SharedNetworkData::getInstance()->isMasterServer() )
76           && this->beSynchronized() && this->getUniqueID() > 0 && !this->isA( CL_MESSAGE_MANAGER ) )
77      NetworkGameManager::getInstance()->removeSynchronizeable( this->getUniqueID() );
78  }
79
80  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
81  {
82    delete *it;
83  }
84  syncVarList.clear();
85
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  }
99
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  }
112}
113
114
115
116/**
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
125 */
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 );
131
132  //calculate needed memory
133  int neededSize = 0;
134
135  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
136  {
137    //PRINTF(0)("SIZE = %d %s\n", (*it)->getSize(), (*it)->getName().c_str());
138    neededSize += (*it)->getSize();
139  }
140
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      }
162
163      delete *it2;
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;
184
185    sentStates[userId].push_back( stateFrom );
186  }
187  else
188    stateFrom = (*it);
189
190  StateHistoryEntry * stateTo = new StateHistoryEntry;
191
192  sentStates[userId].push_back( stateTo );
193
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;
202
203  bool hasPermission = false;
204  bool sizeChanged = false;
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  {
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
216    else if( SharedNetworkData::getInstance()->isProxyServerActive() && (*it)->checkPermission( PERMISSION_PROXY_SERVER ))
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
225#warning this could probably override also clients that are connected to another proxy: the master server overwrites it
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
229    else if( SharedNetworkData::getInstance()->isProxyServerActive() && this->networkStream->isUserClient(userId)
230             && (*it)->checkPermission( PERMISSION_MASTER_SERVER) )
231      hasPermission = true;
232    else if( SharedNetworkData::getInstance()->isProxyServerActive() && this->networkStream->isUserClient(userId)
233             && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ) )
234      hasPermission = true;
235    else
236      hasPermission = false;
237
238
239    if ( sizeIter == stateFrom->sizeList.end() || *sizeIter != (*it)->getSize() )
240      sizeChanged = true;
241
242    if ( ( hasPermission && (*it)->getPriority() >= priorityTH ) || sizeChanged )
243    {
244      n = (*it)->writeToBuf( stateTo->data+i, stateTo->dataLength - i );
245      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
246      //PRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
247      stateTo->sizeList.push_back( n );
248      // this is only for very hardcore debug sessions
249      // (*it)->debug();
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
268  if ( i != neededSize )
269  {
270    PRINTF(0)("strange error: (%s) %d != %d\n", this->getClassCName(), i, neededSize);
271    assert(false);
272  }
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
286/**
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
294 *
295 * @todo check for permissions
296 */
297int Synchronizeable::setStateDiff( int userId, byte* data, int length, int stateId, int fromStateId )
298{
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
313  // search the state from wich the diff is made of
314  StateHistory::iterator it = recvStates[userId].begin();
315  while ( it != recvStates[userId].end() && (*it)->stateId != fromStateId )
316    it++;
317
318  // if this is the first state to receive
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;
328
329    recvStates[userId].push_back( stateFrom );
330  }
331  else
332    stateFrom = (*it);
333
334
335  // apply diff
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  }
343
344  //add state to state history
345  recvStates[userId].push_back( stateTo );
346
347  int i = 0;
348  int n = 0;
349  std::list<int> changes;
350  bool hasPermission = false;
351
352  // extract the new state for every client
353  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
354  {
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
362    else if( this->networkStream->isUserProxyServerActive( userId )  && (*it)->checkPermission( PERMISSION_MASTER_SERVER )
363             && SharedNetworkData::getInstance()->isClient())
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
375    else if( this->networkStream->isUserProxyServerActive( userId ) && SharedNetworkData::getInstance()->isClient()
376              && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
377      hasPermission = true;
378    else
379      hasPermission = false;
380
381
382
383    // if it has the permission to write do it
384    if( hasPermission)
385    {
386      n = (*it)->readFromBuf( stateTo->data + i, stateTo->dataLength - i );
387      i += n;
388      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
389      //PRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
390      //(*it)->debug();
391      if ( (*it)->getHasChanged() )
392      {
393        changes.push_back( (*it)->getVarId() );
394      }
395    }
396    else
397    {
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 );
399      n = (*it)->getSizeFromBuf( stateTo->data + i, stateTo->dataLength - i );
400      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
401      //(*it)->debug();
402      i += n;
403    }
404  }
405
406  this->varChangeHandler( changes );
407
408  return i;
409}
410
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}
419
420/**
421 * registers a varable to be synchronized over network
422 * @param var see src/lib/network/synchronizeable_var/ for available classes
423 */
424void Synchronizeable::registerVar( SynchronizeableVar * var )
425{
426  syncVarList.push_back( var );
427}
428
429/**
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
434 */
435int Synchronizeable::registerVarId( SynchronizeableVar * var )
436{
437  syncVarList.push_back( var );
438  var->setWatched( true );
439  var->setVarId( syncVarList.size()-1 );
440  return syncVarList.size()-1;
441}
442
443/**
444 * removed user's states from memory
445 * @param userId user to clean
446 */
447void Synchronizeable::cleanUpUser( int userId )
448{
449  if ( recvStates.size() > userId )
450  {
451    for ( std::list<StateHistoryEntry*>::iterator it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
452    {
453      if ( (*it)->data )
454      {
455        delete [] (*it)->data;
456        (*it)->data = NULL;
457      }
458
459      delete *it;
460    }
461    recvStates[userId].clear();
462  }
463
464  if ( sentStates.size() > userId )
465  {
466
467    for ( std::list<StateHistoryEntry*>::iterator it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
468    {
469      if ( (*it)->data )
470      {
471        delete [] (*it)->data;
472        (*it)->data = NULL;
473      }
474
475      delete *it;
476    }
477    sentStates[userId].clear();
478  }
479}
480
481/**
482 * this function is called after recieving a state.
483 * @param userId
484 * @param stateId
485 * @param fromStateId
486 */
487void Synchronizeable::handleRecvState( int userId, int stateId, int fromStateId )
488{
489   //make sure this user has his history
490  if ( recvStates.size() <= userId )
491    recvStates.resize( userId+1 );
492
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 ++;
520
521      if ( (*delIt)->data )
522      {
523        delete [] (*delIt)->data;
524        (*delIt)->data = NULL;
525      }
526      delete *delIt;
527      recvStates[userId].erase( delIt );
528
529      continue;
530    }
531    it++;
532  }
533
534  StateHistory::iterator fromState = recvStates[userId].end();
535  StateHistory::iterator toState = recvStates[userId].end();
536
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;
543
544    if ( fromState != recvStates[userId].end() && toState != recvStates[userId].end() )
545      break;
546  }
547
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;
552
553    entry->dataLength = (*fromState)->dataLength;
554    if ( entry->dataLength > 0 )
555    {
556      entry->data = new byte[entry->dataLength];
557
558      assert( (*fromState)->data );
559      memcpy( entry->data, (*fromState)->data, entry->dataLength );
560    }
561    else
562      entry->data = NULL;
563
564    entry->sizeList = (*fromState)->sizeList;
565    entry->stateId = stateId;
566
567    recvStates[userId].push_back(entry);
568  }
569}
570
571/**
572 * this function is called after sending a state
573 * @param userId
574 * @param stateId
575 * @param fromStateId
576 */
577void Synchronizeable::handleSentState( int userId, int stateId, int fromStateId )
578{
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 ++;
592
593      if ( (*delIt)->data )
594      {
595        delete [] (*delIt)->data;
596        (*delIt)->data = NULL;
597      }
598      delete *delIt;
599      sentStates[userId].erase( delIt );
600
601      continue;
602    }
603    it++;
604  }
605
606
607  StateHistory::iterator fromState = sentStates[userId].end();
608  StateHistory::iterator toState = sentStates[userId].end();
609
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;
616
617    if ( fromState != sentStates[userId].end() && toState != sentStates[userId].end() )
618      break;
619  }
620
621
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;
626
627    entry->dataLength = (*fromState)->dataLength;
628    if ( entry->dataLength > 0 )
629    {
630      entry->data = new byte[entry->dataLength];
631
632      assert( (*fromState)->data );
633      memcpy( entry->data, (*fromState)->data, entry->dataLength );
634    }
635    else
636      entry->data = NULL;
637
638    entry->sizeList = (*fromState)->sizeList;
639    entry->stateId = stateId;
640
641    sentStates[userId].push_back(entry);
642  }
643
644}
645
646
647
Note: See TracBrowser for help on using the repository browser.