Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

redirection stuck

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