Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

deep framework switch to enable differentiation of proxy/client network connection attempts

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