Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/proxy/src/lib/network/network_stream.cc @ 9467

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

added more secure implementation of connection update

File size: 32.4 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### File Specific:
12   main-programmer: Christoph Renner rennerc@ee.ethz.ch
13   co-programmer:   Patrick Boenzli  boenzlip@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*/
18
19
20#define DEBUG_MODULE_NETWORK
21
22
23#include "base_object.h"
24#include "network_protocol.h"
25#include "udp_socket.h"
26#include "udp_server_socket.h"
27#include "monitor/connection_monitor.h"
28#include "monitor/network_monitor.h"
29#include "synchronizeable.h"
30#include "ip.h"
31#include "network_game_manager.h"
32#include "shared_network_data.h"
33#include "message_manager.h"
34#include "preferences.h"
35#include "zip.h"
36
37#include "src/lib/util/loading/resource_manager.h"
38
39#include "network_log.h"
40
41#include "player_stats.h"
42
43#include "lib/util/loading/factory.h"
44
45#include "debug.h"
46#include "class_list.h"
47#include <algorithm>
48
49
50#include "network_stream.h"
51
52
53#include "converter.h"
54
55
56#define PACKAGE_SIZE  256
57
58
59/**
60 * empty constructor
61 */
62NetworkStream::NetworkStream()
63    : DataStream()
64{
65  this->init();
66  /* initialize the references */
67  this->pInfo->nodeType = NET_CLIENT;
68}
69
70
71NetworkStream::NetworkStream( int nodeType)
72{
73  this->init();
74
75  this->pInfo->nodeType = nodeType;
76
77  switch( nodeType)
78  {
79    case NET_MASTER_SERVER:
80      // init the shared network data
81      SharedNetworkData::getInstance()->setHostID(NET_ID_MASTER_SERVER);
82      break;
83
84    case NET_PROXY_SERVER_ACTIVE:
85      // init the shared network data
86      SharedNetworkData::getInstance()->setHostID(NET_ID_PROXY_SERVER_01);
87      break;
88    case NET_PROXY_SERVER_PASSIVE:
89      // init the shared network data
90      SharedNetworkData::getInstance()->setHostID(NET_ID_PROXY_SERVER_01);
91      break;
92    case NET_CLIENT:
93      SharedNetworkData::getInstance()->setHostID(NET_ID_UNASSIGNED);
94      break;
95  }
96
97  SharedNetworkData::getInstance()->setDefaultSyncStream(this);
98
99  // get the local ip address
100  IPaddress ip;
101  SDLNet_ResolveHost( &ip, NULL, 0);
102  this->pInfo->ip = ip;
103}
104
105
106
107/**
108 * generic init functions
109 */
110void NetworkStream::init()
111{
112  /* set the class id for the base object */
113  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
114  this->clientSocket = NULL;
115  this->proxySocket = NULL;
116  this->networkGameManager = NULL;
117  this->networkMonitor = NULL;
118
119  this->pInfo = new PeerInfo();
120  this->pInfo->userId = 0;
121  this->pInfo->lastAckedState = 0;
122  this->pInfo->lastRecvedState = 0;
123
124  this->bRedirect = false;
125
126  this->currentState = 0;
127
128  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
129
130  assert( Zip::getInstance()->loadDictionary( "testdict" ) >= 0 );
131  this->dictClient = Zip::getInstance()->loadDictionary( "dict2pl_client" );
132  assert( this->dictClient >= 0 );
133  this->dictServer = Zip::getInstance()->loadDictionary( "dict2p_server" );
134  assert( this->dictServer >= 0 );
135}
136
137
138/**
139 * deconstructor
140 */
141NetworkStream::~NetworkStream()
142{
143  if ( this->clientSocket )
144  {
145    clientSocket->close();
146    delete clientSocket;
147    clientSocket = NULL;
148  }
149  if ( this->proxySocket)
150  {
151    proxySocket->close();
152    delete proxySocket;
153    proxySocket = NULL;
154  }
155  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
156  {
157    if ( i->second.socket )
158    {
159      i->second.socket->disconnectServer();
160      delete i->second.socket;
161      i->second.socket = NULL;
162    }
163
164    if ( i->second.handshake )
165    {
166      delete i->second.handshake;
167      i->second.handshake = NULL;
168    }
169
170    if ( i->second.connectionMonitor )
171    {
172      delete i->second.connectionMonitor;
173      i->second.connectionMonitor = NULL;
174    }
175  }
176  for ( SynchronizeableList::const_iterator it = getSyncBegin(); it != getSyncEnd(); it ++ )
177    (*it)->setNetworkStream( NULL );
178
179  if( this->pInfo)
180    delete this->pInfo;
181
182  if( this->networkMonitor)
183    delete this->networkMonitor;
184}
185
186
187/**
188 * establish a connection to a remote master server
189 * @param host: host name
190 * @param port: the port number
191 */
192void NetworkStream::connectToMasterServer(std::string host, int port)
193{
194  int node = NET_ID_MASTER_SERVER;
195  // this create the new node in the peers map
196  this->peers[node].socket = new UdpSocket( host, port );
197  this->peers[node].userId = NET_ID_MASTER_SERVER;
198
199  this->peers[node].nodeType = NET_MASTER_SERVER;
200  this->peers[node].connectionMonitor = new ConnectionMonitor( NET_ID_MASTER_SERVER );
201  this->peers[node].ip = this->peers[node].socket->getRemoteAddress();
202}
203
204
205/**
206 * establish a connection to a remote proxy server
207 * @param host: host name
208 * @param port: the port number
209 */
210void NetworkStream::connectToProxyServer(int proxyId,std::string host, int port)
211{
212  PRINTF(0)("connect to proxy %s, this is proxyId %i\n", host.c_str(), proxyId);
213
214  // this creates the new proxyId in the peers map
215  this->peers[proxyId].socket = new UdpSocket( host, port );
216  this->peers[proxyId].userId = proxyId;
217
218  this->peers[proxyId].nodeType = NET_PROXY_SERVER_ACTIVE;
219  this->peers[proxyId].connectionMonitor = new ConnectionMonitor( proxyId );
220  this->peers[proxyId].ip = this->peers[proxyId].socket->getRemoteAddress();
221}
222
223
224/**
225 * create a server
226 * @param port: interface port for all clients
227 */
228void NetworkStream::createServer(int clientPort, int proxyPort)
229{
230  this->proxySocket = new UdpServerSocket(clientPort);
231  this->clientSocket= new UdpServerSocket(proxyPort);
232}
233
234
235/**
236 * creates a new instance of the network game manager
237 */
238void NetworkStream::createNetworkGameManager()
239{
240  this->networkGameManager = NetworkGameManager::getInstance();
241
242  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
243  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
244}
245
246
247/**
248 * starts the network handshake
249 * handsakes are always initialized from the client side first. this starts the handshake and therefore is only
250 * executed as client
251 * @param userId: start handshake for this user id (optional, default == 0)
252 */
253void NetworkStream::startHandshake(int userId)
254{
255  Handshake* hs = new Handshake(this->pInfo->nodeType);
256  // fake the unique id
257  hs->setUniqueID( NET_UID_HANDSHAKE );
258  assert( peers[userId].handshake == NULL );
259  peers[userId].handshake = hs;
260
261  // set the preferred nick name
262  hs->setPreferedNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Player" ) );
263
264  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getCName());
265}
266
267
268/**
269 * this functions connects a synchronizeable to the networkstream, therefore synchronizeing
270 * it all over the network and creating it on the other platforms (if and only if it is a
271 * server
272 * @param sync: the synchronizeable to add
273 */
274void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
275{
276  this->synchronizeables.push_back(&sync);
277  sync.setNetworkStream( this );
278}
279
280
281/**
282 * removes the synchronizeable from the list of synchronized entities
283 * @param sync: the syncronizeable to remove
284 */
285void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
286{
287  // removing the Synchronizeable from the List.
288  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
289  if (disconnectSynchro != this->synchronizeables.end())
290    this->synchronizeables.erase(disconnectSynchro);
291
292  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
293}
294
295
296/**
297 * this is called to process data from the network socket to the synchronizeable and vice versa
298 */
299void NetworkStream::processData()
300{
301  // create the network monitor after all the init work and before there is any connection handlings
302  if( this->networkMonitor == NULL)
303    this->networkMonitor = new NetworkMonitor(this);
304
305
306  int tick = SDL_GetTicks();
307
308  this->currentState++;
309  // there was a wrap around
310  if( this->currentState < 0)
311  {
312    PRINTF(1)("A wrap around in the state variable as occured. The server was running so long? Pls restart server or write a mail to the supporters!\n");
313  }
314
315  if ( this->pInfo->isMasterServer())
316  {
317    // execute everytthing the master server shoudl do
318    if ( this->clientSocket )
319      this->clientSocket->update();
320    if( this->proxySocket)
321      this->proxySocket->update();
322
323    this->updateConnectionList();
324  }
325  else if( this->pInfo->isProxyServerActive())
326  {
327    // execute everything the proxy server should do
328    if ( clientSocket )
329      clientSocket->update();
330    if( this->proxySocket)
331      this->proxySocket->update();
332
333    this->updateConnectionList();
334  }
335  else
336  {
337    // check if the connection is ok else terminate and remove
338#warning make this more modular: every proxy/master server connection should be watched for termination
339    if ( !peers.empty() && peers[NET_ID_MASTER_SERVER].socket &&
340          ( !peers[NET_ID_MASTER_SERVER].socket->isOk() ||
341          peers[NET_ID_MASTER_SERVER].connectionMonitor->hasTimedOut() ) )
342    {
343      this->handleDisconnect( NET_ID_MASTER_SERVER);
344      PRINTF(1)("lost connection to server\n");
345    }
346    // check if there is a redirection command
347    if( this->bRedirect)
348    {
349      this->handleReconnect( NET_ID_MASTER_SERVER);
350    }
351  }
352
353  this->cleanUpOldSyncList();
354  this->handleHandshakes();
355
356  // update the network monitor
357  this->networkMonitor->process();
358
359  // order of up/downstream is important!!!!
360  // don't change it
361  this->handleDownstream( tick );
362  this->handleUpstream( tick );
363}
364
365
366/**
367 * if we are a NET_MASTER_SERVER or NET_PROXY_SERVER_ACTIVE update the connection list to accept new
368 * connections (clients) also start the handsake for the new clients
369 */
370void NetworkStream::updateConnectionList( )
371{
372  //check for new connections
373
374  NetworkSocket* tempNetworkSocket = NULL;
375  int userId;
376
377  if( this->clientSocket != NULL)
378  {
379    tempNetworkSocket = this->clientSocket->getNewSocket();
380
381    // we got new NET_CLIENT connecting
382    if ( tempNetworkSocket )
383    {
384      // determine the network node id
385      if ( freeSocketSlots.size() > 0 )
386      {
387        userId = freeSocketSlots.back();
388        freeSocketSlots.pop_back();
389      }
390      else
391      {
392        userId = 1;
393
394        for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
395          if ( it->first >= userId )
396            userId = it->first + 1;
397      }
398      // this creates a new entry in the peers list
399      peers[userId].socket = tempNetworkSocket;
400      this->handleConnect(userId);
401
402      PRINTF(0)("New Client: %d\n", userId);
403    }
404  }
405
406
407  if( this->proxySocket != NULL)
408  {
409    tempNetworkSocket = this->proxySocket->getNewSocket();
410
411    // we got new NET_PROXY_SERVER_ACTIVE connecting
412    if ( tempNetworkSocket )
413    {
414      // determine the network node id
415      if ( freeSocketSlots.size() > 0 )
416      {
417        userId = freeSocketSlots.back();
418        freeSocketSlots.pop_back();
419      }
420      else
421      {
422        userId = 1;
423
424        for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
425          if ( it->first >= userId )
426            userId = it->first + 1;
427      }
428
429      // this creates a new entry in the peers list
430      peers[userId].socket = tempNetworkSocket;
431      this->handleConnect(userId);
432
433      PRINTF(0)("New Proxy: %d\n", userId);
434    }
435  }
436
437
438  //check if connections are ok else remove them
439  for ( PeerList::iterator it = peers.begin(); it != peers.end(); )
440  {
441    if (
442          it->second.socket &&
443          (
444            !it->second.socket->isOk()  ||
445            it->second.connectionMonitor->hasTimedOut()
446          )
447       )
448    {
449      std::string reason = "disconnected";
450      if ( it->second.connectionMonitor->hasTimedOut() )
451        reason = "timeout";
452      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
453
454      this->handleDisconnect( it->second.userId);
455
456      it++;
457      continue;
458    }
459
460    it++;
461  }
462
463
464}
465
466
467void NetworkStream::handleConnect( int userId)
468{
469  // create new handshake and init its variables
470  peers[userId].handshake = new Handshake(this->pInfo->nodeType, userId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
471  peers[userId].handshake->setUniqueID(userId);
472
473  peers[userId].connectionMonitor = new ConnectionMonitor( userId );
474  peers[userId].userId = userId;
475
476  PRINTF(0)("num sync: %d\n", synchronizeables.size());
477
478    // get the proxy server informations and write them to the handshake, if any (proxy)
479  assert( this->networkMonitor != NULL);
480  PeerInfo* pi = this->networkMonitor->getFirstChoiceProxy();
481  if( pi != NULL)
482  {
483    peers[userId].handshake->setProxy1Address( pi->ip);
484  }
485  pi = this->networkMonitor->getSecondChoiceProxy();
486  if( pi != NULL)
487    peers[userId].handshake->setProxy2Address( pi->ip);
488
489    // check if the connecting client should reconnect to a proxy server
490  peers[userId].handshake->setRedirect(this->networkMonitor->isReconnectNextClient());
491
492    // the connecting node of course is a client
493  peers[userId].nodeType = NET_CLIENT;
494  peers[userId].ip = peers[userId].socket->getRemoteAddress();
495}
496
497
498void NetworkStream::debug()
499{
500  if( SharedNetworkData::getInstance()->isMasterServer()) {
501    PRINT(0)(" Host ist Master Server with ID: %i\n", this->pInfo->userId);
502  }
503  else if( SharedNetworkData::getInstance()->isProxyServerActive()) {
504    PRINT(0)(" Host ist Proxy Server with ID: %i\n", this->pInfo->userId);
505  }
506  else {
507    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
508  }
509
510  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
511  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
512  {
513    if( (*it)->beSynchronized() == true)
514      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassCName(), (*it)->getCName(),
515               (*it)->getUniqueID(), (*it)->beSynchronized());
516  }
517  PRINT(0)(" Maximal Connections: %i\n", SharedNetworkData::getInstance()->getMaxPlayer() );
518
519}
520
521
522/**
523 * @returns the number of synchronizeables registered to this stream
524 */
525int NetworkStream::getSyncCount()
526{
527  int n = 0;
528  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
529    if( (*it)->beSynchronized() == true)
530      ++n;
531
532  //return synchronizeables.size();
533  return n;
534}
535
536
537/**
538 * check if handshakes completed. if so create the network game manager else remove it again
539 */
540void NetworkStream::handleHandshakes( )
541{
542  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
543  {
544    if ( it->second.handshake )
545    {
546      // handshake finished
547      if ( it->second.handshake->completed() )
548      {
549        //handshake is correct
550        if ( it->second.handshake->ok() )
551        {
552          // the counter part didn't mark it free for deletion yet
553          if ( !it->second.handshake->allowDel() )
554          {
555            // make sure this is a client
556            if( this->pInfo->isClient())
557            {
558              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
559              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
560
561              it->second.nodeType = it->second.handshake->getRemoteNodeType();
562              it->second.ip = it->second.socket->getRemoteAddress();
563              // add the new server to the nodes list (it can be a NET_MASTER_SERVER or NET_PROXY_SERVER)
564              this->networkMonitor->addNode(&it->second);
565              // get proxy 1 address and add it
566              this->networkMonitor->addNode(it->second.handshake->getProxy1Address(), NET_PROXY_SERVER_ACTIVE);
567              // get proxy 2 address and add it
568              this->networkMonitor->addNode(it->second.handshake->getProxy2Address(), NET_PROXY_SERVER_ACTIVE);
569
570              // now check if the server accepted the connection
571              if( it->second.handshake->redirect() )
572              {
573                this->bRedirect = true;
574              }
575
576              // create the new network game manager and init it
577              this->networkGameManager = NetworkGameManager::getInstance();
578              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
579              // init the new message manager
580              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
581            }
582
583            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
584            it->second.handshake->del();
585
586          }
587          else
588          {
589            // handshake finished registring new player
590            if ( it->second.handshake->canDel() )
591            {
592
593              if ( this->pInfo->isMasterServer() )
594              {
595                it->second.nodeType = it->second.handshake->getRemoteNodeType();
596                it->second.ip = it->second.socket->getRemoteAddress();
597
598                this->networkMonitor->addNode(&it->second);
599
600                this->handleNewClient( it->second.userId );
601
602                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
603                {
604                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
605                }
606              }
607              else if ( this->pInfo->isProxyServerActive() )
608              {
609                it->second.nodeType = it->second.handshake->getRemoteNodeType();
610                it->second.ip = it->second.socket->getRemoteAddress();
611
612                this->networkMonitor->addNode(&it->second);
613
614                this->handleNewClient( it->second.userId );
615
616                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
617                {
618                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
619                }
620              }
621
622              PRINT(0)("handshake finished delete it\n");
623              delete it->second.handshake;
624              it->second.handshake = NULL;
625            }
626          }
627
628        }
629        else
630        {
631          PRINT(1)("handshake failed!\n");
632          it->second.socket->disconnectServer();
633        }
634      }
635    }
636  }
637}
638
639
640/**
641 * this functions handles a reconnect event received from the a NET_MASTER_SERVER or NET_PROXY_SERVER
642 */
643void NetworkStream::handleReconnect(int userId)
644{
645  this->bRedirect = false;
646  PeerInfo* pInfo = &this->peers[userId];
647
648  PRINTF(0)("===============================================\n");
649  PRINTF(0)("Client is redirected to the other proxy servers\n");
650  PRINTF(0)("  user id: %i\n", userId);
651  PRINTF(0)("  connecting to: %s\n", this->networkMonitor->getFirstChoiceProxy()->ip.ipString().c_str());
652  PRINTF(0)("===============================================\n");
653
654  // flush the old synchronization states, since the numbering could be completely different
655  pInfo->lastAckedState = 0;
656  pInfo->lastRecvedState = 0;
657
658  // temp save the ip address here
659  IP proxyIP = pInfo->handshake->getProxy1Address();
660
661  // disconnect from the current server and reconnect to proxy server
662  this->handleDisconnect( userId);
663  this->connectToProxyServer(NET_ID_PROXY_SERVER_01, proxyIP.ipString(), 9999);
664  #warning the ports are not yet integrated correctly in the ip class
665
666  // and restart the handshake
667  this->startHandshake( userId);
668}
669
670
671/**
672 * handles the disconnect event
673 * @param userId id of the user to remove
674 */
675void NetworkStream::handleDisconnect( int userId )
676{
677  peers[userId].socket->disconnectServer();
678  delete peers[userId].socket;
679  peers[userId].socket = NULL;
680
681  if ( peers[userId].handshake )
682    delete peers[userId].handshake;
683  peers[userId].handshake = NULL;
684
685  if ( peers[userId].connectionMonitor )
686    delete peers[userId].connectionMonitor;
687  peers[userId].connectionMonitor = NULL;
688
689
690  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
691    (*it2)->cleanUpUser( userId );
692  }
693
694  if( SharedNetworkData::getInstance()->isMasterServer())
695    NetworkGameManager::getInstance()->signalLeftPlayer(userId);
696
697  this->freeSocketSlots.push_back( userId );
698
699  peers.erase( userId);
700}
701
702
703
704/**
705 * handle upstream network traffic
706 * @param tick: seconds elapsed since last update
707 */
708void NetworkStream::handleUpstream( int tick )
709{
710  int offset;
711  int n;
712
713  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
714  {
715    offset = INTSIZE; // reserve enough space for the packet length
716
717    // continue with the next peer if this peer has no socket assigned (therefore no network)
718    if ( !peer->second.socket )
719      continue;
720
721    // header informations: current state
722    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
723    assert( n == INTSIZE );
724    offset += n;
725
726    // header informations: last acked state
727    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
728    assert( n == INTSIZE );
729    offset += n;
730
731    // header informations: last recved state
732    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
733    assert( n == INTSIZE );
734    offset += n;
735
736    // now write all synchronizeables in the packet
737    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
738    {
739
740      int oldOffset = offset;
741      Synchronizeable & sync = **it;
742
743
744      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
745      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
746        continue;
747
748      // if handshake not finished only sync handshake
749      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
750        continue;
751
752      // if we are a server (both master and proxy servers) and this is not our handshake
753      if ( ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServerActive() ) && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
754        continue;
755
756      /* list of synchronizeables that will never be synchronized over the network: */
757      // do not sync null parent
758      if ( sync.getLeafClassID() == CL_NULL_PARENT )
759        continue;
760
761
762      assert( sync.getLeafClassID() != 0);
763
764      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
765
766      // server fakes uniqueid == 0 for handshake
767      if ( ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServerActive() ) &&
768             sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1) // plus one to handle one client more than the max to redirect it
769        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
770      else
771        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
772
773
774      assert( n == INTSIZE );
775      offset += n;
776
777      // make space for packet size
778      offset += INTSIZE;
779
780      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
781      offset += n;
782
783      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
784
785      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
786      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
787      bool allZero = true;
788      for ( int i = 0; i < n; i++ )
789      {
790         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
791           allZero = false;
792      }
793      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
794      // data that hast not changed
795      if ( allZero )
796      {
797        offset = oldOffset;
798      }
799    } // all synchronizeables written
800
801
802
803    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
804    {
805      Synchronizeable & sync = **it;
806
807      // again exclude all unwanted syncs
808      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED)
809        continue;
810
811      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
812    }
813
814
815    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
816
817    // now compress the data with the zip library
818    int compLength = 0;
819    if ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServerActive())
820      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
821    else
822      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
823
824    if ( compLength <= 0 )
825    {
826      PRINTF(1)("compression failed!\n");
827      continue;
828    }
829
830    assert( peer->second.socket->writePacket( compBuf, compLength ) );
831
832    if ( this->remainingBytesToWriteToDict > 0 )
833      writeToNewDict( buf, offset, true );
834
835    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
836    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
837
838  }
839}
840
841/**
842 * handle downstream network traffic
843 */
844void NetworkStream::handleDownstream( int tick )
845{
846  int offset = 0;
847
848  int length = 0;
849  int packetLength = 0;
850  int compLength = 0;
851  int uniqueId = 0;
852  int state = 0;
853  int ackedState = 0;
854  int fromState = 0;
855  int syncDataLength = 0;
856
857  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
858  {
859
860    if ( !peer->second.socket )
861      continue;
862
863    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
864    {
865      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
866
867      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
868
869      if ( packetLength < 4*INTSIZE )
870      {
871        if ( packetLength != 0 )
872          PRINTF(1)("got too small packet: %d\n", packetLength);
873        continue;
874      }
875
876      if ( this->remainingBytesToWriteToDict > 0 )
877        writeToNewDict( buf, packetLength, false );
878
879      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
880      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
881      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
882      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
883      offset = 4*INTSIZE;
884
885      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
886
887
888      //if this is an old state drop it
889      if ( state <= peer->second.lastRecvedState )
890        continue;
891
892      if ( packetLength != length )
893      {
894        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
895        peer->second.socket->disconnectServer();
896        continue;
897      }
898
899      while ( offset + 2 * INTSIZE < length )
900      {
901        assert( offset > 0 );
902        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
903        offset += INTSIZE;
904
905        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
906        offset += INTSIZE;
907
908        assert( syncDataLength > 0 );
909        assert( syncDataLength < 10000 );
910
911        Synchronizeable * sync = NULL;
912
913        // look for the synchronizeable in question
914        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
915        {
916          // client thinks his handshake has id 0!!!!!
917          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
918          {
919            sync = *it;
920            break;
921          }
922        }
923
924        // this synchronizeable does not yet exist! create it
925        if ( sync == NULL )
926        {
927          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
928
929          // if it is an old synchronizeable already removed, ignore it
930          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
931          {
932            offset += syncDataLength;
933            continue;
934          }
935
936          // if the node we got this unknown sync from is a client we ignore it (since it has no rights to create a new sync)
937          if ( peers[peer->second.userId].isClient() )
938          {
939            offset += syncDataLength;
940            continue;
941          }
942
943          int leafClassId;
944          if ( INTSIZE > length - offset )
945          {
946            offset += syncDataLength;
947            continue;
948          }
949
950          Converter::byteArrayToInt( buf + offset, &leafClassId );
951
952          assert( leafClassId != 0 );
953
954
955          BaseObject * b = NULL;
956          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
957          /* Exception 1: NullParent */
958          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
959          {
960            PRINTF(1)("Don't create Object with ID %x, ignored!\n", (int)leafClassId);
961            offset += syncDataLength;
962            continue;
963          }
964          else
965            b = Factory::fabricate( (ClassID)leafClassId );
966
967          if ( !b )
968          {
969            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
970            offset += syncDataLength;
971            continue;
972          }
973
974          if ( b->isA(CL_SYNCHRONIZEABLE) )
975          {
976            sync = dynamic_cast<Synchronizeable*>(b);
977            sync->setUniqueID( uniqueId );
978            sync->setSynchronized(true);
979
980            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassCName(), sync->getUniqueID());
981          }
982          else
983          {
984            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
985            delete b;
986            offset += syncDataLength;
987            continue;
988          }
989        }
990
991
992        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
993        offset += n;
994
995      }
996
997      if ( offset != length )
998      {
999        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
1000        peer->second.socket->disconnectServer();
1001      }
1002
1003
1004      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
1005      {
1006        Synchronizeable & sync = **it;
1007
1008        if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
1009          continue;
1010
1011        sync.handleRecvState( peer->second.userId, state, fromState );
1012      }
1013
1014      assert( peer->second.lastAckedState <= ackedState );
1015      peer->second.lastAckedState = ackedState;
1016
1017      assert( peer->second.lastRecvedState < state );
1018      peer->second.lastRecvedState = state;
1019
1020    }
1021
1022  }
1023
1024}
1025
1026/**
1027 * is executed when a handshake has finished
1028 */
1029void NetworkStream::handleNewClient( int userId )
1030{
1031  // init and assign the message manager
1032  MessageManager::getInstance()->initUser( userId );
1033  // do all game relevant stuff here
1034  networkGameManager->signalNewPlayer( userId );
1035}
1036
1037
1038/**
1039 * removes old items from oldSynchronizeables
1040 */
1041void NetworkStream::cleanUpOldSyncList( )
1042{
1043  int now = SDL_GetTicks();
1044
1045  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
1046  {
1047    if ( it->second < now - 10*1000 )
1048    {
1049      std::map<int,int>::iterator delIt = it;
1050      it++;
1051      oldSynchronizeables.erase( delIt );
1052      continue;
1053    }
1054    it++;
1055  }
1056}
1057
1058/**
1059 * writes data to DATA/dicts/newdict
1060 * @param data pointer to data
1061 * @param length length
1062 */
1063void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
1064{
1065  if ( remainingBytesToWriteToDict <= 0 )
1066    return;
1067
1068  if ( length > remainingBytesToWriteToDict )
1069    length = remainingBytesToWriteToDict;
1070
1071  std::string fileName = ResourceManager::getInstance()->getDataDir();
1072  fileName += "/dicts/newdict";
1073
1074  if ( upstream )
1075    fileName += "_upstream";
1076  else
1077    fileName += "_downstream";
1078
1079  FILE * f = fopen( fileName.c_str(), "a" );
1080
1081  if ( !f )
1082  {
1083    PRINTF(2)("could not open %s\n", fileName.c_str());
1084    remainingBytesToWriteToDict = 0;
1085    return;
1086  }
1087
1088  if ( fwrite( data, 1, length, f ) != length )
1089  {
1090    PRINTF(2)("could not write to file\n");
1091    fclose( f );
1092    return;
1093  }
1094
1095  fclose( f );
1096
1097  remainingBytesToWriteToDict -= length;
1098}
1099
1100
1101
1102
1103
1104
Note: See TracBrowser for help on using the repository browser.