Example #1
0
void *heartHandler(void *params)
{
    while(1)
    {
        sleep(60);
        if (sendHello()<0)
        {
            ut_err("send hello fail\n");
        }
    }
    return NULL;
}
bool XboxOneControllerDriver::handleStart(IOService *provider)
{
	IOUSBInterface* interface = nullptr;
	IOUSBPipe* interruptPipe = nullptr;
	IOReturn ior = kIOReturnSuccess;
	
	IOUSBFindEndpointRequest pipeRequest = {
		.type = kUSBInterrupt,
		.direction = kUSBOut,
	};
	
	// Apple says you should call super::handleStart at the *beginning* of the method.
	if (!super::handleStart(provider))
	{
		goto cleanup;
	}
	
	// Paranoid check: is it the correct kind of object?
	interface = OSDynamicCast(IOUSBInterface, provider);
	if (interface == nullptr)
	{
		IO_LOG_DEBUG("IOUSBHIDDriver is handling start on an object that's not a IOUSBInterface??");
		goto cleanup;
	}
	
	// Find the pipe through which we have to send the hello message.
	// This is redundant with work that IOUSBHIDDriver already did, but there are no accessors.
	interruptPipe = interface->FindNextPipe(nullptr, &pipeRequest);
	if (interruptPipe == nullptr)
	{
		IO_LOG_DEBUG("No interrupt pipe found on controller");
		goto cleanup;
	}
	
	// `sendHello` needs _interruptPipe to be set, but only retain it if it succeeds.
	_interruptPipe = interruptPipe;
	ior = sendHello();
	if (ior != kIOReturnSuccess)
	{
		IO_LOG_DEBUG("Couldn't send hello message: %08x", ior);
		_interruptPipe = nullptr;
		goto cleanup;
	}
	
	_interruptPipe->retain();
	
cleanup:
	return _interruptPipe != nullptr;
}
Example #3
0
File: main.cpp Project: HuiD/ece590
void init(string ip)
{
    tcpclient = new CClientSocket();
    remoteip = new CIpAddress(ip, 1234);
    Uint16 port=1234;
    udpclient=new CUdpSocket(port);
    if(udpclient==NULL)
    {
        cout<<"couldn't create udp endpoint\n";
        exit(EXIT_FAILURE);
    }
    while(1)
    {
        if(!Connected)
        {
            if(tcpclient->Connect(*remoteip))
            {
                if(tcpclient->Ok()) {
                    Connected=true;
                    cout<<"connected to server"<<endl;
                }
            }
        }
        else {
            break;
        }
    }
    initBlock();
    sendHello();

    background = new Background("img/background.bmp");

    background->setCoords(0,0);

    winScreen = new Background("img/win.bmp");
    winScreen->setCoords(0,0);
    loseScreen = new Background("img/lose.bmp");
    loseScreen->setCoords(0,0);


    mainMusic = Mix_LoadMUS("sound/mainbgm.wav");

    int totalScroll =0;
}
Example #4
0
/* thread for hello packet */
void *sockhello(void *arg){

    HelloArgs *helloArgs;
    helloArgs = (HelloArgs *)malloc(sizeof(HelloArgs));
    helloArgs = (HelloArgs *)arg;

    int clientfd;

    while(1){
        clientfd = Socket(AF_INET, SOCK_STREAM, 0);
        Connect(clientfd, helloArgs->sockaddr, sizeof(helloArgs->sockaddr));
        pthread_mutex_lock(&hello_mutex); // Critical section start
        sendHello(clientfd, helloArgs->packet);
        pthread_mutex_unlock(&hello_mutex); // Critical section end
        
        sleep(HELLO_INTERVAL); //sleep interval time
    } //endof while(1)

}
bool BluetoothSensor::initAll(std::string configFileName)
{
    bool manualSensorID = false;

    print("Reading config file...");

    dictionary* ini ;
    ini = iniparser_load(configFileName.c_str());
    if (!ini) {
        print("Cannot parse config file. Using default values");
    }
    else
    {
        m_brokerAddress = iniparser_getstring(ini, ":broker_address",
                                              (char*)DEFAULT_BROKER_ADDRESS.c_str());
        m_brokerPort = iniparser_getint(ini, ":broker_port",
                                        DEFAULT_BROKER_PORT);
        m_dataFetchUrl = iniparser_getstring(ini, ":data_fetch_url",
                                              (char*)DEFAULT_DATA_FETCH_URL.c_str());
        m_connectAttemptInterval = iniparser_getint(ini, ":connect_attempt_interval",
                                        DEFAULT_CONNECT_ATTEMPT_INTERVAL);

        if (iniparser_find_entry(ini, ":sensor_id"))
        {
            m_sensorID = iniparser_getstring(ini, ":sensor_id", 0);
            manualSensorID = true;
        }
    }
    iniparser_freedict(ini);

    if (!m_bluetoothPoller)
    {
        print("Initializing Bluetooth... ");

        std::string btAddress;
        m_bluetoothPoller = new BluetoothPoller();
        if (!m_bluetoothPoller->init(btAddress))
        {
            printError(m_bluetoothPoller->getLastErrorString());
            return false;
        }
        if (!manualSensorID) m_sensorID = "bt-sensor_" + btAddress;
    }

    if (!m_dataGetter)
    {
        print("Initializing Curl...");

        m_dataGetter = new DataGetter();
        if (!m_dataGetter->init())
        {
            printError(m_dataGetter->getLastErrorString());
            return false;
        }
    }

    if (!m_mosquitto)
    {
        print("Initializing Mosquitto... ");

        m_mosquitto = new MosquittoHandler;
        std::string mosqID = m_sensorID;

        if (!m_mosquitto->init(mosqID.c_str()) || !m_mosquitto->connectToBroker(m_brokerAddress.c_str(), m_brokerPort))
        {
            printError(m_mosquitto->getLastErrorString());
            return false;
        }
        m_mosquitto->subscribe("command/fetch_device_database");
        m_mosquitto->subscribe(std::string("command/scan/bluetooth/" + m_sensorID).c_str());
        m_mosquitto->subscribe("command/scan/bluetooth");

        print("Connecting to broker... ");
        if (!m_mosquitto->waitForConnect())
        {
            // first connection attempt failed, go into retry loop
            printError(m_mosquitto->getLastErrorString());
            while (!connectMosquitto(false))
            {
                if (quit) return false;
            }
        }
    }

    m_updateDBNeeded = !updateDeviceData();

    sendHello();

    print("Sensor ID: " + m_sensorID);

    return true;
}
Example #6
0
bool LANSensor::initAll(std::string configFileName)
{
    if (getuid() != 0)
    {
        printError("Root priviledges needed");
        return false;
    }

    bool manualSensorID = false;

    print("Reading config file... ");

    dictionary* ini;
    ini = iniparser_load(configFileName.c_str());
    if (!ini) {
        print("Cannot parse config file. Using default values");
    }
    else
    {
        m_arpscan_parameters = iniparser_getstring(ini, ":arp-scan_parameters",
                                              (char*)DEFAULT_ARPSCAN_PARAMETERS.c_str());
        m_brokerAddress = iniparser_getstring(ini, ":broker_address",
                                              (char*)DEFAULT_BROKER_ADDRESS.c_str());
        m_brokerPort = iniparser_getint(ini, ":broker_port",
                                        DEFAULT_BROKER_PORT);
        m_dataFetchUrl = iniparser_getstring(ini, ":data_fetch_url",
                                              (char*)DEFAULT_DATA_FETCH_URL.c_str());
        m_scanInterval = iniparser_getint(ini, ":scan_interval",
                                        DEFAULT_SCAN_INTERVAL);
        m_connectAttemptInterval = iniparser_getint(ini, ":connect_attempt_interval",
                                        DEFAULT_CONNECT_ATTEMPT_INTERVAL);

        if (iniparser_find_entry(ini, ":sensor_id"))
        {
            m_sensorID = iniparser_getstring(ini, ":sensor_id", 0);
            manualSensorID = true;
        }
    }
    iniparser_freedict(ini);

    if (!manualSensorID)
    {
        // create sensor id from MAC address
        std::string id = getOwnMAC();
        if (!id.size())
        {
            id = "default";
        }
        m_sensorID = "lan-sensor_" + id;
    }

    if (!m_ARPScanner)
    {
        print("Initializing ARP scanner... ");
        m_ARPScanner = new ARPScanner();
        if (!m_ARPScanner->init(m_arpscan_parameters))
        {
            printError(m_ARPScanner->getLastErrorString());
            delete m_ARPScanner;
            m_ARPScanner = 0;
            return false;
        }
    }

    if (!m_dataGetter)
    {
        print("Initializing Curl... ");

        m_dataGetter = new DataGetter();
        if (!m_dataGetter->init())
        {
            printError(m_dataGetter->getLastErrorString());
            return false;
        }
    }

    if (!m_mosquitto)
    {
        print("Initializing Mosquitto... ");

        m_mosquitto = new MosquittoHandler;
        std::string mosqID = m_sensorID;

        if (!m_mosquitto->init(mosqID.c_str()) || !m_mosquitto->connectToBroker(m_brokerAddress.c_str(), m_brokerPort))
        {
            printError(m_mosquitto->getLastErrorString());
            return false;
        }
        m_mosquitto->subscribe("command/fetch_device_database");
        m_mosquitto->subscribe(std::string("command/scan/lan/" + m_sensorID).c_str());
        m_mosquitto->subscribe("command/scan/lan");

        print("Connecting to broker... ");
        if (!m_mosquitto->waitForConnect())
        {
            printError(m_mosquitto->getLastErrorString());
            while (!connectMosquitto(false))
            {
                if (quit) return false;
            }
        }
    }

    m_updateDBNeeded = !updateDeviceData();

    sendHello();

    print("Sensor ID: " + m_sensorID);

    return true;
}
Example #7
0
void LANSensor::run()
{
    bool updateDB = false;
    bool scan = false;

    print("Running, CTRL+C to quit...");

    while(!quit)
    {
        // update device db if previous update didn't succeed
        if (m_updateDBNeeded) m_updateDBNeeded = !updateDeviceData();

        checkDevices();

        std::stringstream ss;
        ss << "Waiting scan interval (" << m_scanInterval << " sec)...";
        print(ss.str());

        // wait scan interval, check for incoming messages every second while doing so
        for (int timer = 0; timer < m_scanInterval; timer++)
        {
            sleep(1);

            // check if there are arrived mqtt messages (commands)
            do
            {
                processIncomingMessages(updateDB, scan);
                if (updateDB)
                {
                    m_updateDBNeeded = !updateDeviceData();

                    // exit from wait loop
                    timer = m_scanInterval;
                }
                if (scan)
                {
                    discoverDevices();

                    // exit from wait loop
                    timer = m_scanInterval;
                }
            }

            // check arrived messages again after database update or device discovery,
            // so that a possible request for those is processed before continuing
            while ((updateDB || scan) && !quit);

            // check that Mosquitto is still connected.
            // if Mosquitto disconnects there can be messages from this iteration
            // which aren't sent at all, but missing some outgoing messages
            // shouldn't be too big of a problem.
            if (!m_mosquitto->isConnected())
            {
                printError("Mosquitto disconnected");
                if (connectMosquitto())
                {
                    // update device db and send hello after mosquitto reconnect
                    m_updateDBNeeded = !updateDeviceData();
                    sendHello();
                }
                break;
            }
            if (quit) break;
        }   
    }
}
Example #8
0
/* thread for lsrp-client */
void *sockclient(void *arg){
    ThreadParam *threadParam;
    threadParam = (ThreadParam *) arg;

    int clientfd,sendbytes,recvbytes;
    struct hostent *host;
    struct sockaddr_in sockaddr;

    Router *router;
    router = threadParam->router; // get the router cfg
    getaddr(hostname, addrstr); //get hostname and ip, getaddrinfo.h
   
    /* try to get server hostname and port from the host files (.<servername>) */
    char remote_server[32];
    char portstr[6]; // to store the port
    int endsysEthx = -1; // set as iEthx if it's endsys
    char logmsg[128];
    snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): busy wait for new server starting up...\n", pthread_self());
    logging(LOGFILE, logmsg);
    while(1){
        int iEthx;
        memset(portstr, 0, sizeof(portstr)); 
        pthread_mutex_lock(&threadParam->lock_port); // Critical section to read port files
        /* Steps:
         * 1) go through all the direct_link_addr in cfg file
         * 2) if port file do NOT exists, busy wait
         * 3) if port file exists and occupied, skip it
         * 4) if port file exists and NOT occupied, use it
         * 5) update client ip into the port file
         */

        /* 1) go through all the direct_link_addr in cfg file */
        for(iEthx=0;iEthx < router->num_of_interface; iEthx++){
            if(strcmp(router->ethx[iEthx].direct_link_addr, addrstr) != 0){ // skip the local server file
                char templine[128];
                int iget;
                /* 2) if port file do NOT exists, busy wait */
                if((iget = getPort(templine, sizeof(templine), router->ethx[iEthx].direct_link_addr)) < 0 ){ // read the port file
                    continue; // if file does not exists, continue
                }
                /* 3) if port file exists and occupied, check if I'm in the list or not
                 */
                int portFound = 0;
                char tempport[6];
                if(strlen(templine) > 5){
                    char tempsplit[128];
                    strcpy(tempsplit, templine);
                    char *split1, *split2, *strsplit;
                    strsplit = tempsplit;
                    int inList = 0;
                    while(strlen(strsplit) > 0){
                        split1 = strtok_r(strsplit, ":", &split2);
                        if(strlen(split1) == 5){
                            snprintf(tempport, sizeof(tempport), "%s", split1);
                        }
                        else if(strcmp(split1, addrstr) == 0){
                            inList = 1; // in the list
                            break; // break while(strlen(strsplit) > 0)
                        }
                        strsplit = split2;
                    }

                    /* not in the list, then prepare to add me in */
                    if(inList == 0){
                        snprintf(portstr, sizeof(portstr), "%s", tempport);
                        portFound = 1;
                    }
                }
                /* 4) if port file exists and NOT occupied, use it */
                else if(strlen(templine) == 5){
                    snprintf(portstr, sizeof(portstr), "%s", templine);
                    portFound = 1;
                }

                if(portFound == 1){
                    if(router->ethx[iEthx].direct_link_type == 1){
                        endsysEthx = iEthx;
                    }
                    snprintf(remote_server, sizeof(remote_server), "%s", router->ethx[iEthx].direct_link_addr);
                    router->ethx[iEthx].direct_link_port = atoi(portstr);
                    if((host = gethostbyname(router->ethx[iEthx].direct_link_addr)) == NULL ) { // got the remote server
                        perror("gethostbyname");
                        exit(-1);
                    };
                    /* 5) update client ip into the port file, in the format:
                     *    34322:10.0.0.1:10.0.0.2
                     */
                    strcat(templine, ":");
                    strcat(templine, addrstr);
                    markPort(router->ethx[iEthx].direct_link_addr, templine); // mark that port has been used in the port file
                    snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): client %s use port %s:%s now.\n", pthread_self(), \
                                                      addrstr, router->ethx[iEthx].direct_link_addr, portstr);
                    logging(LOGFILE, logmsg);

                    /* 6) connect to remote server */
                    /*create socket*/
                    clientfd = Socket(AF_INET, SOCK_STREAM, 0);
                
                    /*parameters for sockaddr_in*/
                    sockaddr.sin_family = AF_INET;
                    sockaddr.sin_port = htons(atoi(portstr));
                    sockaddr.sin_addr = *((struct in_addr *)host->h_addr);
                    bzero(&(sockaddr.sin_zero), 8);         
                
                    /*connect to server*/
                    Connect(clientfd,sockaddr,sizeof(sockaddr));

                    break; //end the for loop
                }
            }
        }
        pthread_mutex_unlock(&threadParam->lock_port); // Critical section end
    
        sleep(READ_PORT_INTERVAL);

        if(strlen(portstr) == 5){
            break; // end the while loop
        }
        snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): No available port found, make sure all servers in direct_link_addr started.\n", pthread_self());
        logging(LOGFILE, logmsg);
        snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): wait %d seconds to try again..\n", pthread_self(), READ_PORT_INTERVAL);
        logging(LOGFILE, logmsg);
    }

    /* deal with end sys */
    if(endsysEthx != -1 ){
        int needACK;
        while(1){
            needACK = 0;
            /* read data from buffer */
            pthread_mutex_lock(&threadParam->data_buffer[endsysEthx].lock_buffer);
            if(threadParam->data_buffer[endsysEthx].buffsize > 0){
                //printf("sockclient(0x%x): threadParam->data_buffer[%d].buffsize: %d, type of the first item: %s\n", 
                //    pthread_self(), endsysEthx, threadParam->data_buffer[endsysEthx].buffsize,
                //    threadParam->data_buffer[endsysEthx].packet_q->next->packet->PacketType);

                /* out going buffer devided by interface, maybe there are other type of packet exists */
                /* do not handle ACK (110), let server side to deal with it */
                if(strcmp(threadParam->data_buffer[endsysEthx].packet_q->next->packet->PacketType, "100") == 0){
                    //snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): forward File with type %s from %s to endsystem %s through ethx %d\n",
                    printf("sockclient(0x%x): forward File with type %s from %s to endsystem %s through ethx %d\n",
                        pthread_self(), threadParam->data_buffer[endsysEthx].packet_q->next->packet->PacketType,
                        threadParam->data_buffer[endsysEthx].packet_q->next->packet->RouterID, remote_server, endsysEthx);
                    //logging(LOGFILE, logmsg);

                    sendBufferData(clientfd, &threadParam->data_buffer[endsysEthx]);

                    needACK = 1;
                }
            }
            pthread_mutex_unlock(&threadParam->data_buffer[endsysEthx].lock_buffer);

            if(needACK == 1){
                    Packet *packet_ack;
                    packet_ack= (Packet *)malloc(sizeof(Packet));

                    /* got ack from endsys for each of the packet */
                    Recv(clientfd, packet_ack, sizeof(Packet), MSG_NOSIGNAL);

                    /* only add data ack (110) to buffer */
                    if(strcmp(packet_ack->PacketType, "110") == 0){
                        // data, addBuff();
                        //Thans_Data trans_data = (Trans_Data)packet->Data;
                        //getEthx(router, trans_data.des_ip); // calculate the out interface according to the routing table
                        //snprintf(logmsg, sizeof(logmsg), "serverthread(0x%x): got ack data from %s, enqueue...\n", 
                        printf("serverthread(0x%x): got ack data from %s, enqueue...\n", 
                                 pthread_self(), packet_ack->RouterID);
                        //logging(LOGFILE, logmsg);
                        repackData(router, packet_ack);
                        pthread_mutex_lock(&threadParam->data_buffer[endsysEthx].lock_buffer);
                        addBufferData(threadParam, packet_ack);
                        pthread_mutex_unlock(&threadParam->data_buffer[endsysEthx].lock_buffer);
                    }
                    else{
                        snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): data is not ack.\n", pthread_self());
                        logging(LOGFILE, logmsg);
                    }
            }

            usleep(1); //sleep some time for lock relase
        }
    }
    /* other routers */
    else{

        /* there are 5 types of Neighbor Acquisition Packets.
         * neighbor Acquisition Type:
         * neighbor_req: Be_Neighbors_Request(000) or Cease_Neighbors_Request(100)
         * neighbor_reply: Be_Neighbors_Confirm(101), Be_Neighbors_Refuse(111),
         *                 or Cease_Neighbors_Confirm(101)   */
        Packet *neighbor_req, *neighbor_reply;
    
        /* generate neighbors_req according to configure file */
        neighbor_req = genNeighborReq(router, atoi(portstr)); // msg to be sent out
        send(clientfd, neighbor_req, sizeof(Packet), MSG_NOSIGNAL);
    
        neighbor_reply = (Packet *)malloc(sizeof(Packet));
        /* Receive neighbors_reply from remote side */
        Recv(clientfd, neighbor_reply, sizeof(Packet), MSG_NOSIGNAL);
    
        if(strcmp(neighbor_reply->Data.NeighborAcqType, "001") == 0){
    
            int hello_interval = router->hello_interval;
            int ping_interval = router->ping_interval;
            int ls_updated_interval = router->ls_updated_interval;
    
            int hello_sent = 0, ping_sent = 0, lsa_sent = 0;
            time_t now1, now2, now3;
            int ls_sequence_number = 0;
    
            struct timeval timer; // use high quality timer to calculate the ping cost
            struct timezone tzp;
    
            int ethx = getEthx(router, remote_server);
            Packet *packet_req, *packet_reply; // MUST use pointer to fit different Packet
    
            while(1){
    
                gettimeofday(&timer, &tzp);
                time_t now = timer.tv_sec;
    
                /* read data from buffer */
                if(threadParam->data_buffer[ethx].buffsize > 0){
                    snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): threadParam->data_buffer[%d].buffsize: %d, first item type %s\n", 
                            pthread_self(), ethx, threadParam->data_buffer[ethx].buffsize, 
                            threadParam->data_buffer[ethx].packet_q->next->packet->PacketType);
                    logging(LOGFILE, logmsg);
    
                    /* Data or ACK packet */
                    if(strcmp(threadParam->data_buffer[ethx].packet_q->next->packet->PacketType, "100") == 0 ||
                            strcmp(threadParam->data_buffer[ethx].packet_q->next->packet->PacketType, "110") == 0){
                        //snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): forward Data %s packet to %s\n", 
                        printf("sockclient(0x%x): forward Data %s packet to %s\n", 
                                pthread_self(), threadParam->data_buffer[ethx].packet_q->next->packet->RouterID, remote_server);
                        //logging(LOGFILE, logmsg);
                        pthread_mutex_lock(&threadParam->data_buffer[ethx].lock_buffer);
                        sendBufferData(clientfd, &threadParam->data_buffer[ethx]);
                        pthread_mutex_unlock(&threadParam->data_buffer[ethx].lock_buffer);
                    }
    
                }

                if(threadParam->lsa_buffer[ethx].buffsize > 0){
                    snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): threadParam->lsa_buffer[%d].buffsize: %d, first item type %s\n",
                            pthread_self(), ethx, threadParam->lsa_buffer[ethx].buffsize,
                            threadParam->lsa_buffer[ethx].packet_q->next->packet->PacketType);
                    logging(LOGFILE, logmsg);

                    /* LSA packet */
                    if(strcmp(threadParam->lsa_buffer[ethx].packet_q->next->packet->PacketType, "010") == 0){
                        snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): forward LSA %s packet to %s\n",
                                pthread_self(), threadParam->lsa_buffer[ethx].packet_q->next->packet->RouterID, remote_server);
                        logging(LOGFILE, logmsg);
                        pthread_mutex_lock(&threadParam->lsa_buffer[ethx].lock_buffer);
                        sendBufferLSA(clientfd, &threadParam->lsa_buffer[ethx]);
                        pthread_mutex_unlock(&threadParam->lsa_buffer[ethx].lock_buffer);
                    }
                }


                /* sending other packet */
                /* hello message */
                if(now % hello_interval ==0){
                    if(hello_sent == 0){
                        now1 = now;
                        hello_sent = 1;
        
                        pthread_mutex_lock(&threadParam->lock_send); // Critical section to read port files
                        sendHello(clientfd, router, atoi(portstr));
                        pthread_mutex_unlock(&threadParam->lock_send); // Critical section end
    
                        snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): Hello packet sent.\n", pthread_self());
                        logging(LOGFILE, logmsg);
                    }
                    if(now != now1){
                        hello_sent = 0;
                    }
                }
                /* ping message */
                if(now % ping_interval ==0){
                    if(ping_sent == 0){
                        now1 = now;
                        ping_sent = 1;
        
                        pthread_mutex_lock(&threadParam->lock_send); // Critical section to read port files
                        sendPing(clientfd, router, timer, ethx);
                        pthread_mutex_unlock(&threadParam->lock_send); // Critical section end
    
                        snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): Ping packet sent.\n", pthread_self());
                        logging(LOGFILE, logmsg);
                    }
                    if(now != now1){
                        ping_sent = 0;
                    }
                }
                /* lsa message */
                if(now % ls_updated_interval ==0){
                    if(lsa_sent == 0){
                        now2 = now;
                        lsa_sent = 1;
                        ls_sequence_number++;
    
                        /* TODO: check acknowledgment, keep sending if no ack */
                        pthread_mutex_lock(&threadParam->lock_send); // Critical section to read port files
                        //printf("sockclient(0x%x): send LSA packet from %s to %s\n", pthread_self(), addrstr, remote_server);
                        sendNewLSA(clientfd, threadParam, ls_sequence_number, timer);
                        pthread_mutex_unlock(&threadParam->lock_send); // Critical section end
                        snprintf(logmsg, sizeof(logmsg), "sockclient(0x%x): LSA packet sent.\n", pthread_self());
                        logging(LOGFILE, logmsg);
                    }
                    if(now != now2){
                        lsa_sent = 0;
                    }
                }
    
                usleep(1); //sleep some time for lock relase
     
            } //endof while(1)
    
        } // endof if(strcmp(neighbor_reply
    } // endof if endsysEthx

    close(clientfd);
    pthread_exit(0);
}
Example #9
0
void IpcClient::connected()
{
	sendHello();
	infoMessage("connection established");
}
Example #10
0
static int ua_client_connectUA(char* ipaddress,int port, UA_String *endpointUrl, ConnectionInfo *connectionInfo,
                               UA_Boolean stateless, UA_Boolean udp) {
	UA_ByteString reply;
	UA_ByteString_newMembers(&reply, 65536);
	int sock;
	struct sockaddr_in server;
	//Create socket
	if(udp==UA_TRUE){
		sock = socket(AF_INET, SOCK_DGRAM, 0);
	}else{
		sock = socket(AF_INET, SOCK_STREAM, 0);
	}
	if(sock == -1) {
		printf("Could not create socket");
        return 1;
    }
	server.sin_addr.s_addr = inet_addr(ipaddress);
	server.sin_family = AF_INET;
	server.sin_port = htons(port);

	if(connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0) {
			perror("connect failed. Error");
			return 1;
		}
		connectionInfo->socket = sock;

		if(stateless){
			UA_NodeId_init(&connectionInfo->authenticationToken);
			connectionInfo->channelId=0;
			UA_SequenceHeader_init(&connectionInfo->sequenceHdr);
			connectionInfo->tokenId=0;
			return 0;
		}else{
			sendHello(sock, endpointUrl);
			recv(sock, reply.data, reply.length, 0);
			sendOpenSecureChannel(sock);
			recv(sock, reply.data, reply.length, 0);

			size_t recvOffset = 0;
			UA_TcpMessageHeader msghdr;
			UA_TcpMessageHeader_decodeBinary(&reply, &recvOffset, &msghdr);

			UA_AsymmetricAlgorithmSecurityHeader asymHeader;
			UA_NodeId rspType;
			UA_OpenSecureChannelResponse openSecChannelRsp;
			UA_UInt32_decodeBinary(&reply, &recvOffset, &connectionInfo->channelId);
			UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(&reply,&recvOffset,&asymHeader);
			UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
			UA_SequenceHeader_decodeBinary(&reply,&recvOffset,&connectionInfo->sequenceHdr);
			UA_NodeId_decodeBinary(&reply,&recvOffset,&rspType);
			UA_OpenSecureChannelResponse_decodeBinary(&reply,&recvOffset,&openSecChannelRsp);
			connectionInfo->tokenId = openSecChannelRsp.securityToken.tokenId;

			sendCreateSession(sock, connectionInfo->channelId, openSecChannelRsp.securityToken.tokenId, 52, 2, endpointUrl);
			recv(sock, reply.data, reply.length, 0);

			UA_NodeId messageType;
			recvOffset = 24;
			UA_NodeId_decodeBinary(&reply,&recvOffset,&messageType);
			UA_CreateSessionResponse createSessionResponse;
			UA_CreateSessionResponse_decodeBinary(&reply,&recvOffset,&createSessionResponse);
			connectionInfo->authenticationToken = createSessionResponse.authenticationToken;
			sendActivateSession(sock, connectionInfo->channelId, connectionInfo->tokenId, 53, 3,
					connectionInfo->authenticationToken);
			recv(sock, reply.data, reply.length, 0);

			UA_OpenSecureChannelResponse_deleteMembers(&openSecChannelRsp);

			UA_String_deleteMembers(&reply);
			UA_CreateSessionResponse_deleteMembers(&createSessionResponse);
			return 0;
		}
}
Example #11
0
int main(int argc,char** argv)
{
	char _path[260]; 
	char _root[260]; 
    FiEvent evnt;

    INIT_G();    	
    G.logFileSize = _M(100);
    G.logFile.fd = STDOUT_FILENO;
	FiGetCurDir(sizeof(_path),_path);
    strcpy(_root, _path);
	std::string str(_path);
    dirname(_root);
    append_slash(_root);
    G.exe = _path;
    G.root = _root;
	str+="FiUpdateMgr.log";
	freopen(str.c_str(),"a",stdout);
#if 1
    if (0 == chdir(G.exe))
    {
        ut_dbg("change cur dir success\n");
    }
    else
    {
        ut_err("change cur dir fail\n");
    }    
#endif
#ifndef WIN32
    FiEnableCoreDumps();
    pthread_t tid[3];
	pthread_attr_t attr[3];
    struct stat st;
    umparams.type = SERVER;//default type
    umparams.master == false;

    FiUpdateAssistant::getinstance()->set(&evnt);
    
    if (init_param(argc, argv) < 0) 
    {
        print_usage(stderr, 1);
        return -1;
    }
    if (stat("../download", &st) == -1)
    {
        ut_err("stat error num :%d\n", errno);
    }
    else
    {
        if (!S_ISDIR(st.st_mode))
        {
            system("rm ../download -rf");
        }
    }
    system("mkdir -p ../download");
	if (pthread_attr_init(&attr[0]) < 0)
	{
		ut_err("set attr fail\n");
	}
	if (pthread_attr_init(&attr[1]) < 0)
	{
		ut_err("set attr fail\n");
	}
	if (pthread_attr_init(&attr[2]) < 0)
	{
		ut_err("set attr fail\n");
	}
	pthread_attr_setdetachstate(&attr[0], PTHREAD_CREATE_DETACHED);
	pthread_attr_setdetachstate(&attr[1], PTHREAD_CREATE_DETACHED);
	pthread_attr_setdetachstate(&attr[2], PTHREAD_CREATE_DETACHED);
    if (sendHello()<0)
    {
        ut_err("send hello fail\n");
    }

	pthread_create(&tid[0], &attr[0], selfUpdate, NULL);
    if (umparams.master == false)
    {
        pthread_create(&tid[1], &attr[1], recvHelloHandler, NULL);
    }
    else
    {
        pthread_create(&tid[2], &attr[2], heartHandler, NULL);
    }
#endif


    UpdateSrv = new FiRpcSrv<FiUpdateMgrImpl>(RPC_PORT, RPC_SERVER_NAME, (char*)(NULL));
	UpdateSrv->run();
#if 0	
	evnt.wait();
#else
    do
    {
#ifdef WIN32
        Sleep(1000);
#else
        sleep(1);
#endif
    }while(true);
#endif
	
	return 0;	
}
		void CommunicationClientDetector::start(std::string messageData /*= ""*/)
		{
			_udpCommunication->start();
			setCommunicationManagerMessageData(messageData);
			sendHello();
		}
Example #13
0
static int sendSlice(sender_state_t sendst, struct slice *slice,
		     int retransmitting)
{    
    struct net_config *config = sendst->config;

    int nrBlocks, i, rehello;
#ifdef BB_FEATURE_UDPCAST_FEC
    int fecBlocks;
#endif
    int retransmissions=0;

    if(retransmitting) {
	slice->nextBlock = 0;
	if(slice->state != SLICE_XMITTED)
	    return 0;
    } else {
	if(slice->state != SLICE_NEW)
	    return 0;
    }

    nrBlocks = getSliceBlocks(slice, config);
#ifdef BB_FEATURE_UDPCAST_FEC
    if((config->flags & FLAG_FEC) && !retransmitting) {
	fecBlocks = config->fec_redundancy * config->fec_stripes;
    } else {
	fecBlocks = 0;
    }
#endif

#if DEBUG
    if(retransmitting) {
	flprintf("%s slice %d from %d to %d (%d bytes) %d\n",
		retransmitting ? "Retransmitting" : "Sending", 
		slice->sliceNo, slice->nextBlock, nrBlocks, slice->bytes,
		config->blockSize);
    }
#endif

    if((sendst->config->flags & FLAG_STREAMING)) {
      rehello = nrBlocks - sendst->config->rehelloOffset;
      if(rehello < 0)
	rehello = 0;
    } else {
      rehello = -1;
    }

    /* transmit the data */
    for(i = slice->nextBlock; i < nrBlocks
#ifdef BB_FEATURE_UDPCAST_FEC
	  + fecBlocks
#endif
	  ; i++) {
	if(retransmitting) {
	    if(!BIT_ISSET(i, slice->rxmitMap) ||
	       BIT_ISSET(i, slice->isXmittedMap)) {
		/* if slice is not in retransmit list, or has _already_
		 * been retransmitted, skip it */
		if(i > slice->lastGoodBlock)
		    slice->lastGoodBlock = i;
		continue;
	    }
	    SET_BIT(i, slice->isXmittedMap);
	    retransmissions++;
#if DEBUG
	    flprintf("Retransmitting %d.%d\n", slice->sliceNo, i);
#endif
	}

	if(i == rehello) {
	    sendHello(sendst->config, sendst->socket, 1);
	}

	if(i < nrBlocks)
	    transmitDataBlock(sendst, slice, i);
#ifdef BB_FEATURE_UDPCAST_FEC
	else
	    transmitFecBlock(sendst, slice, i - nrBlocks);
#endif
	if(!retransmitting && pc_getWaiting(sendst->rc.incoming)) {
	    i++;
	    break;
	}
    }

    if(retransmissions)
	senderStatsAddRetransmissions(sendst->stats, retransmissions);
    slice->nextBlock = i;
    if(i == nrBlocks
#ifdef BB_FEATURE_UDPCAST_FEC
       + fecBlocks
#endif
       ) {
	slice->needRxmit = 0;
	if(!retransmitting)
	    slice->state = SLICE_XMITTED;
#if DEBUG
	flprintf("Done: at block %d %d %d\n", i, retransmitting,
		 slice->state);
#endif
	return 2;
    }
#if DEBUG
    flprintf("Done: at block %d %d %d\n", i, retransmitting,
	     slice->state);
#endif
    return 1;
}