int main(int argc, char* argv[])
{
    char hostName[200] = DEFAULT_HOSTNAME;
    int port = DEFAULT_RESMGR_TPM_PORT; //DEFAULT_TPM_PORT;

    TPMI_DH_OBJECT keyHandle;
    TPMI_YES_NO decryptVal = NO;
    TPM2B_MAX_BUFFER inData;
    char outFilePath[PATH_MAX] = {0};

    setbuf(stdout, NULL);
    setvbuf (stdout, NULL, _IONBF, BUFSIZ);

    int opt = -1;
    const char *optstring = "hvk:P:D:I:o:p:d:c:";
    static struct option long_options[] = {
      {"help",0,NULL,'h'},
      {"version",0,NULL,'v'},
      {"keyHandle",1,NULL,'k'},
      {"pwdk",1,NULL,'P'},
      {"decrypt",1,NULL,'D'},
      {"inFile",1,NULL,'I'},
      {"outFile",1,NULL,'o'},
      {"port",1,NULL,'p'},
      {"debugLevel",1,NULL,'d'},
      {"keyContext",1,NULL,'c'},
      {0,0,0,0}
    };

    int returnVal = 0;
    int flagCnt = 0;
    int h_flag = 0,
        v_flag = 0,
        k_flag = 0,
        P_flag = 0,
        I_flag = 0,
        c_flag = 0,
        o_flag = 0;
    char *contextKeyFile = NULL;

    if(argc == 1)
    {
        showHelp(argv[0]);
        return 0;
    }

    while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1)
    {
        switch(opt)
        {
        case 'h':
            h_flag = 1;
            break;
        case 'v':
            v_flag = 1;
            break;
        case 'k':
            if(getSizeUint32Hex(optarg,&keyHandle) != 0)
            {
                returnVal = -1;
                break;
            }
            k_flag = 1;
            break;
        case 'P':
            sessionData.hmac.t.size = sizeof(sessionData.hmac.t) - 2;
            if(str2ByteStructure(optarg,&sessionData.hmac.t.size,sessionData.hmac.t.buffer) != 0)
            {
                returnVal = -2;
                break;
            }
            P_flag = 1;
            break;
        case 'D':
            if(strcmp("YES", optarg) == 0)
                decryptVal = YES;
            else if(strcmp("NO", optarg) == 0)
                decryptVal = NO;
            else
            {
                returnVal = -3;
                showArgError(optarg, argv[0]);
                break;
            }
            break;
        case 'I':
            inData.t.size = sizeof(inData) - 2;
            if(loadDataFromFile(optarg, inData.t.buffer, &inData.t.size) != 0)
            {
                returnVal = -4;
                break;
            }
            I_flag = 1;
            break;
        case 'o':
            safeStrNCpy(outFilePath, optarg, sizeof(outFilePath));
            if(checkOutFile(outFilePath) != 0)
            {
                returnVal = -5;
                break;
            }
            o_flag = 1;
            break;
        case 'p':
            if( getPort(optarg, &port) )
            {
                printf("Incorrect port number.\n");
                returnVal = -6;
            }
            break;
        case 'd':
            if( getDebugLevel(optarg, &debugLevel) )
            {
                printf("Incorrect debug level.\n");
                returnVal = -7;
            }
            break;
        case 'c':
            contextKeyFile = optarg;
            if(contextKeyFile == NULL || contextKeyFile[0] == '\0')
            {
                returnVal = -8;
                break;
            }
            printf("contextKeyFile = %s\n", contextKeyFile);
            c_flag = 1;
            break;
        case ':':
//              printf("Argument %c needs a value!\n",optopt);
            returnVal = -9;
            break;
        case '?':
//              printf("Unknown Argument: %c\n",optopt);
            returnVal = -10;
            break;
        //default:
        //  break;
        }
        if(returnVal)
            break;
    };

    if(returnVal != 0)
        return returnVal;
    if(P_flag == 0)
        sessionData.hmac.t.size = 0;

    flagCnt = h_flag + v_flag + k_flag + I_flag + o_flag + c_flag;

    if(flagCnt == 1)
    {
        if(h_flag == 1)
            showHelp(argv[0]);
        else if(v_flag == 1)
            showVersion(argv[0]);
        else
        {
            showArgMismatch(argv[0]);
            return -11;
        }
    }
    else if((flagCnt == 3) && (k_flag == 1 || c_flag == 1) && (I_flag == 1) && (o_flag == 1))
    {
        prepareTest(hostName, port, debugLevel);

        if(c_flag)
            returnVal = loadTpmContextFromFile(sysContext, &keyHandle, contextKeyFile);
        if (returnVal == 0)
            returnVal = encryptDecrypt(keyHandle, decryptVal, &inData, outFilePath);

        finishTest();

        if(returnVal)
            return -12;
    }
    else
    {
        showArgMismatch(argv[0]);
        return -13;
    }
    return 0;
}
int runClient(char *port) {
    char *name = "Client";

    //initialize masterServer, peerList and hostlist
    peerList = NULL;
    connectionList = NULL;
    connectionIdGenerator = 2; //1 is received for the server
    masterServer = NULL;

    int listernerSockfd = -1;
    struct connectionInfo *serverInfo = startServer(port, "CLIENT");
    if (serverInfo == NULL) {
        fprintf(stderr, "Did not get serverInfo from startServer()\n");
        return -1;
    }
    listernerSockfd = serverInfo->listernerSockfd;

    int STDIN = 0; //0 represents STDIN

    FD_ZERO(&masterFDList); // clear the master and temp sets
    FD_ZERO(&tempFDList);

    FD_SET(STDIN, &masterFDList); // add STDIN to master FD list
    fdmax = STDIN;

    FD_SET(listernerSockfd, &masterFDList); //add the listener to master FD list and update fdmax
    if (listernerSockfd > fdmax)
        fdmax = listernerSockfd;


    int actionComplete = 1;
    while (1) //keep waiting for input, connections and data
    {

        //this is ti identify is an activity is in progress
        if (actionComplete == 1) {
            printf("$");
            fflush(stdout); //print the terminal symbol
        }
        actionComplete = 1;

        tempFDList = masterFDList; //make a copy of masterFDList and use it as select() modifies the list

        //int select(int numfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
        if (select(fdmax + 1, &tempFDList, NULL, NULL, NULL) ==
                -1) //select waits till it gets data in an fd in the list
        {
            fprintf(stderr, "Error in select\n");
            return -1;
        }

        // an FD has data so iterate through the list to find the fd with data
        int fd;
        for (fd = 0; fd <= 20; fd++) {
            if (FD_ISSET(fd, &tempFDList)) //found the FD with data
            {
                if (fd == STDIN) //data from commandLine(STDIN)
                {
                    size_t commandLength = 50;
                    char *command = (char *) malloc(commandLength);
                    getline(&command, &commandLength, stdin); //get line the variable if space is not sufficient
                    if (stringEquals(command, "\n")) //to handle the stray \n s
                        continue;
                    //printf("--Got data: %s--\n",command);
                    handleCommands(command, "CLIENT");
                }
                else if (fd == listernerSockfd) //new client trying to connect to listener
                {

                    struct sockaddr_storage clientaddr;
                    socklen_t addrlen = sizeof clientaddr;
                    int clientsockfd;
                    if ((clientsockfd = accept(listernerSockfd, (struct sockaddr *) &clientaddr, &addrlen)) == -1) {
                        fprintf(stderr, "Error accepting connection: %d %s\n", clientsockfd,
                                gai_strerror(clientsockfd));
                        return -1;
                    }
                    else {
                        //accept connection from client add it to the connectionList
                        struct host *client = (struct host *) malloc(sizeof(struct host));
                        struct sockaddr *hostAddress = (struct sockaddr *) &clientaddr;
                        client->id = connectionIdGenerator++;
                        client->sockfd = clientsockfd;
                        client->ipAddress = getIPAddress(hostAddress);
                        client->hostName = getHostFromIp(client->ipAddress);
                        client->port = getPort(hostAddress);
                        addNode(&connectionList, client);
                        FD_SET(client->sockfd, &masterFDList); // add fd to fdlist
                        if (client->sockfd > fdmax)
                            fdmax = client->sockfd;
                        printf("Accepted client: %s/%s.\n", client->hostName, client->port);

                    }

                }
                else if (masterServer != NULL && fd == masterServer->sockfd)// handle data from server
                {

                    struct packet *recvPacket = readPacket(fd);
                    if (recvPacket == NULL) {
                        printf("Master Server has terminated unexpectedly.\n");
                        int connectionId = getIDForFD(connectionList, fd);
                        terminateConnection(connectionId);
                        masterServer = NULL;
                        peerList = NULL;
                        continue;
                    }

//                    printf("Received packet: ");
//                    printPacket(recvPacket);
//                    printf("\n");

                    //received terminate from server
                    if (recvPacket->header->messageType == terminate) {
                        printf("Received TERMINATE command from server.\n");
                        int connectionId = getIDForFD(connectionList, fd);
                        terminateConnection(connectionId);
                        peerList = NULL;
                        masterServer = NULL;
                        continue;
                    }

                    if (recvPacket->header->messageType == hostList) {
                        //split the hostlist
                        int length = 0;
                        char **hostinfo = splitString(recvPacket->message, ' ', &length);
                        free(peerList);
                        peerList = NULL; //destroy the old peerList
                        int i;
                        for (i = 0; i < length; i = i + 2) {
                            if (i + 1 >= length)
                                fprintf(stderr, "Disproportionate terms in hostList sent by server.\n");

                            if (stringEquals(myIpAddress, hostinfo[i]) && stringEquals(myListenerPort, port)) {
                                //this is so that the client doesn't add itself in the peerList
                                continue;
                            }
                            //add all nodes
                            struct host *peer = (struct host *) malloc(sizeof(struct host));
                            peer->sockfd = -1; // we do not have a connection with it yet
                            peer->ipAddress = hostinfo[i];
                            peer->hostName = getHostFromIp(peer->ipAddress);
                            peer->port = hostinfo[i + 1];
                            addNode(&peerList, peer);
                        }
                        printf("New peerList received from server:\n");
                        printPeerList(peerList);
                        continue;
                    }

                    if (recvPacket->header->messageType == syncFiles) {
                        printf("Received a sync initiate request from Server.\n");
                        syncHostnameFiles();
                        continue;
                    }

                }
                else {

                    //handle data from the peers
                    struct packet *recvPacket = readPacket(fd);
                    if (recvPacket == NULL) {
                        //one of the clients terminated unexpectedly
                        int id = getIDForFD(connectionList, fd);
                        struct host *host = getHostByID(connectionList, id);
                        printf("%s/%s terminated unexpectedly. Removing it from the list.\n",
                               host->hostName, host->port, host->sockfd);
                        terminateConnection(id);
                        continue;
                    }
//                    printf("Received packet: ");
//                    printPacket(recvPacket);
//                    printf("\n");

                    //received terminate
                    if (recvPacket->header->messageType == terminate) {
                        int id = getIDForFD(connectionList, fd);
                        struct host *source = getHostByID(connectionList, id);
                        printf("Received TERMINATE command from %s/%s. Removing it.\n", source->hostName, source->port);
                        terminateConnection(id);
                        continue;
                    }//handle error message
                    else if (recvPacket->header->messageType == error) {
                        printf("Received error message: %s\n", recvPacket->message);
                        continue;
                    }//handle get request
                    else if (recvPacket->header->messageType == get) {
                        int connectionId = getIDForFD(connectionList, fd);
                        struct host *destination = getHostByID(connectionList, connectionId);
                        if (destination == NULL) {
                            fprintf(stderr, "Coudn't find the connection id.\n");
                            continue;
                        }
                        printf("Received a get request for file %s from client: %s/%s.\n",
                               recvPacket->header->fileName, destination->hostName, destination->port);
                        sendFile(connectionId, recvPacket->header->fileName);
                    }//hand a put packet
                    else if (recvPacket->header->messageType == put) {
                        int connectionId = getIDForFD(connectionList, fd);
                        receiveFileAsynchronously(connectionId, recvPacket);
                        actionComplete = 0; //action is not complete until a ok packet is received
                        continue;
                    }//handle a ok packet
                    else if (recvPacket->header->messageType == ok) {
                        int connectionId = getIDForFD(connectionList, fd);
                        okPacketHandler(connectionId, recvPacket);
                        actionComplete = 1; // activity completed
                        continue;
                    }

                }
            }
        }
    }
}
示例#3
0
void BmNetworkTCPClient::connectTo()
{
    if ( !isConnected() )
        mSocket->connectToHost( getHostAddress(), getPort() );
}
//The main invoker routine. It takes as argument the next command to execute and does what is necessary
//Self-explanatory code!
void my_invoker (unsigned char command) {
	if(command == BUZZER_ON){
		buzzer_on();
		return;
	}
	else if(command == BUZZER_OFF){
		buzzer_off();
		return;
	}
	else if(command == MOVE_FORWARD) 
    {
        forward();  //forward
        return;
    }

    else if(command == MOVE_BACKWARD)
    {
        back(); //back
        return;
    }

    else if(command == MOVE_LEFT) 
    {
        left();  //left
        return;
    }

    else if(command == MOVE_RIGHT)
    {
        right(); //right
        return;
    }

    else if(command == STOP) 
    {
        stop(); //stop
        return;
    }
	
	else if(command == SET_VELOCITY) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
        
		//assert(numargs == 1);

		int velleft = (int)*(ch);
		int velright = (int)*(ch+1);
		velocity(velleft,velright);

        return;
    }
	
	else if(command == MOVE_BY) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
		int pos_a = (int)*(ch);
		int pos_b = (int)*(ch+1);

		//int pos = 10;
		//while (pos_b--) pos *= 10;
		//pos *= pos_a;
		//forward_mm(pos);
		pos_a += (pos_b << 8);

		forward();
		velocity(120,120);

		while (pos_a--) {
			//delay on 5 ms
			stop_on_timer4_overflow = 1;
			start_timer4();
			while (stop_on_timer4_overflow != 0) {;}
		}
		stop();
		send_char(SUCCESS);		
		leftInt = 0;
		rightInt = 0;
		
		return;
    }

	else if(command == MOVE_BACK_BY) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
		int pos_a = (int)*(ch);
		int pos_b = (int)*(ch+1);

		//int pos = 10;
		//while (pos_b--) pos *= 10;
		//pos *= pos_a;
		//forward_mm(pos);
		pos_a += (pos_b << 8);

		back();
		velocity(120,120);

		while (pos_a--) {
			//delay on 5 ms
			stop_on_timer4_overflow = 1;
			start_timer4();
			while (stop_on_timer4_overflow != 0) {;}
		}
		stop();
		send_char(SUCCESS);		
		leftInt = 0;
		rightInt = 0;
		
		return;
    }
	
	else if(command == TURN_LEFT_BY) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
        already_stopped = 0;
		int pos_a = (int)*(ch);
		int pos_b = (int)*(ch+1);

		pos_a += (pos_b << 8);

		_delay_ms(500);
		left();
		velocity(200,200);

		while (pos_a--) {
			//delay on 5 ms
			stop_on_timer4_overflow = 1;
			start_timer4();
			while (stop_on_timer4_overflow != 0) {;}
		}
		stop();
		send_char(SUCCESS);		
		leftInt = 0;
		rightInt = 0;
		already_modified_stopped = 0;

        return;
    }

	else if(command == TURN_RIGHT_BY) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
        
		//assert(numargs == 2);

		int pos_a = (int)*(ch);
		int pos_b = (int)*(ch+1);

		pos_a += (pos_b << 8);

		_delay_ms(500);
		right();
		velocity(200,200);


		while (pos_a--) {
			//delay on 5 ms
			stop_on_timer4_overflow = 1;
			start_timer4();
			while (stop_on_timer4_overflow != 0) {;}
		}		

		stop();
		send_char(SUCCESS);
		leftInt = 0;
		rightInt = 0;
		already_modified_stopped = 0;
        return;
    }

    else if(command == LCD_SET_STRING) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
        
        int i =0;
		lcd_clear();
        for(;i<numargs;i++)
        {
            lcd_wr_char(*(ch+i));
        }
        return;
    }
	
	else if (command == SET_PORT){
    	int numargs;
    	unsigned char * ch = recieve_args(&numargs); ; 
    	if (numargs != 2){
   
	    }
    	int portnum = (int) *(ch);
    	unsigned char value = (unsigned char) *(ch+1); 
    
		setPort(portnum,value);
    }

    else if(command == GET_SENSOR_VALUE)
    {
    	int numargs;
    	unsigned char * ch = recieve_args(&numargs); ; 
    	if (numargs != 1){
   
	    }
    	int sensornum = (int) *(ch);
    
		//setPort(portnum,value);
		getSensorValue(sensornum);
       
    }
    else if(command == GET_PORT)
    {
      	int numargs;
    	unsigned char * ch = recieve_args(&numargs); ; 
    	if (numargs != 1){
   
	    }
    	int portnum = (int) *(ch); 
    
		getPort(portnum);
        
    }
    else if (command == WHITELINE_FOLLOW_START) {
		whiteline_follow_start();
	}
	else if(command == PRINT_STATE){
		buzzer_on();
		lcd_num(state);
		_delay_ms(1000);
		buzzer_off();
	}
	else if (command == WHITELINE_FOLLOW_END) {
		whiteline_follow_end();
	}
	else if (command == WHITELINE_STOP_INTERSECTION) {
		whiteline_stop_intersection_flag = 1;
	}
    else if(command == ACC_START) {
   		acc_flag = 1;
		
   
    }
	else if(command == ACC_STOP) {
		acc_flag = 0;
		acc_modified_flag = 0;
		buzzer_off();
	}
	else if(command == ACC_MODIFIED){
		acc_modified_flag = 1;
		already_modified_stopped = 0;
	}
	else if(command == ACC_CHECK){
		if (acc_modified_flag == 1 && already_modified_stopped == 1){
			send_char((char)1);
		}
		else {
			char value = PORTA;
			if (value == 0) send_char((char)2);
			else send_char((char)0);
		}
	}
	else if (command == ENABLE_LEFT_WHEEL_INTERRUPT) {
		leftInt = 0;
		left_position_encoder_interrupt_init();
	}
	else if (command == ENABLE_RIGHT_WHEEL_INTERRUPT) {
		rightInt = 0;
		right_position_encoder_interrupt_init();
	}
	else if (command == GET_LEFT_WHEEL_INTERRUPT_COUNT) {
		send_int (leftInt);
		leftInt = 0;
	}
	else if (command == GET_RIGHT_WHEEL_INTERRUPT_COUNT) {
		send_int (rightInt);
		rightInt = 0;
	}
	else if (command == SET_TIMER) {
	int numargs;
    	unsigned char * ch = recieve_args(&numargs); ; 
    	if (numargs != 1){
   
	    }
    	int time = (int) *(ch); 
    
		timer4_init2(time);
	}
	else if (command == DISCONNECT) {
		disconnect();
	}
	else { //Error!!! Unrecognized Command
		buzzer_on();
		_delay_ms(1000);
		buzzer_off();
	}
}
int main(int argc, char* argv[])
{
    char hostName[200] = DEFAULT_HOSTNAME;
    int port = DEFAULT_RESMGR_TPM_PORT; //DEFAULT_TPM_PORT;
    char *contextFilePath = NULL;
    char *keyContextFilePath = NULL;

    setbuf(stdout, NULL);
    setvbuf (stdout, NULL, _IONBF, BUFSIZ);

    int opt = -1;
    const char *optstring = "hvH:c:k:C:P:e:f:o:Xp:d:";
    struct option long_options[] = {
      {"help",0,NULL,'h'},
      {"version",0,NULL,'v'},
      {"handle",1,NULL,'H'},
      {"context",1,NULL,'c'},
      {"keyHandle",1,NULL,'k'},
      {"keyContext",1,NULL,'C'},
      {"Password",1,NULL,'P'},
      {"endorsePasswd",1,NULL,'e'},
      {"inFile",1,NULL,'f'},
      {"outFile",1,NULL,'o'},
      {"passwdInHex",0,NULL,'X'},
      {"port",1,NULL,'p'},
      {"debugLevel",1,NULL,'d'},
      {0,0,0,0},
    };

    int returnVal = 0;
    int flagCnt = 0;
    int h_flag = 0,
        v_flag = 0,
        H_flag = 0,
        c_flag = 0,
        k_flag = 0,
        C_flag = 0,
        e_flag = 0,
        P_flag = 0,
        f_flag = 0,
        o_flag = 0;

    if(argc == 1)
    {
        showHelp(argv[0]);
        return 0;
    }

    cmdAuth.hmac.t.size = 0;
    cmdAuth2.hmac.t.size = 0;

    while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1)
    {
        switch(opt)
        {
        case 'h':
            h_flag = 1;
            break;
        case 'v':
            v_flag = 1;
            break;
        case 'H':
            if(getSizeUint32Hex(optarg,&activateHandle) != 0)
            {
                returnVal = -1;
                break;
            }
            H_flag = 1;
            break;
        case 'c':
            contextFilePath = optarg;
            if(contextFilePath == NULL || contextFilePath[0] == '\0')
            {
                returnVal = -2;
                break;
            }
            printf("contextFile = %s\n", contextFilePath);
            c_flag = 1;
            break;
        case 'k':
            if(getSizeUint32Hex(optarg,&keyHandle) != 0)
            {
                returnVal = -3;
                break;
            }
            k_flag = 1;
            break;
        case 'C':
            keyContextFilePath = optarg;
            if(keyContextFilePath == NULL || keyContextFilePath[0] == '\0')
            {
                returnVal = -4;
                break;
            }
            printf("keyContextFile = %s\n", keyContextFilePath);
            C_flag = 1;
            break;
        case 'P':
            cmdAuth.hmac.t.size = sizeof(cmdAuth.hmac.t) - 2;
            if(str2ByteStructure(optarg,&cmdAuth.hmac.t.size,cmdAuth.hmac.t.buffer) != 0)
            {
                returnVal = -5;
                break;
            }
            P_flag = 1;
            break;
        case 'e':
            cmdAuth2.hmac.t.size = sizeof(cmdAuth2.hmac.t) - 2;
            if(str2ByteStructure(optarg,&cmdAuth2.hmac.t.size,cmdAuth2.hmac.t.buffer) != 0)
            {
                returnVal = -6;
                break;
            }
            e_flag = 1;
            break;
        case 'f':
            if(readCrtSecFromFile(optarg,&credentialBlob,&secret) != 0)
            {
                returnVal = -7;
                break;
            }
            f_flag = 1;
            break;
        case 'o':
            safeStrNCpy(outFilePath, optarg, sizeof(outFilePath));
#if 0
            if(checkOutFile(outFilePath) != 0)
            {
                returnVal = -1;
                break;
            }
#endif
            o_flag = 1;
            break;
        case 'X':
            hexPasswd = true;
            break;
        case 'p':
            if( getPort(optarg, &port) )
            {
                printf("Incorrect port number.\n");
                returnVal = -8;
            }
            break;
        case 'd':
            if( getDebugLevel(optarg, &debugLevel) )
            {
                printf("Incorrect debug level.\n");
                returnVal = -9;
            }
            break;
        case ':':
//              printf("Argument %c needs a value!\n",optopt);
            returnVal = -10;
            break;
        case '?':
//              printf("Unknown Argument: %c\n",optopt);
            returnVal = -11;
            break;
        //default:
        //  break;
        }
        if(returnVal)
            break;
    };

    if(returnVal != 0)
        return returnVal;
    flagCnt = h_flag + v_flag + H_flag + c_flag + k_flag + C_flag + f_flag + o_flag;

    if(flagCnt == 1)
    {
        if(h_flag == 1)
            showHelp(argv[0]);
        else if(v_flag == 1)
            showVersion(argv[0]);
        else
        {
            showArgMismatch(argv[0]);
            return -12;
        }
    }
    else if((flagCnt == 4) && (H_flag == 1 || c_flag == 1) && (k_flag == 1 || C_flag == 1) && (f_flag == 1) && (o_flag == 1))
    {
        prepareTest(hostName, port, debugLevel);

        if(c_flag)
            returnVal = loadTpmContextFromFile(sysContext, &activateHandle, contextFilePath);
        if(C_flag && returnVal == 0)
            returnVal = loadTpmContextFromFile(sysContext, &keyHandle, keyContextFilePath);
        if(returnVal == 0)
            returnVal = activateCredential();

        finishTest();

        if(returnVal)
            return -13;
    }
    else
    {
        showArgMismatch(argv[0]);
        return -14;
    }
    return 0;
}
示例#6
0
bool execute(const std::string& method, const XmlRpc::XmlRpcValue& request, XmlRpc::XmlRpcValue& response, XmlRpc::XmlRpcValue& payload, bool wait_for_master)
{
  ros::WallTime start_time = ros::WallTime::now();

  std::string master_host = getHost();
  uint32_t master_port = getPort();
  XmlRpc::XmlRpcClient *c = XMLRPCManager::instance()->getXMLRPCClient(master_host, master_port, "/");
  bool printed = false;
  bool slept = false;
  bool ok = true;
  do
  {
    bool b = false;
    {
#if defined(__APPLE__)
      boost::mutex::scoped_lock lock(g_xmlrpc_call_mutex);
#endif

      b = c->execute(method.c_str(), request, response);
    }

    ok = !ros::isShuttingDown() && !XMLRPCManager::instance()->isShuttingDown();

    if (!b && ok)
    {
      if (!printed && wait_for_master)
      {
        ROS_ERROR("[%s] Failed to contact master at [%s:%d].  %s", method.c_str(), master_host.c_str(), master_port, wait_for_master ? "Retrying..." : "");
        printed = true;
      }

      if (!wait_for_master)
      {
        XMLRPCManager::instance()->releaseXMLRPCClient(c);
        return false;
      }

      if (!g_retry_timeout.isZero() && (ros::WallTime::now() - start_time) >= g_retry_timeout)
      {
        ROS_ERROR("[%s] Timed out trying to connect to the master after [%f] seconds", method.c_str(), g_retry_timeout.toSec());
        XMLRPCManager::instance()->releaseXMLRPCClient(c);
        return false;
      }

      ros::WallDuration(0.05).sleep();
      slept = true;
    }
    else
    {
      if (!XMLRPCManager::instance()->validateXmlrpcResponse(method, response, payload))
      {
        XMLRPCManager::instance()->releaseXMLRPCClient(c);

        return false;
      }

      break;
    }

    ok = !ros::isShuttingDown() && !XMLRPCManager::instance()->isShuttingDown();
  } while(ok);

  if (ok && slept)
  {
    ROS_INFO("Connected to master at [%s:%d]", master_host.c_str(), master_port);
  }

  XMLRPCManager::instance()->releaseXMLRPCClient(c);

  return true;
}
示例#7
0
	std::string str()
	{
		return std::string(getIp() + DELIMITER + getPort());
	}
示例#8
0
int main(int argc, char* argv[])
{
    int opt;
    char type[100] = "local";
    char hostName[200] = DEFAULT_HOSTNAME;
    int port = DEFAULT_RESMGR_TPM_PORT;
    int returnVal = 0;

    struct option sOpts[] = {
        { "index"       , required_argument, NULL, 'x' },
        { "authHandle"  , required_argument, NULL, 'a' },
        { "file"        , required_argument, NULL, 'f' },
        { "handlePasswd", required_argument, NULL, 'P' },
        { "passwdInHex" , no_argument,       NULL, 'X' },
        { "port"        , required_argument, NULL, 'p' },
        { "dbg"         , required_argument, NULL, 'd' },
        { "help"        , no_argument,       NULL, 'h' },
        { "version"     , no_argument,       NULL, 'v' },
        { NULL          , no_argument,       NULL,  0  },
    };

    if(argc == 1)
    {
        showHelp(argv[0]);
        return 0;
    }

    if( argc > (int)(2*sizeof(sOpts)/sizeof(struct option)) )
    {
        showArgMismatch(argv[0]);
        return -1;
    }

    while ( ( opt = getopt_long( argc, argv, "x:a:f:P:Xp:d:hv", sOpts, NULL ) ) != -1 )
    {
        switch ( opt ) {
        case 'h':
        case '?':
            showHelp(argv[0]);
            return 0;
        case 'v':
            showVersion(argv[0]);
            return 0;

        case 'x':
            if( getSizeUint32Hex(optarg, &nvIndex) != 0 )
            {
                return -2;
            }
            break;

        case 'a':
            if( getSizeUint32Hex(optarg, &authHandle) != 0 )
            {
                return -3;
            }
            break;

        case 'P':
            if( optarg == NULL || (strlen(optarg) >= sizeof(TPMU_HA)) )
            {
                printf("\nPlease input the handle password(optional,no more than %d characters).\n", (int)sizeof(TPMU_HA)-1);
                return -4;
            }
            safeStrNCpy(&handlePasswd[0], optarg, sizeof(handlePasswd));
            break;

        case 'f':
            if( optarg == NULL )
            {
                printf("\nPlease input the nv data file.\n");
                return -5;
            }
            safeStrNCpy(&fileName[0], optarg, sizeof(fileName));
            break;

        case 'X':
            hexPasswd = true;
            break;

        case 'p':
            if( getPort(optarg, &port) )
            {
                printf("Incorrect port number.\n");
                return -6;
            }
            break;
        case 'd':
            if( getDebugLevel(optarg, &debugLevel) )
            {
                printf("Incorrect debug level.\n");
                return -7;
            }
            break;

        default:
            showArgMismatch(argv[0]);
            return -8;
        }
    }

    if( nvIndex == 0 )
    {
        printf("You must provide an index (!= 0) for the NVRAM area.\n");
        return -9;
    }

    if( authHandle == 0 )
    {
        printf("You must provide an right auth handle for this operation.\n");
        return -10;
    }

    dataSize = MAX_NV_INDEX_SIZE;
    if(loadDataFromFile(fileName, nvBuffer, &dataSize))
    {
        printf("Failed to read data from %s\n", fileName);
        return -11;
    }

    prepareTest(hostName, port, debugLevel);

    returnVal = nvWrite();

    finishTest();

    if(returnVal)
        return -12;

    return 0;
}
int main(int argc, char* argv[])
{
    char hostName[200] = DEFAULT_HOSTNAME;
    int port = DEFAULT_RESMGR_TPM_PORT;

    TPMI_DH_OBJECT objectHandle;
    char outFilePath[PATH_MAX] = {0};
    char *contextFile = NULL;

    setbuf(stdout, NULL);
    setvbuf (stdout, NULL, _IONBF, BUFSIZ);

    int opt = -1;
    const char *optstring = "hvH:o:p:d:c:";
    static struct option long_options[] = {
      {"help",0,NULL,'h'},
      {"version",0,NULL,'v'},
      {"object",1,NULL,'H'},
      {"opu",1,NULL,'o'},
      {"port",1,NULL,'p'},
      {"debugLevel",1,NULL,'d'},
      {"contextObject",1,NULL,'c'},
      {0,0,0,0}
    };

    int returnVal = 0;
    int flagCnt = 0;
    int h_flag = 0,
        v_flag = 0,
        H_flag = 0,
        c_flag = 0,
        o_flag = 0;

    if(argc == 1)
    {
        showHelp(argv[0]);
        return 0;
    }

    while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1)
    {
        switch(opt)
        {
        case 'h':
            h_flag = 1;
            break;
        case 'v':
            v_flag = 1;
            break;
        case 'H':
            if(getSizeUint32Hex(optarg,&objectHandle) != 0)
            {
                returnVal = -1;
                break;
            }
            printf("\nobject handle: 0x%x\n\n",objectHandle);
            H_flag = 1;
            break;
        case 'o':
            safeStrNCpy(outFilePath, optarg, sizeof(outFilePath));
            if(checkOutFile(outFilePath) != 0)
            {
                returnVal = -2;
                break;
            }
            o_flag = 1;
            break;
        case 'p':
            if( getPort(optarg, &port) )
            {
                printf("Incorrect port number.\n");
                returnVal = -3;
            }
            break;
        case 'd':
            if( getDebugLevel(optarg, &debugLevel) )
            {
                printf("Incorrect debug level.\n");
                returnVal = -4;
            }
            break;
        case 'c':
            contextFile = optarg;
            if(contextFile == NULL || contextFile[0] == '\0')
            {
                returnVal = -5;
                break;
            }
            printf("contextFile = %s\n", contextFile);
            c_flag = 1;
            break;
        case ':':
//              printf("Argument %c needs a value!\n",optopt);
            returnVal = -6;
            break;
        case '?':
//              printf("Unknown Argument: %c\n",optopt);
            returnVal = -7;
            break;
        //default:
        //  break;
        }
        if(returnVal)
            break;
    };

    if(returnVal != 0)
        return returnVal;

    flagCnt = h_flag + v_flag + H_flag + o_flag + c_flag;
    if(flagCnt == 1)
    {
        if(h_flag == 1)
            showHelp(argv[0]);
        else if(v_flag == 1)
            showVersion(argv[0]);
        else
        {
            showArgMismatch(argv[0]);
            return -8;
        }
    }
    else if(flagCnt == 2 && (H_flag == 1 || c_flag) && o_flag == 1)
    {
        prepareTest(hostName, port, debugLevel);

        if(c_flag)
            returnVal = loadTpmContextFromFile(sysContext, &objectHandle, contextFile);
        if(returnVal == 0)
            returnVal = readPublic(objectHandle, outFilePath);

        finishTest();

        if(returnVal)
            return -9;
    }
    else
    {
        showArgMismatch(argv[0]);
        return -10;
    }

    return 0;
}
void SimulatorController::timerEvent(QTimerEvent *event)
{
  if (event->timerId() == m_timer.timerId())
  {
    QString payload;
    QString currentElementName;
    QString Name, messageID, messageAction, symbolID, type;
    QXmlStreamWriter streamWriter(&payload);
    QString currentTimeString = QDateTime::currentDateTimeUtc().toString(SimulatorController::DATE_FORMAT);

    streamWriter.writeStartElement(TAG_ROOT);
    for(int messageThroughput = 0 ; messageThroughput < m_messageThroughput ; messageThroughput++)
    {
      while (!m_inputReader.atEnd())
      {
        if(QStringRef::compare(m_inputReader.name(), TAG_MESSAGES) == 0)
        {
          m_inputReader.readNext();
          if(m_inputReader.atEnd())
          {
            m_reachedEndOfFile=true;
            m_inputReader.clear();
            m_inputFile.reset();
            m_inputReader.setDevice(&m_inputFile);
            m_currentIndex = 0;
          }
          continue;
        }
        else if (m_inputReader.isEndElement())
        {
          streamWriter.writeEndElement();
          if(QStringRef::compare(m_inputReader.name(), TAG_MESSAGE) == 0)
          {
            //Only emit readGeomessage if this is the first time we have read the message...
            if (m_reachedEndOfFile == false)
            {
              emit readGeomessage(Geomessage(Name, messageID, messageAction, symbolID, type));
            }
            //Only emit advancedToGeomessage when it's the last message in this set...
            if (messageThroughput + 1 == m_messageThroughput)
            {
              emit advancedToGeomessage(m_currentIndex);
            }
            m_currentIndex++;
            break;
          }

          m_inputReader.readNext();
        }
        else if (m_inputReader.isStartElement())
        {
          currentElementName = m_inputReader.name().toString();
          if (m_inputReader.prefix().toString().isEmpty())
          {
            streamWriter.writeStartElement(m_inputReader.name().toString());
          }
          else
          {
            streamWriter.writeStartElement(m_inputReader.prefix().toString()+ ":" + m_inputReader.name().toString());
          }
          if (m_inputReader.attributes().size() > 0)
          {
            streamWriter.writeAttributes(m_inputReader.attributes());
          }
        }
        else if (m_inputReader.isCharacters())
        {
          QString text = m_inputReader.text().toString();
          {
            QMutexLocker locker(&timeOverrideFieldsMutex);
            if (m_timeOverrideFields.contains(currentElementName))
            {
              text = currentTimeString;
            }
          }

          streamWriter.writeCharacters(text);
          if (TAG_NAME == currentElementName)
          {
            Name = text;
          }
          else if (TAG_ACTION == currentElementName)
          {
            messageAction = text;
          }
          else if (TAG_ID == currentElementName)
          {
            messageID = text;
          }
          else if (TAG_SIC == currentElementName)
          {
            symbolID = text;
          }
          else if (TAG_TYPE == currentElementName)
          {
            type = text;
          }
        }
        else if (m_inputReader.isComment())
        {
          /* leave not import */
        }
        else if (m_inputReader.isCDATA())
        {
          /* take cdata */
        }
        m_inputReader.readNext();
      }

      m_inputReader.readNext();
    }

    streamWriter.writeEndElement();

    QByteArray datagram;
    datagram += payload;
    QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
    for (int i = 0; i < ifaces.size(); i++)
    {
      QNetworkInterface::InterfaceFlags flags = ifaces[i].flags();
      if (!(flags & QNetworkInterface::IsLoopBack) && (flags & QNetworkInterface::IsUp))
      {
        QList<QNetworkAddressEntry> entries = ifaces[i].addressEntries();
        for (int j = 0; j < entries.size(); j++)
        {
          m_udpSocket->writeDatagram(datagram.data(), datagram.size(), entries[j].broadcast(), getPort());
        }
      }
    }

    if (verbose())
    {
      consoleOut << payload << endl;
    }
  }
  else
  {
    QObject::timerEvent(event);
  }
}
示例#11
0
文件: sock.cpp 项目: weakwater/easy
 string SockAddr::toString(bool includePort) const {
     string out = getAddr();
     if (includePort && getType() != AF_UNIX && getType() != AF_UNSPEC)
         out += mongoutils::str::stream() << ':' << getPort();
     return out;
 }
struct connectionInfo *startServer(char *port, char *hostType) {

    struct addrinfo *serverAddressInfo = getAddressInfo("localhost", port); //as server needs to be started on localhost

    //struct sockaddr_in *ipv4Address = (struct sockaddr_in *)serverAddressInfo->ai_addr;
    //printf("IPv4 : %d, Sockt_Type : %d\n",ipv4Address->sin_addr.s_addr,serverAddressInfo->ai_socktype);

    if (serverAddressInfo->ai_next != NULL)
        fprintf(stderr, "More than one IPv4 addresses returned");

    int listernerSockfd;

    if ((listernerSockfd = socket(serverAddressInfo->ai_family, serverAddressInfo->ai_socktype,
                                  serverAddressInfo->ai_protocol)) == -1) {
        fprintf(stderr, "Error Creating socket: %d %s\n", listernerSockfd, gai_strerror(listernerSockfd));
        return NULL;
    } else {
        //printf("Created Socket.\n");
    }

    int bindStatus;

    if ((bindStatus = bind(listernerSockfd, serverAddressInfo->ai_addr, serverAddressInfo->ai_addrlen)) == -1) {
        fprintf(stderr, "Error binding %d %s\n", bindStatus, gai_strerror(bindStatus));
        return NULL;
    } else {
        //printf("Done binding socket to port %s.\n", port);
    }

//    if (stringEquals(hostType, "SERVER")) //binding to port only for server, this is only for testing need to bind for client too in production
//    {
//        int bindStatus;
//
//        if ((bindStatus = bind(listernerSockfd, serverAddressInfo->ai_addr, serverAddressInfo->ai_addrlen)) == -1) {
//            fprintf(stderr, "Error binding %d %s\n", bindStatus, gai_strerror(bindStatus));
//            return NULL;
//        } else {
//            printf("Done binding socket to port %s.\n", port);
//        }
//    }

    int listenStatus;

    if ((listenStatus = listen(listernerSockfd, 10)) == -1) {
        //10 is the backlog
        fprintf(stderr, "Error listening: %d %s\n", listenStatus, gai_strerror(listenStatus));
        return NULL;
    } else {
        printf("Listening...\n");
    }

    //updating the global variable myListenerPort
    int sockStatus;
    struct sockaddr listenerAddress;
    socklen_t len = sizeof(listenerAddress);
    if ((sockStatus = getsockname(listernerSockfd, &listenerAddress, &len)) != 0) {
        fprintf(stderr, "Unable to find listening port %s\n", gai_strerror(sockStatus));
        return NULL;
    }
    else
        myListenerPort = getPort(&listenerAddress);

    //updating global variable name and myIpAddress
    // getIPAddress(&listenerAddress) returns 0.0.0.0 hence getting ip using the hostname
    myHostName = (char *) malloc(sizeof(char) * 25);
    gethostname(myHostName, 254);
    myIpAddress = getIpfromHost(myHostName);

    //build the serverInfo structure to be retunrned
    struct connectionInfo *serverInfo = (struct connectionInfo *) malloc(sizeof(struct connectionInfo));
    serverInfo->listernerSockfd = listernerSockfd;
    serverInfo->serverAddressInfo = serverAddressInfo;

    return serverInfo;
}