Example #1
0
	void PacketReader::onDataReady(Uint8* buf, Uint32 size)
	{
		if (error)
			return;

		mutex.lock();
		if (packet_queue.size() == 0)
		{
			Uint32 ret = 0;
			while (ret < size && !error)
			{
				ret += newPacket(buf + ret, size - ret);
			}
		}
		else
		{
			Uint32 ret = 0;
			IncomingPacket::Ptr pck = packet_queue.back();
			if (pck->read == pck->size) // last packet in queue is fully read
				ret = newPacket(buf, size);
			else
				ret = readPacket(buf, size);

			while (ret < size  && !error)
			{
				ret += newPacket(buf + ret, size - ret);
			}
		}
		mutex.unlock();
	}
Example #2
0
//-------------------------------------------------------------------------------------
int32 Bundle::onPacketAppend(int32 addsize, bool inseparable)
{
	if(pCurrPacket_ == NULL)
	{
		newPacket();
	}

	int32 totalsize = (int32)pCurrPacket_->length();
	int32 fwpos = (int32)pCurrPacket_->wpos();

	if(inseparable)
		fwpos += addsize;

	if(fwpos >= packetMaxSize_)
	{
		packets_.push_back(pCurrPacket_);
		currMsgPacketCount_++;
		newPacket();
		totalsize = 0;
	}

	int32 remainsize = packetMaxSize_ - totalsize;
	int32 taddsize = addsize;

	// 如果当前包剩余空间小于要添加的字节则本次填满此包
	if(remainsize < addsize)
		taddsize = remainsize;
	
	currMsgLength_ += taddsize;
	return taddsize;
}
Example #3
0
//-------------------------------------------------------------------------------------
Bundle::Bundle(const Bundle& bundle)
{
	// 这些必须在前面设置
	// 否则中途创建packet可能错误
	isTCPPacket_ = bundle.isTCPPacket_;
	pChannel_ = bundle.pChannel_;
	pCurrMsgHandler_ = bundle.pCurrMsgHandler_;
	currMsgID_ = bundle.currMsgID_;

	Packets::const_iterator iter = bundle.packets_.begin();
	for (; iter != bundle.packets_.end(); ++iter)
	{
		newPacket();
		pCurrPacket_->append(*static_cast<MemoryStream*>((*iter)));
		packets_.push_back(pCurrPacket_);
	}

	pCurrPacket_ = NULL;
	if(bundle.pCurrPacket_)
	{
		newPacket();
		pCurrPacket_->append(*static_cast<MemoryStream*>(bundle.pCurrPacket_));
	}

	numMessages_ = bundle.numMessages_;
	currMsgPacketCount_ = bundle.currMsgPacketCount_;
	currMsgLength_ = bundle.currMsgLength_;
	currMsgHandlerLength_ = bundle.currMsgHandlerLength_;
	currMsgLengthPos_ = bundle.currMsgLengthPos_;
	_calcPacketMaxSize();
}
Example #4
0
	int32 onPacketAppend(int32 addsize, bool inseparable = true)
	{
		if(pCurrPacket_ == NULL)
		{
			newPacket();
		}

		int32 packetmaxsize = PACKET_MAX_CHUNK_SIZE();
		int32 totalsize = (int32)pCurrPacket_->totalSize();
		int32 fwpos = (int32)pCurrPacket_->wpos();

		if(inseparable)
			fwpos += addsize;

		if(fwpos >= packetmaxsize)
		{
			TRACE_BUNDLE_DATA(false, pCurrPacket_, pCurrMsgHandler_, totalsize);
			packets_.push_back(pCurrPacket_);
			currMsgPacketCount_++;
			newPacket();
			totalsize = 0;
		}

		int32 remainsize = packetmaxsize - totalsize;
		int32 taddsize = addsize;

		// 如果 当前包剩余空间小于要添加的字节则本次填满此包
		if(remainsize < addsize)
			taddsize = remainsize;
		
		currMsgLength_ += taddsize;
		return taddsize;
	}
void ProxyOrchestrator::onBlockReceived(Block *block)
{
    BlocksSource * senderObj = dynamic_cast<BlocksSource *>(sender());
    if (senderObj != nullptr) {
        if (senderObj != serverSource && senderObj != clientSource) {
            qCritical() << tr("[ProxyOrchestrator::onBlockReceived] Cannot recognized the sender, dropping the block T_T");
            delete block;
            return;
        }

        QSharedPointer<Packet> pac = QSharedPointer<Packet> (new(std::nothrow) Packet(block));
        if (pac.isNull()) {
            qFatal("Cannot allocate Packet X{");
        }

        if (senderObj == serverSource) {
            pac->setDirection(Packet::LEFTRIGHT);
        } else {
            pac->setDirection(Packet::RIGHTLEFT);
        }

        emit newPacket(pac);
        delete block;
    } else {
        qCritical() << tr("[ProxyOrchestrator::onBlockReceived] Cannot cast the sender T_T");
    }
}
Example #6
0
SerialPacket* turnPacket(char direction, int degrees) {
	SerialPacket* packet = newPacket();

	packet->type = TURN;
	packet->data1 = (uint8)direction;
	packet->data2 = (uint8)degrees;

	printPacket(packet);

	return packet;
}
Example #7
0
/*  PUBLIC FUNCTIONS */
SerialPacket* setPinPacket(int pin, int val) {
	if (pin > 255 || val > 255) {
		return NULL;
	}

	SerialPacket* packet = newPacket();

	packet->type = SET_PIN;
	packet->data1 = (uint8)pin;
	packet->data2 = (uint8)val;

	return packet;
}
Example #8
0
MarkProtocol::MarkProtocol(QSerialPort *port,
                           IPacketsSplitter *packetsSplitter,
                           IDataExtractor *dataExtractor,
                           QObject *parent)
    : IProtocol(parent)
    , m_port(port)
    , m_packetsSplitter(packetsSplitter)
    , m_dataExtractor(dataExtractor)
{
    m_port->setReadBufferSize(bufferSize);    

    connect(m_port, SIGNAL(readyRead()), this, SLOT(readData()));
    connect(m_packetsSplitter, SIGNAL(readedPacket(QByteArray)), this, SLOT(newPacket(QByteArray)));
    connect(m_packetsSplitter, SIGNAL(packetIsReaded(bool)), this, SLOT(newPacket(bool)));
}
Example #9
0
////////////////////////////////////////////////////
// This function decides the fate of the Everquest packet 
// and dispatches it to the correct packet stream for handling function
void EQPacket::dispatchPacket(int size, unsigned char *buffer)
{
#ifdef DEBUG_PACKET
  debug ("EQPacket::dispatchPacket()");
#endif /* DEBUG_PACKET */

  // Create an object to parse the packet
  EQUDPIPPacketFormat packet(buffer, size, false);

  dispatchPacket(packet);

  // signal a new packet. This has to be at the end so that the session is
  // filled in if possible, so that it can report on crc errors properly
  emit newPacket(packet);
}
Example #10
0
//-------------------------------------------------------------------------------------
Bundle::Bundle(Channel * pChannel, ProtocolType pt):
	pChannel_(pChannel),
	numMessages_(0),
	pCurrPacket_(NULL),
	currMsgID_(0),
	currMsgPacketCount_(0),
	currMsgLength_(0),
	currMsgHandlerLength_(0),
	currMsgLengthPos_(0),
	packets_(),
	isTCPPacket_(pt == PROTOCOL_TCP),
	pCurrMsgHandler_(NULL)
{
	 newPacket();
}
Example #11
0
void PhatChat::Server::Client::handlePacket ( sf::Packet packet )
{
	unsigned char operationCodeValue = 0 ;
	packet >> operationCodeValue ;
	PhatChat::OperationCode operationCode = static_cast <PhatChat::OperationCode> ( operationCodeValue ) ;

	if ( operationCode == PhatChat::OperationCode::PING )
	{
		PhatChat::PingPacket pingPacket ( PhatChat::PingPacket::decode ( packet ) ) ;
		std::cout << "Received ping packet with value " << pingPacket.getValue ( ) << "!" << std::endl ;

		sf::Packet newPacket ( PhatChat::PongPacket ( pingPacket.getValue ( ) ).encode ( ) ) ;

        this->socket.send ( newPacket ) ;
	}
	else if ( operationCode == PhatChat::OperationCode::PONG )
	{
		PhatChat::PongPacket pongPacket = PhatChat::PongPacket::decode ( packet ) ;
		std::cout << "Received pong packet with value " << pongPacket.getValue ( ) << "!" << std::endl ;
	}
	else if ( operationCode == PhatChat::OperationCode::REQUEST_USERNAME )
	{
        PhatChat::RequestUsernamePacket requestUsernamePacket = PhatChat::RequestUsernamePacket::decode ( packet ) ;
        this->setUsername ( requestUsernamePacket.getUsername ( ) ) ;
	}
	else if ( operationCode == PhatChat::OperationCode::MESSAGE )
	{
        PhatChat::MessagePacket messagePacket = PhatChat::MessagePacket::decode ( packet ) ;
        
        std::string username = this->username.empty ( ) ? messagePacket.getUsername ( ) : this->username ;
        std::cout << "Received message from " << username << " saying \"" << messagePacket.getMessage ( ) << "\"!" << std::endl ;
        
        if ( * messagePacket.getMessage ( ).begin ( ) == '/' )
        	this->handleCommand ( messagePacket.getMessage ( ) ) ;
        else
		{
        	messagePacket.setUsername ( username ) ;
        	
		    for ( auto client : this->clientManager )
		    {
		        packet = messagePacket.encode ( ) ;
		        client->getSocket ( ).send ( packet ) ;
		    }
		 }
	}
	else
		std::cout << "Operation code is unknown! Skip " << packet.getDataSize ( ) << " bytes." << std::endl ;
}
void RealTrafficIPC::
handleSSIReplies( const PacketContainers& ssiPC,
                  const MC2Coordinates& firstCoord,
                  StreetReplies& streetReplies ) {
   PacketContainers::const_iterator replyIt;
   for ( replyIt = ssiPC.begin(); replyIt != ssiPC.end(); ++replyIt ) {
      StreetSegmentItemReplyPacket* replyPacket =
         static_cast<StreetSegmentItemReplyPacket*>( (*replyIt)->getPacket() );
      if ( replyPacket == NULL ) {
         delete *replyIt;
         // skip this packet or resend?
      } else if ( replyPacket->getStatus() == StringTable::OK ) {
         // packet ok so keep this and handle it.
         streetReplies.insert( make_pair( replyPacket->getIndex(), *replyIt ) );
      } else if ( replyPacket->getStatus() == StringTable::NOT_UNIQUE ) {
         // The mapID is not unique so we need to create new packets for each
         // map. This shouldnt happen to often but still needs to be covered.
         Index index = replyPacket->getIndex();
         uint32 nbrMaps = replyPacket->getNbrMapIDs();
         PacketContainers newPackets;
         for ( uint32 i = 0; i < nbrMaps; ++i ) {
            uint32 currentMapID = replyPacket->getMapID( i );
            // create a packet for each map
            auto_ptr< StreetSegmentItemRequestPacket > newPacket(
                  new StreetSegmentItemRequestPacket( 
                     0, // packetID
                     m_moduleCom.getNextRequestID(),
                     index,
                     firstCoord[ index ].lat,  // latitude 
                     firstCoord[ index ].lon, // longitude
                     TrafficDataTypes::NoDirection ) );

            newPacket->setMapID( currentMapID );
            // create the packet container
            newPackets.push_back( 
                  new PacketContainer( newPacket.release(), 
                                       0, 
                                       0, 
                                       MODULE_TYPE_MAP ) );
         }
         // send them and call this function again
         sendPacketContainers( newPackets );
         handleSSIReplies( newPackets, firstCoord, streetReplies );
         delete *replyIt;
      }
   }
}
Example #13
0
void packet::sendPacket(QTcpSocket *socket)
{
    //sends packetsize then packet
    packet newPacket(channelName, sender, contentType, content);
    QByteArray newPacket_bArray;
    QDataStream newPacket_stream(&newPacket_bArray, QIODevice::WriteOnly);
    //send.setVersion(QDataStream::Qt_5_1);
    newPacket_stream << this;

    int packetSize = newPacket_bArray.size();
    QByteArray packetSize_bArray;
    QDataStream packetSize_stream(&packetSize_bArray, QIODevice::WriteOnly);
    //send.setVersion(QDataStream::Qt_5_1);
    packetSize_stream << packetSize;

    socket->write(packetSize_bArray);
    socket->write(newPacket_bArray);
}
Example #14
0
void ProtocolDecoder::parseBuffer(QByteArray buffer)
{
	for (int i=0;i<buffer.size();i++)
	{
		if (static_cast<unsigned char>(buffer.at(i)) == START_BYTE)
		{
			if (m_isInPacket)
			{
				//Bad start
				QLOG_DEBUG() << "Bad Start";
			}
			m_isInPacket = true;
			m_isInEscape = false;
			m_currMsg.clear();
		}
		else if (static_cast<unsigned char>(buffer.at(i)) == STOP_BYTE)
		{
			if (!m_isInPacket)
			{
				//Bad stop
				QLOG_DEBUG() << "Bad Stop";
				continue;
			}
			m_isInPacket = false;
			QByteArray toemit = m_currMsg;
			toemit.detach();
			emit newPacket(toemit);
			m_currMsg.clear();
		}
		else if (m_isInPacket)
		{
			if (m_isInEscape)
			{
				if (static_cast<unsigned char>(buffer.at(i)) == ESCAPE_START)
				{
					m_currMsg.append(START_BYTE);
				}
				else if (static_cast<unsigned char>(buffer.at(i)) == ESCAPE_ESCAPE)
				{
					m_currMsg.append(ESCAPE_BYTE);
				}
				else if (static_cast<unsigned char>(buffer.at(i)) == ESCAPE_STOP)
				{
					m_currMsg.append(STOP_BYTE);
				}
				else
				{
					//Bad escape character
					QLOG_DEBUG() << "Bad Escape char";
				}
				m_isInEscape = false;
			}
			else if (static_cast<unsigned char>(buffer.at(i)) == ESCAPE_BYTE)
			{
				m_isInEscape = true;
			}
			else
			{
				m_currMsg.append(buffer.at(i));
			}
		}
		else
		{
			//Out of packet bytes.
			QLOG_DEBUG() << "Out of packet bytes" << QString::number(buffer.at(i),16);
		}
	}
}
Example #15
0
void ReginaMain::newSnapPeaTriangulation() {
    newPacket(new NSnapPeaTriangulationCreator(this), 0,
        tr("New SnapPea Triangulation"));
}
Example #16
0
void FGLvar::V(void){
	// creates real vertex, stores location in cv 
	// links bv to cv with edge index e
	// distinguishes the new edge entry in the 
	// bv and cv edge look-up tables
	
// make sure base is OK
	if(isNull(bv)){
		varErr(32);
	}
// get space
	GLref ref;
	newPacket(ref,GLrv);
// set cv
	cv=ref;
// initialize the real vertex
	Ptr DEREF=this&cv;
	xPutPacketisGarbage(DEREF,TRUE);
	xPutPacketisIdeal(DEREF,FALSE);
	GLref NA=FGLink::NA;
	xPutPacketRef(GLir,DEREF,NA);
	xPutPacketRef(GLr,DEREF,NA);
	DEREF=&DEREF[2*sizeof(Boolean)+2*sizeof(GLref)];
	xUnsignedLongZeroInit(DEREF, IDactiveMax);
	this-cv;
// set up base as initial vertex
	DEREF=this&bv;
	Boolean isbvIdeal=xGetPacketisIdeal(DEREF);
	GLflag bflag;
	if(isbvIdeal){
		bflag=GLi;		//an ideal vertex always uses the ideal link
	}
	else {
		bflag=GLr;		//two real vertices use the real link
	}
// set up info for packetWrite.  The refDatum is garbage for this write
// because we don't know what to put here yet
	writePacketInfo info;
	info.flag=bflag;
	info.request=GLunusedOrNew;
	info.index=e;
	info.refDatum=bv;		// this is a "fake" value.  Any valid non null
							// address would do
	info.ownerVertexRef=bv;
	xGetPacketRef(info.entryPacketRef,bflag,DEREF);

	packetWrite(&info);
	GLref bpacketRef=info.exitPacketRef;
	long boffset=info.offset;
	xPutPacketRef(bflag,DEREF,bpacketRef);
	this-bv;
/*set up companion as terminal vertex*/
	GLflag cflag=bflag;
	if(bflag==GLi) cflag=GLir;  //a real vertex connected to an ideal vertex
						     //uses the ideal link of a real vertex
// set up info for packetWrite
	DEREF=this&cv;
	info.flag=cflag;
	info.request=GLunusedOrNew;
	info.index= -e;
	xPacketRefToOwnerRef(info.refDatum,bflag,bpacketRef);
	info.ownerVertexRef=cv;
	xGetPacketRef(info.entryPacketRef,cflag,DEREF);
	packetWrite(&info);
	GLref cpacketRef=info.exitPacketRef;
	xPutPacketRef(cflag,DEREF,cpacketRef);
// now we can set the datum in the base vertex packet
	GLref bDatum;
	xPacketRefToOwnerRef(bDatum,cflag,cpacketRef);
	this-cv;
	DEREF=this&bpacketRef;
	BlockMove((Ptr)&bDatum,&DEREF[boffset],sizeof(GLref));
	this-bpacketRef;
}
Example #17
0
void ReginaMain::newText() {
    newPacket(new BasicPacketCreator<regina::NText>(), 0,
        tr("New Text Packet"));
}
Example #18
0
void ReginaMain::newAngleStructures() {
    newPacket(new NAngleStructureCreator(),
        new SubclassFilter<regina::NTriangulation>(),
        tr("New Angle Structure Solutions"));
}
Example #19
0
void ReginaMain::newContainer() {
    newPacket(new BasicPacketCreator<regina::NContainer>(), 0,
        tr("New Container"));
}
Example #20
0
////////////////////////////////////////////////////
// This function decides the fate of the Everquest packet 
// and dispatches it to the correct packet stream for handling function
void EQPacket::dispatchPacket(int size, unsigned char *buffer)
{
#ifdef DEBUG_PACKET
  debug ("dispatchPacket()");
#endif /* DEBUG_PACKET */
  /* Setup variables */

  // Create an object to parse the packet
  EQUDPIPPacketFormat packet(buffer, size, false);

  // signal a new packet
  emit newPacket(packet);
  
  /* Chat and Login Server Packets, Discard for now */
  if ((packet.getDestPort() == ChatServerPort) ||
      (packet.getSourcePort() == ChatServerPort))
    return;

  if (((packet.getDestPort() >= LoginServerMinPort) &&
       (packet.getDestPort() <= LoginServerMaxPort)) ||
      (packet.getSourcePort() >= LoginServerMinPort) &&
      (packet.getSourcePort() <= LoginServerMaxPort))
    return;

  /* discard pure ack/req packets and non valid flags*/
  if (packet.flagsHi() < 0x02 || packet.flagsHi() > 0x46 || size < 10)
  {
#if defined(PACKET_PROCESS_DIAG)
    printf("discarding packet %s:%d ==>%s:%d flagsHi=%d size=%d\n",
	   (const char*)packet.getIPv4SourceA(), packet.getSourcePort(),
	   (const char*)packet.getIPv4DestA(), packet.getDestPort(),
	   packet.flagsHi(), size);
    printf("%s\n", (const char*)packet.headerFlags(false));
#endif
    return;    
  }

#if defined(PACKET_PROCESS_DIAG) && (PACKET_PROCESS_DIAG > 1)
  printf("%s\n", (const char*)packet.headerFlags((PACKET_PROCESS_DIAG < 3)));
  uint32_t crc = packet.calcCRC32();
  if (crc != packet.crc32())
    printf("CRC: Warning Packet seq = %d CRC (%08x) != calculated CRC (%08x)!\n",
	   packet.seq(), packet.crc32(), crc);
#endif
  
  if (!packet.isValid())
  {
    printf("INVALID PACKET: Bad CRC32 [%s:%d -> %s:%d] seq %04x len %d crc32 (%08x != %08x)\n",
	   (const char*)packet.getIPv4SourceA(), packet.getSourcePort(),
	   (const char*)packet.getIPv4DestA(), packet.getDestPort(),
	   packet.seq(), 
	   packet.payloadLength(),
	   packet.crc32(), packet.calcCRC32());
    return;
  }

  /* Client Detection */
  if (m_detectingClient && packet.getSourcePort() == WorldServerGeneralPort)
  {
    showeq_params->ip = packet.getIPv4DestA();
    m_client_addr = packet.getIPv4DestN();
    m_detectingClient = false;
    emit clientChanged(m_client_addr);
    printf("Client Detected: %s\n", (const char*)showeq_params->ip);
  }
  else if (m_detectingClient && packet.getDestPort() == WorldServerGeneralPort)
  {
    showeq_params->ip = packet.getIPv4SourceA();
    m_client_addr = packet.getIPv4SourceN();
    m_detectingClient = false;
    emit clientChanged(m_client_addr);
    printf("Client Detected: %s\n", (const char*)showeq_params->ip);
  }
  /* end client detection */



  if (packet.getSourcePort() == WorldServerChatPort)
  {
    dispatchWorldChatData(packet.payloadLength(), packet.payload(), DIR_SERVER);
    
    return;
  }
  else if (packet.getDestPort() == WorldServerChatPort)
  {
    dispatchWorldChatData(packet.payloadLength(), packet.payload(), DIR_CLIENT);
    
    return;
  }

  /* stream identification */
  if (packet.getIPv4SourceN() == m_client_addr)
  {
    if (packet.getDestPort() == WorldServerGeneralPort)
      m_client2WorldStream->handlePacket(packet);
    else 
      m_client2ZoneStream->handlePacket(packet);
  }
  else if (packet.getIPv4DestN() == m_client_addr)
  {
    if (packet.getSourcePort() == WorldServerGeneralPort)
      m_world2ClientStream->handlePacket(packet);
    else 
      m_zone2ClientStream->handlePacket(packet);
  }

  return;
} /* end dispatchPacket() */
Example #21
0
void ReginaMain::newDim4Triangulation() {
    newPacket(new Dim4TriangulationCreator(), 0,
        tr("New 4-Manifold Triangulation"));
}
Example #22
0
void ReginaMain::newFilter() {
    newPacket(new NSurfaceFilterCreator(), 0,
        tr("New Normal Surface Filter"));
}
Example #23
0
void ReginaMain::newNormalHypersurfaces() {
    newPacket(new NHypersurfaceCreator(),
        new SubclassFilter<regina::Dim4Triangulation>(),
        tr("New Normal Hypersurface List"));
}
Example #24
0
//-------------------------------------------------------------------------------------
bool BundleBroadcast::receive(MessageArgs* recvArgs, sockaddr_in* psin)
{
	if (!epListen_.good())
		return false;

	struct timeval tv;
	fd_set fds;
	
	int icount = 1;
	tv.tv_sec = 1;
	tv.tv_usec = 0;
	
	if(!pCurrPacket())
		newPacket();

	while (1)
	{
		FD_ZERO( &fds );
		FD_SET((int)epListen_, &fds);
		int selgot = select(epListen_+1, &fds, NULL, NULL, &tv);

		if (selgot == 0)
		{
			if(icount > 5)
			{
				DEBUG_MSG("BundleBroadcast::receive: is failed, the app will be terminated.\n", 
					icount, epListen_.addr().c_str());
				networkInterface_.mainDispatcher().breakProcessing();
				return false;
			}
			else
			{
				DEBUG_MSG("BundleBroadcast::receive: retries(%d), bind_addr(%s) ...\n", icount, epListen_.addr().c_str());
			}

			icount++;
			continue;
		}
		else if (selgot == -1)
		{
			ERROR_MSG("BundleBroadcast::receive: select error. %s.\n",
					kbe_strerror());
			return false;
		}
		else
		{
			sockaddr_in	sin;
			pCurrPacket()->resetPacket();
			
			if(psin == NULL)
				psin = &sin;

			int len = epListen_.recvfrom(pCurrPacket()->data(), recvWindowSize_, *psin);
			if (len == -1)
			{
				ERROR_MSG("BundleBroadcast::receive: recvfrom error. %s.\n",
						kbe_strerror());
				continue;
			}
			
			DEBUG_MSG("BundleBroadcast::receive: from %s, datalen=%d.\n", inet_ntoa((struct in_addr&)psin->sin_addr.s_addr), len);
			pCurrPacket()->wpos(len);
			if(recvArgs != NULL)
				recvArgs->createFromStream(*pCurrPacket());
			break;

		}
	}
	
	return true;
}
Example #25
0
void ReginaMain::newScript() {
    newPacket(new BasicPacketCreator<regina::NScript>(), 0,
        tr("New Script"));
}
Example #26
0
/* Send the configuration file to the controller. */
static int pushConfigFile(char *filename, char *ip, char *port,
									char *id, int type){

	struct sockaddr_in address;
	int sd = -1;
	int fd = -1;
	uint8_t *data = NULL;
	int count = -1;
	int offset = -1;
	uint8_t *packet = NULL;
	char *newid = NULL;
	char *dbstatus = NULL;


	if(filename == NULL || ip == NULL || port == NULL ||
									id == NULL){
		#if DEBUG == 1
			fprintf(stderr, "pushConfigFile :: Argument Error\n");
		#endif
		return ERR;
	}

	newid = (char *)malloc(strlen(id) + 2);
	strcpy(newid, id);
	strcat(newid, "\n");
	
	address.sin_family = AF_INET;
	address.sin_port = htons(atoi(CONTROLLER_NORTH_PORT));



	/* Ask the db daemon, were to find the corresponding 
	 * users connection. */
	dbstatus = libDbGet(tablename, id, ip, port);		

	#if DEBUG == 1 
		fprintf(stderr, "pushConfigFile :: Found controller : %s\n",
													dbstatus);
	#endif

	if(!strlen(dbstatus)){
		/* We could not find an entry for this in the DB,
		 * gracefully fail. */
		return ERR;
	}

	inet_aton(dbstatus, &address.sin_addr);
	sd = socket(AF_INET, SOCK_STREAM, 0);

	/* Try establishing a connection to the controller. */
	if(connect(sd, (struct sockaddr*)&address,
					 sizeof(struct sockaddr_in)) < 0){

		#if DEBUG == 1
			fprintf(stderr, "pushConfigFile :: %s\n", strerror(errno));
		#endif
		return ERR;
	}

	if((fd = open(filename, O_RDONLY)) < 0){
		#if DEBUG == 1
			fprintf(stderr, "pushConfigFile :: %s\n", strerror(errno));
		#endif
		return ERR;	
	}

	data = (uint8_t *)malloc(1024);		
	offset = 0;
	while((count = read(fd, data + offset, 1024)) > 0){
		offset += count;
		data = (uint8_t *)realloc(data, offset + 1024);
	}
	close(fd);
	
	/* Send this over to be turned into a packet. */
	packet = newPacket(type, data, offset);		
	free(data);
	
	write(sd, newid, strlen(newid));

	/* Write the packet after this to the socket. */
	write(sd, packet, ((struct Packet *)packet)->len);

	close(sd);
	free(packet);
	free(newid);
	free(dbstatus);

	return 0;
}
Example #27
0
//-------------------------------------------------------------------------------------
bool BundleBroadcast::receive(MessageArgs* recvArgs, sockaddr_in* psin, int32 timeout, bool showerr)
{
	if (!epListen_.good())
		return false;

	struct timeval tv;
	fd_set fds;
	
	int icount = 1;
	tv.tv_sec = 0;
	tv.tv_usec = timeout;
	
	if(!pCurrPacket())
		newPacket();

	while (1)
	{
		FD_ZERO( &fds );
		FD_SET((int)epListen_, &fds);
		int selgot = select(epListen_+1, &fds, NULL, NULL, &tv);

		if (selgot == 0)
		{
			if(icount > itry_)
			{
				if(showerr)
				{
					ERROR_MSG("BundleBroadcast::receive: is failed(please check {firewall rule => broadcastaddr not is LAN ?})!\n");
				}
				
				return false;
			}
			else
			{
				//DEBUG_MSG(fmt::format("BundleBroadcast::receive: retries({}), bind_addr({}) ...\n", 
				//	icount, epListen_.addr()));
			}

			icount++;
			continue;
		}
		else if (selgot == -1)
		{
			if(showerr)
			{
				ERROR_MSG(fmt::format("BundleBroadcast::receive: select error. {}.\n",
						kbe_strerror()));
			}
			return false;
		}
		else
		{
			sockaddr_in	sin;
			pCurrPacket()->resetPacket();
			
			if(psin == NULL)
				psin = &sin;

			pCurrPacket()->data_resize(recvWindowSize_);

			int len = epListen_.recvfrom(pCurrPacket()->data(), recvWindowSize_, *psin);
			if (len == -1)
			{
				if(showerr)
				{
					ERROR_MSG(fmt::format("BundleBroadcast::receive: recvfrom error. {}.\n",
							kbe_strerror()));
				}
				continue;
			}
			
			//DEBUG_MSG(fmt::format("BundleBroadcast::receive: from {}, datalen={}.\n", 
			//	inet_ntoa((struct in_addr&)psin->sin_addr.s_addr), len));

			pCurrPacket()->wpos(len);

			if(recvArgs != NULL)
			{
				try
				{
					recvArgs->createFromStream(*pCurrPacket());
				}catch(MemoryStreamException &)
				{
					ERROR_MSG(fmt::format("BundleBroadcast::receive: data is error. size={}.\n",
							len));

					continue;
				}
			}

			break;

		}
	}
	
	return true;
}