Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

proxy server now temporarily does not open server ports (so i can test on one client). proxy server id bug fixed

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