Ejemplo n.º 1
0
void IpcServer::testCaseShutdownOnRequest()
{
    LOG4CPLUS_TRACE_METHOD(mLogger, __PRETTY_FUNCTION__);
    mIpc->beginWaitForConnection();
    for (int i = 0; i < mClientsNumber; i++)
    {
        mConnectionSema.wait();
    }
    mIpc->endWaitForConnection();
    assert (mIpc->isConnected());
    assert (mClients.size() == mClientsNumber);
    LOG4CPLUS_INFO(mLogger, "Established connection with all expected clients: " + convertIntegerToString(mClientsNumber));
    if (mClientsNumber == 1)
    {
        sendPing();
        sendKill();
    }
    else
    {
        for (int i = 0; i < mClientsNumber; i++)
        {
            sendPing(&mClients.at(i));
        }
        for (int i = 0; i < mClientsNumber; i++)
        {
            sendKill(&mClients.at(i));
        }

    }
    LOG4CPLUS_INFO(mLogger, "Test passed successfully!");
}
Ejemplo n.º 2
0
void GGWrapper::enterLoop()
{
    while(!mWorkerThread.interruption_requested())
    {
        boost::any item = mpQueue->poll();
        if(item.empty())
        {
            //Logger::log("Looping\r\n");
            gg_event *event = pollGGEvent();
            if(event != 0)
            {
                processGGEvent(*event);
                gg_free_event(event);
            }
        }
        else
        {
            processEvent(boost::any_cast<ggEvent&>(item));
        }

        sendPing();

    }
    Logger::log("Finished Looping!");
    //probably here some cleaning or just do everything in destructor;
}
//-----------------------------------------------------------------------------
int IoHandler::openComPort(const QString &portName)
{
	unsigned int baudrate;

	// Determine baudrate; the MSP430 Virtual UART only supports 9600
	baudrate= portName.contains("MSP430 Application UART") ? 9600: 38400;

    if (comPort->Open(portName,baudrate))
    {
        if (comPort->Read())
        {
            // Check that the connection is established with a ping.
            // Start a one shot timer to check if ping response has been received.
            sendPing();
            pingAnswered = false; 
            QTimer::singleShot(TIMER_PING, this, SLOT(checkPing()));
            return IO_SUCCESS;
        }
        else
        {
            return IO_ERROR;
        }
    }
    else
    {
        return IO_ERROR;
    }
}
void Transmitter::enableAutoPing(bool enable)
{

  if (!enable) {
	// Disable autopinging, if running

	if (autoPing) {
	  autoPing->stop();
	  delete autoPing;
	  autoPing = NULL;
	  return;
	}
  }
  
  // Start autopinging, if not not running already
  if (autoPing) {
	return;
  }

  autoPing = new QTimer();

  // Send ping every second (sending a high priority package restarts the timer)
  connect(autoPing, SIGNAL(timeout()), this, SLOT(sendPing()));
  autoPing->start(1000);
}
Ejemplo n.º 5
0
tlen::tlen( QObject* parent ): QObject( parent ) {
	state = tlen::Disconnected;

	hostname = "s1.tlen.pl";
	hostport = 443;
	Secure = false;
	Reconnect = false;

	Status= tlen::unavailable;
	Descr="";

	tmpDoc=new QDomDocument;

	socket=new QTcpSocket();
	ping=new QTimer();

	connect(socket, SIGNAL(connected()), this, SLOT(socketConnected()));
	connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead()));
	connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));

	connect(this, SIGNAL(tlenLoggedIn()), this, SLOT(writeStatus()));
	connect(this, SIGNAL(statusUpdate()), this, SLOT(writeStatus()));

	connect(this, SIGNAL(eventReceived(QDomNode)), this, SLOT(event(QDomNode)));

	connect(ping, SIGNAL(timeout()), this, SLOT(sendPing()));
	srand(time(NULL));
}
Ejemplo n.º 6
0
WSMessageRequest TembooMessaging::poll() {
	startMessaging();
	long int now = millis();
	WSMessageRequest rc = WS_NO_MESSAGE;
	while (millis() - now < POLL_TIMEOUT) {
		if (millis() - m_lastPingTime >= MCU_PING_PERIOD_MS) {
            m_lastPingTime = millis();
            sendPing();
        }
    	if (Mailbox.messageAvailable()) {
    		uint8_t msg[MAX_MAILBOX_MESSAGE_SIZE] = {0};
    		int recvLen = Mailbox.readMessage(msg, MAX_MAILBOX_MESSAGE_SIZE);
    		if (recvLen > 0) {
	    		rc = handleResponse(msg, m_sensorTable, m_sensorTableDepth, m_connectionStatus);
	    		if (rc == WS_UPDATE_CONNECTED) {
	    			//logTembooDebug("Connected to Temboo");
	    			m_connectionStatus = true;
	    		} else if (rc == WS_UPDATE_DISCONNECTED) {
	    			//logTembooDebug("Disconnected from Temboo");
	    			m_connectionStatus = false;
	    		} else if (rc == WS_REQUEST_ERROR) {
	    			// disconnect
	    			sendError("Message request error");
	    		}
	    	}
    	}
    }
    return rc;
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------
//
void CommonTimeBase::_update(ofEventArgs &e)
{
	int currentLocalMillis = getInternalTimeMillis();
	
	if( (currentLocalMillis-lastPingSentTimeMillis) > millisBetweenPings )
	{
		sendPing();
		lastPingSentTimeMillis = currentLocalMillis;
	}
	
	// Ease the timing offset if this is activated
	if( easeOffset )
	{
		if( offsetMillis != offsetMillisTarget )
		{
			float tmpDiff = (offsetMillisTarget-offsetMillis)/10.0;
			if( fabsf(tmpDiff) < 1.0f )
			{
				offsetMillis = offsetMillisTarget;
			}
			else
			{
				offsetMillis += tmpDiff;
			}
		}
	}
	else
	{
		offsetMillis = offsetMillisTarget;
	}
}
void sig_alrm (int signo){
	if(isTourOver == 0){
		sendPing();
		alarm(1);
	}
	return;
}
Ejemplo n.º 9
0
/**
 * This callback is triggered when the service receives a job.
 * The job can be addressed to this service or to another service.
 */
void JobHandler::notifyMessage(const JobInfo *job)
{
	xlog::trace(className, "notifyMessage");

	if (! job)
	{
		xlog::warn(className, "notifyMessage", "empty message");
		return;
	}

	if (job->jobID == BroadcastStartupID)
	{ 	// sent on master start
		xlog::debug(className, "notifyMessage", "master started");
		sendPing();
		m_ignoreBroadcast = false;
	}
	else if (job->jobID == BroadcastID)
	{ 	// broadcast from the master
		if (! m_ignoreBroadcast)
		{
			sendPing();
			xlog::debug(className, "notifyMessage", "replied to broadcast");
			m_ignoreBroadcast = true;
		}
		else
		{
			xlog::debug(className, "notifyMessage", "broadcast ignored");
			m_broadcastCounter++;
			if (m_broadcastCounter > MaxBroadcastNumber)
			{
				m_ignoreBroadcast = false;
				m_broadcastCounter= 0;
			}
		}
	}
	else if (m_serviceId == job->handlerID)
	{ 	// if the current instructions are for this processor, launch the process
		m_available = false;
		handle(job);
		m_available = true;
		m_ignoreBroadcast = false;
	}
	else
	{	// job for another service
		xlog::debug(className, "notifyMessage", ("message to "+job->handlerID).c_str());
	}
}
Ejemplo n.º 10
0
int main ()
{
    std::string addr = "10.1.15.8";
    int port = 5810;
    udp_client_server::udp_client client (addr, port);
    sendPing(client);
    return 0;
}
Ejemplo n.º 11
0
NetworkMonitor::NetworkMonitor( int listenPort, int sendPort )
{
	this->listenPort = listenPort;
	this->sendPort = sendPort;
	connect( &socket, SIGNAL(readyRead()), this, SLOT( processPendingDatagrams() ) );
	connect( &pingTimer, SIGNAL( timeout() ), this, SLOT( sendPing() ) );
	createPing( );
}
Ejemplo n.º 12
0
double
GetTime ()
{
   struct timeval tp;
   (void) gettimeofday( &tp, NULL );
   sendPing ();
   return (tp.tv_sec + ((double) tp.tv_usec)/1000000.0);
}
Ejemplo n.º 13
0
Client::Client(QTcpSocket *socket, FenPrincipale *parent) : m_parent(parent), m_socket(socket), m_taillePaquet(0), m_pseudo(""), m_account(""), m_loginLevel(0),
m_idCompte(0), m_logoutMessage(""), m_sessionState(NOT_CHECKED), m_channel(0), m_pingsPending(0), m_ping(0)

{
    connect(m_socket, SIGNAL(readyRead()), this, SLOT(donneesRecues()));
    connect(m_socket, SIGNAL(disconnected()), this, SLOT(deconnexion()));

    //Création du timer pour le lancement des pings.
    m_pingTimer = new QTimer(this);
    connect(m_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
    m_pingTimer->start(m_parent->getPingInterval());
    sendPing(); //On lance un ping

    //Génération du hash de l'IP.
    //4 caractères hexa.
    m_hashIP = QCryptographicHash::hash(m_socket->peerAddress().toString().toUtf8(),
                                        QCryptographicHash::Md5).toHex().left(4);
}
Ejemplo n.º 14
0
void sJarvisNode::ping()
{
    sendPing();
    qDebug() << "KeepATimer:" <<m_keepAliveTimer.elapsed();
    if(m_keepAliveTimer.elapsed() > 25000)
    {
        emit rawInput("Timeout, Disconnected!");
        this->closeTCP();
    }
}
Ejemplo n.º 15
0
KegMeterConnection::KegMeterConnection(MainWindow* mainWindow, QObject* parent) :
    QTcpSocket(parent),
    mainWindow(mainWindow) {

    assert(mainWindow != NULL);

    QObject::connect(this, SIGNAL(readyRead()), this, SLOT(processReadyRead()));
    QObject::connect(this, SIGNAL(disconnected()), &this->pingTimer, SLOT(stop()));
    QObject::connect(&this->pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
    QObject::connect(this, SIGNAL(connected()), this, SLOT(onConnected()));
}
Ejemplo n.º 16
0
// Incoming message which has passed through the cryptoauth and needs to be forwarded to the switch.
static Iface_DEFUN receivedPostCryptoAuth(struct Message* msg,
                                          struct Peer* ep,
                                          struct InterfaceController_pvt* ic)
{
    ep->bytesIn += msg->length;

    int caState = CryptoAuth_getState(ep->caSession);
    if (ep->state < InterfaceController_PeerState_ESTABLISHED) {
        // EP states track CryptoAuth states...
        ep->state = caState;
        SwitchCore_setInterfaceState(&ep->switchIf, SwitchCore_setInterfaceState_ifaceState_UP);

        Bits_memcpy(ep->addr.key, ep->caSession->herPublicKey, 32);
        Address_getPrefix(&ep->addr);

        if (caState == CryptoAuth_ESTABLISHED) {
            moveEndpointIfNeeded(ep);
            //sendPeer(0xffffffff, PFChan_Core_PEER, ep);// version is not known at this point.
        } else {
            // prevent some kinds of nasty things which could be done with packet replay.
            // This is checking the message switch header and will drop it unless the label
            // directs it to *this* router.
            if (msg->length < 8 || msg->bytes[7] != 1) {
                Log_info(ic->logger, "DROP message because CA is not established.");
                return 0;
            } else {
                // When a "server" gets a new connection from a "client" the router doesn't
                // know about that client so if the client sends a packet to the server, the
                // server will be unable to handle it until the client has sent inter-router
                // communication to the server. Here we will ping the client so when the
                // server gets the ping response, it will insert the client into its table
                // and know its version.

                // prevent DoS by limiting the number of times this can be called per second
                // limit it to 7, this will affect innocent packets but it doesn't matter much
                // since this is mostly just an optimization and for keeping the tests happy.
                if ((ep->pingCount + 1) % 7) {
                    sendPing(ep);
                }
            }
        }
    } else if (ep->state == InterfaceController_PeerState_UNRESPONSIVE
        && caState == CryptoAuth_ESTABLISHED)
    {
        ep->state = InterfaceController_PeerState_ESTABLISHED;
        SwitchCore_setInterfaceState(&ep->switchIf, SwitchCore_setInterfaceState_ifaceState_UP);
    } else {
        ep->timeOfLastMessage = Time_currentTimeMilliseconds(ic->eventBase);
    }

    Identity_check(ep);
    Assert_true(!(msg->capacity % 4));
    return Iface_next(&ep->switchIf, msg);
}
Ejemplo n.º 17
0
// Incoming message which has passed through the cryptoauth and needs to be forwarded to the switch.
static uint8_t receivedAfterCryptoAuth(struct Message* msg, struct Interface* cryptoAuthIf)
{
    struct InterfaceController_Peer* ep =
        Identity_check((struct InterfaceController_Peer*) cryptoAuthIf->receiverContext);
    struct InterfaceController_pvt* ic = ifcontrollerForPeer(ep);

    // nonce added by the CryptoAuth session.
    Message_pop(msg, NULL, 4, NULL);

    ep->bytesIn += msg->length;

    int caState = CryptoAuth_getState(cryptoAuthIf);
    if (ep->state < InterfaceController_PeerState_ESTABLISHED) {
        // EP states track CryptoAuth states...
        ep->state = caState;
        if (caState == CryptoAuth_ESTABLISHED) {
            moveEndpointIfNeeded(ep, ic);
        } else {
            // prevent some kinds of nasty things which could be done with packet replay.
            // This is checking the message switch header and will drop it unless the label
            // directs it to *this* router.
            if (msg->length < 8 || msg->bytes[7] != 1) {
                Log_info(ic->logger, "DROP message because CA is not established.");
                return Error_NONE;
            } else {
                // When a "server" gets a new connection from a "client" the router doesn't
                // know about that client so if the client sends a packet to the server, the
                // server will be unable to handle it until the client has sent inter-router
                // communication to the server. Here we will ping the client so when the
                // server gets the ping response, it will insert the client into its table
                // and know its version.

                // prevent DoS by limiting the number of times this can be called per second
                // limit it to 7, this will affect innocent packets but it doesn't matter much
                // since this is mostly just an optimization and for keeping the tests happy.
                if ((ep->pingCount + 1) % 7) {
                    sendPing(ep);
                }
            }
        }
    } else if (ep->state == InterfaceController_PeerState_UNRESPONSIVE
        && caState == CryptoAuth_ESTABLISHED)
    {
        ep->state = InterfaceController_PeerState_ESTABLISHED;
    } else {
        ep->timeOfLastMessage = Time_currentTimeMilliseconds(ic->eventBase);
    }

    Identity_check(ep);
    Assert_true(!(msg->capacity % 4));
    return Interface_receiveMessage(&ep->switchIf, msg);
}
Ejemplo n.º 18
0
/**
 * Enter the receive loop
 */
void JobHandler::plug()
{
	xlog::trace(className, "plug");

	sendPing();
	while (true)
	{
		if (m_dispatchChannel.waitForMessageWithTimeout(ReadRetryInterval))
		{	// messages published
			m_dispatchChannel.handleMessages();
		}
	}
}
Ejemplo n.º 19
0
/**
 * @brief ToolPing::ping plays the ping animation at the given position
 * @param pos position to play the animation at
 */
void ToolPing::ping(QPointF pos){
    if(!m_Pinging){
        emit sendPing(pos);

        QRectF rect(pos, QSizeF(32, 32));
        rect.moveCenter(pos);

        m_Proxy->setGeometry(rect);
        m_Movie->start();
        m_Proxy->show();
        m_Pinging = true;
        startTimer(1000);
    }
}
Ejemplo n.º 20
0
// ////////////////////////////////////////////////////////////////////////////
// Droid checking info. keep position and damage in sync.
BOOL sendCheck(void)
{
	UDWORD i;

	NETgetBytesSent();			// update stats.
	NETgetBytesRecvd();
	NETgetPacketsSent();
	NETgetPacketsRecvd();

	// dont send checks till all players are present.
	for(i=0;i<MAX_PLAYERS;i++)
	{
		if(isHumanPlayer(i) && ingame.JoiningInProgress[i])
		{
			return true;
		}
	}

	// send Checks. note each send has it's own send criteria, so might not send anything.
	// Priority is droids -> structures -> power -> score -> ping

	sendDroidCheck();
	sync_counter.sentDroidCheck++;
	sendStructureCheck();
	sync_counter.sentStructureCheck++;
	sendPowerCheck();
	sync_counter.sentPowerCheck++;
	if(okToSend())
	{
		sendScoreCheck();
		sync_counter.sentScoreCheck++;
	}
	else
	{
		sync_counter.unsentScoreCheck++;
	}
	if(okToSend())
	{
		sendPing();
		sync_counter.sentPing++;
	}
	else
	{
		sync_counter.unsentPing++;
	}

	return true;
}
Ejemplo n.º 21
0
MrimConnection::MrimConnection(MrimAccount *account) : p(new MrimConnectionPrivate(account))
{    
    connect(p->SrvReqSocket(),SIGNAL(connected()),this,SLOT(connected()));
    connect(p->SrvReqSocket(),SIGNAL(disconnected()),this,SLOT(disconnected()));
    connect(p->SrvReqSocket(),SIGNAL(readyRead()),this,SLOT(readyRead()));
    connect(p->IMSocket(),SIGNAL(connected()),this,SLOT(connected()));
    connect(p->IMSocket(),SIGNAL(disconnected()),this,SLOT(disconnected()));
    connect(p->IMSocket(),SIGNAL(readyRead()),this,SLOT(readyRead()));
    connect(p->ReadyReadTimer(),SIGNAL(timeout()),this,SLOT(readyRead()));
    connect(p->pingTimer.data(),SIGNAL(timeout()),this,SLOT(sendPing()));
    registerPacketHandler(this);
    MrimUserAgent qutimAgent(QApplication::applicationName(),QApplication::applicationVersion(),
							 "(git)",PROTO_VERSION_MAJOR,PROTO_VERSION_MINOR); //TODO: real build version
    p->selfID = qutimAgent;
    p->messages = new MrimMessages(this);
	registerPacketHandler(p->messages);
}
Ejemplo n.º 22
0
Connection::Connection(QObject *parent) :
    QTcpSocket(parent)
{
    greetingMessage = tr("undefined");
    username = tr("unknown");
    state = WaitingForGreeting;
    currentDataType = Undefined;
    numBytesForCurrentDataType = -1;
    transferTimerId = 0;
    isGreetingMessageSent = false;
    pingTimer.setInterval(PingInterval);

    QObject::connect(this, SIGNAL(readyRead()), this, SLOT(processReadyRead()));
    QObject::connect(this, SIGNAL(disconnected()), &pingTimer, SLOT(stop()));
    QObject::connect(&pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
    QObject::connect(this, SIGNAL(connected()), this, SLOT(sendGreetingMessage()));
}
Ejemplo n.º 23
0
/********************************************************************
  Update sends a keep alive ping and connects / reconnects to slack


********************************************************************/ 
void ArduinoSlackBot::update(){
 
  webSocket.loop();

  if (connected) {
    // Send ping every 5 seconds, to keep the connection alive
    if (millis() - lastPing > 5000) {
      sendPing();
      lastPing = millis();
    }
  } else {
    // Try to connect / reconnect to slack
    connected = connect();
    if (!connected) {
      delay(500);
    }
  }
}
Ejemplo n.º 24
0
int
main(int argc, char *argv[])
{
    motor_t rightMotor = {
        &PORTB, &DDRB, PORTB7, // PWM
        &PORTC, &DDRC, PORTC1, // Direction
        &OCR0A                 // Top value
    };
    
    motor_t leftMotor = {
        &PORTD, &DDRD, PORTD0, // PWM
        &PORTB, &DDRB, PORTB0, // Direction
        &OCR0B                 // Top value
    };
    
    //uint8_t sonarDistance = 0;
    
    cli();
    NO_CLK_PRESCALE();
    //uart_init();
    radio_init(HOV1_ADDRESS, RECEIVE_MODE);
    sonar_init();
    motorInit(&rightMotor);
    motorInit(&leftMotor);
    pwmInit();
    sei();
    
	stop = Event_Init();

    sendPing();
    while(!receivedInit);

    Task_Create((void*)(&motor_task),0, PERIODIC, MOTOR);
    Task_Create((void*)(&fire_sonar),0, PERIODIC, FIRE);
    Task_Create((void*)(&listen_sonar),0,PERIODIC, LISTEN);
    Task_Create((void*)(&sendRadio),0,PERIODIC, RADIO);
	Task_Create((void*)(&stopSystem), 0,SYSTEM, STOP); 
   
    setMotorDirection(&rightMotor, FORWARD);
    setMotorDirection(&leftMotor, FORWARD);
    
    return 0;
}
Ejemplo n.º 25
0
void MainWindow::OnPingTimer(wxTimerEvent & event)
{


	if (! (executing_request || awaiting_input))
	{

		DRUID::SerialUIUserPtr serial_user = connection->serialUser();
		DRUIDString inbufStr = serial_user->getAndClearBufferedMessage();
		if (inbufStr.size())
		{
			DRUID_DEBUG2("******** PING appending buffer: ", inbufStr);

			outputTextCtrl->AppendText(DRUID_STDSTRING_TOWX(inbufStr));
		}

		if (serial_user->messageReceived())
		{
			inbufStr = serial_user->lastMessage();
			if (inbufStr.size())
			{
				serial_user->lastMessageClear();
				DRUID_DEBUG2("******** PING appending lastMessage: ", inbufStr);

				outputTextCtrl->AppendText(DRUID_STDSTRING_TOWX(inbufStr));
			}
		}

		time_t time_now = time(NULL);

		int ping_interval = (tracking_interval_seconds == TRACKING_PERIOD_DISABLED) ? TRACKING_PERIOD_STANDARD : tracking_interval_seconds;
		if (time_now - last_interaction >= ping_interval)
		{
			sendPing(serial_user);
			last_interaction = time_now;

		}

	}

}
Ejemplo n.º 26
0
/*
 * Handles the ping processing for a channel.  Sends a ping to the
 * server if the next send ping time has arrived and checks if a
 * ping has been received from the server within the next receive
 * ping time.
 * chnl - The channel to handle pings for
 */
static void handlePings(RsslChannel* chnl)
{
	time_t currentTime = 0;

	/* get current time */
	time(&currentTime);

	/* handle client pings */
	if (currentTime >= nextSendPingTime)
	{
		/* send ping to server */
		if (sendPing(chnl) != RSSL_RET_SUCCESS)
		{
			cleanUpAndExit();
		}

		/* set time to send next ping from client */
		nextSendPingTime = currentTime + (time_t)pingTimeoutClient;
	}

	/* handle server pings */
	if (currentTime >= nextReceivePingTime)
	{
		/* check if client received message from server since last time */
		if (receivedServerMsg)
		{
			/* reset flag for server message received */
			receivedServerMsg = RSSL_FALSE;

			/* set time client should receive next message/ping from server */
			nextReceivePingTime = currentTime + (time_t)pingTimeoutServer;
		}
		else /* lost contact with server */
		{
			printf("\nLost contact with server...\n");
			cleanUpAndExit();
		}
	}
}
Ejemplo n.º 27
0
CClient::CClient(QWidget *parent, const QString &address, const QString &nick) :
        m_address(address), m_nick(nick)
{
    m_gameBoard = new CGameBoard(this, QPoint(10, 10), QSize(630, 510));
    m_gameBoard->setNick(nick.toStdString());

    m_chatBox = new QTextEdit(this);
    m_chatBox->setReadOnly(true);
    m_chatBox->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    m_chatBox->move(QPoint(10, 530));
    m_chatBox->resize(QSize(530, 100));

    m_message = new QLineEdit(this);
    m_message->move(QPoint(10, 640));
    m_message->resize(QSize(420, 20));
    m_message->installEventFilter(this);

    m_btn_send = new QPushButton(this);
    m_btn_send->setText(tr("Send"));
    m_btn_send->move(QPoint(440, 640));
    m_btn_send->resize(QSize(100, 20));

    m_lst_users = new QListWidget(this);
    m_lst_users->move(QPoint(550, 530));
    m_lst_users->resize(QSize(90, 100));

    m_socket = new QTcpSocket();
    m_gameBoard->setSocket(m_socket);

    m_pingTimer = new QTimer(this);
    m_pingTimer->start(PingSendingTime);

    QObject::connect(m_btn_send, SIGNAL(clicked()), this, SLOT(sendMessage()));
    QObject::connect(m_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));

    setFixedSize(650, 680);
    connectToServer();
}
Ejemplo n.º 28
0
 jbool JConnection::isDead(){
     jbool isDead=false;
     jint oldTimeout=socket->getSoTimeout();
     try{
         sendPing();
         if (connections==NULL){
             socket->setSoTimeout(transport->getTransportConfiguration()->getPingTimeout()->get());
         } else {
             socket->setSoTimeout(connections->getTransport()->getTransportConfiguration()->getPingTimeout()->get());
         }
         if (!readOk()) {
             isDead = true;
         }
     }catch(JIOException* e){
         delete e;
         isDead=true;
     }
     if (isDead && !socket->isClosed()){
         socket->close();
     }
     socket->setSoTimeout(oldTimeout);
     return isDead;
 }
Ejemplo n.º 29
0
/**
 * Check the table for nodes which might need to be pinged, ping a node if necessary.
 * If a node has not responded in unresponsiveAfterMilliseconds then mark them as unresponsive
 * and if the connection is incoming and the node has not responded in forgetAfterMilliseconds
 * then drop them entirely.
 * This is called every PING_INTERVAL_MILLISECONDS but pingCallback is a misleading name.
 */
static void pingCallback(void* vic)
{
    struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) vic);
    if (!ic->peerMap.count) { return; }

    uint64_t now = Time_currentTimeMilliseconds(ic->eventBase);

    // scan for endpoints have not sent anything recently.
    uint32_t startAt = Random_uint32(ic->rand) % ic->peerMap.count;
    for (uint32_t i = startAt, count = 0; (!count || i != startAt) && count <= ic->peerMap.count;) {
        i = (i + 1) % ic->peerMap.count;
        count++;

        struct InterfaceController_Peer* ep = ic->peerMap.values[i];

        if (now < ep->timeOfLastMessage + ic->pingAfterMilliseconds) {
            if (now < ep->timeOfLastPing + ic->pingAfterMilliseconds) {
                // Possibly an out-of-date node which is mangling packets, don't ping too often
                // because it causes the RumorMill to be filled with this node over and over.
                continue;
            }

            struct Node_Link* link = Router_linkForPath(ic->router, ep->switchLabel);
            // It exists, it's parent is the self-node, and it's label is equal to the switchLabel.
            if (link
                && Node_getBestParent(link->child)
                && Node_getBestParent(link->child)->parent->address.path == 1
                && Node_getBestParent(link->child)->cannonicalLabel == ep->switchLabel)
            {
                continue;
            }
        }

        #ifdef Log_DEBUG
              uint8_t key[56];
              Base32_encode(key, 56, CryptoAuth_getHerPublicKey(ep->cryptoAuthIf), 32);
        #endif

        if (ep->isIncomingConnection
            && now > ep->timeOfLastMessage + ic->forgetAfterMilliseconds)
        {
            Log_debug(ic->logger, "Unresponsive peer [%s.k] has not responded in [%u] "
                                  "seconds, dropping connection",
                                  key, ic->forgetAfterMilliseconds / 1024);
            Allocator_free(ep->external->allocator);
            continue;
        }

        bool unresponsive = (now > ep->timeOfLastMessage + ic->unresponsiveAfterMilliseconds);
        if (unresponsive) {
            // our link to the peer is broken...
            Router_disconnectedPeer(ic->router, ep->switchLabel);

            // Lets skip 87% of pings when they're really down.
            if (ep->pingCount % 8) {
                ep->pingCount++;
                continue;
            }

            ep->state = InterfaceController_PeerState_UNRESPONSIVE;
        }

        #ifdef Log_DEBUG
            uint32_t lag = (now - ep->timeOfLastMessage) / 1024;
            Log_debug(ic->logger,
                      "Pinging %s peer [%s.k] lag [%u]",
                      (unresponsive ? "unresponsive" : "lazy"), key, lag);
        #endif

        sendPing(ep);

        // we only ping one node
        return;
    }
}
Ejemplo n.º 30
0
int InterfaceController_bootstrapPeer(struct InterfaceController* ifc,
                                      int interfaceNumber,
                                      uint8_t* herPublicKey,
                                      const struct Sockaddr* lladdrParm,
                                      String* password,
                                      String* login,
                                      String* user,
                                      struct Allocator* alloc)
{
    struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);

    Assert_true(herPublicKey);
    Assert_true(password);

    struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, interfaceNumber);

    if (!ici) {
        return InterfaceController_bootstrapPeer_BAD_IFNUM;
    }

    Log_debug(ic->logger, "bootstrapPeer total [%u]", ici->peerMap.count);

    uint8_t ip6[16];
    AddressCalc_addressForPublicKey(ip6, herPublicKey);
    if (!AddressCalc_validAddress(ip6) || !Bits_memcmp(ic->ca->publicKey, herPublicKey, 32)) {
        return InterfaceController_bootstrapPeer_BAD_KEY;
    }

    struct Allocator* epAlloc = Allocator_child(ici->alloc);

    struct Sockaddr* lladdr = Sockaddr_clone(lladdrParm, epAlloc);

    // TODO(cjd): eps are created in 3 places, there should be a factory function.
    struct Peer* ep = Allocator_calloc(epAlloc, sizeof(struct Peer), 1);
    int index = Map_EndpointsBySockaddr_put(&lladdr, &ep, &ici->peerMap);
    Assert_true(index >= 0);
    ep->alloc = epAlloc;
    ep->handle = ici->peerMap.handles[index];
    ep->lladdr = lladdr;
    ep->ici = ici;
    ep->isIncomingConnection = false;
    Bits_memcpy(ep->addr.key, herPublicKey, 32);
    Address_getPrefix(&ep->addr);
    Identity_set(ep);
    Allocator_onFree(epAlloc, closeInterface, ep);
    Allocator_onFree(alloc, freeAlloc, epAlloc);

    ep->peerLink = PeerLink_new(ic->eventBase, epAlloc);
    ep->caSession = CryptoAuth_newSession(ic->ca, epAlloc, herPublicKey, false, "outer");
    CryptoAuth_setAuth(password, login, ep->caSession);
    if (user) {
        ep->caSession->displayName = String_clone(user, epAlloc);
    }

    ep->switchIf.send = sendFromSwitch;

    if (SwitchCore_addInterface(ic->switchCore, &ep->switchIf, epAlloc, &ep->addr.path)) {
        Log_debug(ic->logger, "bootstrapPeer() SwitchCore out of space");
        Allocator_free(epAlloc);
        return InterfaceController_bootstrapPeer_OUT_OF_SPACE;
    }

    // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
    // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
    // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
    ep->timeOfLastMessage =
        Time_currentTimeMilliseconds(ic->eventBase) - ic->pingAfterMilliseconds - 1;

    if (Defined(Log_INFO)) {
        struct Allocator* tempAlloc = Allocator_child(alloc);
        String* addrStr = Address_toString(&ep->addr, tempAlloc);
        Log_info(ic->logger, "Adding peer [%s] from bootstrapPeer()", addrStr->bytes);
        Allocator_free(tempAlloc);
    }

    // We can't just add the node directly to the routing table because we do not know
    // the version. We'll send it a switch ping and when it responds, we will know it's
    // key (if we don't already) and version number.
    sendPing(ep);

    return 0;
}