Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

reconnection does not segfault anymore now! betta

File size: 31.6 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11### File Specific:
12   main-programmer: Christoph Renner rennerc@ee.ethz.ch
13   co-programmer:   Patrick Boenzli  boenzlip@orxonox.ethz.ch
14
15     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
16     July 2006: some code rearangement and integration of the proxy server mechanism (boenzlip@ee.ethz.ch)
17*/
18
19
20#define DEBUG_MODULE_NETWORK
21
22
23#include "base_object.h"
24#include "network_protocol.h"
25#include "udp_socket.h"
26#include "udp_server_socket.h"
27#include "monitor/connection_monitor.h"
28#include "monitor/network_monitor.h"
29#include "synchronizeable.h"
30#include "ip.h"
31#include "network_game_manager.h"
32#include "shared_network_data.h"
33#include "message_manager.h"
34#include "preferences.h"
35#include "zip.h"
36
37#include "src/lib/util/loading/resource_manager.h"
38
39#include "network_log.h"
40
41#include "player_stats.h"
42
43#include "lib/util/loading/factory.h"
44
45#include "debug.h"
46#include "class_list.h"
47#include <algorithm>
48
49
50#include "network_stream.h"
51
52
53#include "converter.h"
54
55
56#define PACKAGE_SIZE  256
57
58
59/**
60 * empty constructor
61 */
62NetworkStream::NetworkStream()
63    : DataStream()
64{
65  this->init();
66  /* initialize the references */
67  this->pInfo->nodeType = NET_CLIENT;
68}
69
70
71NetworkStream::NetworkStream( int nodeType)
72{
73  this->init();
74
75  this->pInfo->nodeType = nodeType;
76
77  switch( nodeType)
78  {
79    case NET_MASTER_SERVER:
80      // init the shared network data
81      SharedNetworkData::getInstance()->setHostID(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:
89      // init the shared network data
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;
102}
103
104
105
106/**
107 * generic init functions
108 */
109void NetworkStream::init()
110{
111  /* set the class id for the base object */
112  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
113  this->serverSocket = NULL;
114  this->networkGameManager = NULL;
115  this->networkMonitor = NULL;
116
117  this->pInfo = new PeerInfo();
118  this->pInfo->userId = 0;
119  this->pInfo->lastAckedState = 0;
120  this->pInfo->lastRecvedState = 0;
121
122  this->bRedirect = false;
123
124  this->currentState = 0;
125
126  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
127
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 );
133}
134
135
136/**
137 * deconstructor
138 */
139NetworkStream::~NetworkStream()
140{
141  if ( this->serverSocket )
142  {
143    serverSocket->close();
144    delete serverSocket;
145    serverSocket = NULL;
146  }
147  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
148  {
149    if ( i->second.socket )
150    {
151      i->second.socket->disconnectServer();
152      delete i->second.socket;
153      i->second.socket = NULL;
154    }
155
156    if ( i->second.handshake )
157    {
158      delete i->second.handshake;
159      i->second.handshake = NULL;
160    }
161
162    if ( i->second.connectionMonitor )
163    {
164      delete i->second.connectionMonitor;
165      i->second.connectionMonitor = NULL;
166    }
167  }
168  for ( SynchronizeableList::const_iterator it = getSyncBegin(); it != getSyncEnd(); it ++ )
169    (*it)->setNetworkStream( NULL );
170
171  if( this->pInfo)
172    delete this->pInfo;
173
174  if( this->networkMonitor)
175    delete this->networkMonitor;
176}
177
178
179/**
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();
204  PRINTF(0)("connect to proxy %s, this is node %i\n", host.c_str(), node);
205
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/**
226 * creates a new instance of the network game manager
227 */
228void NetworkStream::createNetworkGameManager()
229{
230  this->networkGameManager = NetworkGameManager::getInstance();
231
232  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
233  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
234}
235
236
237/**
238 * starts the network handshake
239 * handsakes are always initialized from the client side first. this starts the handshake and therefore is only
240 * executed as client
241 * @param userId: start handshake for this user id (optional, default == 0)
242 */
243void NetworkStream::startHandshake(int userId)
244{
245  Handshake* hs = new Handshake(this->pInfo->nodeType);
246  hs->setUniqueID( 0 );
247  assert( peers[userId].handshake == NULL );
248  peers[userId].handshake = hs;
249
250  // set the preferred nick name
251  hs->setPreferedNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Player" ) );
252
253  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getCName());
254}
255
256
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
261 * @param sync: the synchronizeable to add
262 */
263void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
264{
265  this->synchronizeables.push_back(&sync);
266  sync.setNetworkStream( this );
267}
268
269
270/**
271 * removes the synchronizeable from the list of synchronized entities
272 * @param sync: the syncronizeable to remove
273 */
274void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
275{
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);
280
281  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
282}
283
284
285/**
286 * this is called to process data from the network socket to the synchronizeable and vice versa
287 */
288void NetworkStream::processData()
289{
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
295  int tick = SDL_GetTicks();
296
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  }
303
304  if ( this->pInfo->isMasterServer())
305  {
306    // execute everytthing the master server shoudl do
307    if ( serverSocket )
308      serverSocket->update();
309
310    this->updateConnectionList();
311  }
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  }
320  else
321  {
322    // check if the connection is ok else terminate and remove
323    if ( !peers.empty() && peers[0].socket && ( !peers[0].socket->isOk() || peers[0].connectionMonitor->hasTimedOut() ) )
324    {
325      this->handleDisconnect( 0);
326      PRINTF(1)("lost connection to server\n");
327    }
328    // check if there is a redirection command
329    if( this->bRedirect)
330    {
331      this->handleReconnect( 0);
332    }
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    }
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->getNewSocket();
363
364  // we got new network node
365  if ( tempNetworkSocket )
366  {
367    int clientId;
368    // if there is a list of free client id slots, take these
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    peers[clientId].socket = tempNetworkSocket;
383
384
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);
388
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)
398    {
399      peers[clientId].handshake->setProxy1Address( pi->ip);
400    }
401    pi = this->networkMonitor->getSecondChoiceProxy();
402    if( pi != NULL)
403      peers[clientId].handshake->setProxy2Address( pi->ip);
404
405    // check if the connecting client should reconnect to a proxy server
406    peers[clientId].handshake->setRedirect(/*this->networkMonitor->isReconnectNextClient()*/true);
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
428  }
429
430
431
432  //check if connections are ok else remove them
433  for ( PeerList::iterator it = peers.begin(); it != peers.end(); )
434  {
435    if (
436          it->second.socket &&
437          (
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
448      this->handleDisconnect( it->second.userId);
449
450      it++;
451      continue;
452    }
453
454    it++;
455  }
456
457
458}
459
460
461void NetworkStream::debug()
462{
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  }
472
473  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
474  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
475  {
476    if( (*it)->beSynchronized() == true)
477      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassCName(), (*it)->getCName(),
478               (*it)->getUniqueID(), (*it)->beSynchronized());
479  }
480  PRINT(0)(" Maximal Connections: %i\n", SharedNetworkData::getInstance()->getMaxPlayer() );
481
482}
483
484
485/**
486 * @returns the number of synchronizeables registered to this stream
487 */
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;
494
495  //return synchronizeables.size();
496  return n;
497}
498
499
500/**
501 * check if handshakes completed. if so create the network game manager else remove it again
502 */
503void NetworkStream::handleHandshakes( )
504{
505  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
506  {
507    if ( it->second.handshake )
508    {
509      // handshake finished
510      if ( it->second.handshake->completed() )
511      {
512        //handshake is correct
513        if ( it->second.handshake->ok() )
514        {
515          // the counter part didn't mark it free for deletion yet
516          if ( !it->second.handshake->allowDel() )
517          {
518            // make sure this is a client
519            if( this->pInfo->isClient())
520            {
521              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
522              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
523
524              it->second.nodeType = it->second.handshake->getRemoteNodeType();
525              it->second.ip = it->second.socket->getRemoteAddress();
526              // add the new server to the nodes list (it can be a NET_MASTER_SERVER or NET_PROXY_SERVER)
527              this->networkMonitor->addNode(&it->second);
528              // get proxy 1 address and add it
529              this->networkMonitor->addNode(it->second.handshake->getProxy1Address(), NET_PROXY_SERVER_ACTIVE);
530              // get proxy 2 address and add it
531              this->networkMonitor->addNode(it->second.handshake->getProxy2Address(), NET_PROXY_SERVER_ACTIVE);
532
533              // now check if the server accepted the connection
534              if( it->second.handshake->redirect() )
535              {
536                this->bRedirect = true;
537              }
538
539              // create the new network game manager and init it
540              this->networkGameManager = NetworkGameManager::getInstance();
541              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
542              // init the new message manager
543              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
544            }
545
546            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
547            it->second.handshake->del();
548
549          }
550          else
551          {
552            // handshake finished registring new player
553            if ( it->second.handshake->canDel() )
554            {
555
556              if ( this->pInfo->isMasterServer() )
557              {
558                it->second.nodeType = it->second.handshake->getRemoteNodeType();
559                it->second.ip = it->second.socket->getRemoteAddress();
560
561                this->networkMonitor->addNode(&it->second);
562
563                this->handleNewClient( it->second.userId );
564
565                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
566                {
567                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
568                }
569              }
570              else if ( this->pInfo->isProxyServer() )
571              {
572                it->second.nodeType = it->second.handshake->getRemoteNodeType();
573                it->second.ip = it->second.socket->getRemoteAddress();
574
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
585              PRINT(0)("handshake finished delete it\n");
586              delete it->second.handshake;
587              it->second.handshake = NULL;
588            }
589          }
590
591        }
592        else
593        {
594          PRINT(1)("handshake failed!\n");
595          it->second.socket->disconnectServer();
596        }
597      }
598    }
599  }
600}
601
602
603/**
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{
608  this->bRedirect = false;
609  PeerInfo* pInfo = &this->peers[userId];
610
611  PRINTF(0)("===============================================\n");
612  PRINTF(0)("Client is redirected to the other proxy servers\n");
613  PRINTF(0)("  user id: %i\n", userId);
614  PRINTF(0)("  connecting to: %s\n", this->networkMonitor->getFirstChoiceProxy()->ip.ipString().c_str());
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;
620
621  // temp save the ip address here
622  IP proxyIP = pInfo->handshake->getProxy1Address();
623
624  // disconnect from the current server and reconnect to proxy server
625//   pInfo->socket->reconnectToServer( proxyIP.ipString(), proxyIP.port());
626  this->handleDisconnect( userId);
627  this->connectToProxyServer(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  PRINTF(0)("nodes: %i\n", peers.size());
664  peers.erase( userId);
665  PRINTF(0)("nodes: %i\n", peers.size());
666
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;
674}
675
676
677
678/**
679 * handle upstream network traffic
680 * @param tick: seconds elapsed since last update
681 */
682void NetworkStream::handleUpstream( int tick )
683{
684  int offset;
685  int n;
686
687  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
688  {
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)
692    if ( !peer->second.socket )
693      continue;
694
695    // header informations: current state
696    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
697    assert( n == INTSIZE );
698    offset += n;
699
700    // header informations: last acked state
701    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
702    assert( n == INTSIZE );
703    offset += n;
704
705    // header informations: last recved state
706    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
707    assert( n == INTSIZE );
708    offset += n;
709
710    // now write all synchronizeables in the packet
711    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
712    {
713
714      int oldOffset = offset;
715      Synchronizeable & sync = **it;
716
717
718      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
719      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
720        continue;
721
722      // if handshake not finished only sync handshake
723      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
724        continue;
725
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 )
728        continue;
729
730      /* list of synchronizeables that will never be synchronized over the network: */
731      // do not sync null parent
732      if ( sync.getLeafClassID() == CL_NULL_PARENT )
733        continue;
734
735
736      assert( sync.getLeafClassID() != 0);
737
738      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
739
740      // server fakes uniqueid == 0 for handshake
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
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 );
746
747
748      assert( n == INTSIZE );
749      offset += n;
750
751      // make space for packet size
752      offset += INTSIZE;
753
754      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
755      offset += n;
756
757      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
758
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
774
775
776
777    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
778    {
779      Synchronizeable & sync = **it;
780
781      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
782        continue;
783
784      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
785    }
786
787
788    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
789
790    // now compress the data with the zip library
791    int compLength = 0;
792    if ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer())
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 );
796
797    if ( compLength <= 0 )
798    {
799      PRINTF(1)("compression failed!\n");
800      continue;
801    }
802
803    assert( peer->second.socket->writePacket( compBuf, compLength ) );
804
805    if ( this->remainingBytesToWriteToDict > 0 )
806      writeToNewDict( buf, offset, true );
807
808    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
809    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
810
811  }
812}
813
814/**
815 * handle downstream network traffic
816 */
817void NetworkStream::handleDownstream( int tick )
818{
819  int offset = 0;
820
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;
829
830  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
831  {
832
833    if ( !peer->second.socket )
834      continue;
835
836    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
837    {
838      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
839
840      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
841
842      if ( packetLength < 4*INTSIZE )
843      {
844        if ( packetLength != 0 )
845          PRINTF(1)("got too small packet: %d\n", packetLength);
846        continue;
847      }
848
849      if ( this->remainingBytesToWriteToDict > 0 )
850        writeToNewDict( buf, packetLength, false );
851
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;
857
858      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
859
860
861      //if this is an old state drop it
862      if ( state <= peer->second.lastRecvedState )
863        continue;
864
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      }
871
872      while ( offset + 2 * INTSIZE < length )
873      {
874        assert( offset > 0 );
875        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
876        offset += INTSIZE;
877
878        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
879        offset += INTSIZE;
880
881        assert( syncDataLength > 0 );
882        assert( syncDataLength < 10000 );
883
884        Synchronizeable * sync = NULL;
885
886        // look for the synchronizeable in question
887        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
888        {
889          // client thinks his handshake has id 0!!!!!
890          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
891          {
892            sync = *it;
893            break;
894          }
895        }
896
897        // this synchronizeable does not yet exist! create it
898        if ( sync == NULL )
899        {
900          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
901
902          // if it is an old synchronizeable already removed, ignore it
903          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
904          {
905            offset += syncDataLength;
906            continue;
907          }
908
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() )
911          {
912            offset += syncDataLength;
913            continue;
914          }
915
916          int leafClassId;
917          if ( INTSIZE > length - offset )
918          {
919            offset += syncDataLength;
920            continue;
921          }
922
923          Converter::byteArrayToInt( buf + offset, &leafClassId );
924
925          assert( leafClassId != 0 );
926
927
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          {
933            PRINTF(1)("Don't create Object with ID %x, ignored!\n", (int)leafClassId);
934            offset += syncDataLength;
935            continue;
936          }
937          else
938            b = Factory::fabricate( (ClassID)leafClassId );
939
940          if ( !b )
941          {
942            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
943            offset += syncDataLength;
944            continue;
945          }
946
947          if ( b->isA(CL_SYNCHRONIZEABLE) )
948          {
949            sync = dynamic_cast<Synchronizeable*>(b);
950            sync->setUniqueID( uniqueId );
951            sync->setSynchronized(true);
952
953            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassCName(), sync->getUniqueID());
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        }
963
964
965        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
966        offset += n;
967
968      }
969
970      if ( offset != length )
971      {
972        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
973        peer->second.socket->disconnectServer();
974      }
975
976
977      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
978      {
979        Synchronizeable & sync = **it;
980
981        if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
982          continue;
983
984        sync.handleRecvState( peer->second.userId, state, fromState );
985      }
986
987      assert( peer->second.lastAckedState <= ackedState );
988      peer->second.lastAckedState = ackedState;
989
990      assert( peer->second.lastRecvedState < state );
991      peer->second.lastRecvedState = state;
992
993    }
994
995  }
996
997}
998
999/**
1000 * is executed when a handshake has finished
1001 */
1002void NetworkStream::handleNewClient( int userId )
1003{
1004  // init and assign the message manager
1005  MessageManager::getInstance()->initUser( userId );
1006  // do all game relevant stuff here
1007  networkGameManager->signalNewPlayer( userId );
1008}
1009
1010
1011/**
1012 * removes old items from oldSynchronizeables
1013 */
1014void NetworkStream::cleanUpOldSyncList( )
1015{
1016  int now = SDL_GetTicks();
1017
1018  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
1019  {
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++;
1028  }
1029}
1030
1031/**
1032 * writes data to DATA/dicts/newdict
1033 * @param data pointer to data
1034 * @param length length
1035 */
1036void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
1037{
1038  if ( remainingBytesToWriteToDict <= 0 )
1039    return;
1040
1041  if ( length > remainingBytesToWriteToDict )
1042    length = remainingBytesToWriteToDict;
1043
1044  std::string fileName = ResourceManager::getInstance()->getDataDir();
1045  fileName += "/dicts/newdict";
1046
1047  if ( upstream )
1048    fileName += "_upstream";
1049  else
1050    fileName += "_downstream";
1051
1052  FILE * f = fopen( fileName.c_str(), "a" );
1053
1054  if ( !f )
1055  {
1056    PRINTF(2)("could not open %s\n", fileName.c_str());
1057    remainingBytesToWriteToDict = 0;
1058    return;
1059  }
1060
1061  if ( fwrite( data, 1, length, f ) != length )
1062  {
1063    PRINTF(2)("could not write to file\n");
1064    fclose( f );
1065    return;
1066  }
1067
1068  fclose( f );
1069
1070  remainingBytesToWriteToDict -= length;
1071}
1072
1073
1074
1075
1076
1077
Note: See TracBrowser for help on using the repository browser.