Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

assertion failure, becaus the proxy tried to accept the own connection

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