Main Page   Namespace List   Class Hierarchy   Alphabetical List   Compound List   File List   Compound Members   File Members   Related Pages  

NetworkLayer.cpp

Go to the documentation of this file.
00001 #include "headers.h"
00002 
00003 /*
00004  * \class NetworkLayer
00005  <pre>
00006      |->Create NetworkLayer
00007      |  |->Create LinkLayerInterface
00008      |  |  |->Create connection table
00009      |  |  |->start thread: listen
00010      |  |  |->start thread: peerConnect
00011      |  |  |->start thread: receivePacket
00012      |  |->register as packet handler for LLI
00013      |  |->Create VirtualCircuitTable
00014      |  |->Create PriorityPacketQueue
00015      |  |->Create LiveBroadcastTable
00016      |  |  |->start thread:onTick 
00017      |  |->start thread: processPackets
00018      |  |->start thread: pingNeighbors
00019  </pre>
00020  *
00021  * \todo Should there be a max LOGICAL connection limit?
00022  */
00023 
00027 NetworkLayer::NetworkLayer()
00028 {
00029     debug(DEBUG_ERR, "This constructor is no longer valid.");
00030     return;
00031     /*
00032     m_networkLayerListener = NULL;
00033 
00034         m_linkLayerInterface = new LinkLayerInterface();
00035         MEMCHECK(m_linkLayerInterface);
00036         debug(DEBUG_NL, "link layer interface created");
00037         // register our packet handler with the LLI
00038         m_linkLayerInterface->registerPacketHandler(this);
00039     //m_linkLayerInterface->registerNodeListener(this);
00040     m_linkLayerInterface->registerConnectionListener(this);
00041 
00042         m_virtualCircuitTable = new VirtualCircuitTable(GlobalObjects::instance()->getConfig()->getSelf()->getNode());
00043         MEMCHECK(m_virtualCircuitTable);
00044         debug(DEBUG_NL, "virtual circuit table created");
00045 
00046         m_packetQueue = new PriorityPacketQueue();
00047         MEMCHECK(m_packetQueue);
00048         debug(DEBUG_NL, "priority packet queue created");
00049 
00050         m_liveBroadcastTable = new LiveBroadcastTable();
00051         MEMCHECK(m_liveBroadcastTable);
00052         debug(DEBUG_NL, "live broadcast table created");
00053 
00054         pthread_attr_t attr;
00055         pthread_attr_init(&attr);
00056         //pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
00057         pthread_create(&m_processPacketThreadId, &attr, processPackets, this);
00058 
00059         pthread_attr_destroy(&attr);
00060     */
00061 } // NetworkLayer constructor
00062 
00063 
00067 NetworkLayer::NetworkLayer(NetworkLayerListener* networkLayerListener)
00068 {
00069     m_networkLayerListener = networkLayerListener;
00070 
00071         m_linkLayerInterface = new LinkLayerInterface();
00072         MEMCHECK(m_linkLayerInterface);
00073         debug(DEBUG_NL, "link layer interface created");
00074 
00075     // register our packet handler with the LLI
00076         m_linkLayerInterface->registerPacketHandler(this);
00077     //m_linkLayerInterface->registerConnectionListener(this);
00078     m_linkLayerInterface->registerListener(this);
00079 
00080         m_virtualCircuitTable = new VirtualCircuitTable(GlobalObjects::instance()->getConfig()->getSelf()->getNode());
00081         MEMCHECK(m_virtualCircuitTable);
00082         debug(DEBUG_NL, "virtual circuit table created");
00083 
00084         m_packetQueue = new PriorityPacketQueue();
00085         MEMCHECK(m_packetQueue);
00086         debug(DEBUG_NL, "priority packet queue created");
00087 
00088         m_liveBroadcastTable = new LiveBroadcastTable();
00089         MEMCHECK(m_liveBroadcastTable);
00090         debug(DEBUG_NL, "live broadcast table created");
00091 
00092     pthread_attr_t attr;
00093         pthread_attr_init(&attr);
00094         pthread_create(&m_processPacketThreadId, &attr, processPackets, this);
00095 
00096         pthread_create(&m_pingThreadId, &attr, pingThread, this);
00097 
00098         pthread_create(&m_discoveryThreadId, &attr, discoveryThread, this);
00099 
00100     pthread_attr_destroy(&attr);
00101 } // NetworkLayer constructor
00102 
00103 
00104 NetworkLayer::~NetworkLayer() 
00105 {
00106         void* statusp;
00107     
00108     // Cancel the ping thread
00109     pthread_cancel(m_pingThreadId);
00110     m_pingThreadInterrupt.signal();
00111     pthread_join(m_pingThreadId, &statusp);
00112     
00113     // Cancel the discovery thread
00114     pthread_cancel(m_discoveryThreadId);
00115     m_discoveryThreadInterrupt.signal();
00116     pthread_join(m_discoveryThreadId, &statusp);
00117 
00118     // Cencel the processPackets thread
00119     pthread_cancel(m_processPacketThreadId);
00120         delete m_virtualCircuitTable;
00121         m_virtualCircuitTable = NULL;
00122         delete m_linkLayerInterface;
00123         m_linkLayerInterface = NULL;
00124         delete m_packetQueue;
00125         m_packetQueue = NULL;
00126         delete m_liveBroadcastTable;
00127         m_liveBroadcastTable = NULL;
00128     pthread_join(m_processPacketThreadId, &statusp);
00129 } // NetworkLayer destructor
00130 
00131 
00136 LinkLayerInterface*
00137 NetworkLayer::getLli() {
00138     return m_linkLayerInterface;
00139 }
00140 
00141 
00146 LiveBroadcastTable*
00147 NetworkLayer::getLiveBroadcastTable() {
00148     return m_liveBroadcastTable;
00149 } // fn getLiveBroadcastTable
00150 
00151 
00162 int 
00163 NetworkLayer::makeVc(int connectionDescriptor)
00164 {
00165 
00166         int returnValue;
00167     VirtualCircuitTableEntry* vcte;
00168 
00169     if (!m_linkLayerInterface->isConnected()) {
00170         debug(DEBUG_NL, "Not connected to any nodes, cant create circuit");
00171         return NL_UNREACHABLE;
00172     }
00173 
00174         ConnectionPacket* connectPacket = new ConnectionPacket();
00175         MEMCHECK(connectPacket);
00176 
00177         // Add entry to virtual circuit table.
00178         //unsigned int originatingVcn = m_virtualCircuitTable->generateVcn();
00179     Node* randomNeighbor = m_linkLayerInterface->getRandomNeighbor();
00180     unsigned int nextHopVcn = m_networkLayerListener->generateConnectionDescriptor();
00181     connectPacket->setVcn(nextHopVcn);
00182 
00183         vcte = m_virtualCircuitTable->add(GlobalObjects::instance()->getConfig()->getSelf()->getNode(),
00184                 connectionDescriptor,
00185                 randomNeighbor,
00186                 nextHopVcn);
00187 
00188     vcte->setIsOriginatingPeer(true);
00189 
00190         // send packet to a random neighbor
00191         returnValue = m_linkLayerInterface->sendPacket(connectPacket, randomNeighbor);
00192 
00193         delete connectPacket;
00194 
00195     if (returnValue <= 0) {
00196         return NL_ERROR;
00197     }
00198 
00199         return NL_OK;
00200 } // fn makeVc
00201 
00202 
00207 void
00208 NetworkLayer::destroyVc(int vcn)
00209 {
00210     VirtualCircuitTableEntry* e = NULL;
00211         FinPacket* disconnect = new FinPacket();
00212         MEMCHECK(disconnect);
00213         disconnect->setVcn(vcn);
00214 
00215     forwardPacket(GlobalObjects::instance()->getConfig()->getSelf()->getNode(), disconnect);
00216         delete disconnect;
00217         disconnect = NULL;
00218 
00219     e = m_virtualCircuitTable->findBySrc(GlobalObjects::instance()->getConfig()->getSelf()->getNode(), vcn);
00220     if (e != NULL) {
00221         m_virtualCircuitTable->remove(e->getDestNode(), e->getDestVcn());
00222         m_virtualCircuitTable->remove(GlobalObjects::instance()->getConfig()->getSelf()->getNode(), vcn);
00223     }
00224     else {
00225         debug(DEBUG_NL, "ERROR: could not find VC entry");
00226     }
00227 } // fn destroyVc
00228 
00229 
00233 void 
00234 NetworkLayer::destroyVcsTo(Node* node) {
00235     VirtualCircuitTableEntry* e = NULL;
00236         FinPacket* disconnect = new FinPacket();
00237         MEMCHECK(disconnect);
00238 
00239     // While there are entries to this node in the VC table
00240     while ((e = m_virtualCircuitTable->findNode(node)) != NULL) {
00241         // Special case: we are OP or TP
00242         if (e->isOriginatingPeer() || e->isTerminatingPeer()) {
00243             // tell the service table that the connection is broken.
00244             m_networkLayerListener->handleNetworkEvent(BREAK_EVENT, e->getSrcVcn(), NULL);
00245             m_networkLayerListener->handleNetworkEvent(BREAK_EVENT, e->getDestVcn(), NULL);
00246 
00247             // They MUST be removed in this order!
00248             m_virtualCircuitTable->remove(e->getDestNode(), e->getDestVcn());
00249             m_virtualCircuitTable->remove(e->getSrcNode(), e->getSrcVcn());
00250 
00251             continue;
00252         }
00253         // we only care about sending the FIN packet along the circuit
00254         // going away from the dead node, not towards it (since it wont go anywhere)
00255         if (e->getSrcNode() == node) {
00256             // Set the VCN in the packet
00257             disconnect->setVcn(e->getDestVcn());
00258             // send it to next hop
00259             forwardPacket(node, disconnect);
00260             // remove the entry in the VC table
00261             m_virtualCircuitTable->remove(e->getSrcNode(), e->getSrcVcn());
00262         }
00263         else {
00264             // just remove the entry if it it going towards the node
00265             m_virtualCircuitTable->remove(e->getDestNode(), e->getDestVcn());
00266         }
00267     }    
00268     delete disconnect;
00269 } // fn destroyVcsTo
00270 
00271 
00275 bool 
00276 NetworkLayer::hasVc(int vcn)
00277 {
00278     VirtualCircuitTableEntry* e;
00279         e = m_virtualCircuitTable->findBySrc(GlobalObjects::instance()->getConfig()->getSelf()->getNode(), vcn);
00280         return (e != NULL);
00281 } // fn hasVc
00282 
00283 
00291 int
00292 NetworkLayer::isThisPacketForMe(Node* fromNode, NpPacket* packet) {
00293     VirtualCircuitTableEntry* e = NULL;
00294     if ((e = m_virtualCircuitTable->findBySrc(fromNode, packet->getVcn())) != NULL) {
00295         if (e->getDestNode()->equals(GlobalObjects::instance()->getConfig()->getSelf()->getNode())) {
00296             return 1;
00297         }
00298         else {
00299             return 0;
00300         }
00301     }
00302     else {
00303         debug(DEBUG_NL, "couldnt find entry in VC table for packet");
00304         return -1;
00305     }
00306 } // fn isThisPacketForMe
00307 
00308 
00313 int 
00314 NetworkLayer::send(TpPacket* packet, int vcn)
00315 {
00316         // Create an NP packet and call link layer send
00317     VirtualCircuitTableEntry* e;
00318         e = m_virtualCircuitTable->findBySrc(GlobalObjects::instance()->getConfig()->getSelf()->getNode(), vcn);
00319 
00320     if (e == NULL) {
00321         return NL_ERROR;
00322     }
00323 
00324     NpPacket* packetToSend = new NpPacket(packet, e->getDestVcn());
00325         MEMCHECK(packetToSend);
00326 
00327         int bytesSent = m_linkLayerInterface->sendPacket(packetToSend, e->getDestNode());
00328         delete packetToSend;
00329         return bytesSent;
00330 } // fn send
00331 
00332 
00339 /*
00340 int NetworkLayer::send(NpPacket* packet, int vcn)
00341 {
00342     VirtualCircuitTableEntry* e = NULL;
00343     // lookup in the virtual circuit table, get node, send to node
00344     e = m_virtualCircuitTable->findBySrc(GlobalObjects::instance()->getConfig()->getSelfNode(), vcn);
00345     if (e == NULL) {
00346         return -1;
00347     }
00348     else {
00349             return (m_linkLayerInterface->sendPacket(packet, e->getDestNode()));
00350     }
00351 } // fn send
00352 */
00353 
00358 void 
00359 NetworkLayer::handlePacket(Node* fromNode, NpPacket* packet)
00360 {
00361         if ((packet != NULL) && (fromNode != NULL)) {
00362                 m_packetQueue->add(fromNode, packet);
00363         }
00364 } // fn handlePacket
00365 
00366 
00370 void 
00371 NetworkLayer::handleEvent(ObservableInterface* observed, int eventType, void* object) {
00372     ConnectionTableEntry* ce;
00373     Node* node;
00374     switch (eventType) {
00375         //case Node::CONNECTION_CLOSED:
00376     case (LinkLayerInterface::CONNECTION_CLOSED):
00377         // remove all virtual circuits flowing over that node
00378         ce = (ConnectionTableEntry*)object;
00379         node = ce->getNode();
00380         destroyVcsTo(node);
00381                 break;
00382         default:
00383         debug(DEBUG_NL, "unhandled event");
00384                 break;
00385         }
00386 } // fn nodeEvent
00387 
00388 
00389 // *******************************************************************  
00390 // Private functions:
00391 // *******************************************************************  
00392 
00396 void* 
00397 NetworkLayer::processPackets(void* arg) {
00398     NetworkLayer* nl = (NetworkLayer*)arg;
00399     nl->processPacketsImpl();
00400     return NULL;
00401 } // fn processPackets
00402 
00403 
00411 void 
00412 NetworkLayer::processPacketsImpl() {
00413 
00414   debug(DEBUG_NL, "starting to process packets...");
00415 
00416   NpPacket* packet = NULL;
00417   Node* fromNode = NULL;
00418   while (true) {
00419          m_packetQueue->getNext(&fromNode, &packet);
00420 
00421      if (packet == NULL) {      
00422         debug(DEBUG_NL, "PacketQueue died!!!");
00423                 //we are dead
00424                 return;
00425          }
00426          if (packet->isControlPacket()) {
00427                 handleControlPacket(fromNode, packet);
00428          }
00429          else {
00430                 handleDataPacket(fromNode, packet);
00431          }
00432          delete packet;
00433          packet = NULL;
00434 
00435          pthread_testcancel();
00436   }  // while
00437 } // fn processPacketsImpl
00438 
00439 
00443 void* 
00444 NetworkLayer::pingThread(void* arg) {
00445     NetworkLayer* nl = (NetworkLayer*)arg;
00446     nl->pingThreadImpl();
00447     return NULL;
00448 } // fn pingThread
00449 
00450 
00456 void
00457 NetworkLayer::pingThreadImpl() {
00458     debug(DEBUG_NL, "Starting ping thread...");
00459     Mutex pingThreadMutex;
00460     Guard guard(&pingThreadMutex);
00461     while (true) {
00462         debug(DEBUG_NL, "Pinging neighbors.");
00463         
00464         ping();
00465         
00466         // timeToWait = (1-5 minutes) * 1000 millisecs per second * 60 seconds per minute
00467         int timeToWait = m_randomNumberGenerator.IRandom(1, 5) * 1000 * 60;
00468         m_pingThreadInterrupt.timedWait(&pingThreadMutex, timeToWait);
00469         
00470         pthread_testcancel();
00471     }  // while
00472 } // fn pingThreadImpl
00473 
00474 
00478 void
00479 NetworkLayer::ping() {
00480     NpPacket packet;
00481     packet.setPacketType(NpPacket::Ping);
00482     m_beginPingTime.setToCurrentTime();
00483     m_linkLayerInterface->broadcast(&packet);
00484 } // fn ping
00485 
00486 
00490 void* 
00491 NetworkLayer::discoveryThread(void* arg) {
00492     NetworkLayer* nl = (NetworkLayer*)arg;
00493     nl->discoveryThreadImpl();
00494     return NULL;
00495 } // fn discoveryThread
00496 
00497 
00503 void
00504 NetworkLayer::discoveryThreadImpl() {
00505     debug(DEBUG_NL, "Starting discovery thread...");
00506     Mutex discoveryThreadMutex;
00507     Guard guard(&discoveryThreadMutex);
00508     while (true) {
00509         debug(DEBUG_NL, "Discovering nodes.");
00510         
00511         discover();
00512         
00513         int timeToWait = LIVE_BROADCAST_TABLE_SIZE * BROADCAST_LIFE;
00514         
00515         //Timer::timedWait(&m_discoveryThreadInterrupt, &discoveryThreadMutex, timeToWait);
00516         m_discoveryThreadInterrupt.timedWait(&discoveryThreadMutex, timeToWait);
00517         
00518         pthread_testcancel();
00519     }  // while
00520 } // fn discoveryThreadImpl
00521 
00522 
00526 void
00527 NetworkLayer::discover() {
00528     // Create discovery packet
00529     DiscoveryPacket discoveryPacket;
00530 
00531     NpPacket* packet = (NpPacket*)&discoveryPacket;
00532 
00533     // broadcast discovery to all neighbors
00534     m_linkLayerInterface->broadcast(packet);
00535 } // fn discover
00536 
00537 
00546 bool 
00547 NetworkLayer::forwardPacket(Node* fromNode, NpPacket* packet)
00548 {
00549         //Node* destNode;
00550         //int destVcn;
00551     VirtualCircuitTableEntry* e;
00552     bool retVal = false;
00553 
00554         // Look up the destination for this packet.
00555     if (e = m_virtualCircuitTable->findBySrc(fromNode, packet->getVcn())) {
00556         // Set the Vcn for this packet to be for its new destination.
00557         packet->setVcn(e->getDestVcn());
00558         
00559         // Call link layer send.
00560         if (m_linkLayerInterface->sendPacket(packet, e->getDestNode()) > 0) {
00561             retVal = true;
00562         }
00563     }
00564     else {
00565         debug(DEBUG_NL, "Could not forward packet, entry missing in VC table.  Packet type: %s, VCN: %d", packet->getControlTypeString(), packet->getVcn());
00566     }
00567     return retVal;
00568 } // fn forwardPacket
00569 
00570 
00575 void 
00576 NetworkLayer::handleControlPacket(Node* fromNode, NpPacket* packet)
00577 {
00578 #ifdef INFO
00579         m_virtualCircuitTable->incrementControlPackets(fromNode, 
00580                                                                                                         packet->getVcn());
00581 #endif
00582         switch (packet->getPacketType()) {
00583         case (NpPacket::Connect):
00584                 handleConnectPacket(fromNode, packet);
00585                 break;
00586         case (NpPacket::Established):
00587                 handleEstablishedPacket(fromNode, packet);
00588                 break;
00589         case (NpPacket::Fin):
00590                 handleFinPacket(fromNode, packet);
00591                 break;
00592         case (NpPacket::Discovery):
00593                 handleDiscoveryPacket(fromNode, packet);
00594                 break;
00595         case (NpPacket::ImHere):
00596                 handleImHerePacket(fromNode, packet);
00597                 break;
00598     case (NpPacket::Ping):
00599         handlePingPacket(fromNode, packet);
00600         break;
00601     case (NpPacket::Pong):
00602         handlePongPacket(fromNode, packet);
00603         break;
00604         default:
00605                 debug(DEBUG_NL, "Unknown control packet type: %d", packet->getPacketType());
00606         stringstream s;
00607                 s << *packet;
00608                 packet->dumpData(s);
00609         debug(DEBUG_NL, "%s", s.str());
00610         } // switch
00611 
00612 } // fn handleControlPacket
00613 
00614 
00624 void 
00625 NetworkLayer::handleConnectPacket(Node* fromNode, NpPacket* packet)
00626 {
00627         debug(DEBUG_NL, "CONNECT PACKET RECEIVED");
00628 
00629     // Check if we already have an entry in the VC table for this circuit.
00630         bool found = (m_virtualCircuitTable->findBySrc(fromNode, packet->getVcn()) != NULL);
00631 
00632     if (found) { 
00633         // Error because we shouldnt get a Connect packet on a 
00634         // circuit that has already been created.
00635         debug(DEBUG_NL, "ERROR: Received duplicate connect packet!");
00636         return;
00637     }
00638     
00639     // do a cast since it has already been decoded.  It is passed in as
00640     // an NpPacket as a convenience
00641     ConnectionPacket *cp = (ConnectionPacket*)packet;
00642 
00643     bool becomeTp = false;
00644     if (!GlobalObjects::instance()->getConfig()->getSelf()->getNode()->isFirewalled()) {
00645         // if we are only connected to one node and we arent censored, become the TP
00646         becomeTp = (m_linkLayerInterface->getNumConnections() <= 1);
00647         // also become the TP randomly
00648         becomeTp |= (m_randomNumberGenerator.Random() > GlobalObjects::instance()->getConfig()->getConnectPropagationProbability());
00649     }    
00650     
00651     if (!becomeTp) {
00652         connectForward(fromNode, cp);
00653     } // if (I am not TP)
00654     else {
00655         connectTerminate(fromNode, cp);
00656     } // else (I am TP)
00657 } // fn handleConnectPacket
00658 
00659 
00663 void
00664 NetworkLayer::connectForward(Node* fromNode, ConnectionPacket* packet) {
00665     // Get a unique number for this circuit
00666     int newVcn = m_networkLayerListener->generateConnectionDescriptor();
00667     
00668     // Get a random neighbor node.
00669     Node* randomNeighbor = m_linkLayerInterface->getRandomNeighbor(fromNode);
00670     
00671     // add to the routing table
00672     m_virtualCircuitTable->add(fromNode, packet->getVcn(), randomNeighbor, newVcn);
00673     
00674     // Set the VCN for the packet for the next hop
00675     packet->setVcn(newVcn);
00676     
00677     // Send the packet to the next hop
00678     if (m_linkLayerInterface->sendPacket(packet, randomNeighbor) != (signed int) packet->getRawLength())
00679     {
00680         debug(DEBUG_NL, "ERROR: could not forward CONNECT packet");
00681     } // if
00682 } // fn connectForward
00683 
00684 
00688 void
00689 NetworkLayer::connectTerminate(Node* fromNode, ConnectionPacket* packet) {
00690     VirtualCircuitTableEntry* e = NULL;
00691     debug(DEBUG_NL, "I will become the TP");
00692     
00693     // make VC table entries 
00694     unsigned int newTerminatingVcn = m_networkLayerListener->generateConnectionDescriptor();
00695     
00696     e = m_virtualCircuitTable->add(fromNode, 
00697         packet->getVcn(), 
00698         GlobalObjects::instance()->getConfig()->getSelf()->getNode(), 
00699         newTerminatingVcn);
00700     e->setIsTerminatingPeer(true);
00701     e = m_virtualCircuitTable->add(GlobalObjects::instance()->getConfig()->getSelf()->getNode(), 
00702         newTerminatingVcn,
00703         fromNode, 
00704         packet->getVcn());
00705     e->setIsTerminatingPeer(true);
00706     
00707     // send Established packet back to where we got it
00708     NpPacket* estPacket = new NpPacket(NpPacket::Established, packet->getVcn());
00709     //debug(DEBUG_NL, "SENDING EST PACKET");
00710     m_linkLayerInterface->sendPacket(estPacket, fromNode);
00711     delete estPacket;
00712     
00713     // tell the service table we have a new connection
00714     m_networkLayerListener->handleNetworkEvent(PASSIVE_CONNECTION_EVENT, newTerminatingVcn, NULL);
00715 } // fn connectTerminate
00716 
00717 
00725 void 
00726 NetworkLayer::handleEstablishedPacket(Node* fromNode, NpPacket* packet)
00727 {
00728         debug(DEBUG_NL, "ESTABLISHED PACKET RECEIVED");
00729 
00730     VirtualCircuitTableEntry* e = m_virtualCircuitTable->findByDest(fromNode,
00731                                                                                 packet->getVcn());
00732     VirtualCircuitTableEntry* newEntry = NULL;
00733 
00734     if (e == NULL) {
00735         debug(DEBUG_NL, "ERROR: Bogus EST packet received");
00736         return;
00737     }
00738 
00739     // If the packet is not for me
00740     if (!e->isOriginatingPeer()) {
00741         // Add an entry to the VC table
00742         m_virtualCircuitTable->add(e->getDestNode(), 
00743             e->getDestVcn(),
00744             e->getSrcNode(),
00745             e->getSrcVcn());
00746         // forward the packet
00747         packet->setVcn(e->getSrcVcn());
00748                 // This shou
00749         if (m_linkLayerInterface->sendPacket(packet, e->getSrcNode()) != (int)packet->getRawLength())
00750         {
00751             debug(DEBUG_NL, "ERROR: could not forward Established packet");
00752         } // if
00753     } // if
00754         else { // I am the OP
00755         debug(DEBUG_NL, "CIRCUIT COMPLETED");
00756         // Add an entry to the VC table
00757         newEntry = m_virtualCircuitTable->add(e->getDestNode(), 
00758             e->getDestVcn(),
00759             e->getSrcNode(),
00760             e->getSrcVcn());
00761         newEntry->setIsOriginatingPeer(true);
00762 
00763         // tell the service table about it
00764         m_networkLayerListener->handleNetworkEvent(ACTIVE_CONNECTION_EVENT, e->getSrcVcn(), NULL);
00765         } // else
00766 } // fn handleEstablishedPacket
00767 
00768 
00777 void 
00778 NetworkLayer::handleFinPacket(Node* fromNode, NpPacket* packet)
00779 {
00780     debug(DEBUG_NL, "FIN PACKET RECEIVED");
00781     VirtualCircuitTableEntry* e = NULL;
00782 
00783     int forMe = isThisPacketForMe(fromNode, packet);
00784     if (forMe < 0) {
00785         // error
00786         debug(DEBUG_NL, "FIN PACKET: could not find entry in VC table");
00787     }
00788     else if (forMe == 0) {
00789         // If it is not for me:
00790         // save the Vcn 
00791         int srcVcn = packet->getVcn();
00792         // forward the packet to the next guy along the virtual circuit.
00793         if (forwardPacket(fromNode, packet)) {
00794             // if the packet forwarding was successful...
00795 
00796             // take the virtual circuit table entries out of the table.
00797             e = m_virtualCircuitTable->findBySrc(fromNode, srcVcn);
00798             if (e != NULL) {
00799                 m_virtualCircuitTable->remove(e->getDestNode(), e->getDestVcn());
00800                 m_virtualCircuitTable->remove(fromNode, srcVcn);
00801             }
00802         }
00803     } // if
00804     else if (forMe > 0) {
00805         // If it is for me: (I am the end node)
00806         // save the Vcn and source node for this packet.
00807                 int srcVcn = packet->getVcn();
00808         e = m_virtualCircuitTable->findBySrc(fromNode, srcVcn);
00809         int myVcn = e->getDestVcn();
00810         // take the virtual circuit table entrys out of the table.
00811         m_virtualCircuitTable->remove(e->getDestNode(), myVcn);
00812         m_virtualCircuitTable->remove(fromNode, srcVcn);
00813         
00814         // Tell the service table that the circuit disconnected.  It will 
00815         // decide if we need to reconnect or not.  
00816         m_networkLayerListener->handleNetworkEvent(DISCONNECTION_EVENT, myVcn, packet);
00817         } // else
00818 } // fn handleFinPacket
00819 
00820 
00824 void 
00825 NetworkLayer::handleDataPacket(Node* fromNode, NpPacket* packet)
00826 {
00827 
00828 #ifdef INFO
00829         m_virtualCircuitTable->incrementDataPackets(fromNode, packet->getVcn());
00830 #endif
00831         // if not for me -> forward
00832     int forMe = isThisPacketForMe(fromNode, packet);
00833     if (forMe < 0) {
00834         // error
00835         debug(DEBUG_NL, "No routing entry in the VC table to handle data packet.");
00836     }
00837         else if (forMe == 0) {
00838         // not for me
00839                 forwardPacket(fromNode, packet);
00840                 debug(DEBUG_NL, "I got a data packet NOT for me");
00841         }               
00842     else if (forMe > 0) { 
00843         // Packet is for me.
00844         // Hand off to Service Table.
00845         VirtualCircuitTableEntry* e;
00846                 e = m_virtualCircuitTable->findBySrc(fromNode, packet->getVcn());
00847         if (e != NULL) {                
00848             debug(DEBUG_NL, "I got a data packet for ME, destination VCN = %d", e->getDestVcn());
00849             m_networkLayerListener->handleNetworkEvent(DATA_EVENT, e->getDestVcn(), packet);
00850         }
00851         }
00852 } // fn handleDataPacket
00853 
00854 
00858 void 
00859 NetworkLayer::handleDiscoveryPacket(Node* fromNode, NpPacket* packet)
00860 {
00861     debug(DEBUG_NL, "DISCOVERY PACKET RECEIVED");
00862 
00863     // do a cast since it has already been decoded.  It is passed in as
00864     // an NpPacket as a convenience
00865     DiscoveryPacket *dp = (DiscoveryPacket*)packet;
00866 
00867     // Check if we have seen this packet already
00868     if (m_liveBroadcastTable->hasId(dp->getId(), NULL)) {
00869         debug(DEBUG_NL, "I have seen this Discovery Packet already!");
00870         return;
00871     } // if
00872 
00873     // add IP to LBT
00874     m_liveBroadcastTable->addId(dp->getId(), fromNode);
00875 
00876     // Check how many times this node has asked for a discovery within the
00877     // past LIVE_BROADCAST_TABLE_SIZE * BROADCAST_LIFE millisecs
00878     int nodeCount;
00879     if ((nodeCount = m_liveBroadcastTable->nodeCount(fromNode)) > MAX_DISCOVERY_REQUESTS) {
00880         return;
00881     }
00882 
00883     // we randomly decide to forward the packet
00884     if (m_randomNumberGenerator.Random() <= GlobalObjects::instance()->getConfig()->getDiscoveryPropagationProbability())
00885     {
00886         // Get a random neighbor node.
00887         Node* randomNeighbor = m_linkLayerInterface->getRandomNeighbor(fromNode);
00888 
00889         if (randomNeighbor != NULL) {
00890             // Send the packet to the next hop
00891             if (m_linkLayerInterface->sendPacket(dp, randomNeighbor) != (signed int) packet->getRawLength())
00892             {
00893                 debug(DEBUG_NL, "ERROR: could not forward DISCOVERY packet");
00894             } // if
00895         }
00896     }
00897     
00898     // Decide if we want to respond to the discovery request
00899     if (m_randomNumberGenerator.Random() <= GlobalObjects::instance()->getConfig()->getDiscoveryResponseProbability())
00900     {
00901         // create and route an ImHere packet back to requesting node
00902         // (our own node info is automatically filled in)
00903         ImHerePacket *ih = new ImHerePacket();
00904         MEMCHECK(ih);
00905         
00906         // this is an essential step for getting the IH packet routed back:
00907         ih->setId(dp->getId());
00908         
00909                 // Put my IP address in there
00910                 ih->setIp(GlobalObjects::instance()->getConfig()->getSelf()->getNode()->getSocketAddress()->getIpAddress());
00911 
00912                 // Put my port in there
00913                 ih->setPort(GlobalObjects::instance()->getConfig()->getSelf()->getNode()->getSocketAddress()->getPort());
00914 
00915         // send the IMHERE packet back where it came from
00916         if (m_linkLayerInterface->sendPacket((NpPacket *)ih, fromNode) != (signed int) ih->getRawLength())
00917         {
00918             debug(DEBUG_NL, "ERROR: Couldn't send back IMHERE packet");
00919         }
00920         delete ih;
00921     } // if ... DiscoveryResponseProbability
00922 } // fn handleDiscoveryPacket
00923 
00924 
00930 void 
00931 NetworkLayer::handleImHerePacket(Node* fromNode, NpPacket* packet)
00932 {
00933     debug(DEBUG_NL, "IMHERE PACKET RECEIVED");
00934 
00935     // The packet has already been decoded for us, it was just passed to us
00936     // as a NpPacket as a convenience
00937     ImHerePacket* imherePacket = (ImHerePacket*)packet; 
00938     
00939     // Create a potentially new Node
00940     Node newNode;
00941 
00942     // Set the IP address and port for the node
00943     newNode.setSocketAddress(&SocketAddress(imherePacket->getIp(), imherePacket->getPort()));
00944 
00945     // Set the version number of the node
00946     newNode.setVersionNumber(imherePacket->getVersionNumber());
00947 
00948     // Set the capabilities of the node
00949     newNode.setIsFirewalled(imherePacket->isFirewalled());
00950     newNode.setIsTrusted(imherePacket->isTrusted());
00951     newNode.setIsNatted(imherePacket->isNatted());
00952 
00953     // Add this node to our master list, this automatically takes care of 
00954     // duplicates 
00955     GlobalObjects::instance()->getCatcher()->addNode(&newNode);
00956     
00957     /*
00958     * done adding node, send imhere packet on, if possible
00959     * we route it via broadcast ID entries left by its Discovery packet
00960     */
00961     Node* prevNode;
00962     if (m_liveBroadcastTable->hasId(imherePacket->getId(), &prevNode)) {
00963         debug(DEBUG_NL, "Routing ImHere packet back...");
00964         if (m_linkLayerInterface->sendPacket(packet, prevNode) != (signed int) packet->getRawLength())
00965         {
00966             debug(DEBUG_NL, "ERROR sending back IMHERE packet");
00967         }
00968     }
00969 } // fn handleImherePacket
00970 
00971 
00976 void 
00977 NetworkLayer::handlePingPacket(Node* fromNode, NpPacket* packet)
00978 {
00979     debug(DEBUG_NL, "PING PACKET RECEIVED");
00980 
00981     packet->setPacketType(NpPacket::Pong);
00982 
00983     // send the PING packet back where it came from
00984     if (m_linkLayerInterface->sendPacket(packet, fromNode) != (signed int) packet->getRawLength())
00985     {
00986         debug(DEBUG_NL, "ERROR: Couldn't send back PONG packet");
00987     }
00988 
00989 } // fn handlePingPacket
00990 
00991 
00995 void 
00996 NetworkLayer::handlePongPacket(Node* fromNode, NpPacket* packet)
00997 {
00998     debug(DEBUG_NL, "PONG PACKET RECEIVED");
00999     TimeValue rtt = TimeValue::getCurrentTime() - m_beginPingTime;
01000 #ifdef DEBUG_ON
01001     stringstream s;
01002     s << rtt;
01003     debug(DEBUG_NL, "RTT: %s", s.str().c_str());
01004 #endif
01005     rtt = (fromNode->getRtt() * RTT_FACTOR) + (rtt * (1 - RTT_FACTOR));
01006     if (rtt.isZero()) {
01007         rtt = TimeValue(0,100);
01008     }
01009     fromNode->setRtt(rtt);
01010 } // fn handlePongPacket
01011 
01012   
01013 void 
01014 NetworkLayer::signalBreak(int connectionDescriptor)
01015 {
01016     debug(DEBUG_NL, "break on ", connectionDescriptor);
01017     m_networkLayerListener->handleNetworkEvent(BREAK_EVENT, connectionDescriptor, NULL);
01018 } // fn signalBreak
01019 
01020 
01025 void 
01026 NetworkLayer::toStream(std::ostream& out) {
01027         out << *m_linkLayerInterface;
01028         out << *m_virtualCircuitTable;
01029 } // fn toStream
01030 
01031 

Generated at Thu Jul 11 13:31:51 2002 for Peekabooty by doxygen1.2.9 written by Dimitri van Heesch, © 1997-2001