Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

localy connected clients get removed also

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