Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

proxy server should now be accepted

File size: 32.2 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 = this->clientSocket->getNewSocket();
375  int userId;
376
377  // we got new NET_CLIENT connecting
378  if ( tempNetworkSocket )
379  {
380    // determine the network node id
381    if ( freeSocketSlots.size() > 0 )
382    {
383      userId = freeSocketSlots.back();
384      freeSocketSlots.pop_back();
385    }
386    else
387    {
388      userId = 1;
389
390      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
391        if ( it->first >= userId )
392          userId = it->first + 1;
393    }
394    // this creates a new entry in the peers list
395    peers[userId].socket = tempNetworkSocket;
396    this->handleConnect(userId);
397
398    PRINTF(0)("New Client: %d\n", userId);
399  }
400
401  tempNetworkSocket = this->proxySocket->getNewSocket();
402
403  // we got new NET_PROXY_SERVER_ACTIVE connecting
404  if ( tempNetworkSocket )
405  {
406    // determine the network node id
407    if ( freeSocketSlots.size() > 0 )
408    {
409      userId = freeSocketSlots.back();
410      freeSocketSlots.pop_back();
411    }
412    else
413    {
414      userId = 1;
415
416      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
417        if ( it->first >= userId )
418          userId = it->first + 1;
419    }
420
421    // this creates a new entry in the peers list
422    peers[userId].socket = tempNetworkSocket;
423    this->handleConnect(userId);
424
425    PRINTF(0)("New Proxy: %d\n", userId);
426  }
427
428
429
430  //check if connections are ok else remove them
431  for ( PeerList::iterator it = peers.begin(); it != peers.end(); )
432  {
433    if (
434          it->second.socket &&
435          (
436            !it->second.socket->isOk()  ||
437            it->second.connectionMonitor->hasTimedOut()
438          )
439       )
440    {
441      std::string reason = "disconnected";
442      if ( it->second.connectionMonitor->hasTimedOut() )
443        reason = "timeout";
444      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
445
446      this->handleDisconnect( it->second.userId);
447
448      it++;
449      continue;
450    }
451
452    it++;
453  }
454
455
456}
457
458
459void NetworkStream::handleConnect( int userId)
460{
461  // create new handshake and init its variables
462  peers[userId].handshake = new Handshake(this->pInfo->nodeType, userId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
463  peers[userId].handshake->setUniqueID(userId);
464
465  peers[userId].connectionMonitor = new ConnectionMonitor( userId );
466  peers[userId].userId = userId;
467
468  PRINTF(0)("num sync: %d\n", synchronizeables.size());
469
470    // get the proxy server informations and write them to the handshake, if any (proxy)
471  assert( this->networkMonitor != NULL);
472  PeerInfo* pi = this->networkMonitor->getFirstChoiceProxy();
473  if( pi != NULL)
474  {
475    peers[userId].handshake->setProxy1Address( pi->ip);
476  }
477  pi = this->networkMonitor->getSecondChoiceProxy();
478  if( pi != NULL)
479    peers[userId].handshake->setProxy2Address( pi->ip);
480
481    // check if the connecting client should reconnect to a proxy server
482  peers[userId].handshake->setRedirect(this->networkMonitor->isReconnectNextClient());
483
484    // the connecting node of course is a client
485  peers[userId].nodeType = NET_CLIENT;
486  peers[userId].ip = peers[userId].socket->getRemoteAddress();
487}
488
489
490void NetworkStream::debug()
491{
492  if( SharedNetworkData::getInstance()->isMasterServer()) {
493    PRINT(0)(" Host ist Master Server with ID: %i\n", this->pInfo->userId);
494  }
495  else if( SharedNetworkData::getInstance()->isProxyServerActive()) {
496    PRINT(0)(" Host ist Proxy Server with ID: %i\n", this->pInfo->userId);
497  }
498  else {
499    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
500  }
501
502  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
503  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
504  {
505    if( (*it)->beSynchronized() == true)
506      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassCName(), (*it)->getCName(),
507               (*it)->getUniqueID(), (*it)->beSynchronized());
508  }
509  PRINT(0)(" Maximal Connections: %i\n", SharedNetworkData::getInstance()->getMaxPlayer() );
510
511}
512
513
514/**
515 * @returns the number of synchronizeables registered to this stream
516 */
517int NetworkStream::getSyncCount()
518{
519  int n = 0;
520  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
521    if( (*it)->beSynchronized() == true)
522      ++n;
523
524  //return synchronizeables.size();
525  return n;
526}
527
528
529/**
530 * check if handshakes completed. if so create the network game manager else remove it again
531 */
532void NetworkStream::handleHandshakes( )
533{
534  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
535  {
536    if ( it->second.handshake )
537    {
538      // handshake finished
539      if ( it->second.handshake->completed() )
540      {
541        //handshake is correct
542        if ( it->second.handshake->ok() )
543        {
544          // the counter part didn't mark it free for deletion yet
545          if ( !it->second.handshake->allowDel() )
546          {
547            // make sure this is a client
548            if( this->pInfo->isClient())
549            {
550              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
551              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
552
553              it->second.nodeType = it->second.handshake->getRemoteNodeType();
554              it->second.ip = it->second.socket->getRemoteAddress();
555              // add the new server to the nodes list (it can be a NET_MASTER_SERVER or NET_PROXY_SERVER)
556              this->networkMonitor->addNode(&it->second);
557              // get proxy 1 address and add it
558              this->networkMonitor->addNode(it->second.handshake->getProxy1Address(), NET_PROXY_SERVER_ACTIVE);
559              // get proxy 2 address and add it
560              this->networkMonitor->addNode(it->second.handshake->getProxy2Address(), NET_PROXY_SERVER_ACTIVE);
561
562              // now check if the server accepted the connection
563              if( it->second.handshake->redirect() )
564              {
565                this->bRedirect = true;
566              }
567
568              // create the new network game manager and init it
569              this->networkGameManager = NetworkGameManager::getInstance();
570              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
571              // init the new message manager
572              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
573            }
574
575            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
576            it->second.handshake->del();
577
578          }
579          else
580          {
581            // handshake finished registring new player
582            if ( it->second.handshake->canDel() )
583            {
584
585              if ( this->pInfo->isMasterServer() )
586              {
587                it->second.nodeType = it->second.handshake->getRemoteNodeType();
588                it->second.ip = it->second.socket->getRemoteAddress();
589
590                this->networkMonitor->addNode(&it->second);
591
592                this->handleNewClient( it->second.userId );
593
594                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
595                {
596                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
597                }
598              }
599              else if ( this->pInfo->isProxyServerActive() )
600              {
601                it->second.nodeType = it->second.handshake->getRemoteNodeType();
602                it->second.ip = it->second.socket->getRemoteAddress();
603
604                this->networkMonitor->addNode(&it->second);
605
606                this->handleNewClient( it->second.userId );
607
608                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
609                {
610                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
611                }
612              }
613
614              PRINT(0)("handshake finished delete it\n");
615              delete it->second.handshake;
616              it->second.handshake = NULL;
617            }
618          }
619
620        }
621        else
622        {
623          PRINT(1)("handshake failed!\n");
624          it->second.socket->disconnectServer();
625        }
626      }
627    }
628  }
629}
630
631
632/**
633 * this functions handles a reconnect event received from the a NET_MASTER_SERVER or NET_PROXY_SERVER
634 */
635void NetworkStream::handleReconnect(int userId)
636{
637  this->bRedirect = false;
638  PeerInfo* pInfo = &this->peers[userId];
639
640  PRINTF(0)("===============================================\n");
641  PRINTF(0)("Client is redirected to the other proxy servers\n");
642  PRINTF(0)("  user id: %i\n", userId);
643  PRINTF(0)("  connecting to: %s\n", this->networkMonitor->getFirstChoiceProxy()->ip.ipString().c_str());
644  PRINTF(0)("===============================================\n");
645
646  // flush the old synchronization states, since the numbering could be completely different
647  pInfo->lastAckedState = 0;
648  pInfo->lastRecvedState = 0;
649
650  // temp save the ip address here
651  IP proxyIP = pInfo->handshake->getProxy1Address();
652
653  // disconnect from the current server and reconnect to proxy server
654  this->handleDisconnect( userId);
655  this->connectToProxyServer(NET_ID_PROXY_SERVER_01, proxyIP.ipString(), 9999);
656  #warning the ports are not yet integrated correctly in the ip class
657
658  // and restart the handshake
659  this->startHandshake( userId);
660}
661
662
663/**
664 * handles the disconnect event
665 * @param userId id of the user to remove
666 */
667void NetworkStream::handleDisconnect( int userId )
668{
669  peers[userId].socket->disconnectServer();
670  delete peers[userId].socket;
671  peers[userId].socket = NULL;
672
673  if ( peers[userId].handshake )
674    delete peers[userId].handshake;
675  peers[userId].handshake = NULL;
676
677  if ( peers[userId].connectionMonitor )
678    delete peers[userId].connectionMonitor;
679  peers[userId].connectionMonitor = NULL;
680
681
682  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
683    (*it2)->cleanUpUser( userId );
684  }
685
686  if( SharedNetworkData::getInstance()->isMasterServer())
687    NetworkGameManager::getInstance()->signalLeftPlayer(userId);
688
689  this->freeSocketSlots.push_back( userId );
690
691  peers.erase( userId);
692}
693
694
695
696/**
697 * handle upstream network traffic
698 * @param tick: seconds elapsed since last update
699 */
700void NetworkStream::handleUpstream( int tick )
701{
702  int offset;
703  int n;
704
705  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
706  {
707    offset = INTSIZE; // reserve enough space for the packet length
708
709    // continue with the next peer if this peer has no socket assigned (therefore no network)
710    if ( !peer->second.socket )
711      continue;
712
713    // header informations: current state
714    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
715    assert( n == INTSIZE );
716    offset += n;
717
718    // header informations: last acked state
719    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
720    assert( n == INTSIZE );
721    offset += n;
722
723    // header informations: last recved state
724    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
725    assert( n == INTSIZE );
726    offset += n;
727
728    // now write all synchronizeables in the packet
729    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
730    {
731
732      int oldOffset = offset;
733      Synchronizeable & sync = **it;
734
735
736      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
737      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
738        continue;
739
740      // if handshake not finished only sync handshake
741      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
742        continue;
743
744      // if we are a server (both master and proxy servers) and this is not our handshake
745      if ( ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServerActive() ) && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
746        continue;
747
748      /* list of synchronizeables that will never be synchronized over the network: */
749      // do not sync null parent
750      if ( sync.getLeafClassID() == CL_NULL_PARENT )
751        continue;
752
753
754      assert( sync.getLeafClassID() != 0);
755
756      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
757
758      // server fakes uniqueid == 0 for handshake
759      if ( ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServerActive() ) &&
760             sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1) // plus one to handle one client more than the max to redirect it
761        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
762      else
763        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
764
765
766      assert( n == INTSIZE );
767      offset += n;
768
769      // make space for packet size
770      offset += INTSIZE;
771
772      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
773      offset += n;
774
775      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
776
777      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
778      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
779      bool allZero = true;
780      for ( int i = 0; i < n; i++ )
781      {
782         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
783           allZero = false;
784      }
785      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
786      // data that hast not changed
787      if ( allZero )
788      {
789        offset = oldOffset;
790      }
791    } // all synchronizeables written
792
793
794
795    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
796    {
797      Synchronizeable & sync = **it;
798
799      // again exclude all unwanted syncs
800      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED)
801        continue;
802
803      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
804    }
805
806
807    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
808
809    // now compress the data with the zip library
810    int compLength = 0;
811    if ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServerActive())
812      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
813    else
814      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
815
816    if ( compLength <= 0 )
817    {
818      PRINTF(1)("compression failed!\n");
819      continue;
820    }
821
822    assert( peer->second.socket->writePacket( compBuf, compLength ) );
823
824    if ( this->remainingBytesToWriteToDict > 0 )
825      writeToNewDict( buf, offset, true );
826
827    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
828    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
829
830  }
831}
832
833/**
834 * handle downstream network traffic
835 */
836void NetworkStream::handleDownstream( int tick )
837{
838  int offset = 0;
839
840  int length = 0;
841  int packetLength = 0;
842  int compLength = 0;
843  int uniqueId = 0;
844  int state = 0;
845  int ackedState = 0;
846  int fromState = 0;
847  int syncDataLength = 0;
848
849  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
850  {
851
852    if ( !peer->second.socket )
853      continue;
854
855    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
856    {
857      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
858
859      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
860
861      if ( packetLength < 4*INTSIZE )
862      {
863        if ( packetLength != 0 )
864          PRINTF(1)("got too small packet: %d\n", packetLength);
865        continue;
866      }
867
868      if ( this->remainingBytesToWriteToDict > 0 )
869        writeToNewDict( buf, packetLength, false );
870
871      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
872      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
873      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
874      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
875      offset = 4*INTSIZE;
876
877      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
878
879
880      //if this is an old state drop it
881      if ( state <= peer->second.lastRecvedState )
882        continue;
883
884      if ( packetLength != length )
885      {
886        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
887        peer->second.socket->disconnectServer();
888        continue;
889      }
890
891      while ( offset + 2 * INTSIZE < length )
892      {
893        assert( offset > 0 );
894        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
895        offset += INTSIZE;
896
897        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
898        offset += INTSIZE;
899
900        assert( syncDataLength > 0 );
901        assert( syncDataLength < 10000 );
902
903        Synchronizeable * sync = NULL;
904
905        // look for the synchronizeable in question
906        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
907        {
908          // client thinks his handshake has id 0!!!!!
909          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
910          {
911            sync = *it;
912            break;
913          }
914        }
915
916        // this synchronizeable does not yet exist! create it
917        if ( sync == NULL )
918        {
919          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
920
921          // if it is an old synchronizeable already removed, ignore it
922          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
923          {
924            offset += syncDataLength;
925            continue;
926          }
927
928          // 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)
929          if ( peers[peer->second.userId].isClient() )
930          {
931            offset += syncDataLength;
932            continue;
933          }
934
935          int leafClassId;
936          if ( INTSIZE > length - offset )
937          {
938            offset += syncDataLength;
939            continue;
940          }
941
942          Converter::byteArrayToInt( buf + offset, &leafClassId );
943
944          assert( leafClassId != 0 );
945
946
947          BaseObject * b = NULL;
948          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
949          /* Exception 1: NullParent */
950          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
951          {
952            PRINTF(1)("Don't create Object with ID %x, ignored!\n", (int)leafClassId);
953            offset += syncDataLength;
954            continue;
955          }
956          else
957            b = Factory::fabricate( (ClassID)leafClassId );
958
959          if ( !b )
960          {
961            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
962            offset += syncDataLength;
963            continue;
964          }
965
966          if ( b->isA(CL_SYNCHRONIZEABLE) )
967          {
968            sync = dynamic_cast<Synchronizeable*>(b);
969            sync->setUniqueID( uniqueId );
970            sync->setSynchronized(true);
971
972            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassCName(), sync->getUniqueID());
973          }
974          else
975          {
976            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
977            delete b;
978            offset += syncDataLength;
979            continue;
980          }
981        }
982
983
984        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
985        offset += n;
986
987      }
988
989      if ( offset != length )
990      {
991        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
992        peer->second.socket->disconnectServer();
993      }
994
995
996      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
997      {
998        Synchronizeable & sync = **it;
999
1000        if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
1001          continue;
1002
1003        sync.handleRecvState( peer->second.userId, state, fromState );
1004      }
1005
1006      assert( peer->second.lastAckedState <= ackedState );
1007      peer->second.lastAckedState = ackedState;
1008
1009      assert( peer->second.lastRecvedState < state );
1010      peer->second.lastRecvedState = state;
1011
1012    }
1013
1014  }
1015
1016}
1017
1018/**
1019 * is executed when a handshake has finished
1020 */
1021void NetworkStream::handleNewClient( int userId )
1022{
1023  // init and assign the message manager
1024  MessageManager::getInstance()->initUser( userId );
1025  // do all game relevant stuff here
1026  networkGameManager->signalNewPlayer( userId );
1027}
1028
1029
1030/**
1031 * removes old items from oldSynchronizeables
1032 */
1033void NetworkStream::cleanUpOldSyncList( )
1034{
1035  int now = SDL_GetTicks();
1036
1037  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
1038  {
1039    if ( it->second < now - 10*1000 )
1040    {
1041      std::map<int,int>::iterator delIt = it;
1042      it++;
1043      oldSynchronizeables.erase( delIt );
1044      continue;
1045    }
1046    it++;
1047  }
1048}
1049
1050/**
1051 * writes data to DATA/dicts/newdict
1052 * @param data pointer to data
1053 * @param length length
1054 */
1055void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
1056{
1057  if ( remainingBytesToWriteToDict <= 0 )
1058    return;
1059
1060  if ( length > remainingBytesToWriteToDict )
1061    length = remainingBytesToWriteToDict;
1062
1063  std::string fileName = ResourceManager::getInstance()->getDataDir();
1064  fileName += "/dicts/newdict";
1065
1066  if ( upstream )
1067    fileName += "_upstream";
1068  else
1069    fileName += "_downstream";
1070
1071  FILE * f = fopen( fileName.c_str(), "a" );
1072
1073  if ( !f )
1074  {
1075    PRINTF(2)("could not open %s\n", fileName.c_str());
1076    remainingBytesToWriteToDict = 0;
1077    return;
1078  }
1079
1080  if ( fwrite( data, 1, length, f ) != length )
1081  {
1082    PRINTF(2)("could not write to file\n");
1083    fclose( f );
1084    return;
1085  }
1086
1087  fclose( f );
1088
1089  remainingBytesToWriteToDict -= length;
1090}
1091
1092
1093
1094
1095
1096
Note: See TracBrowser for help on using the repository browser.