Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

using the new id scheme

File size: 31.5 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 = NET_ID_MASTER_SERVER;
187  // this create the new node in the peers map
188  this->peers[node].socket = new UdpSocket( host, port );
189  this->peers[node].userId = NET_ID_MASTER_SERVER;
190
191  this->peers[node].nodeType = NET_MASTER_SERVER;
192  this->peers[node].connectionMonitor = new ConnectionMonitor( NET_ID_MASTER_SERVER );
193  this->peers[node].ip = this->peers[node].socket->getRemoteAddress();
194}
195
196
197/**
198 * establish a connection to a remote proxy server
199 * @param host: host name
200 * @param port: the port number
201 */
202void NetworkStream::connectToProxyServer(int proxyId,std::string host, int port)
203{
204  PRINTF(0)("connect to proxy %s, this is proxyId %i\n", host.c_str(), proxyId);
205
206  // this creates the new proxyId in the peers map
207  this->peers[proxyId].socket = new UdpSocket( host, port );
208  this->peers[proxyId].userId = proxyId;
209
210  this->peers[proxyId].nodeType = NET_PROXY_SERVER_ACTIVE;
211  this->peers[proxyId].connectionMonitor = new ConnectionMonitor( proxyId );
212  this->peers[proxyId].ip = this->peers[proxyId].socket->getRemoteAddress();
213}
214
215
216/**
217 * create a server
218 * @param port: interface port for all clients
219 */
220void NetworkStream::createServer(int port)
221{
222  this->serverSocket = new UdpServerSocket(port);
223}
224
225
226/**
227 * creates a new instance of the network game manager
228 */
229void NetworkStream::createNetworkGameManager()
230{
231  this->networkGameManager = NetworkGameManager::getInstance();
232
233  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
234  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
235}
236
237
238/**
239 * starts the network handshake
240 * handsakes are always initialized from the client side first. this starts the handshake and therefore is only
241 * executed as client
242 * @param userId: start handshake for this user id (optional, default == 0)
243 */
244void NetworkStream::startHandshake(int userId)
245{
246  Handshake* hs = new Handshake(this->pInfo->nodeType);
247  // fake the unique id
248  hs->setUniqueID( NET_UID_HANDSHAKE );
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#warning make this more modular: every proxy/master server connection should be watched for termination
326    if ( !peers.empty() && peers[NET_ID_MASTER_SERVER].socket &&
327          ( !peers[NET_ID_MASTER_SERVER].socket->isOk() ||
328          peers[NET_ID_MASTER_SERVER].connectionMonitor->hasTimedOut() ) )
329    {
330      this->handleDisconnect( NET_ID_MASTER_SERVER);
331      PRINTF(1)("lost connection to server\n");
332    }
333    // check if there is a redirection command
334    if( this->bRedirect)
335    {
336      this->handleReconnect( NET_ID_MASTER_SERVER);
337    }
338  }
339
340  this->cleanUpOldSyncList();
341  this->handleHandshakes();
342
343  // update the network monitor
344  this->networkMonitor->process();
345
346  // order of up/downstream is important!!!!
347  // don't change it
348  this->handleDownstream( tick );
349  this->handleUpstream( tick );
350}
351
352
353/**
354 * if we are a NET_MASTER_SERVER or NET_PROXY_SERVER_ACTIVE update the connection list to accept new
355 * connections (clients) also start the handsake for the new clients
356 */
357void NetworkStream::updateConnectionList( )
358{
359  //check for new connections
360
361  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
362
363  // we got new network node
364  if ( tempNetworkSocket )
365  {
366    int clientId;
367    // if there is a list of free client id slots, take these
368    if ( freeSocketSlots.size() > 0 )
369    {
370      clientId = freeSocketSlots.back();
371      freeSocketSlots.pop_back();
372    }
373    else
374    {
375      clientId = 1;
376
377      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
378        if ( it->first >= clientId )
379          clientId = it->first + 1;
380    }
381    // this creates a new entry in the peers list
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());
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  this->handleDisconnect( userId);
626  this->connectToProxyServer(NET_ID_PROXY_SERVER_01, proxyIP.ipString(), 9999);
627  #warning the ports are not yet integrated correctly in the ip class
628
629  // and restart the handshake
630  this->startHandshake( userId);
631}
632
633
634/**
635 * handles the disconnect event
636 * @param userId id of the user to remove
637 */
638void NetworkStream::handleDisconnect( int userId )
639{
640  peers[userId].socket->disconnectServer();
641  delete peers[userId].socket;
642  peers[userId].socket = NULL;
643
644  if ( peers[userId].handshake )
645    delete peers[userId].handshake;
646  peers[userId].handshake = NULL;
647
648  if ( peers[userId].connectionMonitor )
649    delete peers[userId].connectionMonitor;
650  peers[userId].connectionMonitor = NULL;
651
652
653  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
654    (*it2)->cleanUpUser( userId );
655  }
656
657  if( SharedNetworkData::getInstance()->isMasterServer())
658    NetworkGameManager::getInstance()->signalLeftPlayer(userId);
659
660  this->freeSocketSlots.push_back( userId );
661
662  peers.erase( userId);
663}
664
665
666
667/**
668 * handle upstream network traffic
669 * @param tick: seconds elapsed since last update
670 */
671void NetworkStream::handleUpstream( int tick )
672{
673  int offset;
674  int n;
675
676  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
677  {
678    offset = INTSIZE; // reserve enough space for the packet length
679
680    // continue with the next peer if this peer has no socket assigned (therefore no network)
681    if ( !peer->second.socket )
682      continue;
683
684    // header informations: current state
685    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
686    assert( n == INTSIZE );
687    offset += n;
688
689    // header informations: last acked state
690    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
691    assert( n == INTSIZE );
692    offset += n;
693
694    // header informations: last recved state
695    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
696    assert( n == INTSIZE );
697    offset += n;
698
699    // now write all synchronizeables in the packet
700    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
701    {
702
703      int oldOffset = offset;
704      Synchronizeable & sync = **it;
705
706
707      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
708      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
709        continue;
710
711      // if handshake not finished only sync handshake
712      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
713        continue;
714
715      // if we are a server (both master and proxy servers) and this is not our handshake
716      if ( ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer() ) && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
717        continue;
718
719      /* list of synchronizeables that will never be synchronized over the network: */
720      // do not sync null parent
721      if ( sync.getLeafClassID() == CL_NULL_PARENT )
722        continue;
723
724
725      assert( sync.getLeafClassID() != 0);
726
727      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
728
729      // server fakes uniqueid == 0 for handshake
730      if ( ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer() ) &&
731             sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1) // plus one to handle one client more than the max to redirect it
732        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
733      else
734        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
735
736
737      assert( n == INTSIZE );
738      offset += n;
739
740      // make space for packet size
741      offset += INTSIZE;
742
743      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
744      offset += n;
745
746      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
747
748      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
749      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
750      bool allZero = true;
751      for ( int i = 0; i < n; i++ )
752      {
753         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
754           allZero = false;
755      }
756      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
757      // data that hast not changed
758      if ( allZero )
759      {
760        offset = oldOffset;
761      }
762    } // all synchronizeables written
763
764
765
766    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
767    {
768      Synchronizeable & sync = **it;
769
770      // again exclude all unwanted syncs
771      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED)
772        continue;
773
774      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
775    }
776
777
778    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
779
780    // now compress the data with the zip library
781    int compLength = 0;
782    if ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer())
783      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
784    else
785      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
786
787    if ( compLength <= 0 )
788    {
789      PRINTF(1)("compression failed!\n");
790      continue;
791    }
792
793    assert( peer->second.socket->writePacket( compBuf, compLength ) );
794
795    if ( this->remainingBytesToWriteToDict > 0 )
796      writeToNewDict( buf, offset, true );
797
798    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
799    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
800
801  }
802}
803
804/**
805 * handle downstream network traffic
806 */
807void NetworkStream::handleDownstream( int tick )
808{
809  int offset = 0;
810
811  int length = 0;
812  int packetLength = 0;
813  int compLength = 0;
814  int uniqueId = 0;
815  int state = 0;
816  int ackedState = 0;
817  int fromState = 0;
818  int syncDataLength = 0;
819
820  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
821  {
822
823    if ( !peer->second.socket )
824      continue;
825
826    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
827    {
828      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
829
830      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
831
832      if ( packetLength < 4*INTSIZE )
833      {
834        if ( packetLength != 0 )
835          PRINTF(1)("got too small packet: %d\n", packetLength);
836        continue;
837      }
838
839      if ( this->remainingBytesToWriteToDict > 0 )
840        writeToNewDict( buf, packetLength, false );
841
842      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
843      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
844      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
845      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
846      offset = 4*INTSIZE;
847
848      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
849
850
851      //if this is an old state drop it
852      if ( state <= peer->second.lastRecvedState )
853        continue;
854
855      if ( packetLength != length )
856      {
857        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
858        peer->second.socket->disconnectServer();
859        continue;
860      }
861
862      while ( offset + 2 * INTSIZE < length )
863      {
864        assert( offset > 0 );
865        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
866        offset += INTSIZE;
867
868        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
869        offset += INTSIZE;
870
871        assert( syncDataLength > 0 );
872        assert( syncDataLength < 10000 );
873
874        Synchronizeable * sync = NULL;
875
876        // look for the synchronizeable in question
877        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
878        {
879          // client thinks his handshake has id 0!!!!!
880          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
881          {
882            sync = *it;
883            break;
884          }
885        }
886
887        // this synchronizeable does not yet exist! create it
888        if ( sync == NULL )
889        {
890          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
891
892          // if it is an old synchronizeable already removed, ignore it
893          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
894          {
895            offset += syncDataLength;
896            continue;
897          }
898
899          // 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)
900          if ( peers[peer->second.userId].isClient() )
901          {
902            offset += syncDataLength;
903            continue;
904          }
905
906          int leafClassId;
907          if ( INTSIZE > length - offset )
908          {
909            offset += syncDataLength;
910            continue;
911          }
912
913          Converter::byteArrayToInt( buf + offset, &leafClassId );
914
915          assert( leafClassId != 0 );
916
917
918          BaseObject * b = NULL;
919          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
920          /* Exception 1: NullParent */
921          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
922          {
923            PRINTF(1)("Don't create Object with ID %x, ignored!\n", (int)leafClassId);
924            offset += syncDataLength;
925            continue;
926          }
927          else
928            b = Factory::fabricate( (ClassID)leafClassId );
929
930          if ( !b )
931          {
932            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
933            offset += syncDataLength;
934            continue;
935          }
936
937          if ( b->isA(CL_SYNCHRONIZEABLE) )
938          {
939            sync = dynamic_cast<Synchronizeable*>(b);
940            sync->setUniqueID( uniqueId );
941            sync->setSynchronized(true);
942
943            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassCName(), sync->getUniqueID());
944          }
945          else
946          {
947            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
948            delete b;
949            offset += syncDataLength;
950            continue;
951          }
952        }
953
954
955        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
956        offset += n;
957
958      }
959
960      if ( offset != length )
961      {
962        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
963        peer->second.socket->disconnectServer();
964      }
965
966
967      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
968      {
969        Synchronizeable & sync = **it;
970
971        if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
972          continue;
973
974        sync.handleRecvState( peer->second.userId, state, fromState );
975      }
976
977      assert( peer->second.lastAckedState <= ackedState );
978      peer->second.lastAckedState = ackedState;
979
980      assert( peer->second.lastRecvedState < state );
981      peer->second.lastRecvedState = state;
982
983    }
984
985  }
986
987}
988
989/**
990 * is executed when a handshake has finished
991 */
992void NetworkStream::handleNewClient( int userId )
993{
994  // init and assign the message manager
995  MessageManager::getInstance()->initUser( userId );
996  // do all game relevant stuff here
997  networkGameManager->signalNewPlayer( userId );
998}
999
1000
1001/**
1002 * removes old items from oldSynchronizeables
1003 */
1004void NetworkStream::cleanUpOldSyncList( )
1005{
1006  int now = SDL_GetTicks();
1007
1008  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
1009  {
1010    if ( it->second < now - 10*1000 )
1011    {
1012      std::map<int,int>::iterator delIt = it;
1013      it++;
1014      oldSynchronizeables.erase( delIt );
1015      continue;
1016    }
1017    it++;
1018  }
1019}
1020
1021/**
1022 * writes data to DATA/dicts/newdict
1023 * @param data pointer to data
1024 * @param length length
1025 */
1026void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
1027{
1028  if ( remainingBytesToWriteToDict <= 0 )
1029    return;
1030
1031  if ( length > remainingBytesToWriteToDict )
1032    length = remainingBytesToWriteToDict;
1033
1034  std::string fileName = ResourceManager::getInstance()->getDataDir();
1035  fileName += "/dicts/newdict";
1036
1037  if ( upstream )
1038    fileName += "_upstream";
1039  else
1040    fileName += "_downstream";
1041
1042  FILE * f = fopen( fileName.c_str(), "a" );
1043
1044  if ( !f )
1045  {
1046    PRINTF(2)("could not open %s\n", fileName.c_str());
1047    remainingBytesToWriteToDict = 0;
1048    return;
1049  }
1050
1051  if ( fwrite( data, 1, length, f ) != length )
1052  {
1053    PRINTF(2)("could not write to file\n");
1054    fclose( f );
1055    return;
1056  }
1057
1058  fclose( f );
1059
1060  remainingBytesToWriteToDict -= length;
1061}
1062
1063
1064
1065
1066
1067
Note: See TracBrowser for help on using the repository browser.