Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

nick name handling

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