Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7613 was 7613, checked in by rennerc, 18 years ago

subprojects/network can test handshake now

File size: 18.4 KB
RevLine 
[5566]1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11### File Specific:
[5601]12   main-programmer: claudio
[5800]13   co-programmer:
[5566]14*/
15
16
17/* this is for debug output. It just says, that all calls to PRINT() belong to the DEBUG_MODULE_NETWORK module
18   For more information refere to https://www.orxonox.net/cgi-bin/trac.cgi/wiki/DebugOutput
19*/
20#define DEBUG_MODULE_NETWORK
21
[5747]22
[5647]23#include "base_object.h"
[5731]24#include "network_protocol.h"
[7565]25#include "udp_socket.h"
26#include "udp_server_socket.h"
[5647]27#include "connection_monitor.h"
28#include "synchronizeable.h"
[6341]29#include "network_game_manager.h"
[6959]30#include "shared_network_data.h"
[6341]31
[7565]32#include "lib/util/loading/factory.h"
33
[5649]34#include "debug.h"
[6139]35#include "class_list.h"
[6144]36#include <algorithm>
[5647]37
[5566]38/* include your own header */
39#include "network_stream.h"
40
[5595]41/* probably unnecessary */
[5594]42using namespace std;
43
[5595]44
[5747]45#define PACKAGE_SIZE  256
[5647]46
[5747]47
[5800]48NetworkStream::NetworkStream()
[5996]49    : DataStream()
[5647]50{
51  this->init();
[5648]52  /* initialize the references */
[5996]53  this->type = NET_CLIENT;
[5741]54  this->networkProtocol = new NetworkProtocol();
[5648]55  this->connectionMonitor = new ConnectionMonitor();
[5647]56}
57
[6695]58
[7540]59NetworkStream::NetworkStream( std::string host, int port )
[5996]60{
[6139]61  this->type = NET_CLIENT;
[5996]62  this->init();
[7565]63  this->peers[0].socket = new UdpSocket( host, port );
[5996]64  this->networkProtocol = new NetworkProtocol();
65  this->connectionMonitor = new ConnectionMonitor();
66}
67
68
[7565]69NetworkStream::NetworkStream( int port )
[5647]70{
[6139]71  this->type = NET_SERVER;
[5647]72  this->init();
[7565]73  this->serverSocket = new UdpServerSocket(port);
[5741]74  this->networkProtocol = new NetworkProtocol();
75  this->connectionMonitor = new ConnectionMonitor();
[5996]76  this->bActive = true;
[5649]77}
78
79
[5647]80void NetworkStream::init()
81{
82  /* set the class id for the base object */
83  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
[5996]84  this->bActive = false;
[6139]85  this->serverSocket = NULL;
[6341]86  this->networkGameManager = NULL;
[6139]87  myHostId = 0;
[7565]88  currentState = 0;
[5594]89}
90
[5647]91
[5566]92NetworkStream::~NetworkStream()
[5598]93{
[6139]94  if ( this->serverSocket )
95  {
96    serverSocket->close();
97    delete serverSocket;
98  }
[5723]99
[7565]100  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
[6139]101  {
[7565]102    if ( i->second.socket )
[6139]103    {
[7565]104      i->second.socket->disconnectServer();
105      delete i->second.socket;
106      i->second.socket = NULL;
[6139]107    }
[7565]108   
109    if ( i->second.handshake )
[6139]110    {
[7565]111      delete i->second.handshake;
112      i->second.handshake = NULL;
[6139]113    }
114  }
[7565]115 
116  if ( serverSocket )
117  {
118    delete serverSocket;
119    serverSocket = NULL;
120  }
[5805]121
[5996]122  delete connectionMonitor;
123  delete networkProtocol;
[5598]124}
125
[5996]126
[6695]127void NetworkStream::createNetworkGameManager()
128{
129  this->networkGameManager = NetworkGameManager::getInstance();
130  // setUniqueID( maxCon+2 ) because we need one id for every handshake
131  // and one for handshake to reject client maxCon+1
[7575]132  this->networkGameManager->setUniqueID( MAX_CONNECTIONS + 2 );
[7565]133
[6695]134}
135
136
137void NetworkStream::startHandshake()
138{
139  Handshake* hs = new Handshake(false);
140  hs->setUniqueID( 0 );
[7565]141  assert( peers[0].handshake == NULL );
142  peers[0].handshake = hs;
[7575]143//   peers[0].handshake->setSynchronized( true );
[6695]144  //this->connectSynchronizeable(*hs);
[7591]145  //this->connectSynchronizeable(*hs);
[7575]146  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getName());
[6695]147}
148
149
[5996]150void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
151{
[6139]152  this->synchronizeables.push_back(&sync);
153  sync.setNetworkStream( this );
154
[7565]155  this->bActive = true;
[5996]156}
157
[6695]158
[6139]159void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
160{
[6144]161  // removing the Synchronizeable from the List.
162  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
163  if (disconnectSynchro != this->synchronizeables.end())
164    this->synchronizeables.erase(disconnectSynchro);
[7602]165 
166  //TODO set timestamp
167  oldSynchronizeables[sync.getUniqueID()] = 0;
[6139]168}
169
170
[5604]171void NetworkStream::processData()
172{
[7565]173  currentState++;
174 
[6139]175  if ( this->type == NET_SERVER )
[7571]176  {
177    if ( serverSocket )
178      serverSocket->update();
179   
[6139]180    this->updateConnectionList();
[7571]181  }
[6139]182  else
183  {
[7565]184    if ( peers[0].socket && !peers[0].socket->isOk() )
[6139]185    {
186      PRINTF(1)("lost connection to server\n");
[5741]187
[7565]188      peers[0].socket->disconnectServer();
189      delete peers[0].socket;
190      peers[0].socket = NULL;
[6498]191
[7565]192      if ( peers[0].handshake )
193        delete peers[0].handshake;
194      peers[0].handshake = NULL;
[6139]195    }
196  }
197
[7575]198  handleHandshakes();
199  handleUpstream();
200  handleDownstream();
[6341]201
[6498]202
[6341]203
[5650]204  /* DOWNSTREAM */
[7565]205#if 0
[5800]206
[6695]207
[6139]208  int dataLength;
209  int reciever;
210  Header header;
[6959]211  int counter;
212
[6139]213  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
[5996]214  {
[6959]215    counter = 0;
216
[6695]217    if ( (*it)!=NULL && (*it)->beSynchronized() /*&& (*it)->getOwner() == myHostId*/ )
[6139]218    {
219      do {
[6959]220        counter++;
221
[6139]222        reciever = 0;
[7444]223#warning fix this
224dataLength = 0;
225//TODO fix
226        //dataLength = (*it)->readBytes(downBuffer, DATA_STREAM_BUFFER_SIZE, &reciever);
[5730]227
[6139]228        if ( dataLength<=0 ){
229          reciever = 0;
230          continue;
231        }
232
233        dataLength = networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE, static_cast<const Synchronizeable&>(*(*it)));
234
235        Header* header = (Header*)downBuffer;
[6341]236        if ( header->synchronizeableID < this->maxConnections+2 )
237        {
238          //if ( !isServer() ) PRINTF(0)("RESET UNIQUEID FROM %d TO 0 maxCon=%d\n", header->synchronizeableID, this->maxConnections);
[6139]239          header->synchronizeableID = 0;
[6341]240        }
241        else
242        {
243          //if ( !isServer() ) PRINTF(0)("UNIQUEID=%d\n", header->synchronizeableID);
244        }
[6139]245
246        if ( dataLength<=0 )
247          continue;
248
249        if ( reciever!=0 )
250        {
[6868]251          if ( reciever < 0)
[6139]252          {
[6868]253            for ( int i = 0; i<networkSockets.size(); i++)
254            {
[6959]255              if ( i!=abs(reciever) && networkSockets[i] != NULL )
[6868]256              {
[6959]257                PRINTF(0)("write %d bytes to socket %d uniqueid %d reciever %d\n", dataLength, i, (*it)->getUniqueID(), reciever);
[6868]258                networkSockets[i]->writePacket(downBuffer, dataLength);
259              }
260            }
[6139]261          }
262          else
263          {
[6868]264            if ( networkSockets[reciever] != NULL )
265            {
266              PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
267              networkSockets[reciever]->writePacket(downBuffer, dataLength);
268            }
269            else
270            {
271              PRINTF(1)("networkSockets[reciever] == NULL\n");
272            }
[6139]273          }
274        }
275        else
276        {
277          for ( int i = 0; i<networkSockets.size(); i++)
278          {
279            if ( networkSockets[i] != NULL )
280            {
[6634]281              PRINTF(5)("write %d bytes to socket %d\n", dataLength, i);
[6139]282              networkSockets[i]->writePacket(downBuffer, dataLength);
283            }
284          }
285        }
286
287      } while( reciever!=0 );
288    }
[5996]289  }
[5741]290
291  /* UPSTREAM */
[5809]292
[6139]293  for ( int i = 0; i<networkSockets.size(); i++)
[5802]294  {
[6139]295    if ( networkSockets[i] )
[5810]296    {
[6139]297      do {
298        dataLength = networkSockets[i]->readPacket(upBuffer, DATA_STREAM_BUFFER_SIZE);
[5730]299
[6139]300        if ( dataLength<=0 )
301          continue;
302
303        header = networkProtocol->extractHeader(upBuffer, dataLength);
304        dataLength -= sizeof(header);
305
[6498]306        PRINTF(5)("read %d bytes from socket uniqueID = %d\n", dataLength, header.synchronizeableID);
[6341]307
[6139]308        if ( dataLength != header.length )
309        {
310          PRINTF(1)("packetsize in header and real packetsize do not match! %d:%d\n", dataLength, header.length);
311          continue;
312        }
313
314        if ( header.synchronizeableID == 0 )
315        {
316          header.synchronizeableID = i;
317        }
318
319        for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
320        {
[7444]321#warning fix this
[7565]322
[6139]323          if ( *it && (*it)->getUniqueID()==header.synchronizeableID )
[6341]324          {
325            if ( (*it)->writeBytes(upBuffer+sizeof(header), dataLength, i) != header.length )
326            {
[6634]327              PRINTF(1)("%s did not read all the data id = %d!\n", (*it)->getClassName(), (*it)->getUniqueID());
[6341]328              break;
329            }
330            continue;
331          }
[7565]332
[6139]333        }
334
335      } while ( dataLength>0 );
[5810]336    }
[7565]337
[5810]338  }
[7565]339#endif
[6139]340}
341
342void NetworkStream::updateConnectionList( )
343{
344  //check for new connections
345
346  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
347
348  if ( tempNetworkSocket )
[5810]349  {
[6139]350    int clientId;
351    if ( freeSocketSlots.size() >0 )
[5810]352    {
[6139]353      clientId = freeSocketSlots.back();
354      freeSocketSlots.pop_back();
[7565]355      peers[clientId].socket = tempNetworkSocket;
356      peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
357      peers[clientId].handshake->setUniqueID(clientId);
358      peers[clientId].userId = clientId;
[6139]359    } else
360    {
[7575]361      clientId = 1;
[7565]362     
363      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
364        if ( it->first >= clientId )
365          clientId = it->first + 1;
366     
367      peers[clientId].socket = tempNetworkSocket;
368      peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID());
369      peers[clientId].handshake->setUniqueID(clientId);
370      peers[clientId].userId = clientId;
[7613]371     
372      PRINTF(0)("num sync: %d\n", synchronizeables.size());
[6139]373    }
[5730]374
[7575]375    if ( clientId > MAX_CONNECTIONS )
[6139]376    {
[7565]377      peers[clientId].handshake->doReject( "too many connections" );
[6139]378      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
[5810]379    }
[6139]380    else
381
382    PRINTF(0)("New Client: %d\n", clientId);
383
[6695]384    //this->connectSynchronizeable(*handshakes[clientId]);
[5802]385  }
[5800]386
[5809]387
[6139]388  //check if connections are ok else remove them
[7565]389  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
[6139]390  {
[7565]391    if ( it->second.socket && !it->second.socket->isOk() )
[6139]392    {
[7565]393      PRINTF(0)("Client is gone: %d\n", it->second.userId);
[6139]394
[7565]395      it->second.socket->disconnectServer();
396      delete it->second.socket;
397      it->second.socket = NULL;
[6498]398
[7565]399      if ( it->second.handshake )
400        delete it->second.handshake;
401      it->second.handshake = NULL;
[6139]402
[6737]403
[7565]404      NetworkGameManager::getInstance()->signalLeftPlayer(it->second.userId);
[6737]405
[7565]406      freeSocketSlots.push_back( it->second.userId );
407
[6139]408    }
409  }
410
411
[5604]412}
[6139]413
[6695]414void NetworkStream::debug()
415{
416  if( this->isServer())
417    PRINT(0)(" Host ist Server with ID: %i\n", this->myHostId);
418  else
419    PRINT(0)(" Host ist Client with ID: %i\n", this->myHostId);
420
421  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
422  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
423  {
424    if( (*it)->beSynchronized() == true)
425      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
426               (*it)->getUniqueID(), (*it)->beSynchronized());
427  }
[7575]428  PRINT(0)(" Maximal Connections: %i\n", MAX_CONNECTIONS );
[6695]429
430}
431
432
433int NetworkStream::getSyncCount()
434{
435  int n = 0;
436  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
437    if( (*it)->beSynchronized() == true)
438      ++n;
439
440  //return synchronizeables.size();
441  return n;
442}
443
[7565]444/**
445 * check if handshakes completed
446 */
447void NetworkStream::handleHandshakes( )
448{
449  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
450  {
451    if ( it->second.handshake )
452    {
453      if ( it->second.handshake->completed() )
454      {
455        if ( it->second.handshake->ok() )
456        {
457          if ( type != NET_SERVER )
458          {
459            SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
460            myHostId = SharedNetworkData::getInstance()->getHostID();
[6695]461
[7565]462            this->networkGameManager = NetworkGameManager::getInstance();
463            this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
464          }
[6695]465
[7565]466          PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
[7602]467          assert(false);
[6695]468
[7565]469          delete it->second.handshake;
470          it->second.handshake = NULL;
471        }
472        else
473        {
474          PRINT(1)("handshake failed!\n");
475          it->second.socket->disconnectServer();
[7602]476          assert(false);
[7565]477        }
478      }
479    }
480  }
481}
[6695]482
[7565]483/**
484 * handle upstream network traffic
485 */
486void NetworkStream::handleUpstream( )
487{
488  byte buf[UDP_PACKET_SIZE];
489  int offset;
490  int n;
491 
492  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
493  {
494    offset = INTSIZE; //make already space for length
495   
[7575]496    if ( !peer->second.socket )
[7565]497      continue;
498   
499    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
500    assert( n == INTSIZE );
501    offset += n;
502   
503    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
504    assert( n == INTSIZE );
505    offset += n;
506   
507    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
508    assert( n == INTSIZE );
509    offset += n;
510   
511    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
512    {
513      Synchronizeable & sync = **it;
[7591]514     
[7575]515      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
516        continue;
517
518      //if handshake not finished only sync handshake
519      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
520        continue;
[7591]521     
522      if ( isServer() && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
523        continue;
[7575]524
[7565]525      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
526     
[7575]527      //server fakes uniqueid=0 for handshake
528      if ( this->isServer() && sync.getUniqueID() < MAX_CONNECTIONS - 1 )
529        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
530      else
531        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
[7565]532      assert( n == INTSIZE );
533      offset += n;
534     
[7602]535      //make space for size
536      offset += INTSIZE;
537     
538      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, 0 );
539      offset += n;
540     
541      assert( Converter::intToByteArray( n, buf + offset - n, INTSIZE ) == INTSIZE );
[7565]542    }
543   
544    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
545   
546    assert( peer->second.socket->writePacket( buf, offset ) );
[7602]547    PRINTF(0)("send packet: %d userId = %d %x %d\n", offset, peer->second.userId, peer->second.handshake->getLeafClassID(), peer->second.handshake->getUniqueID());
548    assert( peer->second.handshake->getLeafClassID() == CL_HANDSHAKE );
[7565]549  }
550}
551
552/**
553 * handle downstream network traffic
554 */
555void NetworkStream::handleDownstream( )
556{
557  byte buf[UDP_PACKET_SIZE];
558  int offset = 0;
559 
560  int length = 0;
561  int packetLength = 0;
562  int uniqueId = 0;
563  int state = 0;
564  int ackedState = 0;
565  int fromState = 0;
[7602]566  int syncDataLength = 0;
[7565]567 
568  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
569  {
[7575]570    if ( !peer->second.socket )
571      continue;
572
[7565]573    packetLength = peer->second.socket->readPacket( buf, UDP_PACKET_SIZE );
[7575]574
575    if ( packetLength < 4*INTSIZE )
576    {
577      if ( packetLength != 0 )
578        PRINTF(1)("got too small packet: %d\n", packetLength);
579      continue;
580    }
[7565]581   
582    assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
583    assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
584    assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
585    assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
[7578]586    offset = 4*INTSIZE;
[7575]587
588    PRINTF(0)("got packet: %d, %d\n", length, packetLength);
[7565]589   
590    //if this is an old state drop it
591    if ( state <= peer->second.lastRecvedState )
592      continue;
593   
594    if ( packetLength != length )
595    {
596      PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
597      peer->second.socket->disconnectServer();
598      continue;
599    }
600   
601    while ( offset < length )
602    {
603      assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
604      offset += INTSIZE;
605     
[7602]606      assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
607      offset += INTSIZE;
608     
[7565]609      Synchronizeable * sync = NULL;
610     
611      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
[7575]612      { 
613        //                                        client thinks his handshake has id 0!!!!!
614        if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
[7565]615        {
616          sync = *it;
617          break;
618        }
619      }
620     
621      if ( sync == NULL )
622      {
[7602]623        if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
624        {
625          offset += syncDataLength;
626          continue;
627        }
628       
[7565]629        //TODO dont accept new object from all peers (probably only servers)
630        int leafClassId;
631        if ( INTSIZE > length - offset )
632          break;
633       
634        Converter::byteArrayToInt( buf + offset, &leafClassId );
635       
636        BaseObject * b;
637        /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
638        /* Exception 1: NullParent */
639        if( leafClassId == CL_NULL_PARENT)
640        {
641          PRINTF(1)("Can not create Class with ID %x!", (int)leafClassId);
642          break;
643        }
644        else
645          b = Factory::fabricate( (ClassID)leafClassId );
646
647        if ( !b )
648        {
649          PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
650          break;
651        }
652       
653        if ( b->isA(CL_SYNCHRONIZEABLE) )
654        {
655          sync = dynamic_cast<Synchronizeable*>(b);
656          sync->setUniqueID( uniqueId );
657          sync->setSynchronized(true);
658 
659          PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
660        }
661        else
662        {
663          PRINTF(1)("Class with ID %x is not a synchronizeable!", (int)leafClassId);
664          delete b;
665          break;
666        }
667      }
668      offset += sync->setStateDiff( peer->second.userId, buf+offset, length-offset, state, fromState );
669    }
670   
671    if ( offset != length )
672    {
673      peer->second.socket->disconnectServer();
674    }
675   
676    peer->second.lastAckedState = ackedState;
677  }
678}
679
680
681
682
683
684
Note: See TracBrowser for help on using the repository browser.