Example #1
0
/**
 * Looks for a connection
 */
uint8_t tftpPoll()
{
	uint8_t response = ACK;
	// Get the size of the recieved data
	uint16_t packetSize = netReadWord(REG_S3_RX_RSR0);

	if(packetSize) {
		tftpFlashing = TRUE;

		for(;;) {
			if(!(netReadReg(REG_S3_IR) & IR_RECV)) break;

			netWriteReg(REG_S3_IR, IR_RECV);

			//FIXME: is this right after all? smaller delay but
			//still a delay and it still breaks occasionally
			_delay_ms(400);
		}
		// Process Packet and get TFTP response code
#ifdef _DEBUG_TFTP
		response = processPacket(packetSize);
#else
		response = processPacket();
#endif
		// Send the response
		sendResponse(response);
	}
	if(response == FINAL_ACK) {
		netWriteReg(REG_S3_CR, CR_CLOSE);
		// Complete
		return(0);
	}
	// Tftp continues
	return(1);
}
Example #2
0
// --------------------------------------------------------------------
// main
// --------------------------------------------------------------------
int main(int argc, char*argv[]) 
{    
    parseArgs(argc, argv);

    struct sigaction a;
    a.sa_handler = traitementInterrupt;      /* fonction à lancer */
    sigemptyset(&a.sa_mask);    /* rien à masquer */
    
    sigaction(SIGTSTP, &a, NULL);       /* pause contrôle-Z */
    sigaction(SIGINT,  &a, NULL);       /* fin contrôle-C */
    sigaction(SIGTERM, &a, NULL);       /* arrêt */
    sigaction(SIGSEGV, &a, NULL);       /* segmentation fault ! */

    int sock=0;
    initSocket(sock);
    sock_=sock;
    
    ZFile file;
    initFile(&file);
    file_=&file;
    
    while(1) {
	bool close=false;
        processPacket(sock, &file, false, close);
	if (close) {
	    file.close();
	    initFile(&file);
	    file_=&file;
	}
    }
    return(EXIT_SUCCESS);
}
Example #3
0
void playGame(void)
{
    int len;
    struct packet p;
    lcdPrintln("Now playing:");
    lcdPrintln(gameTitle);
    lcdRefresh();

    while(1){
        uint8_t button = getInputRaw();
        sendButton(button);
        
        while(1){
            if( flags & FLAGS_LONG_RECV )
                len = nrf_rcv_pkt_time(64,sizeof(p),(uint8_t*)&p);
            else
                len = nrf_rcv_pkt_time(32,sizeof(p),(uint8_t*)&p);
                
            if(len==sizeof(p)){
                processPacket(&p);
            }else{
                break;
            }
        }
        int rnd = getRandom() % jitter;
        delayms(interval*5+rnd);
        
        volatile uint16_t i;
        i = getRandom()&0xfff;
        while(i--);

    };
}
Example #4
0
NetworkServer::AutoPacket NetworkServer::receive()
{
	assert(isConnected());

	for (;;) {
		if (_queuedUser) {
			removeUser(_queuedUser);
			_queuedUser = 0;
		}

		Packet* raw = _peer->Receive();
		if (!raw) {
			return AutoPacket();
		}
		AutoDepacketer depacketer(*_peer, raw);

		AutoPacket packet(processPacket(*raw));
		if (packet.get()) {
			User *user = findUser(raw->systemAddress);
			if (!user) {
				packetHeader(std::cout, *raw);
				std::cout << "Packet from unknown user: " << int(packet->kind()) << std::endl;
				continue;
			}
			packet->read(raw, user);
			return packet;
		}
	}
}
bool Communicator::readFromClient()
{
	bool result = false;
	ssize_t r = 0;
	uint32_t packetSize = 0;

	r = read(mSocket, &packetSize, 4);

	if (r == 4) {
		packetSize = le32toh(packetSize);
		//syslog(LOG_INFO, "incoming packet size: %d", packetSize);

		uint8_t *buf = (uint8_t *) malloc(packetSize - 4);

		r = read(mSocket, buf, packetSize - 4);

		if (r == (packetSize - 4)) {
			result = processPacket(buf, packetSize - 4);
		}
		else
			syslog(LOG_ERR, "Error reading packet : %ld", r);

		free(buf);

	} else
		syslog(LOG_ERR, "Error reading total packet size: %ld", r);



	return result;
}
void JobThread::run()
{
   Packet* packet = NULL;
   while ( !terminated ) {
      
      packet = m_jobQueue->dequeue();

      // loop until we get a packet
      if ( packet == NULL ) {
         continue;
      }

      if ( packet->timedOut() ) {
         mc2dbg << "[JobThread]: Packet timed out, type="
                << packet->getSubTypeAsString()
                << " age "
                << float(packet->getTimeSinceArrival() / 1000.0 )
                << " max age " << packet->getTimeout() << endl;
         delete packet;
         continue;
      }

      processPacket( packet );

   }
   // make sure the dispatcher dies quickly 
   m_dispatcher.reset( NULL );
}
int ManageMemberSessionOutput::svc()
{
	ACE_Time_Value sleep_time(0, 1000);
	PacketVec_t	output_packet_vec;
	while (true)
	{
		{
			ACE_GUARD_RETURN(ACE_Thread_Mutex, guard, m_output_packet_vec_mutex, 1);
			std::copy(m_output_packet_vec.begin(), m_output_packet_vec.end(), std::back_inserter(output_packet_vec));
			m_output_packet_vec.clear();
		}

		if (output_packet_vec.size() == 0)
		{
			ACE_OS::sleep(sleep_time);
			continue;
		}
	
		for (PacketVec_t::iterator it = output_packet_vec.begin(); it != output_packet_vec.end(); ++it)
		{
			Packet * packet = *it;
			processPacket(packet);
		}

		output_packet_vec.clear();
	}
	return 0;
}
Example #8
0
void playGame(void)
{
    int len;
    struct packet p;

    while(1){
        uint8_t button = getInputRaw();
        sendButton(button);
        
        while(1){
            if( flags & FLAGS_LONG_RECV )
                len = nrf_rcv_pkt_time(64,sizeof(p),(uint8_t*)&p);
            else
                len = nrf_rcv_pkt_time(32,sizeof(p),(uint8_t*)&p);
                
            if(len==sizeof(p)){
                processPacket(&p);
            }else{
                break;
            }
        }
        int rnd = getRandom() % jitter;
        delayms(interval+rnd);
    };
}
Example #9
0
    bool WirelessParser::findPacketInBytes(DataBuffer& data, WirelessTypes::Frequency freq)
    {
        //create a read save point for the DataBuffer
        ReadBufferSavePoint savePoint(&data);

        std::size_t lastReadPosition;

        //while there are enough bytes remaining to make an ASPP response packet
        while(data.bytesRemaining() > WirelessPacket::ASPP_MIN_RESPONSE_PACKET_SIZE)
        {
            lastReadPosition = data.readPosition();

            //move to the next byte
            data.read_uint8();

            WirelessPacket packet;

            //if we found a packet within the bytes
            if(parseAsPacket(data, packet, freq) == parsePacketResult_completePacket)
            {
                //commit the data that was read
                savePoint.commit();

                //process the packet
                processPacket(packet, lastReadPosition);
                return true;
            }
        }

        //we didn't find any packet in the bytes buffer
        return false;
    }
Example #10
0
// Receives 16 byte buffers
int SocketConnection::readPackets() {
    if (m_readdone) {
        m_readbufoffset = 0;
        m_readbuf = std::string(16, 0);
        m_readdone = false;
    }

    int error = recv(fd, &m_readbuf[0], m_readbuf.length() -
                     m_readbufoffset, 0);
    if (error == 0 || (error == -1 && errno != EAGAIN)) {
        // recv(3) failed, so return failure so socket is closed
        return -1;
    }
    m_readbufoffset += error;

    if (m_readbufoffset == m_readbuf.length()) {
        // Add null terminator
        m_readbuf[15] = 0;
        processPacket(m_readbuf);
        m_readbufoffset = 0;
        m_readdone = true;
    }

    return 0;
}
Example #11
0
//
// bool processPackets()
// Last modified: 27Aug2006
//
// Attempts to process all packets received by the cell,
// returning true if successful, false otherwise.
//
// Returns:     true if successful, false otherwise
// Parameters:  <none>
//
bool Cell::processPackets()
{
    Packet p;
    while (msgQueue.dequeue(p))
        if (!processPacket(p)) return false;
    return true;
}   // processPackets()
Example #12
0
////////////////////////////////////////////////////
// handle a new packet on the stream
void EQPacketStream::handlePacket(EQUDPIPPacketFormat& packet)
{
  emit numPacket(++m_packetCount, (int)m_streamid);

  // Only accept packets if we've been initialized unless they are
  // initialization packets!
  if (packet.getNetOpCode() != OP_SessionRequest &&
      packet.getNetOpCode() != OP_SessionResponse &&
      ! m_sessionKey)
  {
#if (defined(PACKET_PROCESS_DIAG) && (PACKET_PROCESS_DIAG > 1)) || defined(PACKET_SESSION_DIAG)
    seqDebug("discarding packet %s:%d ==>%s:%d netopcode=%04x size=%d. Session not initialized. Need to zone to start picking up packets. Session tracking %s.",
      (const char*)packet.getIPv4SourceA(), packet.getSourcePort(),
      (const char*)packet.getIPv4DestA(), packet.getDestPort(),
      packet.getNetOpCode(), packet.payloadLength(),
        (m_session_tracking_enabled == 2 ? "locked on" : 
          (m_session_tracking_enabled == 1 ? "enabled" : "disabled")));
#endif
    return;
  }

  emit rawPacket(packet.payload(), packet.payloadLength(), m_dir,
    packet.getNetOpCode());

  processPacket(packet, false); // false = isn't subpacket

  // if the cache isn't empty, then process it.
  if (!m_cache.empty()) 
    processCache();
}
Example #13
0
    bool InertialParser::findPacketInBytes(DataBuffer& data)
    {
        //create a read save point for the DataBuffer
        ReadBufferSavePoint savePoint(&data);

        //while there are enough bytes remaining to make a MIP packet
        while(data.bytesRemaining() > InertialPacketInfo::MIP_MIN_PACKET_SIZE)
        {
            //move to the next byte
            data.read_uint8();

            InertialPacket packet;

            //if we found a packet within the bytes
            if(parseAsPacket(data, packet) == inertialParserResult_completePacket)
            {
                //commit the data that was read
                savePoint.commit();

                //process the packet
                processPacket(packet);
                return true;
            }
        }

        //we didn't find any packet in the bytes buffer
        return false;
    }
Example #14
0
void* connection_handler(void* argsp) {
    //Get the socket descriptor
    struct threadArgs* args = argsp;
    int client_socket = args->sock, read_size;
    List* codeList = args->list;
    free(argsp);
    unsigned char* client_message = (unsigned char*) malloc(BUFFER_SIZE);
     
    //Receive a message from client
    while((read_size = recv(client_socket, client_message, BUFFER_SIZE-1, 0)) > 0) {

        client_message[read_size] = '\0';
        processPacket(client_socket, client_message, read_size, codeList);

    }

    free(client_message);
     
    if(read_size == 0) {
        puts("Client disconnected");
    } else if(read_size == -1){
        perror("recv failed");
    }
     
    return NULL;
}
Example #15
0
void packetPrinter (u_char *user, struct pcap_pkthdr *h, u_char *pp)
{
	int rc;
	nfs_pkt_t record;

	rc = processPacket (h, pp, &record);

}
Example #16
0
Packet* IPReassembly::processPacket(RawPacket* fragment, ReassemblyStatus& status, ProtocolType parseUntil, OsiModelLayer parseUntilLayer)
{
	Packet* parsedFragment = new Packet(fragment, false, parseUntil, parseUntilLayer);
	Packet* result = processPacket(parsedFragment, status, parseUntil, parseUntilLayer);
	if (result != parsedFragment)
		delete parsedFragment;

	return result;
}
Example #17
0
void Server::receivePackets()
{
	for (auto client = clients.begin(); client != clients.end(); ++client)
	{
		sf::Packet p;
		if (client->receive(p))
			processPacket(p, client);
	}	
}	
Example #18
0
uint8_t selectGame()
{  
    int len, i, selected;
    struct packet p;
    int a = 0;
    config.channel = ANNOUNCE_CHANNEL;
    memcpy(config.mac0, ANNOUNCE_MAC, 5);
    nrf_config_set(&config);

    gamecount = 0;
    for(i=0;i<60;i++){
        len= nrf_rcv_pkt_time(30, sizeof(p), (uint8_t*)&p);
        if (len==sizeof(p)){
            if( a ) a = 0; else a = 1;
            gpioSetValue (RB_LED2, a);
            processPacket(&p);
        }
    }
    selected = 0;
    while(1){
        showGames(selected);
        int key=getInputWait();
        getInputWaitRelease();
        switch(key){
            case BTN_DOWN:
                if( selected < gamecount-1 ){
                    selected++;
                }
                break;
            case BTN_UP:
                if( selected > 0 ){
                    selected--;
                }
                break;
            case BTN_LEFT:
                return 0;
            case BTN_ENTER:
            case BTN_RIGHT:
                if( gamecount == 0 )
                    return 0;
                gameId = games[selected].gameId;
                memcpy(config.txmac, games[selected].gameMac, 5);
                memcpy(config.mac0, games[selected].gameMac, 5);
                config.mac0[4]++;
                config.channel = games[selected].gameChannel;
                interval = games[selected].interval;
                jitter = games[selected].jitter;
                flags = games[selected].gameFlags;
                nrf_config_set(&config);
                if( games[selected].gameFlags & FLAGS_MASS_GAME )
                    return 1;
                else
                    return joinGame();
        }
    }
}
Example #19
0
void Drf1600::onReadyRead()
{
	if (mCurrentCommand == Idle) {
		mSerialPort->read(mSerialPort->bytesAvailable());
		return;
	}
	if (mSerialPort->bytesAvailable() < mBytesExpected)
		return;
	processPacket(mSerialPort->read(mSerialPort->bytesAvailable()));
}
bool RtspStreamWorker::processStream()
{
    bool ok;
    AVPacket packet = readPacket(&ok);
    if (!ok)
        return false;

    bool result = processPacket(packet);
    av_packet_unref(&packet);
    return result;
}
/** Entry point. This is the first thing which is called after startup code.
  * This never returns. */
int main(void)
{
	initUsart();
	initAdc();
	initLcdAndInput();

	do
	{
		processPacket();
	} while (true);
}
//
// bool processPackets()
// Last modified: 29Nov2009
//
// Handles incoming packets, returning true
// if successful, false otherwise.
//
// Returns:    true if successful, false otherwise
// Parameters: <none>
bool Robot::processPackets()
{
    bool   success = true;
    Packet p;
    while (!msgQueue.empty())
    {
        p = msgQueue.front();
        if (!processPacket(p)) success = false;
        msgQueue.pop();
		}
    return success;
}   // processPackets()
Example #23
0
void NetInterface::checkIncomingPackets()
{
   PacketStream stream;
   NetError error;
   Address sourceAddress;

   mCurrentTime = Platform::getRealMilliseconds();

   // read out all the available packets:
   while((error = stream.recvfrom(mSocket, &sourceAddress)) == NoError)
      processPacket(sourceAddress, &stream);
}
Example #24
0
int netLoop(int tunFd)
{
	char *tunPkt = NULL;

	while(1)
	{
		tunPkt = get_packet(tunFd);

		processPacket(tunPkt);
		//tunPkt = NULL;
	}
	return 0; 
}
        bool Packetizer::putPacket(PacketPtr ptr) {
          bool result = false;
          //in case of stream is not mapped through stream_data element, discard packet
          if (_streams.find(ptr->getStreamIndex()) == _streams.end()) {
            return false;
          }

          if (_codec_overlap.find(_streams[ptr->getStreamIndex()].decoder->getCodecId()) == _codec_overlap.end()) {
            _codec_overlap[_streams[ptr->getStreamIndex()].decoder->getCodecId()] = 0;
          }
          result = processPacket(ptr);
          return result;
        }
Example #26
0
void ClientData::ClientThreadGetInfo() // NEW THREAD TO RECEIVE INFORMATIONS FROM THE SERVER
{
	Packet packetType;
	while (GameLogic::getGameOn())
	{
		if (!getPacketType(packetType)) std::cout << "Failed to get packet from server..." << std::endl;
		if (!processPacket(packetType)) std::cout << "Failed to process packet from server..." << std::endl;

	}
	cout << "Lost connection to the server - ClientThread" << endl;
	if (closeConnection()) cout << "Socket was closed successfuly" << endl;
	else cout << "Couldn't close the socket" << endl;
}
Example #27
0
void					GameCore::receivePacket()
{
  GamerInfo*				client;
  IClientPacket<ClientUDPCommand>*	packet;

  if ((client = _network->selectClient()))
    {
      _firstClient = true;
      packet = _network->receiveFrom(client);
      if (packet)
	processPacket(client, packet);
    }
}
static void readProc(const MIDIPacketList *pktlist, void *readProcRefCon, void *srcConnRefCon)
{
	// farm out the packets
	const MIDIPacket *packet = &pktlist->packet[0];
	for (int i=0; i <  pktlist->numPackets; ++i)
	{
		// process the packet - in our case, receive a surface message
		processPacket(packet->data, packet->length);
		
		// next
		packet = MIDIPacketNext(packet);
	}
}
bool ReceivedPacketProcessor::process() {
    quint64 now = usecTimestampNow();
    quint64 sinceLastWindow = now - _lastWindowAt;

    if (sinceLastWindow > USECS_PER_SECOND) {
        lock();
        float secondsSinceLastWindow = sinceLastWindow / USECS_PER_SECOND;
        float incomingPacketsPerSecondInWindow = (float)_lastWindowIncomingPackets / secondsSinceLastWindow;
        _incomingPPS.updateAverage(incomingPacketsPerSecondInWindow);

        float processedPacketsPerSecondInWindow = (float)_lastWindowProcessedPackets / secondsSinceLastWindow;
        _processedPPS.updateAverage(processedPacketsPerSecondInWindow);

        _lastWindowAt = now;
        _lastWindowIncomingPackets = 0;
        _lastWindowProcessedPackets = 0;
        unlock();
    }

    if (_packets.size() == 0) {
        _waitingOnPacketsMutex.lock();
        _hasPackets.wait(&_waitingOnPacketsMutex, getMaxWait());
        _waitingOnPacketsMutex.unlock();
    }

    preProcess();
    if (!_packets.size()) {
        return isStillRunning();
    }

    lock();
    std::list<NodeSharedReceivedMessagePair> currentPackets;
    currentPackets.swap(_packets);
    unlock();

    for(auto& packetPair : currentPackets) {
        processPacket(packetPair.second, packetPair.first);
        _lastWindowProcessedPackets++;
        midProcess();
    }

    lock();
    for(auto& packetPair : currentPackets) {
        _nodePacketCounts[packetPair.first->getUUID()]--;
    }
    unlock();

    postProcess();
    return isStillRunning();  // keep running till they terminate us
}
Example #30
0
void PacketInterface::readPendingDatagrams()
{
    while (mUdpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(mUdpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        mUdpSocket->readDatagram(datagram.data(), datagram.size(),
                                &sender, &senderPort);

        processPacket((unsigned char*)datagram.data(), datagram.length());
    }
}