Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

some more permission rules for data forwarding to server

File size: 19.1 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)  && this->networkStream->isUserLocal(userId))
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    // check for forwarded data
370    else if( this->networkStream->isUserProxyServerActive( userId )  && SharedNetworkData::getInstance()->isMasterServer() &&
371             !this->networkStream->isUserLocal( userId ))
372      hasPermission = true;
373    // now check OWNER permissions
374    else if( this->owner == userId && (*it)->checkPermission( PERMISSION_OWNER ))
375      hasPermission = true;
376    // now check ALL permissions
377    else if( (*it)->checkPermission( PERMISSION_ALL ))
378      hasPermission = true;
379    // SPECIAL: get write permissions if im sending to a master server that does not own this sync
380    else if( this->networkStream->isUserMasterServer( userId ) && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
381      hasPermission = true;
382    // SPECIAL: get write permissions if im sending to a proxy server that does not own this sync
383    else if( this->networkStream->isUserProxyServerActive( userId ) && SharedNetworkData::getInstance()->isClient()
384              && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
385      hasPermission = true;
386    else
387      hasPermission = false;
388
389
390
391    // if it has the permission to write do it
392    if( hasPermission)
393    {
394      n = (*it)->readFromBuf( stateTo->data + i, stateTo->dataLength - i );
395      i += n;
396      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
397      //PRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
398      //(*it)->debug();
399      if ( (*it)->getHasChanged() )
400      {
401        changes.push_back( (*it)->getVarId() );
402      }
403    }
404    else
405    {
406//       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 );
407      n = (*it)->getSizeFromBuf( stateTo->data + i, stateTo->dataLength - i );
408      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
409      //(*it)->debug();
410      i += n;
411    }
412  }
413
414  this->varChangeHandler( changes );
415
416  return i;
417}
418
419 /**
420 * override this function to be notified on change
421 * of your registred variables.
422 * @param id id's which have changed
423 */
424void Synchronizeable::varChangeHandler( std::list<int> & id )
425{
426}
427
428/**
429 * registers a varable to be synchronized over network
430 * @param var see src/lib/network/synchronizeable_var/ for available classes
431 */
432void Synchronizeable::registerVar( SynchronizeableVar * var )
433{
434  syncVarList.push_back( var );
435}
436
437/**
438 * registers a varable to be synchronized over network
439 * return value is passed to varChangeHandler on change
440 * @param var see src/lib/network/synchronizeable_var/ for available classes
441 * @return handle passed to varChangeHandler on changes
442 */
443int Synchronizeable::registerVarId( SynchronizeableVar * var )
444{
445  syncVarList.push_back( var );
446  var->setWatched( true );
447  var->setVarId( syncVarList.size()-1 );
448  return syncVarList.size()-1;
449}
450
451/**
452 * removed user's states from memory
453 * @param userId user to clean
454 */
455void Synchronizeable::cleanUpUser( int userId )
456{
457  if ( recvStates.size() > userId )
458  {
459    for ( std::list<StateHistoryEntry*>::iterator it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
460    {
461      if ( (*it)->data )
462      {
463        delete [] (*it)->data;
464        (*it)->data = NULL;
465      }
466
467      delete *it;
468    }
469    recvStates[userId].clear();
470  }
471
472  if ( sentStates.size() > userId )
473  {
474
475    for ( std::list<StateHistoryEntry*>::iterator it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
476    {
477      if ( (*it)->data )
478      {
479        delete [] (*it)->data;
480        (*it)->data = NULL;
481      }
482
483      delete *it;
484    }
485    sentStates[userId].clear();
486  }
487}
488
489/**
490 * this function is called after recieving a state.
491 * @param userId
492 * @param stateId
493 * @param fromStateId
494 */
495void Synchronizeable::handleRecvState( int userId, int stateId, int fromStateId )
496{
497   //make sure this user has his history
498  if ( recvStates.size() <= userId )
499    recvStates.resize( userId+1 );
500
501  //remove old states
502  StateHistory::iterator it = recvStates[userId].begin();
503
504#if 0
505  while ( it != recvStates[userId].end() && (*it)->stateId < fromStateId )
506    it++;
507
508  if ( it != recvStates[userId].begin() )
509  {
510    for ( StateHistory::iterator it2 = recvStates[userId].begin(); it2 != it; it2++ )
511    {
512      if ( (*it2)->data != NULL )
513      {
514        delete [] (*it2)->data;
515        (*it2)->data = NULL;
516      }
517    }
518    recvStates[userId].erase( recvStates[userId].begin(), it );
519  }
520#endif
521
522  for ( it = recvStates[userId].begin(); it != recvStates[userId].end();  )
523  {
524    if ( (*it)->stateId < fromStateId )
525    {
526      StateHistory::iterator delIt = it;
527      it ++;
528
529      if ( (*delIt)->data )
530      {
531        delete [] (*delIt)->data;
532        (*delIt)->data = NULL;
533      }
534      delete *delIt;
535      recvStates[userId].erase( delIt );
536
537      continue;
538    }
539    it++;
540  }
541
542  StateHistory::iterator fromState = recvStates[userId].end();
543  StateHistory::iterator toState = recvStates[userId].end();
544
545  for ( it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
546  {
547    if ( (*it)->stateId == stateId )
548      toState = it;
549    if ( (*it)->stateId == fromStateId )
550      fromState = it;
551
552    if ( fromState != recvStates[userId].end() && toState != recvStates[userId].end() )
553      break;
554  }
555
556  // setStateDiff was not called and i know fromStateId
557  if ( fromState != recvStates[userId].end() && toState == recvStates[userId].end() )
558  {
559    StateHistoryEntry * entry = new StateHistoryEntry;
560
561    entry->dataLength = (*fromState)->dataLength;
562    if ( entry->dataLength > 0 )
563    {
564      entry->data = new byte[entry->dataLength];
565
566      assert( (*fromState)->data );
567      memcpy( entry->data, (*fromState)->data, entry->dataLength );
568    }
569    else
570      entry->data = NULL;
571
572    entry->sizeList = (*fromState)->sizeList;
573    entry->stateId = stateId;
574
575    recvStates[userId].push_back(entry);
576  }
577}
578
579/**
580 * this function is called after sending a state
581 * @param userId
582 * @param stateId
583 * @param fromStateId
584 */
585void Synchronizeable::handleSentState( int userId, int stateId, int fromStateId )
586{
587   //make sure this user has his history
588  if ( sentStates.size() <= userId )
589    sentStates.resize( userId+1 );
590
591   //remove old states
592  StateHistory::iterator it = sentStates[userId].begin();
593
594  for ( it = sentStates[userId].begin(); it != sentStates[userId].end();  )
595  {
596    if ( (*it)->stateId < fromStateId )
597    {
598      StateHistory::iterator delIt = it;
599      it ++;
600
601      if ( (*delIt)->data )
602      {
603        delete [] (*delIt)->data;
604        (*delIt)->data = NULL;
605      }
606      delete *delIt;
607      sentStates[userId].erase( delIt );
608
609      continue;
610    }
611    it++;
612  }
613
614
615  StateHistory::iterator fromState = sentStates[userId].end();
616  StateHistory::iterator toState = sentStates[userId].end();
617
618  for ( it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
619  {
620    if ( (*it)->stateId == stateId )
621      toState = it;
622    if ( (*it)->stateId == fromStateId )
623      fromState = it;
624
625    if ( fromState != sentStates[userId].end() && toState != sentStates[userId].end() )
626      break;
627  }
628
629
630  // getStateDiff was not called and i know fromStateId
631  if ( fromState != sentStates[userId].end() && toState == sentStates[userId].end() )
632  {
633    StateHistoryEntry * entry = new StateHistoryEntry;
634
635    entry->dataLength = (*fromState)->dataLength;
636    if ( entry->dataLength > 0 )
637    {
638      entry->data = new byte[entry->dataLength];
639
640      assert( (*fromState)->data );
641      memcpy( entry->data, (*fromState)->data, entry->dataLength );
642    }
643    else
644      entry->data = NULL;
645
646    entry->sizeList = (*fromState)->sizeList;
647    entry->stateId = stateId;
648
649    sentStates[userId].push_back(entry);
650  }
651
652}
653
654
655
Note: See TracBrowser for help on using the repository browser.