Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/network/network_stream.cc @ 9596

Last change on this file since 9596 was 9494, checked in by bensch, 18 years ago

merged the proxy back

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