Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

found another bug: forward permissions from proxy to master

File size: 18.8 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: permission to forward syncs from the master server to the clients
229    else if( SharedNetworkData::getInstance()->isProxyServerActive() && this->networkStream->isUserClient(userId)
230             && (*it)->checkPermission( PERMISSION_MASTER_SERVER) )
231      hasPermission = true;
232    // SPECIAL: permission to forward to the master server
233    else if( SharedNetworkData::getInstance()->isProxyServerActive() && this->networkStream->isUserMasterServer(userId)
234             && (*it)->checkPermission( PERMISSION_MASTER_SERVER) )
235      hasPermission = true;
236    else if( SharedNetworkData::getInstance()->isProxyServerActive() && this->networkStream->isUserClient(userId)
237             && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ) )
238      hasPermission = true;
239    else
240      hasPermission = false;
241
242
243    if ( sizeIter == stateFrom->sizeList.end() || *sizeIter != (*it)->getSize() )
244      sizeChanged = true;
245
246    if ( ( hasPermission && (*it)->getPriority() >= priorityTH ) || sizeChanged )
247    {
248      n = (*it)->writeToBuf( stateTo->data+i, stateTo->dataLength - i );
249      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
250      //PRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
251      stateTo->sizeList.push_back( n );
252      // this is only for very hardcore debug sessions
253      // (*it)->debug();
254      i += n;
255    }
256    else
257    {
258      for ( int j = 0; j<(*sizeIter); j++ )
259      {
260        assert( i < stateFrom->dataLength );
261        stateTo->data[i] = stateFrom->data[i];
262        i++;
263      }
264      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), *sizeIter);
265      stateTo->sizeList.push_back( (*sizeIter) );
266    }
267
268    if ( sizeIter != stateFrom->sizeList.end() )
269      sizeIter++;
270  }
271
272  if ( i != neededSize )
273  {
274    PRINTF(0)("strange error: (%s) %d != %d\n", this->getClassCName(), i, neededSize);
275    assert(false);
276  }
277
278  //write diff to data
279  for ( i = 0; i<neededSize; i++ )
280  {
281    if ( i < stateFrom->dataLength )
282      data[i] = stateTo->data[i] - stateFrom->data[i];
283    else
284      data[i] = stateTo->data[i];
285  }
286
287  return neededSize;
288}
289
290/**
291 * sets a new state out of a diff created on another host
292 * @param userId hostId of user who send me that diff
293 * @param data pointer to diff
294 * @param length length of diff
295 * @param stateId id of current state
296 * @param fromStateId id of the base state id
297 * @return number bytes read
298 *
299 * @todo check for permissions
300 */
301int Synchronizeable::setStateDiff( int userId, byte* data, int length, int stateId, int fromStateId )
302{
303  //make sure this user has his history
304  if ( recvStates.size() <= userId )
305    recvStates.resize( userId+1 );
306
307  //create new state
308  StateHistoryEntry * stateTo = new StateHistoryEntry();
309  stateTo->stateId = stateId;
310  stateTo->dataLength = length;
311  stateTo->data = new byte[ length ];
312
313
314  //find state to apply diff to
315  StateHistoryEntry * stateFrom = NULL;
316
317  // search the state from wich the diff is made of
318  StateHistory::iterator it = recvStates[userId].begin();
319  while ( it != recvStates[userId].end() && (*it)->stateId != fromStateId )
320    it++;
321
322  // if this is the first state to receive
323  if ( it == recvStates[userId].end() )
324  {
325    StateHistoryEntry * initialEntry = new StateHistoryEntry();
326
327    initialEntry->stateId = fromStateId;
328    initialEntry->dataLength = 0;
329    initialEntry->data = NULL;
330
331    stateFrom = initialEntry;
332
333    recvStates[userId].push_back( stateFrom );
334  }
335  else
336    stateFrom = (*it);
337
338
339  // apply diff
340  for ( int i = 0; i<length; i++ )
341  {
342    if ( i < stateFrom->dataLength )
343      stateTo->data[i] = stateFrom->data[i] + data[i];
344    else
345      stateTo->data[i] = data[i];
346  }
347
348  //add state to state history
349  recvStates[userId].push_back( stateTo );
350
351  int i = 0;
352  int n = 0;
353  std::list<int> changes;
354  bool hasPermission = false;
355
356  // extract the new state for every client
357  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
358  {
359    // DATA PERMISSIONS
360    // check if this synchronizeable has the permissions to write the data
361
362    // first check MASTER_SERVER permissions
363    if(  this->networkStream->isUserMasterServer( userId ) && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
364      hasPermission = true;
365    // now check PROXY_SERVER permissions
366    else if( this->networkStream->isUserProxyServerActive( userId )  && (*it)->checkPermission( PERMISSION_MASTER_SERVER )
367             && SharedNetworkData::getInstance()->isClient())
368      hasPermission = true;
369    // now check OWNER permissions
370    else if( this->owner == userId && (*it)->checkPermission( PERMISSION_OWNER ))
371      hasPermission = true;
372    // now check ALL permissions
373    else if( (*it)->checkPermission( PERMISSION_ALL ))
374      hasPermission = true;
375    // SPECIAL: get write permissions if im sending to a master server that does not own this sync
376    else if( this->networkStream->isUserMasterServer( userId ) && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
377      hasPermission = true;
378    // SPECIAL: get write permissions if im sending to a proxy server that does not own this sync
379    else if( this->networkStream->isUserProxyServerActive( userId ) && SharedNetworkData::getInstance()->isClient()
380              && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
381      hasPermission = true;
382    else
383      hasPermission = false;
384
385
386
387    // if it has the permission to write do it
388    if( hasPermission)
389    {
390      n = (*it)->readFromBuf( stateTo->data + i, stateTo->dataLength - i );
391      i += n;
392      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
393      //PRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
394      //(*it)->debug();
395      if ( (*it)->getHasChanged() )
396      {
397        changes.push_back( (*it)->getVarId() );
398      }
399    }
400    else
401    {
402//       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 );
403      n = (*it)->getSizeFromBuf( stateTo->data + i, stateTo->dataLength - i );
404      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
405      //(*it)->debug();
406      i += n;
407    }
408  }
409
410  this->varChangeHandler( changes );
411
412  return i;
413}
414
415 /**
416 * override this function to be notified on change
417 * of your registred variables.
418 * @param id id's which have changed
419 */
420void Synchronizeable::varChangeHandler( std::list<int> & id )
421{
422}
423
424/**
425 * registers a varable to be synchronized over network
426 * @param var see src/lib/network/synchronizeable_var/ for available classes
427 */
428void Synchronizeable::registerVar( SynchronizeableVar * var )
429{
430  syncVarList.push_back( var );
431}
432
433/**
434 * registers a varable to be synchronized over network
435 * return value is passed to varChangeHandler on change
436 * @param var see src/lib/network/synchronizeable_var/ for available classes
437 * @return handle passed to varChangeHandler on changes
438 */
439int Synchronizeable::registerVarId( SynchronizeableVar * var )
440{
441  syncVarList.push_back( var );
442  var->setWatched( true );
443  var->setVarId( syncVarList.size()-1 );
444  return syncVarList.size()-1;
445}
446
447/**
448 * removed user's states from memory
449 * @param userId user to clean
450 */
451void Synchronizeable::cleanUpUser( int userId )
452{
453  if ( recvStates.size() > userId )
454  {
455    for ( std::list<StateHistoryEntry*>::iterator it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
456    {
457      if ( (*it)->data )
458      {
459        delete [] (*it)->data;
460        (*it)->data = NULL;
461      }
462
463      delete *it;
464    }
465    recvStates[userId].clear();
466  }
467
468  if ( sentStates.size() > userId )
469  {
470
471    for ( std::list<StateHistoryEntry*>::iterator it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
472    {
473      if ( (*it)->data )
474      {
475        delete [] (*it)->data;
476        (*it)->data = NULL;
477      }
478
479      delete *it;
480    }
481    sentStates[userId].clear();
482  }
483}
484
485/**
486 * this function is called after recieving a state.
487 * @param userId
488 * @param stateId
489 * @param fromStateId
490 */
491void Synchronizeable::handleRecvState( int userId, int stateId, int fromStateId )
492{
493   //make sure this user has his history
494  if ( recvStates.size() <= userId )
495    recvStates.resize( userId+1 );
496
497  //remove old states
498  StateHistory::iterator it = recvStates[userId].begin();
499
500#if 0
501  while ( it != recvStates[userId].end() && (*it)->stateId < fromStateId )
502    it++;
503
504  if ( it != recvStates[userId].begin() )
505  {
506    for ( StateHistory::iterator it2 = recvStates[userId].begin(); it2 != it; it2++ )
507    {
508      if ( (*it2)->data != NULL )
509      {
510        delete [] (*it2)->data;
511        (*it2)->data = NULL;
512      }
513    }
514    recvStates[userId].erase( recvStates[userId].begin(), it );
515  }
516#endif
517
518  for ( it = recvStates[userId].begin(); it != recvStates[userId].end();  )
519  {
520    if ( (*it)->stateId < fromStateId )
521    {
522      StateHistory::iterator delIt = it;
523      it ++;
524
525      if ( (*delIt)->data )
526      {
527        delete [] (*delIt)->data;
528        (*delIt)->data = NULL;
529      }
530      delete *delIt;
531      recvStates[userId].erase( delIt );
532
533      continue;
534    }
535    it++;
536  }
537
538  StateHistory::iterator fromState = recvStates[userId].end();
539  StateHistory::iterator toState = recvStates[userId].end();
540
541  for ( it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
542  {
543    if ( (*it)->stateId == stateId )
544      toState = it;
545    if ( (*it)->stateId == fromStateId )
546      fromState = it;
547
548    if ( fromState != recvStates[userId].end() && toState != recvStates[userId].end() )
549      break;
550  }
551
552  // setStateDiff was not called and i know fromStateId
553  if ( fromState != recvStates[userId].end() && toState == recvStates[userId].end() )
554  {
555    StateHistoryEntry * entry = new StateHistoryEntry;
556
557    entry->dataLength = (*fromState)->dataLength;
558    if ( entry->dataLength > 0 )
559    {
560      entry->data = new byte[entry->dataLength];
561
562      assert( (*fromState)->data );
563      memcpy( entry->data, (*fromState)->data, entry->dataLength );
564    }
565    else
566      entry->data = NULL;
567
568    entry->sizeList = (*fromState)->sizeList;
569    entry->stateId = stateId;
570
571    recvStates[userId].push_back(entry);
572  }
573}
574
575/**
576 * this function is called after sending a state
577 * @param userId
578 * @param stateId
579 * @param fromStateId
580 */
581void Synchronizeable::handleSentState( int userId, int stateId, int fromStateId )
582{
583   //make sure this user has his history
584  if ( sentStates.size() <= userId )
585    sentStates.resize( userId+1 );
586
587   //remove old states
588  StateHistory::iterator it = sentStates[userId].begin();
589
590  for ( it = sentStates[userId].begin(); it != sentStates[userId].end();  )
591  {
592    if ( (*it)->stateId < fromStateId )
593    {
594      StateHistory::iterator delIt = it;
595      it ++;
596
597      if ( (*delIt)->data )
598      {
599        delete [] (*delIt)->data;
600        (*delIt)->data = NULL;
601      }
602      delete *delIt;
603      sentStates[userId].erase( delIt );
604
605      continue;
606    }
607    it++;
608  }
609
610
611  StateHistory::iterator fromState = sentStates[userId].end();
612  StateHistory::iterator toState = sentStates[userId].end();
613
614  for ( it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
615  {
616    if ( (*it)->stateId == stateId )
617      toState = it;
618    if ( (*it)->stateId == fromStateId )
619      fromState = it;
620
621    if ( fromState != sentStates[userId].end() && toState != sentStates[userId].end() )
622      break;
623  }
624
625
626  // getStateDiff was not called and i know fromStateId
627  if ( fromState != sentStates[userId].end() && toState == sentStates[userId].end() )
628  {
629    StateHistoryEntry * entry = new StateHistoryEntry;
630
631    entry->dataLength = (*fromState)->dataLength;
632    if ( entry->dataLength > 0 )
633    {
634      entry->data = new byte[entry->dataLength];
635
636      assert( (*fromState)->data );
637      memcpy( entry->data, (*fromState)->data, entry->dataLength );
638    }
639    else
640      entry->data = NULL;
641
642    entry->sizeList = (*fromState)->sizeList;
643    entry->stateId = stateId;
644
645    sentStates[userId].push_back(entry);
646  }
647
648}
649
650
651
Note: See TracBrowser for help on using the repository browser.