bool RangeUnitTest::runOnModule(Module & M) {
	MAX_BIT_INT = InterProceduralRA<Cousot>::getMaxBitWidth(M);
	Min = APInt::getSignedMinValue(MAX_BIT_INT);
	Max = APInt::getSignedMaxValue(MAX_BIT_INT);
	Zero = APInt(MAX_BIT_INT, 0, true);

	errs() << "Running unit tests for Range class!\n";
	// --------------------------- Shared Objects -------------------------//
	Range unknown(Min, Max, Unknown);
	Range empty(Min, Max, Empty);
	Range zero(Zero, Zero);
	Range infy(Min, Max);
	Range pos(Zero, Max);
	Range neg(Min, Zero);
	Range smallNeg(NEW_APINT(-17), Zero);
	Range smallPos(Zero, NEW_APINT(35));
	Range avgNeg(NEW_APINT(-27817), Zero);
	Range avgPos(Zero, NEW_APINT(182935));
	Range bigNeg(NEW_APINT(-281239847), Zero);
	Range bigPos(Zero, NEW_APINT(211821935));

	// -------------------------------- ADD --------------------------------//
	// [a, b] - [c, d] = [a + c, b + d]
	ASSERT_TRUE("ADD1", add, infy, infy, infy);
	ASSERT_TRUE("ADD2", add, zero, infy, infy);
	ASSERT_TRUE("ADD3", add, zero, zero, zero);
	ASSERT_TRUE("ADD4", add, neg, zero, neg);
	ASSERT_TRUE("ADD5", add, neg, infy, infy);
	ASSERT_TRUE("ADD6", add, neg, neg, neg);
	ASSERT_TRUE("ADD7", add, pos, zero, pos);
	ASSERT_TRUE("ADD8", add, pos, infy, infy);
	ASSERT_TRUE("ADD9", add, pos, neg, infy);
	ASSERT_TRUE("ADD10", add, pos, pos, pos);
	ASSERT_TRUE("ADD11", add, smallNeg, infy, infy);
	ASSERT_TRUE("ADD12", add, smallNeg, zero, smallNeg);
	ASSERT_TRUE("ADD13", add, smallNeg, pos, NEW_RANGE_MAX(-17));
	ASSERT_TRUE("ADD14", add, smallNeg, neg, neg);
	ASSERT_TRUE("ADD15", add, smallNeg, smallNeg, NEW_RANGE_N(-34,0));
	ASSERT_TRUE("ADD16", add, smallNeg, smallPos, NEW_RANGE_N(-17,35));
	ASSERT_TRUE("ADD17", add, smallNeg, avgNeg, NEW_RANGE_N(-27834,0));
	ASSERT_TRUE("ADD18", add, smallNeg, avgPos, NEW_RANGE_N(-17,182935));
	ASSERT_TRUE("ADD19", add, smallNeg, bigNeg, NEW_RANGE_N(-281239864,0));
	ASSERT_TRUE("ADD20", add, smallNeg, bigPos, NEW_RANGE_N(-17, 211821935));
	ASSERT_TRUE("ADD21", add, smallPos, infy, infy);
	ASSERT_TRUE("ADD22", add, smallPos, zero, smallPos);
	ASSERT_TRUE("ADD23", add, smallPos, pos, pos);
	ASSERT_TRUE("ADD24", add, smallPos, neg, NEW_RANGE_MIN(35));
	ASSERT_TRUE("ADD25", add, smallPos, smallPos, NEW_RANGE_N(0,70));
	ASSERT_TRUE("ADD26", add, smallPos, avgNeg, NEW_RANGE_N(-27817, 35));
	ASSERT_TRUE("ADD27", add, smallPos, avgPos, NEW_RANGE_N(0, 182970));
	ASSERT_TRUE("ADD28", add, smallPos, bigNeg, NEW_RANGE_N(-281239847, 35));
	ASSERT_TRUE("ADD29", add, smallPos, bigPos, NEW_RANGE_N(0, 211821970));
	ASSERT_TRUE("ADD30", add, avgNeg, infy, infy);
	ASSERT_TRUE("ADD31", add, avgNeg, zero, avgNeg);
	ASSERT_TRUE("ADD32", add, avgNeg, pos, NEW_RANGE_MAX(-27817));
	ASSERT_TRUE("ADD33", add, avgNeg, neg, neg);
	ASSERT_TRUE("ADD34", add, avgNeg, avgNeg, NEW_RANGE_N(-55634, 0));
	ASSERT_TRUE("ADD35", add, avgNeg, avgPos, NEW_RANGE_N(-27817, 182935));
	ASSERT_TRUE("ADD36", add, avgNeg, bigNeg, NEW_RANGE_N(-281267664, 0));
	ASSERT_TRUE("ADD37", add, avgNeg, bigPos, NEW_RANGE_N(-27817, 211821935));
	ASSERT_TRUE("ADD38", add, avgPos, infy, infy);
	ASSERT_TRUE("ADD39", add, avgPos, zero, avgPos);
	ASSERT_TRUE("ADD40", add, avgPos, pos, pos);
	ASSERT_TRUE("ADD41", add, avgPos, neg, NEW_RANGE_MIN(182935));
	ASSERT_TRUE("ADD42", add, avgPos, avgPos, NEW_RANGE_N(0, 365870));
	ASSERT_TRUE("ADD43", add, avgPos, bigNeg, NEW_RANGE_N(-281239847, 182935));
	ASSERT_TRUE("ADD44", add, avgPos, bigPos, NEW_RANGE_N(0, 212004870));
	ASSERT_TRUE("ADD45", add, bigNeg, infy, infy);
	ASSERT_TRUE("ADD46", add, bigNeg, zero, bigNeg);
	ASSERT_TRUE("ADD47", add, bigNeg, pos, NEW_RANGE_MAX(-281239847));
	ASSERT_TRUE("ADD48", add, bigNeg, neg, neg);
	ASSERT_TRUE("ADD49", add, bigNeg, bigNeg, NEW_RANGE_N(-562479694, 0));
	ASSERT_TRUE("ADD50", add, bigNeg, bigPos, NEW_RANGE_N(-281239847, 211821935));
	ASSERT_TRUE("ADD51", add, bigPos, infy, infy);
	ASSERT_TRUE("ADD52", add, bigPos, zero, bigPos);
	ASSERT_TRUE("ADD53", add, bigPos, pos, pos);
	ASSERT_TRUE("ADD54", add, bigPos, neg, NEW_RANGE_MIN(211821935));
	ASSERT_TRUE("ADD55", add, bigPos, bigPos, NEW_RANGE_N(0,423643870));

	// -------------------------------- SUB --------------------------------//
	// [a, b] - [c, d] = [a - d, b - c]
	ASSERT_TRUE("SUB1", sub, infy, infy, infy);
	ASSERT_TRUE("SUB2", sub, infy, zero, infy);
	ASSERT_TRUE("SUB3", sub, infy, pos, infy);
	ASSERT_TRUE("SUB4", sub, infy, neg, infy);
	ASSERT_TRUE("SUB5", sub, zero, zero, zero);
	ASSERT_TRUE("SUB6", sub, zero, infy, infy);
	ASSERT_TRUE("SUB7", sub, zero, pos, neg);
	ASSERT_TRUE("SUB8", sub, zero, neg, pos);
	ASSERT_TRUE("SUB9", sub, pos, zero, pos);
	ASSERT_TRUE("SUB10", sub, pos, infy, infy);
	ASSERT_TRUE("SUB11", sub, pos, neg, pos);
	ASSERT_TRUE("SUB12", sub, pos, pos, infy);
	ASSERT_TRUE("SUB13", sub, neg, zero, neg);
	ASSERT_TRUE("SUB14", sub, neg, infy, infy);
	ASSERT_TRUE("SUB15", sub, neg, neg, infy);
	ASSERT_TRUE("SUB16", sub, neg, pos, neg);

	// -------------------------------- MUL --------------------------------//
	//  [a, b] * [c, d] = [Min(a*c, a*d, b*c, b*d), Max(a*c, a*d, b*c, b*d)]
	ASSERT_TRUE("MUL1", mul, infy, infy, infy);
	ASSERT_TRUE("MUL2", mul, zero, infy, infy);
	ASSERT_TRUE("MUL3", mul, zero, zero, zero);
	ASSERT_TRUE("MUL4", mul, neg, zero, zero);
	ASSERT_TRUE("MUL5", mul, neg, infy, infy);
	ASSERT_TRUE("MUL6", mul, neg, neg, pos);
	ASSERT_TRUE("MUL7", mul, pos, zero, zero);
	ASSERT_TRUE("MUL8", mul, pos, infy, infy);
	ASSERT_TRUE("MUL9", mul, pos, neg, neg);
	ASSERT_TRUE("MUL10", mul, pos, pos, pos);
	ASSERT_TRUE("MUL11", mul, smallNeg, infy, infy);
	ASSERT_TRUE("MUL12", mul, smallNeg, zero, zero);
	ASSERT_TRUE("MUL13", mul, smallNeg, pos, neg);
	ASSERT_TRUE("MUL14", mul, smallNeg, neg, pos);
	ASSERT_TRUE("MUL15", mul, smallNeg, smallNeg, NEW_RANGE_N(0, 289));
	ASSERT_TRUE("MUL16", mul, smallNeg, smallPos, NEW_RANGE_N(-595, 0));
	ASSERT_TRUE("MUL17", mul, smallNeg, avgNeg, NEW_RANGE_N(0, 472889));
	ASSERT_TRUE("MUL18", mul, smallNeg, avgPos, NEW_RANGE_N(-3109895, 0));
	ASSERT_TRUE("MUL19", mul, smallNeg, bigNeg, NEW_RANGE_N(0, 486110103));
	ASSERT_TRUE("MUL20", mul, smallNeg, bigPos, NEW_RANGE_N(0, 693994401));
	ASSERT_TRUE("MUL21", mul, smallPos, infy, infy);
	ASSERT_TRUE("MUL22", mul, smallPos, zero, zero);
	ASSERT_TRUE("MUL23", mul, smallPos, pos, pos);
	ASSERT_TRUE("MUL24", mul, smallPos, neg, neg);
	ASSERT_TRUE("MUL25", mul, smallPos, smallPos, NEW_RANGE_N(0, 1225));
	ASSERT_TRUE("MUL26", mul, smallPos, avgNeg, NEW_RANGE_N(-973595, 0));
	ASSERT_TRUE("MUL27", mul, smallPos, avgPos, NEW_RANGE_N(0, 6402725));
	ASSERT_TRUE("MUL28", mul, smallPos, bigNeg, NEW_RANGE_N(-1253460053, 0));
	ASSERT_TRUE("MUL29", mul, smallPos, bigPos, NEW_RANGE_N(-1176166867, 0));
	ASSERT_TRUE("MUL30", mul, avgNeg, infy, infy);
	ASSERT_TRUE("MUL31", mul, avgNeg, zero, zero);
	ASSERT_TRUE("MUL32", mul, avgNeg, pos, neg);
	ASSERT_TRUE("MUL33", mul, avgNeg, neg, pos);
	ASSERT_TRUE("MUL34", mul, avgNeg, avgNeg, NEW_RANGE_N(0, 773785489));
	ASSERT_TRUE("MUL35", mul, avgNeg, avgPos, NEW_RANGE_N(-793735599, 0));
	ASSERT_TRUE("MUL38", mul, avgPos, infy, infy);
	ASSERT_TRUE("MUL39", mul, avgPos, zero, zero);
	ASSERT_TRUE("MUL40", mul, avgPos, pos, pos);
	ASSERT_TRUE("MUL41", mul, avgPos, neg, neg);
	ASSERT_TRUE("MUL45", mul, bigNeg, infy, infy);
	ASSERT_TRUE("MUL46", mul, bigNeg, zero, zero);
	ASSERT_TRUE("MUL47", mul, bigNeg, pos, neg);
	ASSERT_TRUE("MUL48", mul, bigNeg, neg, pos);
	ASSERT_TRUE("MUL51", mul, bigPos, infy, infy);
	ASSERT_TRUE("MUL52", mul, bigPos, zero, zero);
	ASSERT_TRUE("MUL53", mul, bigPos, pos, pos);
	ASSERT_TRUE("MUL54", mul, bigPos, neg, neg);

	// -------------------------------- DIV --------------------------------//
	// [a, b] / [c, d] = [Min(a/c, a/d, b/c, b/d), Max(a/c, a/d, b/c, b/d)]
	ASSERT_TRUE("UDIV1", udiv, infy, infy, unknown);
	ASSERT_TRUE("UDIV2", udiv, infy, zero, unknown);
	ASSERT_TRUE("UDIV3", udiv, infy, pos, unknown);
	ASSERT_TRUE("UDIV4", udiv, infy, neg, unknown);
	ASSERT_TRUE("UDIV5", udiv, infy, smallNeg, unknown);
	ASSERT_TRUE("UDIV6", udiv, infy, smallPos, unknown);
	ASSERT_TRUE("UDIV7", udiv, infy, avgNeg, unknown);
	ASSERT_TRUE("UDIV8", udiv, infy, avgPos, unknown);
	ASSERT_TRUE("UDIV9", udiv, infy, bigNeg, unknown);
	ASSERT_TRUE("UDIV10", udiv, infy, bigPos, unknown);
	ASSERT_TRUE("UDIV11", udiv, zero, zero, unknown);
	ASSERT_TRUE("UDIV12", udiv, zero, infy, zero);
	ASSERT_TRUE("UDIV13", udiv, zero, pos, unknown);
	ASSERT_TRUE("UDIV14", udiv, zero, neg, unknown);
	ASSERT_TRUE("UDIV15", udiv, zero, smallNeg, unknown);
	ASSERT_TRUE("UDIV16", udiv, zero, smallPos, unknown);
	ASSERT_TRUE("UDIV17", udiv, zero, avgNeg, unknown);
	ASSERT_TRUE("UDIV18", udiv, zero, avgPos, unknown);
	ASSERT_TRUE("UDIV19", udiv, zero, bigNeg, unknown);
	ASSERT_TRUE("UDIV20", udiv, zero, bigPos, unknown);
	ASSERT_TRUE("UDIV21", udiv, pos, zero, unknown);
	ASSERT_TRUE("UDIV22", udiv, pos, infy, unknown);
	ASSERT_TRUE("UDIV23", udiv, pos, neg, unknown);
	ASSERT_TRUE("UDIV24", udiv, pos, pos, unknown);
	ASSERT_TRUE("UDIV25", udiv, pos, smallNeg, unknown);
	ASSERT_TRUE("UDIV26", udiv, pos, smallPos, unknown);
	ASSERT_TRUE("UDIV27", udiv, pos, avgNeg, unknown);
	ASSERT_TRUE("UDIV28", udiv, pos, avgPos, unknown);
	ASSERT_TRUE("UDIV29", udiv, pos, bigNeg, unknown);
	ASSERT_TRUE("UDIV30", udiv, pos, bigPos, unknown);
	ASSERT_TRUE("UDIV31", udiv, neg, zero, unknown);
	ASSERT_TRUE("UDIV32", udiv, neg, infy, unknown);
	ASSERT_TRUE("UDIV33", udiv, neg, neg, unknown);
	ASSERT_TRUE("UDIV34", udiv, neg, pos, unknown);
	ASSERT_TRUE("UDIV35", udiv, neg, smallNeg, unknown);
	ASSERT_TRUE("UDIV36", udiv, neg, smallPos, unknown);
	ASSERT_TRUE("UDIV37", udiv, neg, avgNeg, unknown);
	ASSERT_TRUE("UDIV38", udiv, neg, avgPos, unknown);
	ASSERT_TRUE("UDIV39", udiv, neg, bigNeg, unknown);
	ASSERT_TRUE("UDIV40", udiv, neg, bigPos, unknown);
	ASSERT_TRUE("UDIV41", udiv, smallNeg, infy, unknown);
	ASSERT_TRUE("UDIV42", udiv, smallNeg, zero, unknown);
	ASSERT_TRUE("UDIV43", udiv, smallNeg, pos, unknown);
	ASSERT_TRUE("UDIV44", udiv, smallNeg, neg, unknown);
	ASSERT_TRUE("UDIV45", udiv, smallNeg, smallNeg, unknown);
	ASSERT_TRUE("UDIV46", udiv, smallNeg, smallPos, unknown);
	ASSERT_TRUE("UDIV47", udiv, smallNeg, avgNeg, unknown);
	ASSERT_TRUE("UDIV48", udiv, smallNeg, avgPos, unknown);
	ASSERT_TRUE("UDIV49", udiv, smallNeg, bigNeg, unknown);
	ASSERT_TRUE("UDIV50", udiv, smallNeg, bigPos, unknown);
	ASSERT_TRUE("UDIV51", udiv, smallPos, infy, unknown);
	ASSERT_TRUE("UDIV52", udiv, smallPos, zero, unknown);
	ASSERT_TRUE("UDIV53", udiv, smallPos, pos, unknown);
	ASSERT_TRUE("UDIV54", udiv, smallPos, neg, unknown);
	ASSERT_TRUE("UDIV55", udiv, smallPos, smallNeg, unknown);
	ASSERT_TRUE("UDIV56", udiv, smallPos, smallPos, unknown);
	ASSERT_TRUE("UDIV57", udiv, smallPos, avgNeg, unknown);
	ASSERT_TRUE("UDIV58", udiv, smallPos, avgPos, unknown);
	ASSERT_TRUE("UDIV59", udiv, smallPos, bigNeg, unknown);
	ASSERT_TRUE("UDIV60", udiv, smallPos, bigPos, unknown);
	ASSERT_TRUE("UDIV61", udiv, avgNeg, infy, unknown);
	ASSERT_TRUE("UDIV62", udiv, avgNeg, zero, unknown);
	ASSERT_TRUE("UDIV63", udiv, avgNeg, pos, unknown);
	ASSERT_TRUE("UDIV64", udiv, avgNeg, neg, unknown);
	ASSERT_TRUE("UDIV65", udiv, avgNeg, smallNeg, unknown);
	ASSERT_TRUE("UDIV66", udiv, avgNeg, smallPos, unknown);
	ASSERT_TRUE("UDIV67", udiv, avgNeg, avgNeg, unknown);
	ASSERT_TRUE("UDIV68", udiv, avgNeg, avgPos, unknown);
	ASSERT_TRUE("UDIV69", udiv, avgNeg, bigNeg, unknown);
	ASSERT_TRUE("UDIV70", udiv, avgNeg, bigPos, unknown);
	ASSERT_TRUE("UDIV71", udiv, avgPos, infy, unknown);
	ASSERT_TRUE("UDIV72", udiv, avgPos, zero, unknown);
	ASSERT_TRUE("UDIV73", udiv, avgPos, pos, unknown);
	ASSERT_TRUE("UDIV74", udiv, avgPos, neg, unknown);
	ASSERT_TRUE("UDIV75", udiv, avgPos, smallNeg, unknown);
	ASSERT_TRUE("UDIV76", udiv, avgPos, smallPos, unknown);
	ASSERT_TRUE("UDIV77", udiv, avgPos, avgNeg, unknown);
	ASSERT_TRUE("UDIV78", udiv, avgPos, avgPos, unknown);
	ASSERT_TRUE("UDIV79", udiv, avgPos, bigNeg, unknown);
	ASSERT_TRUE("UDIV80", udiv, avgPos, bigPos, unknown);
	ASSERT_TRUE("UDIV81", udiv, bigNeg, infy, unknown);
	ASSERT_TRUE("UDIV82", udiv, bigNeg, zero, unknown);
	ASSERT_TRUE("UDIV83", udiv, bigNeg, pos, unknown);
	ASSERT_TRUE("UDIV84", udiv, bigNeg, neg, unknown);
	ASSERT_TRUE("UDIV85", udiv, bigNeg, smallNeg, unknown);
	ASSERT_TRUE("UDIV86", udiv, bigNeg, smallPos, unknown);
	ASSERT_TRUE("UDIV87", udiv, bigNeg, avgNeg, unknown);
	ASSERT_TRUE("UDIV88", udiv, bigNeg, avgPos, unknown);
	ASSERT_TRUE("UDIV89", udiv, bigNeg, bigNeg, unknown);
	ASSERT_TRUE("UDIV90", udiv, bigNeg, bigPos, unknown);
	ASSERT_TRUE("UDIV91", udiv, bigPos, infy, unknown);
	ASSERT_TRUE("UDIV92", udiv, bigPos, zero, unknown);
	ASSERT_TRUE("UDIV93", udiv, bigPos, pos, unknown);
	ASSERT_TRUE("UDIV94", udiv, bigPos, neg, unknown);
	ASSERT_TRUE("UDIV95", udiv, bigPos, smallNeg, unknown);
	ASSERT_TRUE("UDIV96", udiv, bigPos, smallPos, unknown);
	ASSERT_TRUE("UDIV97", udiv, bigPos, avgNeg, unknown);
	ASSERT_TRUE("UDIV98", udiv, bigPos, avgPos, unknown);
	ASSERT_TRUE("UDIV99", udiv, bigPos, bigNeg, unknown);
	ASSERT_TRUE("UDIV100", udiv, bigPos, bigPos, unknown);

	printStats();
	return true;
}
int main (int argc, char **argv) {
    int fcgiSock = -1;
    FCGX_Stream *paramsStream;
    char *pool = NULL;
    char *content, *data;
    int type, count;
    struct json_object  *obj, *slaveobj;

    /* Set signal handling and alarm */
    if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR)
        critical("Setup SIGALRM trap failed!");

    /* Process check arguments */
    if (process_arguments(argc, argv) != OK)
        unknown("Parsing arguments failed!");

    /* Start plugin timeout */
    alarm(mp_timeout);

    /* Connect to fcgi server */
    fcgiSock = mp_fcgi_connect(fcgisocket);

    /* Prepare Begin Request */
    FCGI_BeginRequestBody body;
    body.roleB1 = 0x00;
    body.roleB0 = FCGI_RESPONDER;
    body.flags  = 0x000;
    memset(body.reserved, 0, sizeof(body.reserved));
    mp_fcgi_write(fcgiSock, 42, FCGI_BEGIN_REQUEST, (char*)&body, sizeof(body));

    /* Set FCGI Params */
    paramsStream = FCGX_CreateWriter(fcgiSock, 1, 8192, FCGI_PARAMS);
    mp_fcgi_putkv(paramsStream, "REQUEST_METHOD", "GET");
    mp_fcgi_putkv(paramsStream, "SCRIPT_NAME", query);
    mp_fcgi_putkv(paramsStream, "SCRIPT_FILENAME", query);
    mp_fcgi_putkv(paramsStream, "QUERY_STRING", "json&");
    FCGX_FClose(paramsStream);
    FCGX_FreeStream(&paramsStream);

    /* Start request processing by stdin closing */
    mp_fcgi_write(fcgiSock, 42, FCGI_STDIN, NULL, 0);

    /* Wait for answer */
    data = NULL;
    do {
        content = NULL;
        type = mp_fcgi_read(fcgiSock, &content, &count);
        if (type == FCGI_STDOUT)
            data = content;
        else if (content)
            free(content);
    } while (type != FCGI_END_REQUEST);

    /* Skip http headers */
    content = data;
    do {
        (void)strsep(&data, "\n");
    } while (data && data[0] != '\r');

    /* Parse JSON */
    obj = mp_json_tokener_parse(data);

    /* Read pool name */
    mp_json_object_object_get(obj, "pool", &slaveobj);
    pool = mp_strdup(json_object_get_string(slaveobj));

    /* Read accepted connections */
    mp_json_object_object_get(obj, "accepted conn", &slaveobj);
    mp_perfdata_int("accepted_conn", json_object_get_int(slaveobj), "c", NULL);

    /* Read listen queue */
    mp_json_object_object_get(obj, "listen queue", &slaveobj);
    mp_perfdata_int("listen_queue", json_object_get_int(slaveobj), "", NULL);

    /* Read idle processes */
    mp_json_object_object_get(obj, "idle processes", &slaveobj);
    mp_perfdata_int("idle_processes", json_object_get_int(slaveobj), "", NULL);

    /* Read active processes */
    mp_json_object_object_get(obj, "active processes", &slaveobj);
    mp_perfdata_int("active_processes", json_object_get_int(slaveobj), "", NULL);

    free(content);
    json_object_put(obj);

    ok("PHP-FPM: %s", pool);
}
/*
 * The routeTcpMessage() receives messages from any TCP connection. The Daemon can be connected with server and deskApp at the same time, but it will know which connection received data.
 * Any message arrive by TCP must to have two parts. The first part defines the data size of the coming package (second part) and must to be an 8 bytes String (always 8 bytes).
 *
 * The algoritm works like this:
 * When some data arrive it verifies (using the hasPackage variable) if is the first part or the second one of the complete message;
 * If hasPackage is true then is especting the second part of the message, otherwise the dada just arrived is the size information.
 *
 * The information of size correspond to the size of the message package. So, when more data arrive it verifies if the size is greater than or equals to the expected size.
 * If true the message is all here and can go on, otherwise the message is coming and it will wait for more data.
 *
 * When all the message arrives it will interpret and route it (by message type) to the right way.
 *
 */
void RFIDMonitorDaemon::routeTcpMessage()
{
    QTcpSocket *connection = (QTcpSocket *) QObject::sender();

    static bool hasPackage = false;
    static quint64 packageSize = 0;

    if( ! hasPackage){

        if((quint64)connection->bytesAvailable() < sizeof(quint64))
            return;

        //    	m_tcpSocket->read((char *)&packageSize, sizeof(quint64));
        QString packageSizeStr(connection->read(sizeof(quint64)));
        packageSize = packageSizeStr.toULongLong();

        qDebug() <<  QString("Message = %1 - Size of coming package: %2").arg(packageSizeStr).arg(QString::number(packageSize));
        hasPackage = true;
    }

    if((quint64)connection->bytesAvailable() >=  packageSize){
        QByteArray data(connection->read(packageSize));

        json::NodeJSMessage nodeMessage;

        nodeMessage.read(QJsonDocument::fromJson(data).object());
        QString messageType(nodeMessage.type());

        qDebug() << QString("New Message Received: %1").arg(QString(data));


        if(messageType == "SYN-ALIVE"){

            tcpSendMessage(connection, buildMessage(m_configManager->identification(), "ACK-ALIVE").toJson());
            qDebug() << QString("New Message Received: %1").arg(messageType);
        }
        else if (messageType == "ACK-SYN") {

            QJsonObject obj(nodeMessage.jsonData());
            if(!obj.isEmpty()){
                m_configManager->setIdentification(obj);
            }

            bool statusDateTime = m_configManager->setDateTime(nodeMessage.dateTime());
            QJsonObject response = m_configManager->identification();
            response["success"] = QJsonValue(statusDateTime);

            tcpSendMessage(connection, buildMessage(response, "ACK").toJson());

            // Informe RFIDMonitor that server is now connected. Wait 2 seconds;
            if(connection->objectName() == "server"){
                isConnected = true;
                QTimer *timer = new QTimer();
                timer->setSingleShot(true);
                timer->setInterval(2000);
                connect(timer, &QTimer::timeout, [=](){
                    ipcSendMessage(buildMessage(QJsonObject(), "SYNC").toJson());
                    timer->deleteLater();
                });
                timer->start();
            }
        }else if (messageType == "GET-CONFIG") {
            tcpSendMessage(connection, buildMessage(m_configManager->currentConfig(), "CONFIG").toJson());

        }else if (messageType == "READER-COMMAND") {

            QJsonObject command(nodeMessage.jsonData());
            /*
             * When a 'reader command' message is received is because someone is sending a command to the reader. So it needs to send also who is doing this.
             * To perform this it uses a field called 'sender' that carry the name of who is sending the 'command message'.
             * And based on that, it will respond to the server connection or to the deskApp connection
             *
             * see reoutIcpMessage (messageType == "READER-RESPONSE")
             */
            if(connection->objectName() == "server")
                command.insert("sender", QString("server"));
            else
                command.insert("sender", QString("app"));

            ipcSendMessage(buildMessage(command, "READER-COMMAND").toJson());

        }else if (messageType == "NEW-CONFIG") {

            QJsonObject newConfig(nodeMessage.jsonData());
            bool ackConf;
            if(m_configManager->newConfig(newConfig))
            {
                // Send a message to stop the RFIDMonitor
                emit restartMonitor();
                ackConf = true;
            }else{
                ackConf = false;
            }
            QJsonObject dataObj;
            dataObj.insert("success", QJsonValue(ackConf));
            tcpSendMessage(connection, buildMessage(dataObj, "ACK-NEW-CONFIG").toJson());

            if(m_tcpAppSocket->isOpen())
                m_tcpAppSocket->close();

        }else if (messageType == "DATETIME") {

            QJsonObject dataObj;
            dataObj["success"] =  QJsonValue(m_configManager->setDateTime(nodeMessage.dateTime()));
            tcpSendMessage(connection, buildMessage(dataObj, "ACK").toJson());

        }else if (messageType == "ACK-DATA") {
            // A ACK-DATA message means that the server is trying to inform the RFIDMonitor that some data is now synced. So, it just send this message to the RFIDMonitor.
            ipcSendMessage(data);

        }else if (messageType == "GET-NET-CONFIG") {
            // Only return the network configuration.
            tcpSendMessage(connection, buildMessage(m_configManager->netConfig(), "NET-CONFIG").toJson());

        }else if (messageType == "NEW-NET") {

            QJsonObject network = nodeMessage.jsonData();
            // Receive a new configuration for the network (ssid and password).
            QJsonObject dataObj;
            dataObj.insert("success", QJsonValue(m_configManager->setNetConfig(network)));

            // returns a message ACK-NET to inform the sender that the new configuration was set
            tcpSendMessage(connection, buildMessage(dataObj, "ACK-NET").toJson());

            // Try to restar the network service to already use the new configuration
            bool resetNet = m_configManager->restartNetwork();
            qDebug() <<  QString(resetNet? "Network restarted" : "Networkt Don't restarted");

        }else if (messageType == "ACK-UNKNOWN") {
            QJsonDocument unknown(nodeMessage.jsonData());
            QJsonObject oldMessage(unknown.object().value("unknownmessage").toObject());
            qDebug() <<  "The server don't understand the message type: " << oldMessage.value("type").toString();
            qDebug() <<  "ERROR message: " << unknown.object().value("errorinfo").toString();

        }else if (messageType == "FULL-READ"){
            ipcSendMessage(data);

        }else{
            /* When receives a message that can't be interpreted like any type is an unknown message.
             * In this case an ACK-UNKNOWN message is built and sent to the connection that received this message
             */
            qDebug() <<  "UNKNOWN MESSAGE";
            QJsonObject unknownObj;
            unknownObj.insert("unknownmessage", QJsonValue(QJsonDocument::fromJson(data).object()));
            unknownObj.insert("errorinfo", QString("Unknown message received"));
            tcpSendMessage(connection, buildMessage(unknownObj, "ACK-UNKNOWN").toJson());
        }

        /* when all the process is done, reset the expecting message size to zero and the haspackage to false.
         * Then when more data arrive it must to be the size information again.
         */
        packageSize = 0;
        hasPackage = false;
    }
}
Exemplo n.º 4
0
int test11() {
  (void)(unknown() && halt3());
} // expected-warning {{control may reach end of non-void function}}
Exemplo n.º 5
0
int test13() {
  (void)(halt3() && unknown());
}
Exemplo n.º 6
0
int test25() {
  1 ? halt3() : unknown();
}
Exemplo n.º 7
0
int test7() {
  unknown();
} // expected-warning {{control reaches end of non-void function}}
Exemplo n.º 8
0
void CameraItemPropertiesTab::setCurrentItem(const CamItemInfo& itemInfo, const DMetadata& meta)
{
    if (itemInfo.isNull())
    {
        d->labelFile->setAdjustedText(QString());
        d->labelFolder->setAdjustedText(QString());
        d->labelFileIsReadable->setAdjustedText(QString());
        d->labelFileIsWritable->setAdjustedText(QString());
        d->labelFileDate->setAdjustedText(QString());
        d->labelFileSize->setAdjustedText(QString());
        d->labelImageMime->setAdjustedText(QString());
        d->labelImageDimensions->setAdjustedText(QString());
        d->labelImageRatio->setAdjustedText(QString());
        d->labelNewFileName->setAdjustedText(QString());
        d->labelAlreadyDownloaded->setAdjustedText(QString());

        d->labelPhotoMake->setAdjustedText(QString());
        d->labelPhotoModel->setAdjustedText(QString());
        d->labelPhotoDateTime->setAdjustedText(QString());
        d->labelPhotoLens->setAdjustedText(QString());
        d->labelPhotoAperture->setAdjustedText(QString());
        d->labelPhotoFocalLength->setAdjustedText(QString());
        d->labelPhotoExposureTime->setAdjustedText(QString());
        d->labelPhotoSensitivity->setAdjustedText(QString());
        d->labelPhotoExposureMode->setAdjustedText(QString());
        d->labelPhotoFlash->setAdjustedText(QString());
        d->labelPhotoWhiteBalance->setAdjustedText(QString());

        d->labelVideoAspectRatio->setAdjustedText(QString());
        d->labelVideoAudioBitRate->setAdjustedText(QString());
        d->labelVideoAudioChannelType->setAdjustedText(QString());
        d->labelVideoAudioCompressor->setAdjustedText(QString());
        d->labelVideoDuration->setAdjustedText(QString());
        d->labelVideoFrameRate->setAdjustedText(QString());
        d->labelVideoVideoCodec->setAdjustedText(QString());

        setEnabled(false);
        return;
    }

    setEnabled(true);

    QString str;
    QString unknown(i18n("<i>unknown</i>"));

    // -- Camera file system information ------------------------------------------

    d->labelFile->setAdjustedText(itemInfo.name);
    d->labelFolder->setAdjustedText(itemInfo.folder);

    if (itemInfo.readPermissions < 0)
    {
        str = unknown;
    }
    else if (itemInfo.readPermissions == 0)
    {
        str = i18n("No");
    }
    else
    {
        str = i18n("Yes");
    }

    d->labelFileIsReadable->setAdjustedText(str);

    if (itemInfo.writePermissions < 0)
    {
        str = unknown;
    }
    else if (itemInfo.writePermissions == 0)
    {
        str = i18n("No");
    }
    else
    {
        str = i18n("Yes");
    }

    d->labelFileIsWritable->setAdjustedText(str);

    if (itemInfo.ctime.isValid())
    {
        d->labelFileDate->setAdjustedText(QLocale().toString(itemInfo.ctime, QLocale::ShortFormat));
    }
    else
    {
        d->labelFileDate->setAdjustedText(unknown);
    }

    str = i18n("%1 (%2)", ImagePropertiesTab::humanReadableBytesCount(itemInfo.size), QLocale().toString(itemInfo.size));
    d->labelFileSize->setAdjustedText(str);

    // -- Image Properties --------------------------------------------------

    if (itemInfo.mime == QLatin1String("image/x-raw"))
    {
        d->labelImageMime->setAdjustedText(i18n("RAW Image"));
    }
    else
    {
        QMimeType mimeType = QMimeDatabase().mimeTypeForName(itemInfo.mime);

        if (mimeType.isValid())
        {
            d->labelImageMime->setAdjustedText(mimeType.comment());
        }
        else
        {
            d->labelImageMime->setAdjustedText(itemInfo.mime);    // last fallback
        }
    }

    QString mpixels;
    QSize dims;

    if (itemInfo.width == -1 && itemInfo.height == -1)
    {
        // delayed loading to list faster from UMSCamera
        if (itemInfo.mime == QLatin1String("image/x-raw"))
        {
            dims = meta.getImageDimensions();
        }
        else
        {
            dims = meta.getPixelSize();
        }
    }
    else
    {
        // if available (GPCamera), take dimensions directly from itemInfo
        dims = QSize(itemInfo.width, itemInfo.height);
    }

    mpixels.setNum(dims.width()*dims.height()/1000000.0, 'f', 2);
    str = (!dims.isValid()) ? unknown : i18n("%1x%2 (%3Mpx)",
            dims.width(), dims.height(), mpixels);
    d->labelImageDimensions->setAdjustedText(str);

    if (!dims.isValid()) str = unknown;
    else ImagePropertiesTab::aspectRatioToString(dims.width(), dims.height(), str);

    d->labelImageRatio->setAdjustedText(str);

    // -- Download information ------------------------------------------

    d->labelNewFileName->setAdjustedText(itemInfo.downloadName.isEmpty() ? i18n("<i>unchanged</i>") : itemInfo.downloadName);

    if (itemInfo.downloaded == CamItemInfo::DownloadUnknown)
    {
        str = unknown;
    }
    else if (itemInfo.downloaded == CamItemInfo::DownloadedYes)
    {
        str = i18n("Yes");
    }
    else
    {
        str = i18n("No");
    }

    d->labelAlreadyDownloaded->setAdjustedText(str);

    // -- Photograph information ------------------------------------------
    // Note: If something is changed here, please updated albumfiletip section too.

    QString unavailable(i18n("<i>unavailable</i>"));
    PhotoInfoContainer photoInfo = meta.getPhotographInformation();

    if (photoInfo.isEmpty())
    {
        widget(1)->hide();
    }
    else
    {
        widget(1)->show();
    }

    ImagePropertiesTab::shortenedMakeInfo(photoInfo.make);
    ImagePropertiesTab::shortenedModelInfo(photoInfo.model);
    d->labelPhotoMake->setAdjustedText(photoInfo.make.isEmpty()   ? unavailable : photoInfo.make);
    d->labelPhotoModel->setAdjustedText(photoInfo.model.isEmpty() ? unavailable : photoInfo.model);

    if (photoInfo.dateTime.isValid())
    {
        str = QLocale().toString(photoInfo.dateTime, QLocale::ShortFormat);
        d->labelPhotoDateTime->setAdjustedText(str);
    }
    else
    {
        d->labelPhotoDateTime->setAdjustedText(unavailable);
    }

    d->labelPhotoLens->setAdjustedText(photoInfo.lens.isEmpty() ? unavailable : photoInfo.lens);
    d->labelPhotoAperture->setAdjustedText(photoInfo.aperture.isEmpty() ? unavailable : photoInfo.aperture);

    if (photoInfo.focalLength35mm.isEmpty())
    {
        d->labelPhotoFocalLength->setAdjustedText(photoInfo.focalLength.isEmpty() ? unavailable : photoInfo.focalLength);
    }
    else
    {
        str = i18n("%1 (%2)", photoInfo.focalLength, photoInfo.focalLength35mm);
        d->labelPhotoFocalLength->setAdjustedText(str);
    }

    d->labelPhotoExposureTime->setAdjustedText(photoInfo.exposureTime.isEmpty() ? unavailable : photoInfo.exposureTime);
    d->labelPhotoSensitivity->setAdjustedText(photoInfo.sensitivity.isEmpty() ? unavailable : i18n("%1 ISO", photoInfo.sensitivity));

    if (photoInfo.exposureMode.isEmpty() && photoInfo.exposureProgram.isEmpty())
    {
        d->labelPhotoExposureMode->setAdjustedText(unavailable);
    }
    else if (!photoInfo.exposureMode.isEmpty() && photoInfo.exposureProgram.isEmpty())
    {
        d->labelPhotoExposureMode->setAdjustedText(photoInfo.exposureMode);
    }
    else if (photoInfo.exposureMode.isEmpty() && !photoInfo.exposureProgram.isEmpty())
    {
        d->labelPhotoExposureMode->setAdjustedText(photoInfo.exposureProgram);
    }
    else
    {
        str = QString::fromUtf8("%1 / %2").arg(photoInfo.exposureMode).arg(photoInfo.exposureProgram);
        d->labelPhotoExposureMode->setAdjustedText(str);
    }

    d->labelPhotoFlash->setAdjustedText(photoInfo.flash.isEmpty() ? unavailable : photoInfo.flash);
    d->labelPhotoWhiteBalance->setAdjustedText(photoInfo.whiteBalance.isEmpty() ? unavailable : photoInfo.whiteBalance);

    // -- Video information ------------------------------------------

    VideoInfoContainer videoInfo = meta.getVideoInformation();

    if (videoInfo.isEmpty())
    {
        widget(2)->hide();
    }
    else
    {
        widget(2)->show();
    }

    d->labelVideoAspectRatio->setAdjustedText(videoInfo.aspectRatio.isEmpty()           ? unavailable : videoInfo.aspectRatio);
    d->labelVideoAudioBitRate->setAdjustedText(videoInfo.audioBitRate.isEmpty()         ? unavailable : videoInfo.audioBitRate);
    d->labelVideoAudioChannelType->setAdjustedText(videoInfo.audioChannelType.isEmpty() ? unavailable : videoInfo.audioChannelType);
    d->labelVideoAudioCompressor->setAdjustedText(videoInfo.audioCompressor.isEmpty()   ? unavailable : videoInfo.audioCompressor);
    d->labelVideoDuration->setAdjustedText(videoInfo.duration.isEmpty()                 ? unavailable : videoInfo.duration);
    d->labelVideoFrameRate->setAdjustedText(videoInfo.frameRate.isEmpty()               ? unavailable : videoInfo.frameRate);
    d->labelVideoVideoCodec->setAdjustedText(videoInfo.videoCodec.isEmpty()             ? unavailable : videoInfo.videoCodec);
}
Exemplo n.º 9
0
Arquivo: emu.c Projeto: aunali1/exopc
int emu_0f(unsigned char *lina)
{
    unsigned char *orig_lina = lina;

    switch (lina[1]) {
    case 0x00:		/* lldt, ltr */
    {
	switch (REG_OPCODE(lina[2])) {
	case 2:		/* 0F 00 /2 LLDT r/m16 Load segment selector r/m16 into LDTR */
	{
	    u_int addr, is_addr, reg, selector;

	    trace("lldt\n");
	    if (!opa.pe) {
		set_guest_exc(EXC_UD, 0);
		goto exc;
	    }
	    if (opa.cpl != 0) {
		set_guest_exc(EXC_GP, 0);
		goto exc;
	    }
	    lina += 2;	/* move up to RM byte */
	    decode_rm16(&addr, &is_addr, &reg, &lina);
	    if (emu_get(is_addr, addr, &selector, 2))
		goto exc;
	    if (load_ldtr(selector))
		goto exc;

	    break;
	}
	case 3: 	 /* 0F 00 /3 LTR r/m16 Load r/m16 into TR */
	{
	    u_int addr, is_addr, reg;
	    Bit32u dtr;
	    
	    trace("ltr\n");
	    if (!opa.pe) {
		set_guest_exc(EXC_UD, 0);
		goto exc;
	    }
	    if (opa.cpl != 0) {
		set_guest_exc(EXC_GP, 0);
		goto exc;
	    }
	    lina += 2;  /* move up to RM byte */
	    decode_rm16(&addr, &is_addr, &reg, &lina);
	    if (emu_get(is_addr, addr, &dtr, 2))
		goto exc;
	    if (load_tr(dtr))
		goto exc;

	    break;
	}
	default:
	    unknown(lina);
	}
	break;
    }
    
    case 0x01:		/* invlpg, lgdt, lidt, lmsw */
    {
	int reg_op = REG_OPCODE(lina[2]);
	switch (reg_op) {
	case 2:				/* lgdt */
	case 3:				/* lidt */
	{
	    u_int addr, is_addr, reg, limit, base;
	    
	    lina += 2;                       /* move up to RM byte */
	    decode_rm(&addr, &is_addr, &reg, &lina);
	    ASSERT(is_addr);
	    /* addr now points to the m16&32; lina is at next instr */
	    if (get_memory(opa.seg, addr, &limit, 2) != 0 ||
		get_memory(opa.seg, addr+2, &base, opa.opb==4 ? 4 : 3) != 0)
		goto exc;
	    
	    /* by definition of lgdt/lidt, base is a linear address already. */
	    if (reg_op == 2) {
		set_gdt(base, limit);
	    } else {
		set_idt(base, limit);
	    }
	    debug_mem("loaded %cdt from 0x%08x\n", reg_op==2 ? 'g' : 'i', base);
	    break;
	}
	case 6:		/* 0F 01 /6  LMSW r/m16  Loads r/m16 in msw of CR0 */
	{
	    u_int addr, is_addr, reg, val;
	    
	    trace("lmsw\n");
	    
	    if (opa.pe && opa.cpl!=0) {
		set_guest_exc(13, 0);
		goto exc;
	    }
	    
	    lina += 2;         /* move up to RM byte */
	    decode_rm16(&addr, &is_addr, &reg, &lina);
	    if (emu_get(is_addr, addr, &val, 2))
		goto exc;
	    if (vmstate.cr[0] & 1 && !(val & 1))
		val |= 1;  /* can't clear PE with lmsw */
	    mov_to_cr(0, val, 0x0000000f); /* only PE, MP, EM, and TS can be affected */
	    
	    break;
	}
	case 7:		/* invlpg */
	{
	    Bit32u ptr;
	    
	    debug("invlpg\n");
	    
	    lina += 2;         /* move up to memory operand */
	    if (opa.opb==4) {
		ptr = *(Bit32u*)lina;
	    } else {
		ptr = *(Bit16u*)lina;
	    }
	    lina += opa.opb;
	    
	    if (vmstate.cr[0]&PG_MASK) {
		/* Modify a pte with itself.  This should have the desired side
		   effect of flushing that TLB entry. */
		sys_self_mod_pte_range(0, 0, /* add no flag bits */
				       0, /* remove no flag bits */
				       ptr, 1);
	    }

	    break;
	}
	default:
	    unknown(lina);
	}
	break;
    }

    case 0x06:		/* clts  0F 06 */
    {
	if (opa.cpl!=0) {
	    set_guest_exc(13, 0);
	    goto exc;
	} else {	
	    vmstate.cr[0] &= ~TS_MASK;
	    lina += 2;
	}
	break;
    }

    case 0x08:		/* invd  0F 08 */
    case 0x09:		/* wbinvd  0F 09 */
    {
	if (opa.cpl!=0) {
	    set_guest_exc(13, 0);
	    goto exc;
	} else {
	    /* will not implement */
	    lina += 2;
	}
	break;
    }

    case 0x0b:		/* UD2 */
    {
	set_guest_exc(6, 0);
	goto exc;
    }

    case 0x20:		/* MOV r <- CRx */
    {
	int cr = REG_OPCODE(lina[2]);
	int reg = RM(lina[2]);
	
	ASSERT(cr<5);
	set_reg(reg, vmstate.cr[cr], 4);
	lina += 3;
	break;
    }

    case 0x21:		/* MOV r <- DRx */
    {
	int dr = REG_OPCODE(lina[2]);
	int reg = RM(lina[2]);
	
	set_reg(reg, vmstate.dr[dr], 4);
	lina += 3;
	break;
    }

    case 0x22:		/* MOV CRx <- r */
    {
	int cr = REG_OPCODE(lina[2]);
	
	ASSERT(cr<5);
	if (opa.pe && opa.cpl!=0) {
	    set_guest_exc(13, 0);
	    goto exc;
	}
	
	mov_to_cr(cr, get_reg(RM(lina[2]), 4), 0xffffffff);
	lina += 3;
	break;
    }

    case 0x23:		/* MOV DRx <- r */
    {
	int dr = REG_OPCODE(lina[2]);

	debug("mov dr%d <- r%d\n", dr, RM(lina[2]));

	if (opa.pe && opa.cpl!=0) {
	    set_guest_exc(13, 0);
	    goto exc;
	}
	
	vmstate.dr[dr] = get_reg(RM(lina[2]), 4);
	lina += 3;
	break;
    }

    case 0x30:		/* wrmsr */
    {
	int ctr = 0;

	if (REG(ecx) == P6MSR_CTRSEL0)
	    ctr = 0;
	else if (REG(ecx) == P6MSR_CTRSEL1)
	    ctr = 1;
	else
	    unknown(lina);    /* only performance counters are implemented */

	sys_pctr(ctr==0 ? PCIOCS0 : PCIOCS1, 0, &REG(eax));
	lina += 2;
	break;
    }

    case 0x32:		/* rdmsr */
    {
	struct pctrst p;
	int ctr = 0;

	if (REG(ecx) == P6MSR_CTR0)
	    ctr = 0;
	else if (REG(ecx) == P6MSR_CTR1)
	    ctr = 1;
	else
	    unknown(lina);    /* only performance counters are implemented */

	sys_pctr(PCIOCRD, 0, &p);
	REG(eax) = p.pctr_hwc[ctr];
	REG(edx) = p.pctr_hwc[ctr] >> 32;
	lina += 2;
	break;
    }

#if 0
    case 0x33:		/* rdpmc */
    {
	struct pctrst p;

	/* or cpl!=0 and cr4 ... */
	if (REG(ecx)>1) {
	    set_guest_exc(EXC_GP, 0);
	    goto exc;
	}

	sys_pctr(PCIOCRD, 0, &p);
	REG(eax) = p.pctr_hwc[REG(ecx)];
	REG(edx) = p.pctr_hwc[REG(ecx)] >> 32;

	lina += 2;
	break;
    }
#endif

    case 0xa2:		/* cpuid */
    {
	/* cpuid may trap on a Cyrix.  I don't care. */
	leaveemu(ERR_UNIMPL);
	break;
    }

    case 0xb2:		/* lss */
    case 0xb4:		/* lfs */
    case 0xb5:		/* lgs */
    {
	int seg;

	if (lina[1]==0xb2) {
	    seg = REGNO_SS;
	} else if (lina[1]==0xb4) {
	    seg = REGNO_FS;
	} else
	    seg = REGNO_GS;
	if (load_far_pointer(&lina, seg))
	    goto exc;
	break;
    }

    case 0x31:		/* rdtsc ... should be enabled in xok */
    case 0xc8:		/* bswap  should not trap */
    default:
	unknown(lina);
    }

    REG(eip) += lina-orig_lina;
    return 0;

 exc:
    return -1;
}
Exemplo n.º 10
0
Approximation Approximator::find(const NullaryFunction& fun) {
    if (Ob val = fun.find()) {
        return Approximation(val, m_less);
    }
    return unknown();
}
Exemplo n.º 11
0
int main (int argc, char **argv) {
    /* Local Vars */
    CURL        *curl;
    char        *url;
    double      size;
    double      time;

    /* Set signal handling and alarm */
    if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR)
        critical("Setup SIGALRM trap failed!");

    /* Process check arguments */
    if (process_arguments(argc, argv) != OK)
        unknown("Parsing arguments failed!");

    /* Start plugin timeout */
    alarm(mp_timeout);

    /* Magik */

    size_t urllen = strlen(hostname)+strlen(filename) + 9;

    url = mp_malloc(urllen);

    snprintf(url, urllen, "tftp://%s/%s", hostname, filename);

    if (mp_verbose > 0) {
        printf("CURL Version: %s\n", curl_version());
        printf("Try fetch %s\n", url);
        print_thresholds("fetch_thresholds", fetch_thresholds);
    }

    /* Init libcurl */
    curl = mp_curl_init();

    /* Setup request */
    if (curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_TFTP) == CURLE_UNSUPPORTED_PROTOCOL)
        unknown("libcurl don't support tftp.");
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, mp_curl_recv_blackhole);
    if (port != 0)
        curl_easy_setopt(curl, CURLOPT_LOCALPORT, port);

    /* Perform Request */
    mp_curl_perform(curl);

    /* Get metric */
    curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &time);
    curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD , &size);

    /* Clenup libcurl */
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    mp_perfdata_float("time", (float)time, "s", fetch_thresholds);
    free(url);

    switch(get_status(time, fetch_thresholds)) {
    case STATE_OK:
        free_threshold(fetch_thresholds);
        ok("Received %'.0fbyte in %fs.", size, time);
        break;
    case STATE_WARNING:
        free_threshold(fetch_thresholds);
        warning("Received %'.0fbyte in %fs.", size, time);
        break;
    case STATE_CRITICAL:
        free_threshold(fetch_thresholds);
        critical("Received %'.0fbyte in %fs.", size, time);
        break;
    }
    free_threshold(fetch_thresholds);

    critical("You should never reach this point.");
}
Exemplo n.º 12
0
// Inference rules, in order of appearance
//
//                LESS x y   LESS x z
//   ----------   -------------------
//   LESS x TOP     LESS x RAND y z
//
//                LESS y x   LESS z x   LESS y x   LESS z x
//   ----------   -------------------   -------------------
//   LESS BOT x     LESS JOIN y z x       LESS RAND y z x
//
bool Approximator::try_close(Approximation& approx, DenseSet& temp_set) {
    POMAGMA_ASSERT_EQ(approx.lower.item_dim(), m_item_dim);
    POMAGMA_ASSERT_EQ(approx.upper.item_dim(), m_item_dim);
    POMAGMA_ASSERT_EQ(temp_set.item_dim(), m_item_dim);

    Approximation start = unknown();
    start = approx;

    if (approx.ob) {
        approx.upper.raw_insert(approx.ob);
        approx.lower.raw_insert(approx.ob);
    }

    approx.upper.raw_insert(m_top);
    for (auto iter = approx.upper.iter(); iter.ok(); iter.next()) {
        Ob ob = *iter;
        approx.upper += m_less.get_Lx_set(ob);

        if (m_rand) {
            temp_set.set_insn(approx.upper, m_rand->get_Lx_set(ob));
            for (auto iter = temp_set.iter(); iter.ok(); iter.next()) {
                Ob other = *iter;
                if (other >= ob) {
                    break;
                }
                Ob val = m_rand->find(ob, other);
                approx.upper.raw_insert(val);
            }
        }
    }

    approx.lower.raw_insert(m_bot);
    for (auto iter = approx.lower.iter(); iter.ok(); iter.next()) {
        Ob ob = *iter;
        approx.lower += m_less.get_Rx_set(ob);

        if (m_join) {
            temp_set.set_insn(approx.lower, m_join->get_Lx_set(ob));
            for (auto iter = temp_set.iter(); iter.ok(); iter.next()) {
                Ob other = *iter;
                if (other >= ob) {
                    break;
                }
                Ob val = m_join->find(ob, other);
                approx.lower.raw_insert(val);
            }
        }

        if (m_rand) {
            temp_set.set_insn(approx.lower, m_rand->get_Lx_set(ob));
            for (auto iter = temp_set.iter(); iter.ok(); iter.next()) {
                Ob other = *iter;
                if (other >= ob) {
                    break;
                }
                Ob val = m_rand->find(ob, other);
                approx.lower.raw_insert(val);
            }
        }
    }

    if (not approx.ob) {
        temp_set.set_insn(approx.upper, approx.lower);
        for (auto iter = temp_set.iter(); iter.ok(); iter.next()) {
            approx.ob = *iter;
            break;
        }
    }

    return approx == start;
}
Exemplo n.º 13
0
int main (int argc, char **argv) {
    /* Local Vars */
    char        *output = NULL;
    char        *pdu_name = NULL;
    int         status = STATE_OK;
    long        pdu_psu1 = -1;
    long        pdu_psu2 = -1;
    long int    outlet_state;
    char        *outlet_name;
    int         i;
    int         rc = 0;
    mp_snmp_subtree         table_state;
    netsnmp_session         *ss;

    /* Set signal handling and alarm */
    if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR)
        critical("Setup SIGALRM trap failed!");

    /* Process check arguments */
    if (process_arguments(argc, argv) != OK)
        unknown("Parsing arguments failed!");

    /* Start plugin timeout */
    alarm(mp_timeout);

    ss = mp_snmp_init();

    /* OIDs to query */
    mp_snmp_query_cmd snmpcmd[] = {
        {{1,3,6,1,4,1,318,1,1,12,4,1,1,0}, 14,
            ASN_INTEGER, (void *)&pdu_psu1, sizeof(long int)},
        {{1,3,6,1,4,1,318,1,1,12,4,1,2,0}, 14,
            ASN_INTEGER, (void *)&pdu_psu2, sizeof(long int)},
        {{1,3,6,1,2,1,1,5,0}, 9,
            ASN_OCTET_STR, (void *)&pdu_name, 0},
        {{0}, 0, 0, 0},
    };

    rc = mp_snmp_query(ss, snmpcmd);
    if (rc != STAT_SUCCESS) {
        char *string;
        snmp_error(ss, NULL, NULL, &string);
        unknown("APC PDU: Error fetching values: %s", string);
    }

    rc = mp_snmp_subtree_query(ss, MP_OID(1,3,6,1,4,1,318,1,1,12,3,5,1),
        &table_state);
    if (rc != STAT_SUCCESS) {
        char *string;
        snmp_error(ss, NULL, NULL, &string);
        unknown("APC PDU: Error fetching table: %s", string);
    }

    mp_snmp_deinit();

    // Check for PSU Failure
    if (pdu_psu1 != 1) {
        status = STATE_CRITICAL;
        output = strdup("Power Supply 1 Failed!");
    } else if (pdu_psu2 != 1) {
        status = STATE_CRITICAL;
        output = strdup("Power Supply 2 Failed!");
    }

    outlet_name = mp_malloc(64);

    if (stateOn == NULL && stateOff == NULL) {
        // Check all outlets for on.
        long int outlet_state;
        for (i = 0; i<table_state.size; i++) {
            rc = mp_snmp_subtree_get_value(&table_state,
                MP_OID(1,3,6,1,4,1,318,1,1,12,3,5,1,1,4), i,
                ASN_INTEGER, (void *)&outlet_state, sizeof(long int));
            
            if (rc != 1)
                break;

            if (outlet_state != 1) {
                mp_snmp_subtree_get_value(&table_state,
                    MP_OID(1,3,6,1,4,1,318,1,1,12,3,5,1,1,2), i,
                    ASN_OCTET_STR, (void *)&outlet_name, 64);

                mp_strcat_space(&output, outlet_name);
                mp_strcat_space(&output, " is off!");
                status = STATE_CRITICAL;
            }
        }
    } else {
        if (stateOn != NULL) {
            char *c, *s, *p;
            p = s = strdup(stateOn);
            while((c = strsep(&s, ","))) {
                i = strtol(c, NULL, 10);
                if (i == 0) {
                    for (i = 0; i<table_state.size; i++) {
                        rc = mp_snmp_subtree_get_value(&table_state,
                            MP_OID(1,3,6,1,4,1,318,1,1,12,3,5,1,1,2), i,
                            ASN_OCTET_STR, (void *)&outlet_name, 64);

                        if (rc == 0 || strcmp(c, outlet_name) == 0)
                            break;
                    }
                    if (rc == 0) {
                        mp_strcat_space(&output, c);
                        mp_strcat_space(&output, " not found!");
                        status = status == STATE_OK ? STATE_UNKNOWN : status;
                        continue;
                    }
                } else {
                    i--;
                }
                    
                rc = mp_snmp_subtree_get_value(&table_state,
                    MP_OID(1,3,6,1,4,1,318,1,1,12,3,5,1,1,4), i,
                    ASN_INTEGER, (void *)&outlet_state, sizeof(long int));

                if (rc == 0) {
                    mp_strcat_space(&output, c);
                    mp_strcat_space(&output, " not found!");
                    status = status == STATE_OK ? STATE_UNKNOWN : status;
                    continue;
                }

                if (outlet_state != 1) {
                    mp_snmp_subtree_get_value(&table_state,
                        MP_OID(1,3,6,1,4,1,318,1,1,12,3,5,1,1,2), i,
                        ASN_OCTET_STR, (void *)&outlet_name, 64);

                    mp_strcat_space(&output, outlet_name);
                    mp_strcat_space(&output, " is off!");
                    status = STATE_CRITICAL;
                }
            }
            free( p );
        }
        if (stateOff != NULL) {
            char *c, *s, *p;
            p = s = strdup(stateOff);
            while((c = strsep(&s, ","))) {
                i = strtol(c, NULL, 10);
                if (i == 0) {
                    for (i = 0; i<table_state.size; i++) {
                        rc = mp_snmp_subtree_get_value(&table_state,
                            MP_OID(1,3,6,1,4,1,318,1,1,12,3,5,1,1,2), i,
                            ASN_OCTET_STR, (void *)&outlet_name, 64);

                        if (rc == 0 || strcmp(c, outlet_name) == 0)
                            break;
                    }
                    if (rc == 0) {
                        mp_strcat_space(&output, c);
                        mp_strcat_space(&output, " not found!");
                        status = status == STATE_OK ? STATE_UNKNOWN : status;
                        continue;
                    }
                } else {
                    i--;
                }

                rc = mp_snmp_subtree_get_value(&table_state,
                    MP_OID(1,3,6,1,4,1,318,1,1,12,3,5,1,1,4), i,
                    ASN_INTEGER, (void *)&outlet_state, sizeof(long int));

                if (rc == 0) {
                    mp_strcat_space(&output, c);
                    mp_strcat_space(&output, " not found!");
                    status = status == STATE_OK ? STATE_UNKNOWN : status;
                    continue;
                }

                if (outlet_state != 2) {
                    mp_snmp_subtree_get_value(&table_state,
                        MP_OID(1,3,6,1,4,1,318,1,1,12,3,5,1,1,2), i,
                        ASN_OCTET_STR, (void *)&outlet_name, 64);

                    mp_strcat_space(&output, outlet_name);
                    mp_strcat_space(&output, " is on!");
                    status = STATE_CRITICAL;
                }
            }
            free( p );
        }
    }

    mp_snmp_subtree_free(&table_state);
    free(outlet_name);

    /* Output and return */
    if (status == STATE_OK)
        ok("APC PDU %s", pdu_name);
    if (status == STATE_WARNING)
        warning("APC PDU %s [%s]", pdu_name, output);
    if (status == STATE_UNKNOWN)
        unknown("APC PDU %s [%s]", pdu_name, output);
    critical("APC PDU %s [%s]", pdu_name, output);
}
Exemplo n.º 14
0
int main (int argc, char **argv) {
    /* Local Vars */
    int             state = STATE_OK;
    char            *ups_ident              = NULL;
    long            ups_battery_status      = LONG_MIN;
    long            ups_seconds_on_battery  = LONG_MIN;
    long            ups_remaining_runtime   = LONG_MIN;
    long            ups_remaining_charge    = LONG_MIN;
    long            ups_battery_voltage     = LONG_MIN;
    long            ups_battery_current     = LONG_MIN;
    long            ups_battery_temperature = LONG_MIN;
    long            ups_input_line_bads     = LONG_MIN;
    long            ups_input_lines         = LONG_MIN;
    long            ups_output_source       = LONG_MIN;
    long            ups_output_frequency    = LONG_MIN;
    long            ups_output_lines        = LONG_MIN;
    long            ups_alarms_present      = LONG_MIN;
    char            *output = NULL;
    char            buf[64];
    netsnmp_session *snmp_session;

    mp_snmp_query_cmd snmpcmd[] = {
        {{1,3,6,1,2,1,33,1,1,5,0}, 11, ASN_OCTET_STR,
         (void *)&ups_ident, 0},
        {{1,3,6,1,2,1,33,1,2,1,0}, 11, ASN_INTEGER,
         (void *)&ups_battery_status, sizeof(long int)},
        {{1,3,6,1,2,1,33,1,2,2,0}, 11, ASN_INTEGER,
         (void *)&ups_seconds_on_battery, sizeof(long int)},
        {{1,3,6,1,2,1,33,1,2,3,0}, 11, ASN_INTEGER,
         (void *)&ups_remaining_runtime, sizeof(long int)},
        {{1,3,6,1,2,1,33,1,2,4,0}, 11, ASN_INTEGER,
         (void *)&ups_remaining_charge, sizeof(long int)},
        {{1,3,6,1,2,1,33,1,2,5,0}, 11, ASN_INTEGER,
         (void *)&ups_battery_voltage, sizeof(long int)},     /* 0.1 volts DC */
        {{1,3,6,1,2,1,33,1,2,6,0}, 11, ASN_INTEGER,
         (void *)&ups_battery_current, sizeof(long int)},     /* 0.1 amps DC */
        {{1,3,6,1,2,1,33,1,2,7,0}, 11, ASN_INTEGER,
         (void *)&ups_battery_temperature, sizeof(long int)}, /* deg C */
        {{1,3,6,1,2,1,33,1,3,1,0}, 11, ASN_COUNTER,
         (void *)&ups_input_line_bads, sizeof(long int)},
        {{1,3,6,1,2,1,33,1,3,2,0}, 11, ASN_INTEGER,
         (void *)&ups_input_lines, sizeof(long int)},
        {{1,3,6,1,2,1,33,1,4,1,0}, 11, ASN_INTEGER,
         (void *)&ups_output_source, sizeof(long int)},
        {{1,3,6,1,2,1,33,1,4,2,0}, 11, ASN_INTEGER,
         (void *)&ups_output_frequency, sizeof(long int)}, /* 0.1 RMS */
        {{1,3,6,1,2,1,33,1,4,3,0}, 11, ASN_INTEGER,
         (void *)&ups_output_lines, sizeof(long int)},
        {{1,3,6,1,2,1,33,1,6,1,0}, 11, ASN_GAUGE,
         (void *)&ups_alarms_present, sizeof(long int)},
        {{0}, 0, 0, NULL},
    };

    /* set threshold defaults */
    mp_threshold_set_warning(&threshold_charge, DEFAULT_CHARGE_WARNING, NOEXT);
    mp_threshold_set_critical(&threshold_charge, DEFAULT_CHARGE_CRITICAL, NOEXT);
    mp_threshold_set_warning(&threshold_runtime, DEFAULT_RUNTIME_WARNING, NOEXT);
    mp_threshold_set_critical(&threshold_runtime, DEFAULT_RUNTIME_CRITICAL, NOEXT);

    /* Set signal handling and alarm */
    if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR)
        critical("Setup SIGALRM trap failed!");

    /* Process check arguments */
    if (process_arguments(argc, argv) != OK)
        unknown("Parsing arguments failed!");

    /* Start plugin timeout */
    alarm(mp_timeout);

    snmp_session = mp_snmp_init();
    mp_snmp_query(snmp_session, snmpcmd);
    mp_snmp_deinit();

    if (mp_verbose > 1) {
        printf("battery status: %ld\n", ups_battery_status);
        printf("output source: %ld\n", ups_output_source);
        printf("alarms present: %ld\n", ups_alarms_present);
        printf("input lines: %ld\n", ups_input_lines);
        printf("output lines: %ld\n", ups_output_lines);
        printf("input line bads: %ld\n", ups_input_line_bads);
    }

    if (ups_ident) {
        if (*ups_ident != '\0') {
            mp_snprintf((char *)&buf, sizeof(buf), "[%s] ", ups_ident);
            mp_strcat(&output, buf);
        }
        free(ups_ident);
    }

    /* always warning, if on battery */
    if ((ups_seconds_on_battery > 0) ||
        (ups_output_source == OUTPUT_BATTERY)) {
        state = STATE_WARNING;
        if (ups_seconds_on_battery > 0) {
            mp_snprintf((char *) &buf, sizeof(buf),
                        "ON BATTERY (since %d sec%s), ",
                        ups_seconds_on_battery,
                        ((ups_seconds_on_battery != 1) ? "s" : ""));
            mp_strcat(&output, buf);
        } else {
            mp_strcat(&output, "ON BATTERY, ");
        }
    }

    /* check alarms */
    if ((ups_alarms_present != LONG_MIN) && (ups_alarms_present > 0)) {
        if (state != STATE_CRITICAL)
            state = STATE_WARNING;

        if (ups_alarms_present == 1)
            mp_strcat(&output, "UPS REPORTS AN ALARM, ");
        else
            mp_strcat(&output, "UPS REPORTS MULTIPLE ALARMS, ");
    }

    /* check remaining runtime threshold */
    if (ups_remaining_runtime > LONG_MIN) {
        switch (get_status(ups_remaining_runtime, threshold_runtime)) {
        case STATE_CRITICAL:
            state = STATE_CRITICAL;
            mp_strcat(&output, "RUNTIME CRITICAL, ");
            break;
        case STATE_WARNING:
            if (state == STATE_OK)
                state = STATE_WARNING;
            mp_strcat(&output, "RUNTIME WARNING, ");
            break;
        } /* switch */
    }

    /* check remaining charge threshold */
    if (ups_remaining_charge > LONG_MIN) {
        switch (get_status(ups_remaining_charge, threshold_charge)) {
        case STATE_CRITICAL:
            state = STATE_CRITICAL;
            mp_strcat(&output, "CHARGE CRITICAL, ");
            break;
        case STATE_WARNING:
            if (state == STATE_OK)
                state = STATE_WARNING;
            mp_strcat(&output, "CHARGE WARNING, ");
            break;
        } /* switch */
    }

    /* check battery status */
    switch (ups_battery_status) {
    case BATTERY_NORMAL:
        break;
    case BATTERY_LOW:
        state = STATE_CRITICAL;
        break;
    case BATTERY_DEPLETED:
        state = STATE_CRITICAL;
        break;
    case BATTERY_UNKNOWN:
        /* FALL-THROUGH */
    default:
        if (state == STATE_OK)
            state = STATE_UNKNOWN;
        break;
    } /* switch */

    /* check output source */
    switch (ups_output_source) {
    case OUTPUT_NORMAL:
        /* DO NOTHING */
        break;
    case OUTPUT_OTHER:
        /* FALL-THROUGH */
    case OUTPUT_BYPASS:
        /* FALL-THROUGH */
    case OUTPUT_BOOSTER:
        /* FALL-THROUGH */
    case OUTPUT_REDUCER:
        /* FALL-THROUGH */
    case OUTPUT_BATTERY:
        /* FALL-THROUGH */
        if (state != STATE_CRITICAL)
            state = STATE_WARNING;
        break;
    case OUTPUT_NONE:
        state = STATE_CRITICAL;
        break;
    default:
        if (state == STATE_OK)
            state = STATE_UNKNOWN;
        break;
    } /* switch */

    /*
     * status line
     */
    mp_snprintf((char *) &buf, sizeof(buf), "battery: %s",
                battery_status_to_string(ups_battery_status));
    mp_strcat(&output, buf);

    if ((ups_remaining_runtime > LONG_MIN) &&
        (ups_remaining_charge > LONG_MIN)) {
        mp_snprintf((char *) &buf, sizeof(buf),
                    "remaining: %ld min%s [%d%%]",
                    ups_remaining_runtime,
                    ((ups_remaining_runtime != 1) ? "s" : ""),
                    (int) ups_remaining_charge);
        mp_strcat_comma(&output, buf);
    } else if (ups_remaining_runtime > LONG_MIN) {
        mp_snprintf((char *) &buf, sizeof(buf),
                    "remaining: %ld min%s",
                    ups_remaining_runtime,
                    ((ups_remaining_runtime != 1) ? "s" : ""));
        mp_strcat_comma(&output, buf);
    } else if (ups_remaining_charge > LONG_MIN) {
        mp_snprintf((char *) &buf, sizeof(buf),
                    "remaining: %d%%",
                    (int) ups_remaining_charge);
        mp_strcat_comma(&output, buf);
    }

    mp_snprintf((char *) &buf, sizeof(buf), "source: %s",
                output_source_to_string(ups_output_source));
    mp_strcat_comma(&output, buf);

    if (extended_status) {
        if (ups_battery_voltage > LONG_MIN) {
            mp_snprintf((char *) &buf, sizeof(buf),
                        "voltage: %1.0f V",
                        (ups_battery_voltage * 0.1f));
            mp_strcat_comma(&output, buf);
        }
        if (ups_battery_current > LONG_MIN) {
            mp_snprintf((char *) &buf, sizeof(buf),
                        "current: %1.1f A",
                        (ups_battery_current * 0.1f));
            mp_strcat_comma(&output, buf);
        }
        if (ups_battery_temperature > LONG_MIN) {
            mp_snprintf((char *) &buf, sizeof(buf),
                        "temperature: %ld C",
                        ups_battery_temperature);
            mp_strcat_comma(&output, buf);
        }
        if (ups_output_frequency > LONG_MIN) {
            mp_snprintf((char *) &buf, sizeof(buf),
                        "output frequency: %3.1f Hz",
                        (ups_output_frequency * 0.1f));
            mp_strcat_comma(&output, buf);
        }
        if (ups_input_line_bads > LONG_MIN) {
            mp_snprintf((char *) &buf, sizeof(buf),
                        "input line bads: %ld",
                        ups_input_line_bads);
            mp_strcat_comma(&output, buf);
        }
    }

    /*
     * performance data
     */
    if (mp_showperfdata) {
        if (ups_remaining_charge > LONG_MIN) {
            mp_perfdata_int("remaining_charge",
                            ups_remaining_charge,
                            "%", threshold_charge);
        }
        if (ups_remaining_runtime > LONG_MIN) {
            mp_perfdata_int("remaining_runtime",
                            ups_remaining_charge,
                            "minutes", threshold_runtime);
        }
        if (ups_battery_voltage > LONG_MIN) {
            mp_perfdata_float("battery_voltage",
                              ups_battery_voltage * 0.1f,
                              "V", NULL);
        }
        if (ups_battery_current > LONG_MIN) {
            mp_perfdata_float("battery_current",
                              ups_battery_current * 0.1f,
                              "A", NULL);
        }
        if (ups_battery_temperature > LONG_MIN) {
            mp_perfdata_int("battery_temperature",
                            ups_battery_temperature,
                            "C", NULL);
        }
        if (ups_output_frequency > LONG_MIN) {
            mp_perfdata_float("output_frequency",
                              ups_output_frequency * 0.1f,
                              "Hz", NULL);
        }
        if (ups_input_line_bads > LONG_MIN) {
            mp_perfdata_int("input_line_bads",
                            ups_input_line_bads,
                            "", NULL);
        }
    }

    switch (state) {
        case STATE_OK:
            ok("UPS: %s", output);
            break;
        case STATE_WARNING:
            warning("UPS: %s", output);
            break;
        case STATE_CRITICAL:
            critical("UPS: %s", output);
            break;
        default:
            unknown("UPS: %s", output);
            break;
    }
}
Exemplo n.º 15
0
double Teval::function(void)
{
    char_t f[20], *p;
    double v;

    p = f;
    while (p - f < 19 && *c >= 'a' && *c <= 'z') {
        *p++ = *c;
        next();
    }

    *p = 0;

    double var;
    if (getVariable(f, &var)) {
        return var;
    }

    v = term();

    if (strcmp(f, _l("abs")) == 0) {
        return fabs(v);
    } else if (strcmp(f, _l("fabs")) == 0) {
        return fabs(v);
    } else if (strcmp(f, _l("floor")) == 0) {
        return floor(v);
    } else if (strcmp(f, _l("ceil")) == 0) {
        return ceil(v);
    } else if (strcmp(f, _l("sqrt")) == 0) {
        return sqrt(v);
    } else if (strcmp(f, _l("exp")) == 0) {
        return exp(v);
    }

    else if (strcmp(f, _l("sin")) == 0) {
        return sin(v);
    } else if (strcmp(f, _l("cos")) == 0) {
        return cos(v);
    } else if (strcmp(f, _l("tan")) == 0) {
        return tan(v);
    } else if (strcmp(f, _l("asin")) == 0) {
        return asin(v);
    } else if (strcmp(f, _l("acos")) == 0) {
        return acos(v);
    } else if (strcmp(f, _l("atan")) == 0) {
        return atan(v);
    }

    else if (strcmp(f, _l("sinh")) == 0) {
        return sinh(v);
    } else if (strcmp(f, _l("cosh")) == 0) {
        return cosh(v);
    } else if (strcmp(f, _l("tanh")) == 0) {
        return tanh(v);
    }

    else if (strcmp(f, _l("ln")) == 0) {
        return log(v);
    } else if (strcmp(f, _l("log")) == 0) {
        return log(v) / M_LN2;
    } else {
        unknown(f);
        return 0;
    }
}
Exemplo n.º 16
0
void Browser::DetachEvents() {
  LOG(TRACE) << "Entering Browser::DetachEvents";
  CComQIPtr<IDispatch> dispatch(this->browser_);
  CComPtr<IUnknown> unknown(dispatch);
  HRESULT hr = this->DispEventUnadvise(unknown);
}
Exemplo n.º 17
0
int test19() {
  (void)(unknown_nohalt() && unknown());
} // expected-warning {{control reaches end of non-void function}}
Exemplo n.º 18
0
void PixmapItem::loadPixmap(QDomElement text )
{
    QDomNode node = text.firstChild();

    qreal posX = 0;
    qreal posY = 0;
    qreal zValue = 0;

    while(!node.isNull())
    {
        if(node.toElement().tagName() == "name")
        {
            name = node.toElement().text();
        }
        if(node.toElement().tagName() == "source")
        {
            source = node.toElement().text().toInt();
        }
        if(node.toElement().tagName() == "file")
        {
            file = node.toElement().text();
        }
        if(node.toElement().tagName() == "posX")
        {
            posX = node.toElement().text().toInt();
        }
        if(node.toElement().tagName() == "posY")
        {
            posY = node.toElement().text().toInt();
        }
        if(node.toElement().tagName() == "zValue")
        {
            zValue = node.toElement().text().toFloat();
        }

        if(node.toElement().tagName() == "width")
        {
            size.setWidth( node.toElement().text().toInt() );
        }
        if(node.toElement().tagName() == "height")
        {
            size.setHeight(node.toElement().text().toInt());
        }

        if(node.toElement().tagName() == "isLocked")
        {
            isLocked = node.toElement().text().toInt();

            if(isLocked) {
                setFlag(QGraphicsItem::ItemIsMovable, false);
            }

        }

        node = node.nextSibling();
    }

    setZValue(zValue);

    if(source==0)
    {
        QPixmap p(file);
        p = p.scaledToWidth(size.width(),Qt::SmoothTransformation);
        setPos(posX, posY);
        setPixmap(p);
    }
    else
    {
        setPos(posX, posY);

        QFile unknown(":/images/unknown.jpg");

        if(unknown.open(QIODevice::ReadOnly)) {
            pictureBufferUnknown.setData(unknown.readAll());
            setHoruxPixmap(pictureBufferUnknown.data());
        }
    }
}
Exemplo n.º 19
0
int test26() {
  0 ? halt3() : unknown();
} // expected-warning {{control reaches end of non-void function}}
Exemplo n.º 20
0
// TODO: Implement common engine function for read and processing of sound blocks
//       for use by this opcode and VIEW sound block.
// TODO: Though the playSound and PlaySoundBlocking opcodes play sounds immediately,
//       this opcode changes the main background sound playing..
//       Current behavior here and with VIEW sound block is not right as demonstrated
//       by Channelwood Card 3280 (Tank Valve) and water flow sound behavior in pipe
//       on cards leading from shed...
void MystScriptParser::o_changeBackgroundSound(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	varUnusedCheck(op, var);

	int16 *soundList = NULL;
	uint16 *soundListVolume = NULL;

	// Used on Stoneship Card 2080
	// Used on Channelwood Card 3225 with argc = 8 i.e. Conditional Sound List
	if (argc == 1 || argc == 2 || argc == 8) {
		debugC(kDebugScript, "Opcode %d: Process Sound Block", op);
		uint16 decodeIdx = 0;

		int16 soundAction = argv[decodeIdx++];
		uint16 soundVolume = 65535;
		if (soundAction == kMystSoundActionChangeVolume || soundAction > 0) {
			soundVolume = argv[decodeIdx++];
		} else if (soundAction == kMystSoundActionConditional) {
			debugC(kDebugScript, "Conditional sound list");
			uint16 condVar = argv[decodeIdx++];
			uint16 condVarValue = getVar(condVar);
			uint16 condCount = argv[decodeIdx++];

			debugC(kDebugScript, "\tcondVar: %d = %d", condVar, condVarValue);
			debugC(kDebugScript, "\tcondCount: %d", condCount);

			soundList = new int16[condCount];
			soundListVolume = new uint16[condCount];

			if (condVarValue >= condCount)
				warning("Opcode %d: Conditional sound variable outside range",  op);
			else {
				for (uint16 i = 0; i < condCount; i++) {
					soundList[i] = argv[decodeIdx++];
					debugC(kDebugScript, "\t\tCondition %d: Action %d", i, soundList[i]);
					if (soundAction == kMystSoundActionChangeVolume || soundAction > 0) {
						soundListVolume[i] = argv[decodeIdx++];
					} else
						soundListVolume[i] = 65535;
					debugC(kDebugScript, "\t\tCondition %d: Volume %d", i, soundListVolume[i]);
				}

				soundAction = soundList[condVarValue];
				soundVolume = soundListVolume[condVarValue];
			}
		}

		if (soundAction == kMystSoundActionContinue)
			debugC(kDebugScript, "Continue current sound");
		else if (soundAction == kMystSoundActionChangeVolume) {
			debugC(kDebugScript, "Continue current sound, change volume");
			debugC(kDebugScript, "\tVolume: %d", soundVolume);
			_vm->_sound->changeBackgroundVolumeMyst(soundVolume);
		} else if (soundAction == kMystSoundActionStop) {
			debugC(kDebugScript, "Stop sound");
			_vm->_sound->stopBackgroundMyst();
		} else if (soundAction > 0) {
			debugC(kDebugScript, "Play new Sound, change volume");
			debugC(kDebugScript, "\tSound: %d", soundAction);
			debugC(kDebugScript, "\tVolume: %d", soundVolume);
			_vm->_sound->replaceBackgroundMyst(soundAction, soundVolume);
		} else {
			debugC(kDebugScript, "Unknown");
			warning("Unknown sound control value in opcode %d", op);
		}
	} else
		unknown(op, var, argc, argv);

	delete[] soundList;
	soundList = NULL;
	delete[] soundListVolume;
	soundListVolume = NULL;
}
Exemplo n.º 21
0
int test9() {
  (void)(halt3() + unknown());
}
Exemplo n.º 22
0
void stunHash()
{
    QString m_localUser = "******";
    QString m_remoteUser = "******";
    QString m_remotePassword = "******";

    QByteArray username = QString("%1:%2").arg(m_remoteUser, m_localUser).toUtf8();
    quint16 usernameSize = username.size();
    username += QByteArray::fromHex("e1c318");
//    username += QByteArray(4 * ((usernameSize + 3) / 4) - usernameSize, 0);
    quint32 priority = 1862270975;
    QByteArray unknown(8, 0);
    QByteArray key = m_remotePassword.toUtf8();

    QByteArray buffer;
    QDataStream stream(&buffer, QIODevice::WriteOnly);
    quint16 type = BindingRequest;
    quint16 length = 0;
    QByteArray id = QByteArray::fromHex("93be62deb6e5418f9f87b68b");
    stream << type;
    stream << length;
    stream << MAGIC_COOKIE;
    stream.writeRawData(id.data(), id.size());

    stream << quint16(Priority);
    stream << quint16(sizeof(priority));
    stream << priority;

    stream << quint16(Unknown);
    stream << quint16(unknown.size());
    stream.writeRawData(unknown.data(), unknown.size());

    stream << quint16(Username);
    stream << usernameSize;
    stream.writeRawData(username.data(), username.size());

    // integrity
    length = buffer.size() - 20 + 24;
    qint64 pos = stream.device()->pos();
    stream.device()->seek(2);
    stream << length;
    stream.device()->seek(pos);

    QByteArray integrity = QXmppUtils::generateHmacSha1(key, buffer);
    qDebug() << "integrity" << integrity.toHex();
    stream << quint16(MessageIntegrity);
    stream << quint16(integrity.size());
    stream.writeRawData(integrity.data(), integrity.size());

    // fingerprint
    length = buffer.size() - 20 + 8;
    pos = stream.device()->pos();
    stream.device()->seek(2);
    stream << length;
    stream.device()->seek(pos);

    quint32 fingerprint = QXmppUtils::generateCrc32(buffer) ^ 0x5354554eL;
    qDebug() << "fingerprint" << fingerprint;
    stream << quint16(Fingerprint);
    stream << quint16(sizeof(fingerprint));
    stream << fingerprint;

    // output
    buffer.prepend(QByteArray(10, 0));
    for (int i = 0; i < buffer.size(); i += 16)
    {
        QByteArray chunk = buffer.mid(i, 16);
        QString str;
        for (int j = 0; j < 16; j += 1)
            str += chunk.mid(j, 1).toHex() + " ";
        qDebug() << str;
    }

}
Exemplo n.º 23
0
int test12() {
  (void)(halt3() || unknown());
}
Exemplo n.º 24
0
int main (int argc, char **argv) {
    /* Local Vars */
    int             i;
    int             j;
    char            *filename;
    bonding_info    *info;
    char            *buf;
    char            *output = NULL;
    int             status = STATE_OK;

    /* Set signal handling and alarm */
    if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR)
        critical("Setup SIGALRM trap failed!");

    /* Process check arguments */
    if (process_arguments(argc, argv) != OK)
        unknown("Parsing arguments failed!");

    /* Start plugin timeout */
    alarm(mp_timeout);

    if (bonds==0) {
        DIR *dir;
        struct dirent   *entry;
        dir = opendir("/proc/net/bonding/");
        if (dir == NULL)
            critical("Can't open '/proc/net/bonding/'");

        while ((entry = readdir(dir)) != NULL) {
            if (strncmp(entry->d_name, "bond", 4) == 0) {
                mp_array_push(&bond, strdup(entry->d_name), &bonds);
            }
        }

        closedir(dir);
    }

    filename = mp_malloc(sizeof(char)*32);
    buf = mp_malloc(sizeof(char)*64);

    for(i=0; i < bonds; i++) {
        mp_sprintf(filename, "/proc/net/bonding/%s", bond[i]);
        info = parseBond(filename);
        if (info == NULL) {
            status = STATE_CRITICAL;
            mp_snprintf(buf, 64, "%s not found", bond[i]);
            mp_strcat_comma(&output, buf);
        } else if (info->mii_status) {
            char *up = NULL;
            char *down = NULL;
            for(j=0; j < info->slaves; j++) {
                if (info->slave[j]->mii_status) {
                    mp_strcat_comma(&up, info->slave[j]->interface);
                } else {
                    mp_strcat_comma(&down, info->slave[j]->interface);
                }
            }
            if (down) {
                mp_snprintf(buf, 64, "%s up (%s, down: %s)", bond[i], up, down);
                status = status == STATE_OK ? STATE_WARNING : status;
            } else {
                mp_snprintf(buf, 64, "%s up (%s)", bond[i], up);
            }
            mp_strcat_comma(&output, buf);
        } else {
            mp_snprintf(buf, 64, "%s down (%s)", bond[i], info->mode);
            mp_strcat_comma(&output, buf);
            status = STATE_CRITICAL;
        }

    }

    switch (status) {
        case STATE_OK:
            ok(output);
            break;
        case STATE_WARNING:
            warning(output);
            break;
        case STATE_CRITICAL:
            critical(output);
            break;
        case STATE_UNKNOWN:
            unknown(output);
            break;
    }

    critical("You should never reach this point.");
}
Exemplo n.º 25
0
int test17() {
  (void)(1 && unknown());
} // expected-warning {{control reaches end of non-void function}}
Exemplo n.º 26
0
static int
flags(int ac, char **av)
{
	int	i;

	for (i = 1; i < ac && av[i][0] == '-'; i++) {
	nxt:	switch (av[i][1]) {
		case 'e':
			eflag = validate(&av[i][2], 'e');
			continue;
		case 'E':
			if (av[i][2])
				eflag = validate(&av[i][2], 'E');
			else if (++i < ac)
				eflag = validate(av[i], 'E');
			else
				missing('E');
			continue;
		case 'i':
			if (av[i][2])
				iflag = validate(&av[i][2], 'i');
			else
				iflag = "{}";
			continue;
		case 'I':
			if (av[i][2])
				iflag = validate(&av[i][2], 'i');
			else if (++i < ac)
				iflag = validate(av[i], 'i');
			else
				missing('I');
			continue;
		case 'l':
			if (av[i][2])
				lflag = number('l', &av[i][2]);
			else
				lflag = 1;
			xflag = 1;
			iflag = NULL;
			continue;
		case 'L':
			if (av[i][2])
				lflag = number('L', &av[i][2]);
			else if (++i < ac)
				lflag = number('L', av[i]);
			else
				mustbepos('L', "");
			xflag = 1;
			iflag = NULL;
			nflag = 0;
			continue;
		case 'n':
			if (av[i][2])
				nflag = number('n', &av[i][2]);
			else if (++i < ac)
				nflag = number('n', av[i]);
			else
				mustbepos('n', "");
			lflag = 0;
			continue;
		case 'p':
			pflag = open("/dev/tty", O_RDONLY);
			fcntl(pflag, F_SETFD, FD_CLOEXEC);
			tflag = 1;
			break;
		case 's':
			if (av[i][2])
				sflag = &av[i][2];
			else if (++i < ac)
				sflag = av[i];
			else
				sflag = "0";
			continue;
		case 't':
			tflag = 1;
			break;
		case 'x':
			xflag = 1;
			break;
		case '-':
			return ++i;
		default:
			unknown(&av[i][1]);
		}
		if (av[i][2]) {
			(av[i])++;
			goto nxt;
		}
	}
	return i;
}
int main () {
    /************************
        FILL 5 FIRST WHEELS
    ************************/
    char * tmp;
    int i,j,position;
    int input[5];

    for(i=0;i<73;i++) {
        R47[i%47] = 2;
        R61[i%61] = 2;
        R73[i%73] = 2;
        R71[i%71] = 2;
        R65[i%65] = 2;
    }

    for(i=0;i<1300-26;i++) {
        if(ciphertext[i]==29) {
            tmp = alphabet[i%26];
            R47[i%47] = (tmp[0]-48)^1;
            R61[i%61] = (tmp[1]-48)^1;
            R73[i%73] = (tmp[2]-48)^1;
            R71[i%71] = (tmp[3]-48)^1;
            R65[i%65] = (tmp[4]-48)^1;
        }
        else if (ciphertext[i]==32) {
            tmp = alphabet[i%26];
            R47[i%47] = (tmp[0]-48)^0;
            R61[i%61] = (tmp[1]-48)^0;
            R73[i%73] = (tmp[2]-48)^0;
            R71[i%71] = (tmp[3]-48)^0;
            R65[i%65] = (tmp[4]-48)^0;
        }
    }

    for(i=0;i<1300-26;i++) {
        tmp = alphabet[i%26];
        if(R47[i%47]==0 || R47[i%47]==1) input[0] = R47[i%47]^(tmp[0]-48); else input[0] = 2;
        if(R61[i%61]==0 || R61[i%61]==1) input[1] = R61[i%61]^(tmp[1]-48); else input[1] = 2;
        if(R73[i%73]==0 || R73[i%73]==1) input[2] = R73[i%73]^(tmp[2]-48); else input[2] = 2;
        if(R71[i%71]==0 || R71[i%71]==1) input[3] = R71[i%71]^(tmp[3]-48); else input[3] = 2;
        if(R65[i%65]==0 || R65[i%65]==1) input[4] = R65[i%65]^(tmp[4]-48); else input[4] = 2;

        if(hamingsweight(input)==weightoutput(extendedalphabet[ciphertext[i]-1])) {
            if(input[0]==2) R47[i%47] = 0^(tmp[0]-48);
            if(input[1]==2) R61[i%61] = 0^(tmp[1]-48);
            if(input[2]==2) R73[i%73] = 0^(tmp[2]-48);
            if(input[3]==2) R71[i%71] = 0^(tmp[3]-48);
            if(input[4]==2) R65[i%65] = 0^(tmp[4]-48);
        }
        else if(unknown(input)==weightoutput(extendedalphabet[ciphertext[i]-1]) && hamingsweight(input)==0) {
            if(input[0]==2) R47[i%47] = 1^(tmp[0]-48);
            if(input[1]==2) R61[i%61] = 1^(tmp[1]-48);
            if(input[2]==2) R73[i%73] = 1^(tmp[2]-48);
            if(input[3]==2) R71[i%71] = 1^(tmp[3]-48);
            if(input[4]==2) R65[i%65] = 1^(tmp[4]-48);

        }
    }

    /*for(i=0;i<1300-26;i++) {
        tmp = alphabet[i%26];
        printf("%d%d%d%d%d\n",(tmp[0]-48)^R47[i%47],(tmp[1]-48)^R61[i%61],(tmp[2]-48)^R73[i%73],(tmp[3]-48)^R71[i%71],(tmp[4]-48)^R65[i%65]);
        printf("%s\n\n",extendedalphabet[ciphertext[i]-1]);
    }*/

    /***************************
        PRINT 5 FIRST WHEELS
    ***************************/

    printf("\nWHEEL 47\n");
    for(i=0;i<47;i++)
        printf("%d ",R47[i]);

    printf("\nWHEEL 61\n");
    for(i=0;i<61;i++)
        printf("%d ",R61[i]);

    printf("\nWHEEL 73\n");
    for(i=0;i<73;i++)
        printf("%d ",R73[i]);

    printf("\nWHEEL 71\n");
    for(i=0;i<71;i++)
        printf("%d ",R71[i]);

    printf("\nWHEEL 65\n");
    for(i=0;i<65;i++)
        printf("%d ",R65[i]);

    /**************************
        FIND LAST CABLINGS
    **************************/

    /*for(i=0;i<73;i++) {
        input[0] = (alphabet[i%26][0]-48)^R47[i%47];
        input[1] = (alphabet[i%26][1]-48)^R61[i%61];
        input[2] = (alphabet[i%26][2]-48)^R73[i%73];
        input[3] = (alphabet[i%26][3]-48)^R71[i%71];
        input[4] = (alphabet[i%26][4]-48)^R65[i%65];

        if((hamingsweight(input)==1 && weightoutput(extendedalphabet[ciphertext[i]-1])==1) || (hamingsweight(input)==4 && weightoutput(extendedalphabet[ciphertext[i]-1])==4)) {
            for(j=0;j<5;j++)
                    printf("%d",input[j]);
            printf(" / %s\n",extendedalphabet[ciphertext[i]-1]);

            position = i + N;
            while(position<(1300-26)) {
                input[0] = (alphabet[position%26][0]-48)^R47[position%47];
                input[1] = (alphabet[position%26][1]-48)^R61[position%61];
                input[2] = (alphabet[position%26][2]-48)^R73[position%73];
                input[3] = (alphabet[position%26][3]-48)^R71[position%71];
                input[4] = (alphabet[position%26][4]-48)^R65[position%65];

                if((hamingsweight(input)==1 && weightoutput(extendedalphabet[ciphertext[position]-1])==1) || (hamingsweight(input)==4 && weightoutput(extendedalphabet[ciphertext[position]-1])==4)) {
                    for(j=0;j<5;j++)
                            printf("%d",input[j]);
                    printf(" / %s\n",extendedalphabet[ciphertext[position]-1]);
                }
                position += N;
            }
            printf("\n");
        }
    }*/

    /***********************
        FILL LAST WHEELS
    ***********************/

    for(i=0;i<73;i++) {
        R69[i%69] = 2;
        R59[i%59] = 2;
        R64[i%64] = 2;
        R53[i%53] = 2;
        R67[i%67] = 2;
    }

    char * control;
    for(i=0;i<1300-26;i++) {
        input[0] = (alphabet[i%26][0]-48)^R47[i%47];
        input[1] = (alphabet[i%26][1]-48)^R61[i%61];
        input[2] = (alphabet[i%26][2]-48)^R73[i%73];
        input[3] = (alphabet[i%26][3]-48)^R71[i%71];
        input[4] = (alphabet[i%26][4]-48)^R65[i%65];

        if((hamingsweight(input)==1 && weightoutput(extendedalphabet[ciphertext[i]-1])==1) || (hamingsweight(input)==4 && weightoutput(extendedalphabet[ciphertext[i]-1])==4)) {
            char * output = extendedalphabet[ciphertext[i]-1];
            control = controlbits(input,output);
            /*for(j=0;j<5;j++)
                printf("%d",input[j]);
            printf(" %s\n%s\n",output,control);*/
            if(strcmp(control,"NOMATCH")!=0) {
                if(control[0]=='0' || control[0]=='1') R69[i%69] = control[0]-48;
                if(control[1]=='0' || control[1]=='1') R59[i%59] = control[1]-48;
                if(control[2]=='0' || control[2]=='1') R64[i%64] = control[2]-48;
                if(control[3]=='0' || control[3]=='1') R53[i%53] = control[3]-48;
                if(control[4]=='0' || control[4]=='1') R67[i%67] = control[4]-48;
            }
        }
    }

    for(i=0;i<1300-26;i++) {
        input[0] = (alphabet[i%26][0]-48)^R47[i%47];
        input[1] = (alphabet[i%26][1]-48)^R61[i%61];
        input[2] = (alphabet[i%26][2]-48)^R73[i%73];
        input[3] = (alphabet[i%26][3]-48)^R71[i%71];
        input[4] = (alphabet[i%26][4]-48)^R65[i%65];

        char * output = extendedalphabet[ciphertext[i]-1];

        if((input[0]==1 && input[1]==0 && input[2]==1 && input[3]==0 && input[4]==0) && strcmp(output,"10100")==0) {
            R69[i%69] = 1;
            R64[i%64] = 1;
            R53[i%53] = 1;
            R67[i%67] = 1;
        }
        else if((input[0]==1 && input[1]==1 && input[2]==0 && input[3]==0 && input[4]==0) && strcmp(output,"11000")==0) {
            R69[i%69] = 1;
            R53[i%53] = 1;
        }
        else if((input[0]==1 && input[1]==0 && input[2]==1 && input[3]==0 && input[4]==1) && strcmp(output,"10101")==0) {
            R59[i%59] = 1;
            R64[i%64] = 1;
            R53[i%53] = 1;
            R67[i%67] = 1;
        }
        else if((input[0]==0 && input[1]==0 && input[2]==0 && input[3]==1 && input[4]==1) && strcmp(output,"00011")==0) {
            R69[i%69] = 1;
            R64[i%64] = 1;
        }
        else if((input[0]==0 && input[1]==0 && input[2]==1 && input[3]==1 && input[4]==1) && strcmp(output,"00111")==0) {
            R69[i%69] = 1;
            R53[i%53] = 1;
        }
        else if((input[0]==0 && input[1]==1 && input[2]==0 && input[3]==1 && input[4]==1) && strcmp(output,"01011")==0) {
            R69[i%69] = 1;
            R64[i%64] = 1;
            R53[i%53] = 1;
            R67[i%67] = 1;
        }
        else if((input[0]==0 && input[1]==1 && input[2]==0 && input[3]==0 && input[4]==1) && strcmp(output,"01001")==0) {
            R69[i%69] = 1;
            R59[i%59] = 1;
            R53[i%53] = 1;
            R67[i%67] = 1;
        }
        else if((input[0]==1 && input[1]==0 && input[2]==0 && input[3]==0 && input[4]==1) && strcmp(output,"10001")==0) {
            R59[i%59] = 1;
            R67[i%67] = 1;
        }
        else if((input[0]==1 && input[1]==0 && input[2]==0 && input[3]==1 && input[4]==1) && strcmp(output,"10011")==0) {
            R64[i%64] = 1;
            R67[i%67] = 1;
        }
        else if((input[0]==1 && input[1]==0 && input[2]==0 && input[3]==1 && input[4]==0) && strcmp(output,"10010")==0) {
            R69[i%69] = 1;
            R59[i%59] = 1;
            R64[i%64] = 1;
            R67[i%67] = 1;
        }
        else if((input[0]==0 && input[1]==1 && input[2]==0 && input[3]==1 && input[4]==0) && strcmp(output,"01010")==0) {
            R59[i%59] = 1;
            R64[i%64] = 1;
            R53[i%53] = 1;
            R67[i%67] = 1;
         }
         else if((input[0]==0 && input[1]==0 && input[2]==1 && input[3]==1 && input[4]==0) && strcmp(output,"00110")==0) {
            R59[i%59] = 1;
            R53[i%53] = 1;
         }
         else if((input[0]==0 && input[1]==0 && input[2]==1 && input[3]==0 && input[4]==1) && strcmp(output,"00101")==0) {
            R69[i%69] = 1;
            R59[i%59] = 1;
            R64[i%64] = 1;
            R53[i%53] = 1;
         }
         else if((input[0]==0 && input[1]==1 && input[2]==1 && input[3]==1 && input[4]==0) && strcmp(output,"00111")==0) {
            R59[i%59] = 0;
            R64[i%64] = 0;
            R53[i%53] = 0;
         }
         else if((input[0]==1 && input[1]==1 && input[2]==1 && input[3]==0 && input[4]==0) && strcmp(output,"00111")==0) {
            R69[i%69] = 0;
            R59[i%59] = 1;
            R64[i%64] = 0;
            R53[i%53] = 0;
         }
         else if((input[0]==1 && input[1]==1 && input[2]==1 && input[3]==0 && input[4]==0) && strcmp(output,"10011")==0) {
            R69[i%69] = 0;
            R59[i%59] = 1;
            R64[i%64] = 0;
            R53[i%53] = 1;
            R67[i%67] = 0;
         }
         else if((input[0]==1 && input[1]==1 && input[2]==0 && input[3]==1 && input[4]==0) && strcmp(output,"10011")==0) {
            R69[i%69] = 0;
            R64[i%64] = 1;
            R53[i%53] = 1;
            R67[i%67] = 0;
         }
    }

    R69[3] = 1;
    R69[4] = 0;
    R69[5] = 1;
    R69[15] = 1;
    R69[16] = 1;
    R69[17] = 1;
    R69[21] = 1;
    R69[22] = 0;
    R69[23] = 0;
    R69[27] = 0;
    R69[32] = 0;
    R69[39] = 0;
    R69[40] = 1;
    R69[48] = 0;
    R69[51] = 0;
    R69[52] = 0;
    R69[53] = 1;
    R69[58] = 0;
    R69[62] = 0;
    R69[66] = 1;

    R59[53] = 0;
    R59[54] = 1;

    R64[11] = 0;
    R64[20] = 0;
    R64[21] = 0;
    R64[24] = 0;
    R64[52] = 0;

    R53[10] = 0;
    R53[16] = 0;
    R53[31] = 0;
    R53[48] = 0;

    R67[4] = 1;
    R67[10] = 1;
    R67[15] = 0;
    R67[16] = 0;
    R67[19] = 0;
    R67[28] = 0;
    R67[36] = 0;
    R67[38] = 0;
    R67[40] = 0;
    R67[41] = 1;
    R67[50] = 0;
    R67[52] = 1;
    R67[53] = 0;
    R67[54] = 0;
    R67[56] = 0;
    R67[62] = 1;
    R67[64] = 0;
    R67[65] = 1;
    R67[66] = 0;

    /*********************
        PRINT LAST WHEELS
    *********************/

    printf("\nWHEEL 69\n");
    for(i=0;i<69;i++)
        printf("%d ",R69[i]);

    printf("\nWHEEL 59\n");
    for(i=0;i<59;i++)
        printf("%d ",R59[i]);

    printf("\nWHEEL 64\n");
    for(i=0;i<64;i++)
        printf("%d ",R64[i]);

    printf("\nWHEEL 53\n");
    for(i=0;i<53;i++)
        printf("%d ",R53[i]);

    printf("\nWHEEL 67\n");
    for(i=0;i<67;i++)
        printf("%d ",R67[i]);

    /***********************************
        PRINT BOTH OUTPUTS TO COMPARE
    ***********************************/

    int s;
    int test = 1;
    for(i=0;i<1300-26;i++) {
        input[0] = (alphabet[i%26][0]-48)^R47[i%47];
        input[1] = (alphabet[i%26][1]-48)^R61[i%61];
        input[2] = (alphabet[i%26][2]-48)^R73[i%73];
        input[3] = (alphabet[i%26][3]-48)^R71[i%71];
        input[4] = (alphabet[i%26][4]-48)^R65[i%65];

        int control[5] = {R69[i%69],R59[i%59],R64[i%64],R53[i%53],R67[i%67]};

        //if(inconnues(control)==0) {
            if(R69[i%69]==0) {s = input[4]; input[4] = input[0]; input[0] = s;}
            if(R59[i%59]==0) {s = input[3]; input[3] = input[4]; input[4] = s;}
            if(R64[i%64]==0) {s = input[2]; input[2] = input[3]; input[3] = s;}
            if(R53[i%53]==0) {s = input[1]; input[1] = input[2]; input[2] = s;}
            if(R67[i%67]==0) {s = input[0]; input[0] = input[1]; input[1] = s;}

            char * output = extendedalphabet[ciphertext[i]-1];
            //printf("%d  ",i);
            for(j=0;j<5;j++) {
                //printf("%d",input[j]);
                if(input[j]!=output[j]-48)
                    test = 0;
            }
            //printf("    %s  %d\n\n",output,test);
        //}
    }

    printf("\n\n\nIS EVERYTHING CORRECT ?\n\n");
    if(test)
        printf("YES, END OF WORK !! (ALMOST)\n\n");
    else
        printf("NO...");

    printf("LET'S CIPHER THE ALPHABET !!\n\n");

    /*****************************
        PRINT LAST ALPHABET
    *****************************/

    int depart = 1300-26+1;
    for(i=depart;i<=1300;i++) {
        input[0] = (alphabet[i%26][0]-48)^R47[i%47];
        input[1] = (alphabet[i%26][1]-48)^R61[i%61];
        input[2] = (alphabet[i%26][2]-48)^R73[i%73];
        input[3] = (alphabet[i%26][3]-48)^R71[i%71];
        input[4] = (alphabet[i%26][4]-48)^R65[i%65];

        int control[5] = {R69[i%69],R59[i%59],R64[i%64],R53[i%53],R67[i%67]};

        if(R69[i%69]==0) {s = input[4]; input[4] = input[0]; input[0] = s;}
        if(R59[i%59]==0) {s = input[3]; input[3] = input[4]; input[4] = s;}
        if(R64[i%64]==0) {s = input[2]; input[2] = input[3]; input[3] = s;}
        if(R53[i%53]==0) {s = input[1]; input[1] = input[2]; input[2] = s;}
        if(R67[i%67]==0) {s = input[0]; input[0] = input[1]; input[1] = s;}

        for(j=0;j<5;j++)
            printf("%d",input[j]);
        printf("\n");
    }
    return 0;
}
Exemplo n.º 28
0
/*
 * Parse the configuration file at `path' and execute the `action' call-back
 * functions for any directives defined by the array of config options (first
 * argument).
 *
 * For unknown directives that are encountered, you can optionally pass a
 * call-back function for the third argument to be called for unknowns.
 *
 * Returns zero on success; otherwise returns -1 and errno should be consulted.
*/
int
parse_config(struct fp_config options[], const char *path,
    int (*unknown)(struct fp_config *option, uint32_t line, char *directive,
    char *value), uint16_t processing_options)
{
	uint8_t bequals;
	uint8_t bsemicolon;
	uint8_t case_sensitive;
	uint8_t comment = 0;
	uint8_t end;
	uint8_t found;
	uint8_t have_equals = 0;
	uint8_t quote;
	uint8_t require_equals;
	uint8_t strict_equals;
	char p[2];
	char *directive;
	char *t;
	char *value;
	int error;
	int fd;
	ssize_t r = 1;
	uint32_t dsize;
	uint32_t line = 1;
	uint32_t n;
	uint32_t vsize;
	uint32_t x;
	off_t charpos;
	off_t curpos;
	char rpath[PATH_MAX];

	/* Sanity check: if no options and no unknown function, return */
	if (options == NULL && unknown == NULL)
		return (-1);

	/* Processing options */
	bequals = (processing_options & FP_BREAK_ON_EQUALS) == 0 ? 0 : 1;
	bsemicolon = (processing_options & FP_BREAK_ON_SEMICOLON) == 0 ? 0 : 1;
	case_sensitive = (processing_options & FP_CASE_SENSITIVE) == 0 ? 0 : 1;
	require_equals = (processing_options & FP_REQUIRE_EQUALS) == 0 ? 0 : 1;
	strict_equals = (processing_options & FP_STRICT_EQUALS) == 0 ? 0 : 1;

	/* Initialize strings */
	directive = value = 0;
	vsize = dsize = 0;

	/* Resolve the file path */
	if (realpath(path, rpath) == 0)
		return (-1);

	/* Open the file */
	if ((fd = open(rpath, O_RDONLY)) < 0)
		return (-1);

	/* Read the file until EOF */
	while (r != 0) {
		r = read(fd, p, 1);

		/* skip to the beginning of a directive */
		while (r != 0 && (isspace(*p) || *p == '#' || comment ||
		    (bsemicolon && *p == ';'))) {
			if (*p == '#')
				comment = 1;
			else if (*p == '\n') {
				comment = 0;
				line++;
			}
			r = read(fd, p, 1);
		}
		/* Test for EOF; if EOF then no directive was found */
		if (r == 0) {
			close(fd);
			return (0);
		}

		/* Get the current offset */
		curpos = lseek(fd, 0, SEEK_CUR) - 1;
		if (curpos == -1) {
			close(fd);
			return (-1);
		}

		/* Find the length of the directive */
		for (n = 0; r != 0; n++) {
			if (isspace(*p))
				break;
			if (bequals && *p == '=') {
				have_equals = 1;
				break;
			}
			if (bsemicolon && *p == ';')
				break;
			r = read(fd, p, 1);
		}

		/* Test for EOF, if EOF then no directive was found */
		if (n == 0 && r == 0) {
			close(fd);
			return (0);
		}

		/* Go back to the beginning of the directive */
		error = (int)lseek(fd, curpos, SEEK_SET);
		if (error == (curpos - 1)) {
			close(fd);
			return (-1);
		}

		/* Allocate and read the directive into memory */
		if (n > dsize) {
			if ((directive = realloc(directive, n + 1)) == NULL) {
				close(fd);
				return (-1);
			}
			dsize = n;
		}
		r = read(fd, directive, n);

		/* Advance beyond the equals sign if appropriate/desired */
		if (bequals && *p == '=') {
			if (lseek(fd, 1, SEEK_CUR) != -1)
				r = read(fd, p, 1);
			if (strict_equals && isspace(*p))
				*p = '\n';
		}

		/* Terminate the string */
		directive[n] = '\0';

		/* Convert directive to lower case before comparison */
		if (!case_sensitive)
			strtolower(directive);

		/* Move to what may be the start of the value */
		if (!(bsemicolon && *p == ';') &&
		    !(strict_equals && *p == '=')) {
			while (r != 0 && isspace(*p) && *p != '\n')
				r = read(fd, p, 1);
		}

		/* An equals sign may have stopped us, should we eat it? */
		if (r != 0 && bequals && *p == '=' && !strict_equals) {
			have_equals = 1;
			r = read(fd, p, 1);
			while (r != 0 && isspace(*p) && *p != '\n')
				r = read(fd, p, 1);
		}

		/* If no value, allocate a dummy value and jump to action */
		if (r == 0 || *p == '\n' || *p == '#' ||
		    (bsemicolon && *p == ';')) {
			/* Initialize the value if not already done */
			if (value == NULL && (value = malloc(1)) == NULL) {
				close(fd);
				return (-1);
			}
			value[0] = '\0';
			goto call_function;
		}

		/* Get the current offset */
		curpos = lseek(fd, 0, SEEK_CUR) - 1;
		if (curpos == -1) {
			close(fd);
			return (-1);
		}

		/* Find the end of the value */
		quote = 0;
		end = 0;
		while (r != 0 && end == 0) {
			/* Advance to the next character if we know we can */
			if (*p != '\"' && *p != '#' && *p != '\n' &&
			    (!bsemicolon || *p != ';')) {
				r = read(fd, p, 1);
				continue;
			}

			/*
			 * If we get this far, we've hit an end-key
			 */

			/* Get the current offset */
			charpos = lseek(fd, 0, SEEK_CUR) - 1;
			if (charpos == -1) {
				close(fd);
				return (-1);
			}

			/*
			 * Go back so we can read the character before the key
			 * to check if the character is escaped (which means we
			 * should continue).
			 */
			error = (int)lseek(fd, -2, SEEK_CUR);
			if (error == -3) {
				close(fd);
				return (-1);
			}
			r = read(fd, p, 1);

			/*
			 * Count how many backslashes there are (an odd number
			 * means the key is escaped, even means otherwise).
			 */
			for (n = 1; *p == '\\'; n++) {
				/* Move back another offset to read */
				error = (int)lseek(fd, -2, SEEK_CUR);
				if (error == -3) {
					close(fd);
					return (-1);
				}
				r = read(fd, p, 1);
			}

			/* Move offset back to the key and read it */
			error = (int)lseek(fd, charpos, SEEK_SET);
			if (error == (charpos - 1)) {
				close(fd);
				return (-1);
			}
			r = read(fd, p, 1);

			/*
			 * If an even number of backslashes was counted meaning
			 * key is not escaped, we should evaluate what to do.
			 */
			if ((n & 1) == 1) {
				switch (*p) {
				case '\"':
					/*
				 	 * Flag current sequence of characters
					 * to follow as being quoted (hashes
					 * are not considered comments).
					 */
					quote = !quote;
					break;
				case '#':
					/*
					 * If we aren't in a quoted series, we
					 * just hit an inline comment and have
					 * found the end of the value.
					 */
					if (!quote)
						end = 1;
					break;
				case '\n':
					/*
					 * Newline characters must always be
					 * escaped, whether inside a quoted
					 * series or not, otherwise they
					 * terminate the value.
					 */
					end = 1;
				case ';':
					if (!quote && bsemicolon)
						end = 1;
					break;
				}
			} else if (*p == '\n')
				/* Escaped newline character. increment */
				line++;

			/* Advance to the next character */
			r = read(fd, p, 1);
		}

		/* Get the current offset */
		charpos = lseek(fd, 0, SEEK_CUR) - 1;
		if (charpos == -1) {
			close(fd);
			return (-1);
		}

		/* Get the length of the value */
		n = (uint32_t)(charpos - curpos);
		if (r != 0) /* more to read, but don't read ending key */
			n--;

		/* Move offset back to the beginning of the value */
		error = (int)lseek(fd, curpos, SEEK_SET);
		if (error == (curpos - 1)) {
			close(fd);
			return (-1);
		}

		/* Allocate and read the value into memory */
		if (n > vsize) {
			if ((value = realloc(value, n + 1)) == NULL) {
				close(fd);
				return (-1);
			}
			vsize = n;
		}
		r = read(fd, value, n);

		/* Terminate the string */
		value[n] = '\0';

		/* Cut trailing whitespace off by termination */
		t = value + n;
		while (isspace(*--t))
			*t = '\0';

		/* Escape the escaped quotes (replaceall is in string_m.c) */
		x = strcount(value, "\\\""); /* in string_m.c */
		if (x != 0 && (n + x) > vsize) {
			if ((value = realloc(value, n + x + 1)) == NULL) {
				close(fd);
				return (-1);
			}
			vsize = n + x;
		}
		if (replaceall(value, "\\\"", "\\\\\"") < 0) {
			/* Replace operation failed for some unknown reason */
			close(fd);
			return (-1);
		}

		/* Remove all new line characters */
		if (replaceall(value, "\\\n", "") < 0) {
			/* Replace operation failed for some unknown reason */
			close(fd);
			return (-1);
		}

		/* Resolve escape sequences */
		strexpand(value); /* in string_m.c */

call_function:
		/* Abort if we're seeking only assignments */
		if (require_equals && !have_equals)
			return (-1);

		found = have_equals = 0; /* reset */

		/* If there are no options defined, call unknown and loop */
		if (options == NULL && unknown != NULL) {
			error = unknown(NULL, line, directive, value);
			if (error != 0) {
				close(fd);
				return (error);
			}
			continue;
		}

		/* Loop through the array looking for a match for the value */
		for (n = 0; options[n].directive != NULL; n++) {
			error = fnmatch(options[n].directive, directive,
			    FNM_NOESCAPE);
			if (error == 0) {
				found = 1;
				/* Call function for array index item */
				if (options[n].action != NULL) {
					error = options[n].action(
					    &options[n],
					    line, directive, value);
					if (error != 0) {
						close(fd);
						return (error);
					}
				}
			} else if (error != FNM_NOMATCH) {
				/* An error has occurred */
				close(fd);
				return (-1);
			}
		}
		if (!found && unknown != NULL) {
			/*
			 * No match was found for the value we read from the
			 * file; call function designated for unknown values.
			 */
			error = unknown(NULL, line, directive, value);
			if (error != 0) {
				close(fd);
				return (error);
			}
		}
	}

	close(fd);
	return (0);
}
/*
 * This function works pretty much like routTcpMessage only that this one interpretes message from RFIDMonitor and don't verify packages size.
 * it only tries to interpret data just arrived.
 */
void RFIDMonitorDaemon::routeIpcMessage()
{
    QByteArray message = ipcConnection->readAll();
    json::NodeJSMessage nodeMessage;

    nodeMessage.read(QJsonDocument::fromJson(message).object());
    QString messageType(nodeMessage.type());

    if(messageType == "SYN"){

        m_restoreTimer.stop();
        ipcSendMessage(buildMessage(QJsonObject(), "ACK-SYN").toJson());
        qApp->processEvents();

        /* When the deskApp change some configuration the RFIDMonitor is restarted.
         * But, the RFIDMonitor starts with flag connection=false. And if the server is connected the RFIDMonitor don't know that yet.
         * To solve this, after 1 seconds a SYNC message is sent to RFIDMonitor to set true to connection flag.
         */
        if(isConnected)
        {
            QTimer *timer = new QTimer();
            timer->setSingleShot(true);
            timer->setInterval(1000);
            connect(timer, &QTimer::timeout, [=](){
                ipcSendMessage(buildMessage(QJsonObject(), "SYNC").toJson());
                timer->deleteLater();
            });
            timer->start();
        }

        m_configManager->restartNetwork();

    }else if (messageType == "READER-RESPONSE") {
        QJsonObject command(nodeMessage.jsonData());
        /*
         * When a 'reader response' message is received is because someone sent a 'reader command' message. So it needs to know who did it.
         * To perform this it uses a field called 'sender' that carry the name of who sent the 'command message'.
         * And based on that, it will respond to the server connection or to the deskApp connection.
         *
         * see reoutTcpMessage (messageType == "READER-COMMAND")
         */
        if(command.value("sender").toString() == "server")
            tcpSendMessage(m_tcpSocket, message);
        else
            tcpSendMessage(m_tcpAppSocket, message);

    }else if (messageType == "DATA"){
        /*
         * A Data message means that the RFIDMonitor is trying to sync some data into the server. So, it just send this message to the server.
         */
//        qDebug() <<  "DATA Message Received from Monitor\n";
//        qDebug() <<  QString(QJsonDocument(nodeMessage.jsonData()).toJson());
        // Only a node.js server receives DATA messages.
        tcpSendMessage(m_tcpSocket, message);

    }else if (messageType == "STOPPED"){
        qDebug() << "STOPPED";
        m_process.kill();
//        qDebug() << "Process Killed, PID: " << m_process.pid();
    }
    else if (messageType == "ACK-UNKNOWN") {
        QJsonDocument unknown(nodeMessage.jsonData());
        QJsonObject dataObj(unknown.object().value("unknownmessage").toObject());
        qDebug() <<  "The Monitor don't understand the message type: "
                        << dataObj.value("type").toString();
    }
    else{
        /* When receives a message that can't be interpreted like any type is an unknown message.
         * In this case an ACK-UNKNOWN message is built and sent to the connection that received this message
         */
        qDebug() <<  "UNKNOWN MESSAGE";

        QJsonObject unknownObj;
        unknownObj.insert("unknownmessage", QJsonDocument::fromJson(message).object());
        unknownObj.insert("errorinfo", QString("Unknown message received"));

        ipcSendMessage(buildMessage(unknownObj, "ACK-UNKNOWN").toJson());
    }
}
Exemplo n.º 30
0
int main(int argc, char *argv[]){
	init_parse();

	// Parses the commandline arguments
	parse_opts(argc, argv); // IE: ./server -cserver.cfg --name "My Server"

	// server config
	ReadServerCfg(cfg_file ? :"server.cfg");

	// init sockets
	struct sockaddr_in newclient;
	unsigned char buffer[MAX_BUF];
	int size;
	fd_set descriptor; //I don't know
	sock = create_socket();
	bind_socket(&sock, INADDR_ANY, sv_hostport);

	// on termination
	atexit(&cleanup);
	signal(SIGABRT, &exit);
	signal(SIGTERM, &exit);
	signal(SIGINT, &exit);

	// initialize rest of stuff
	OnServerStart();

#ifndef _WIN32
	// fps control
	const int inc = NS_PER_S / sv_fps;
	int frame = 0;
	int previous = 0;

	struct timespec current, next;
	clock_gettime(CLOCK_MONOTONIC, &next);
#endif

	// timeval for select
	struct timeval timeout;
	timeout.tv_sec = 0;
	timeout.tv_usec = 0;

	//main loop
	while (1) {
#ifndef _WIN32
		frame++;
		next.tv_nsec += inc;
		while (next.tv_nsec > NS_PER_S) { //happens exactly once a second
			next.tv_nsec -= NS_PER_S;
			next.tv_sec++;

			fpsnow = frame - previous;
			previous = frame;
			OnSecond();
		}
#endif
		OnFrame();

		FD_ZERO(&descriptor);
		FD_SET(sock, &descriptor);
		select(sock + 1, &descriptor, NULL, NULL, &timeout);

		if (FD_ISSET(sock, &descriptor)){
			size = udp_receive(sock, buffer, MAX_BUF, &newclient);

			if (size < 3) {
				perror("Invalid packet! (size < 3)\n");
			} else {
				stream *packet = init_stream(NULL);
				Stream.write(packet, buffer+2, size-2);

				// There's a chance that the guy left before all of the packet has been processed.
				while(1){
					int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port);
					if (id){
						if (ValidatePacket(buffer,id)){
							PacketConfirmation(buffer,id); //If the numbering is even, send a confirmation
							player[id].lastpacket = mtime();
							int pid = Stream.read_byte(packet);
							known_handler h = known_table[pid];
							if (!h){
								printf("Unhandled packet originating from %s (id:%d)\n", player[id].name, id);
								//stream *lolbuf = init_stream(NULL);
								//Stream.write(lolbuf, buffer, size);
								//unknown(lolbuf, pid);
								unknown(packet, pid);
							} else
								h(packet, id);
						}
					}else{
						int pid = Stream.read_byte(packet);
						unknown_handler h = unknown_table[pid];
						if (!h)
							unknown(packet, pid);
						else
							h(packet, &newclient);
					}

					if (EMPTY_STREAM(packet)){
						free(packet);
						break;
					}
				}
			}
		}

		check_sendqueue();

#ifdef _WIN32
		Sleep(1000 / sv_fps); //who cares about windows :D
#else
		clock_gettime(CLOCK_MONOTONIC, &current);
		if (((current.tv_sec == next.tv_sec) && (current.tv_nsec < next.tv_nsec)) || (current.tv_sec < next.tv_sec)) {
			clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL);
		} else {
			next.tv_nsec = current.tv_nsec + (current.tv_sec - next.tv_sec) * NS_PER_S;
		}
#endif
	}
	return EXIT_SUCCESS;
}