Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

reconnection does not segfault anymore now! betta

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