Пример #1
0
int main(int argc, char **argv)
{
	(void)argc;
	(void)argv;
	const uint32_t net = 0x0a0a0a00;
	char *password;

	setup_test("tcpr-test", "test-spurious-fins");
	password = get_password(htonl(net | 2), 8888, htonl(net | 3), 9999);

	setup_connection(net | 2, net | 4, net | 3, 8888, 9999, 0xdeadbeef,
				0xcafebabe, test_options_size, test_options,
				peer_mss, peer_ws, password);

	fprintf(stderr, "Application: FIN (failure)\n");
	send_segment(internal_log, net | 4, net | 2, 9999, 8888,
			TH_ACK | TH_FIN, 0xcafebabe + 1, 0xdeadbeef + 1, 0,
			NULL, 0, NULL, password);

	fprintf(stderr, "     Filter: RST\n");
	recv_segment(internal_log, net | 2, net | 4, 8888, 9999, TH_RST,
			0xdeadbeef + 1, 0, 0, NULL, 0, NULL, password);

	cleanup_connection(net | 2, net | 4, 8888, 9999, 0xcafebabe + 1,
				0xdeadbeef + 1, 0);

	cleanup_test();
	return EXIT_SUCCESS;
}
Пример #2
0
/* this is not public */
static void setup_keep_connection( int* tmp_socket )
{
	tmp_socket[0] = setup_connection();
	if ( tmp_socket[0] == -1 )
		printf("Failed, falling back to one shoot connection (slow).\n");
	else
		printf("Success, socket is n. %d\n", tmp_socket[0] );
}
Пример #3
0
NewusGui::NewusGui(QWidget* parent)
	: QWidget(parent), _feedMan(), _list(), _newsView(), _layout()
{
	setup_connection();
	setup_ui();

	debug_testInsert();
}
Пример #4
0
static bool test_internal_dns_update_self(struct torture_context *tctx)
{
	struct dns_connection *conn;
	struct dns_update_request *req, *resp;
	struct dns_rrec *rec = NULL;
	char *host;
	DNS_ERROR err;
	struct sockaddr_storage *ss;

	conn = setup_connection(tctx);
	if (conn == NULL) {
		return false;
	}

	host = talloc_asprintf(tctx, "%s.%s", getenv("DC_SERVER"), get_dns_domain(tctx));
	if (host == NULL) {
		return false;
	}

	err = dns_create_update(conn, get_dns_domain(tctx), &req);
	if (!ERR_DNS_IS_OK(err)) {
		printf("Failed to update packet\n");
		return false;
	}

	ss = str_to_sockaddr(conn, getenv("DC_SERVER_IP"));
	if (ss == NULL) {
		printf("Converting '%s' to sockaddr_storage failed\n", getenv("DC_SERVER_IP"));
		return false;
	}

	err = dns_create_a_record(req, host, 300, ss, &rec);
	if (!ERR_DNS_IS_OK(err)) {
		printf("Failed to create A update record\n");
		return false;
	}

	err = dns_add_rrec(req, rec, &req->num_updates, &req->updates);
	if (!ERR_DNS_IS_OK(err)) {
		printf("Failed to add A update record to update packet\n");
		return false;
	}

	err = dns_update_transaction(conn, conn, req, &resp);
	if (!ERR_DNS_IS_OK(err)) {
		printf("Failed to send update\n");
		return false;
	}

	if (dns_response_code(resp->flags) != DNS_REFUSED) {
		printf("Update returned %u\n", dns_response_code(resp->flags));
		return false;
	}

	/* FIXME: is there _any_ way to unmarshal the response to check this? */

	return true;
}
Пример #5
0
int main(int argc, char **argv)
{       
	int rtn,ch,i,pid,ppid;
        char buffer[10];
        char rcvfrom[30];
        char buffer1[4];
        int port_l,value,loops,ct;
        int ipaddr;
        char sipaddr[4];


        rtn = mk_daemon(argc, argv);
        rtn = shared_memory_attach();
        T->pid[LISTEN_IO24_PID].pids = getpid();
        rtn = io24_message_que_init();
        rtn = io24_out_message_que_init();      //use this to signal io24_out
        rtn = in_event_message_que_init();      //necessage to send messages in driver.c
        rtn = lcd_message_que_init();

	rtn = setup_connection();
	if (rtn != 0)
	{
		if (!Daemon) printf("***Unable to bind to IO24_PORT\n");
	}

//now split into two separate programs to read and to write UDP data
	pid = fork();
        if (pid <  0)
        {
                perror("Unable to fork:\n");
                exit(-1);
        }
        if ( pid == 0 ) //child process
        {
                if (Daemon)
                {
                        //close(0);
                        //close(1);
                }
                //Daemon = 1;
                //printf("Child process\n");
              	rtn = read_data();
        }
        if (pid > 0)            //parent process
        {
                if (Daemon)
                {
                        //close(0);
                        //close(1);
                }
                //Daemon = 1;
                //printf ("Parent process.....\n:");
                T->pid[IO24_PID].pids = getpid();
                //ppid = getpid();
                if (!Daemon) printf("Started io24 parent with pid = %d\n",ppid);
               	wait_for_msg();
        }
}
Пример #6
0
int main(int argc, char **argv)
{
    handle_options(argc, argv);
    setup_tcpr();
    setup_connection();
    setup_state();
    handle_events();
    teardown();
    return EXIT_SUCCESS;
}
Пример #7
0
/* BTW, in case you're wondering, this returns void* so that
 * it can be used as a pthread... 
 */
static void *default_start_server(void *arg)
{
	server_t self = arg;
	connection_t con;
	int i;

	if (!self) return NULL;

	/* 
	 * TODO.
	 * This shouldn't be done here. It doesn't really matter
	 * because it is basically a no-op right now anyway.
	 * A single process can have several servers running 
	 * in it, conceivably.
	 *
	 * Maybe it should be moved to ag.c and left up to main.
	 */
	become_daemon(self);


	/* configure the wait_queue's max size */
	self->wq->max = self->maxcon;

	/* this is the connection handler: */
	self->handlers = ag_malloc(sizeof(handler_rec) * self->numthreads);

	for (i = 0; i < self->numthreads; i++) {
		handler_t hd;
		hd = self->newhandler();
		hd->svr = self;
		self->handlers[i].hd = hd;
		(void) pthread_create(&self->handlers[i].tid,  /* thread id */
				      NULL,                   /* attributes */
				      hd->start,              /* function to run */
				      (void *)hd              /* arg to pass to function */
			);
	}

	/* 
	 * must do this before changing uids, because we may want to bind
	 * to a port < 1024 and then become a non-root user.
	 *
	 * TODO
	 * At this point we should also open up the logfile.
	*/
	self->listen_sk = setup_connection(self);

	/* only change users if self->uid is non-zero (non-root) */
	if (self->uid) become_user(self);

	for (;;) {
		con = accept_connection(self->listen_sk);
		if (!self->wq->add_con(self->wq, con)) con->destroy(con);
	}
}
Пример #8
0
int main(int argc, char** argv)
{
    int erl_fd; // FD to the ERL VM
    char* bufp; // storage for incoming messages
    int bufsz = 1024;

    // the following are basically magic values.
    erl_fd = setup_connection(1, "secretcookie", 0, "e1@am335x-evm");

    ErlMessage* emsg;
    emsg = (ErlMessage*)malloc(sizeof(ErlMessage));
    bufp = (char*)malloc(bufsz * sizeof(char));

    while (1) // main loop - we don't ever expect to leave.
    {
        TRACE(("starting main loop"));

        TRACE(("waiting for a message..."));
        int msg_status = erl_receive_msg(erl_fd, bufp, bufsz, emsg);
        TRACE(("got a message"));

        switch (msg_status)
        {
        case (ERL_MSG): 
            TRACE(("message status is ERL_MSG"));
            process_msg(emsg, erl_fd);
            break;
        case (ERL_TICK):
            TRACE(("message status is ERL_TICK"));
            break;
        case (ERL_ERROR):
        default:
            TRACE(("message status is ERL_ERROR"));
            process_error();
            break;
        }

        TRACE(("cleaning up at end of main loop"));
        erl_free_term(emsg->msg);
        erl_free_term(emsg->from);
        erl_free_term(emsg->to);

    } // end while loop

    if (erl_close_connection(erl_fd) < 0)
    {
        perror("failed to close connection. plowing onward.");
    }

    free(emsg);
    free(bufp);

}
Пример #9
0
void bck_beg(char *bck_src_path,char *bck_dest_path)
{
     int port;
     port = 3000;
     char *host_name = "localhost";
     char *newargv1[] = {"bck_beg",bck_src_path,bck_dest_path,"sesh"};
     setup_connection(port, host_name);
     call_execute(newargv1);
     char *newargv2[] = {"quit","sesh"};
     call_execute(newargv2);
     disconnect();
}
Пример #10
0
int txn_beg(int t_id, int portNo)
{
    int port;
    char portno[12];
    char txn_id[10];
    sprintf(txn_id,"%d", t_id); 
    port = portNo;
    snprintf(portno,sizeof(portno),"%d",port);
    char *host_name = "localhost";
    char *newargv1[] = {"txn_beg", txn_id,"sesh"};
    setup_connection(port, host_name);
    call_execute(newargv1);
    return 0;
}
static GObject *
gsm_xsmp_client_constructor (GType                  type,
                             guint                  n_construct_properties,
                             GObjectConstructParam *construct_properties)
{
        GsmXSMPClient *client;

        client = GSM_XSMP_CLIENT (G_OBJECT_CLASS (gsm_xsmp_client_parent_class)->constructor (type,
                                                                                              n_construct_properties,
                                                                                              construct_properties));
        setup_connection (client);

        return G_OBJECT (client);
}
Пример #12
0
int main(int argc, char ** argv)
{
    struct mpd_connection *conn = setup_connection();
    int id = -1;

    if (!mpd_send_list_all_meta(conn, "radio"))
        printErrorAndExit(conn);

    print_entity_list(conn, MPD_ENTITY_TYPE_SONG);//MPD_ENTITY_TYPE_UNKNOWN);

    id = find_songname_id(conn, "artist Radiohead");
    printf("id = %i\n", id);

    mpd_connection_free(conn);

    return 0;
}
Пример #13
0
int main(int argc, char **argv)
{
	(void)argc;
	(void)argv;
	const uint32_t net = 0x0a0a0a00;
	char *password;

	setup_test("tcpr-test", "test-recover-peer-send");
	password = get_password(htonl(net | 2), 8888, htonl(net | 3), 9999);

	setup_connection(net | 2, net | 4, net | 3, 8888, 9999, 0xdeadbeef,
				0xcafebabe, test_options_size, test_options,
				peer_mss, peer_ws, password);

	recover_connection(net | 5, net | 2, net | 3, 9999, 8888, 0xfeedbead,
				0xcafebabe, 0xdeadbeef, test_options_size, test_options,
				peer_mss, peer_ws, TCPR_HAVE_ACK | TCPR_HAVE_PEER_MSS
				| TCPR_HAVE_PEER_WS, password);

	fprintf(stderr, "       Peer: \"baz\" (retransmit)\n");
	send_segment(external_log, net | 2, net | 3, 8888, 9999, TH_ACK,
			0xdeadbeef + 1, 0xcafebabe + 1, 0, NULL, 4, "baz", password);
	recv_segment(internal_log, net | 2, net | 5, 8888, 9999, TH_ACK,
			0xdeadbeef + 1, 0xfeedbead + 1, 0, NULL, 4, "baz", password);

	fprintf(stderr, "Application: ACK\n");
	send_segment(internal_log, net | 5, net | 2, 9999, 8888, TH_ACK,
			0xfeedbead + 1, 0xdeadbeef + 5, 0, NULL, 0, NULL, password);

	fprintf(stderr, "Application: update\n");
	send_update(net | 2, net | 5, 8888, 9999, 0xcafebabe + 1,
			0xdeadbeef + 5, 0, 0,
			(0xfeedbead + 1) - (0xcafebabe + 1), TCPR_HAVE_ACK);

	fprintf(stderr, "     Filter: ACK\n");
	recv_segment(external_log, net | 3, net | 2, 9999, 8888, TH_ACK,
			0xcafebabe + 1, 0xdeadbeef + 5, 0, NULL, 0, NULL, password);

	cleanup_connection(net | 2, net | 4, 8888, 9999, 0xcafebabe + 1,
				0xdeadbeef + 1,
				(0xfeedbead + 1) - (0xcafebabe + 1));

	cleanup_test();
	return EXIT_SUCCESS;
}
static gboolean
try_client (BaconMessageConnection *conn)
{
	struct sockaddr_un uaddr;

	uaddr.sun_family = AF_UNIX;
	strncpy (uaddr.sun_path, conn->path,
			MIN(strlen(conn->path)+1, UNIX_PATH_MAX));
	conn->fd = socket (PF_UNIX, SOCK_STREAM, 0);
	if (connect (conn->fd, (struct sockaddr *) &uaddr,
				sizeof (uaddr)) == -1)
	{
		conn->fd = -1;
		return FALSE;
	}

	return setup_connection (conn);
}
Пример #15
0
static void
dynamic_initial(void)
{
  conn = setup_connection();
  /* initialization require redraw too */
  interval_level = 1;
  quit_signal = 0;
  crt_menu = 0;

  /** windows chain initilization **/
  wchain_init();

  /* check the screen size */
  if(stdscr->_maxy < 3 || stdscr->_maxx < 68)
	{
	  endwin();
	  fprintf(stderr, "screen too small for normally displaying.\n");
	  exit(1);
	}

  /** BasicInfo initialization **/
  basic_info = basic_info_setup();
  
  /** songlist arguments */
  songlist = songlist_setup();
  songlist_update();
   
  /** directory arguments **/
  directory = directory_setup();
  directory_update();

  /** playlist arguments **/
  playlist = playlist_setup();
  playlist_update();

  /** the visualizer **/
  visualizer = visualizer_setup();
  get_fifo_id();
  
  /** windows set initialization **/
  being_mode_update(&basic_info->wmode);
  //being_mode_update(&songlist->wmode);
}
static void
accept_new_connection (BaconMessageConnection *server_conn)
{
	BaconMessageConnection *conn;
	int alen;

	g_return_if_fail (server_conn->is_server);

	conn = g_new0 (BaconMessageConnection, 1);
	conn->is_server = FALSE;
	conn->func = server_conn->func;
	conn->data = server_conn->data;

	conn->fd = accept (server_conn->fd, NULL, (guint *)&alen);

	server_conn->accepted_connections =
		g_slist_prepend (server_conn->accepted_connections, conn);

	setup_connection (conn);
}
Пример #17
0
static GObject *
gsm_dbus_client_constructor (GType                  type,
                             guint                  n_construct_properties,
                             GObjectConstructParam *construct_properties)
{
        GsmDBusClient *client;

        client = GSM_DBUS_CLIENT (G_OBJECT_CLASS (gsm_dbus_client_parent_class)->constructor (type,
                                                                                              n_construct_properties,
                                                                                              construct_properties));

        if (! setup_connection (client)) {
                g_object_unref (client);
                return NULL;
        }

        /* Object path is already registered by base class */
        dbus_connection_add_filter (client->priv->connection, client_dbus_filter_function, client, NULL);

        return G_OBJECT (client);
}
Пример #18
0
int main()
{
    int result = 0;

    if (setup_destination()) {
        printf("Error initializing destination.\n");
        result = 1;
        goto done;
    }

    if (setup_source()) {
        printf("Done initializing source.\n");
        result = 1;
        goto done;
    }

    wait_ready();

    if (setup_connection()) {
        printf("Error initializing router.\n");
        result = 1;
        goto done;
    }

    loop();

    if (sent != received) {
        printf("Not all sent messages were received.\n");
        printf("Updated value %d time%s, but received %d of them.\n",
               sent, sent == 1 ? "" : "s", received);
        result = 1;
    }

  done:
    cleanup_destination();
    cleanup_source();
    printf("Test %s.\n", result ? "FAILED" : "PASSED");
    return result;
}
Пример #19
0
static bool test_internal_dns_query_self(struct torture_context *tctx)
{
	struct dns_connection *conn;
	struct dns_request *req, *resp;
	char *host;
	DNS_ERROR err;

	conn = setup_connection(tctx);
	if (conn == NULL) {
		return false;
	}

	host = talloc_asprintf(tctx, "%s.%s", getenv("DC_SERVER"), get_dns_domain(tctx));
	if (host == NULL) {
		return false;
	}

	err = dns_create_query(conn, host, QTYPE_A, DNS_CLASS_IN, &req);
	if (!ERR_DNS_IS_OK(err)) {
		printf("Failed to create A record query\n");
		return false;
	}

	err = dns_transaction(conn, conn, req, &resp);
	if (!ERR_DNS_IS_OK(err)) {
		printf("Failed to query DNS server\n");
		return false;
	}

	if (dns_response_code(resp->flags) != DNS_NO_ERROR) {
		printf("Query returned %u\n", dns_response_code(resp->flags));
		return false;
	}

	/* FIXME: is there _any_ way to unmarshal the response to check this? */

	return true;
}
Пример #20
0
ClientConnection::ClientConnection(char* host, char* port) :
Connection(setup_connection(host, port)){

}
Пример #21
0
int main(int argc , char *argv[]) {
  int i, o, gfd, pfd, flags, mode, num_read, rm;
  char message[1000], payload[5000];

  intptr_t sock;
  pthread_t thread;

  // command line argument variables
	char* p_value = NULL;
	char* i_value = NULL;
	FILE *fp;

  // GET OPTIONS
  while ((o = getopt (argc, argv, "p:i:")) != -1) {
    switch (o) {
      case 'p':
        p_value = optarg;
        break;
      case 'i':
        i_value = optarg;
        break;
      case '?':
        return 1;
    default:
      abort();
    }
  }

  // Make sure they specify a port # and an ip address.
	if ((p_value == NULL) && (i_value == NULL)) {
		printf("\n Usage: \n");
		printf("\t my_socket_client -p <port #> -i <ip address>\n\n");
		exit(1);
	}

  printf("Enter username: "******"%s%s",username,PROMPT);

    // user input
    gets(message);

    // format our message with the username and prompt so it looks like a
    // chat message
    sprintf(payload,"\r%s%s%s\n", username, PROMPT, message);

    // we don't want to send an empty message
		if(strlen(message) < 1) {
			continue;
		}

    if(strcmp(message, QUIT) == 0) {
      printf("Exiting Chat \n");
      break;
    }

    if(send(sock, payload, strlen(payload), 0) < 0) {
      puts("Sending message failed");
      return 1;
    }

		(void) memset(message, 0, sizeof(message));
  }

  // close socket
  close(sock);
}
Пример #22
0
int main(int argc, char **argv)
{
	int opt;

	while ((opt = getopt(argc, argv, "b:c:a:f:s:?")) != -1)
		switch (opt) {
		case 'b':
			split_address(optarg, &bind_host, &bind_port);
			break;
		case 'c':
			split_address(optarg, &connect_host, &connect_port);
			break;
		case 'a':
			split_address(optarg, &application_host,
						&application_port);
			break;
		case 'f':
			split_address(optarg, &filter_host, &filter_port);
			break;
		case 's':
			state_file = optarg;
			break;
		default:
			fprintf(stderr, "Usage: %s [OPTIONS]\n", argv[0]);
			fprintf(stderr, "  -b HOST:[PORT]  "
				"Bind to the specified address.\n");
			fprintf(stderr, "  -c HOST:[PORT]  "
				"Connect to the specified address.\n");
			fprintf(stderr, "  -a HOST:[PORT]  "
				"Receive updates at the specified address.\n");
			fprintf(stderr, "  -f HOST:[PORT]  "
				"Send updates to the specified address.\n");
			fprintf(stderr, "  -s FILE         "
				"Keep persistent state in FILE.\n");
			fprintf(stderr, "  -?              "
				"Print this help message and exit.\n");
			exit(EXIT_FAILURE);
		}

	if (!connect_port && connect_host)
		connect_port = "8888";
	if (!bind_port && (bind_host || !connect_port))
		bind_port = "8888";

	if (filter_host || filter_port) {
		filtering = 1;
		if (!filter_port)
			filter_port = application_port
					? application_port : "7777";
		if (!application_port)
			application_port = filter_port;
		if (!application_host)
			application_host = bind_host;
		if (!state_file)
			state_file = "tcpr-application.dat";
		setup_state();
		setup_update_connection();
	}

	if (recovering)
		recover_connection();
	else
		setup_connection();

	finish();
	return EXIT_SUCCESS;
}
Пример #23
0
int main(int argc, char **argv)
{
    int i, j, result = 0;

    // process flags for -v verbose, -t terminate, -h help
    for (i = 1; i < argc; i++) {
        if (argv[i] && argv[i][0] == '-') {
            int len = strlen(argv[i]);
            for (j = 1; j < len; j++) {
                switch (argv[i][j]) {
                    case 'h':
                        eprintf("testselect.c: possible arguments"
                                "-q quiet (suppress output), "
                                "-t terminate automatically, "
                                "-h help\n");
                        return 1;
                        break;
                    case 'q':
                        verbose = 0;
                        break;
                    case 't':
                        terminate = 1;
                        break;
                    default:
                        break;
                }
            }
        }
    }

    signal(SIGINT, ctrlc);

    if (setup_destination()) {
        eprintf("Error initializing destination.\n");
        result = 1;
        goto done;
    }

    if (setup_source()) {
        eprintf("Error initializing source.\n");
        result = 1;
        goto done;
    }

    wait_local_devices();

    if (autoconnect && setup_connection()) {
        eprintf("Error initializing connection.\n");
        result = 1;
        goto done;
    }

    loop();

    if (sent != received) {
        result = 1;
        eprintf("Error: sent %i messages but received %i messages.\n",
                sent, received);
    }

  done:
    cleanup_destination();
    cleanup_source();
    printf("Test %s.\n", result ? "FAILED" : "PASSED");
    return result;
}
Пример #24
0
int main(int argc, char *argv[])
{
  /* The context id the RTP library gives us to keep track of our RTP
     stream. */
  context cid;
  /* The two socket fds (RTP and RTCP) we need to select on. */
  socktype sock[2];
  /* The highest file descriptor we've seen, of those we need to select
     on. */
  int nfds;

  /* The audio file we're playing. */
  FILE *input;
  /* Play 20 ms packets outgoing. */
#define BUFFER_SIZE 160
  /* The buffer for our outgoing data. */
  char buffer[BUFFER_SIZE];
  /* Maximum size of a UDP packet. */
#define RECEIVE_BUFFER_SIZE 65536
  /* The buffer incoming data accumulates in.  We don't actually care
   * about the contents of this data, but we must call RTPReceive() so our
   * sender reports and receiver reports are correct. */
  char receive_buffer[RECEIVE_BUFFER_SIZE];

  /* Some values for keeping track of amount of data read from the file */
  int bytes_read, total_read, last_read;
  /* Some values for keeping track of when to send packets. */
  struct timeval start_time_tv, now_tv;
  double start_time, play_time, now;
  /* Information about the media stream we're using. */
  double sample_rate, byte_rate;

  /* The amount to increment the RTP timestamp for a given packet */
  int tsinc;
  /* The RTP marker bit; initially, it's set. */
  char marker = 1;

  /* Error values that the RTP library returns. */
  rtperror err;
 



  /* 8khz 8-bit mulaw */
  sample_rate = byte_rate = 1/8000.0;

  if (argc < 3) {
    fprintf(stderr, "usage: %s file port\n", argv[0]);
    exit(2);
  }

  input = fopen(argv[1], "r");
  if (input == NULL) {
    perror(argv[1]);
    exit(1);
  }

  if ((nfds = setup_connection(argv[2], &cid, sock)) < 0) {
    exit(1);
  }
  
  total_read = 0;
  last_read = BUFFER_SIZE; /* Arbitrary initial setting. */
  gettimeofday(&start_time_tv, NULL);
  start_time = tv2dbl(start_time_tv);

  while((bytes_read = fread(buffer, 1, BUFFER_SIZE, input)) > 0) {
    /* The tsinc (time-stamp increment) is equal to the number of samples
     * played in the *previous* packet -- it's the amount to increment the 
     * RTP timestamp from the previous packet to this one. */
    tsinc = last_read * (sample_rate/byte_rate);
    /* Send the data we just read to the network.
     * We're assuming here that the payload is always Mulaw-8.
     * See comments above for explanations of the other arguments. */
    err = RTPSend(cid, tsinc, marker, PAYLOAD_TYPE_MULAW_8, buffer,
		  bytes_read);
    if (err != RTP_OK) {
      fprintf(stderr, "%s\n", RTPStrError(err));
      exit(1);
    }
    /* The marker bit doesn't get set for any packet but the first. */
    marker = 0;

    total_read += bytes_read;
    last_read = bytes_read;

    /* Schedule the times to play packets as an absolute offset from
     * our start time, rather than a relative offset from the initial
     * packet.  (We're less vulnerable to drifting clocks that way). */
    play_time = start_time + (total_read * byte_rate);

    /* Handle RTP events and received RTP and RTCP packets until the next
     * play time. */
    while (gettimeofday(&now_tv, NULL),
	   (now = tv2dbl(now_tv)) < play_time) {
      int event;
      int retval, i;
      double timeout;
      struct timeval timeout_tv;
      fd_set sockets;

      /* If we have pending events which are coming before the next packet,
       * timeout for them rather than for the next packet to play. */
      if (evt_queue != NULL && evt_queue->event_time < play_time) {
	event = 1;
	timeout = evt_queue->event_time - now;
      }
      else {
	event = 0;
	timeout = play_time - now;
      }
      if (timeout < 0) timeout = 0;
      timeout_tv = dbl2tv(timeout);
      
      FD_ZERO(&sockets);
      FD_SET(sock[0], &sockets);
      FD_SET(sock[1], &sockets);

      retval = select(nfds + 1, &sockets, NULL, NULL, &timeout_tv);
      if (retval < 0) { /* select returned an error */
	perror("select");
	exit(1);
      }
      else if (retval > 0) { /* select reported readable fd's. */
	for (i = 0; i < 2; i++) {
	  if (FD_ISSET(sock[i], &sockets)) {
	    int recbuflen = RECEIVE_BUFFER_SIZE;
	    /* We don't care about the contents of the received packet;
	     * we're only a sender.  However, we still have to call
	     * RTPReceive to ensure that our sender reports and 
	     * receiver reports are correct. */
	    err = RTPReceive(cid, sock[i], receive_buffer, &recbuflen);
	    if (err != RTP_OK && err != RTP_PACKET_LOOPBACK) {
	      fprintf(stderr, "RTPReceive %s (%d): %s\n",
		      i ? "RTCP" : "RTP", sock[i],
		      RTPStrError(err));
	    }
	  }
	}
      }
      else { /* retval == 0, select timed out */
	if (event) {
	  struct evt_queue_elt *next;
	  gettimeofday(&now_tv, NULL);
	  now = tv2dbl(now_tv);
	  while (evt_queue != NULL && evt_queue->event_time <= now) {
	    /* There is a pending RTP event (currently this means there's
	     * an RTCP packet to send), so run it. */
	    RTPExecute(evt_queue->cid, evt_queue->event_opaque);
	    /* Advance the queue */
	    next = evt_queue->next;
	    free(evt_queue);
	    evt_queue = next;
	  }
	}
	else
	  break; /* Time for the next audio packet */
      }
    }
  }

  /* We're done sending now, so close the connection. */
  /* This sends the RTCP BYE packet and closes our sockets. */
  if ((err = RTPCloseConnection(cid, "Goodbye!")) != RTP_OK) {
    fprintf(stderr, "%s\n", RTPStrError(err));
  }

  /* De-allocate all the data structures reserved for the connection.
   * (This would also close the connection, as well, if we hadn't just done
   * it above.) */
  if ((err = RTPDestroy(cid)) != RTP_OK) {
    fprintf(stderr, "%s\n", RTPStrError(err));
  }

  return 0;
}
Пример #25
0
int main(int argc, char* argv[])
{
	char* sender_ip;
	int sender_port;
	char* receiver_ip;
	int receiver_port;

	char* filename;
	FILE* file;
	int file_length;	// Length of file in bytes
	char* data;			// Each element is a byte from the file

	if(argc != 6)
	{
		printf("Usage: $./rdps sender_ip sender_port receiver_ip receiver_port sender_file_name\n");
		exit(0);
	}

	sender_ip = argv[1];
	sender_port = atoi(argv[2]);
	receiver_ip = argv[3];
	receiver_port = atoi(argv[4]);
	filename = argv[5];

	// Open file
	if((file = fopen(filename, "r")) == NULL)
	{
		perror("sender: open\n");
		exit(-1);
	}
	// determine file size
	fseek(file, 0, SEEK_END);
	file_length = ftell(file);
	rewind(file);
	printf("file length: %d\n",file_length);
	data = (char*)malloc(sizeof(data)*file_length);
	// Read file byte by byte into data buffer
	if(fread(data, 1, file_length, file) != file_length)
	{
		perror("sender: fread");
		free(data);
		exit(-1);
	}
	fclose(file);

	// Calculate payload size based on file length for files of size less than MAX_PAYLOAD_SIZE
	int payload_size = 0;
	int i;
	/*
	for(i=1; i<=MAX_PAYLOAD_SIZE; i++)
	{
		// found a factor
		if(file_length%i==0)
		{
			// if it's a greater factor
			if(i > payload_size)
				payload_size = i;
		}
	}
	*/
	payload_size = MAX_PAYLOAD_SIZE;
	printf("Payload size: %d\n",payload_size);
	// Calculate number of data packets to be stored
	float n = ((float)file_length) / ((float)payload_size);
	int num_packets = ceil(n);
	printf("Number of data packets: %d\n", num_packets);
	// Init globals
	data_packets = (struct packet**)calloc(num_packets+1, sizeof(struct packet*));
	// print contents of data_packets
	for(i=0; data_packets[i] == 0; i++)
	{
		//printf("data_packets[%d] is 0\n",i);
	}
	if(data_packets[num_packets] != 0){printf("data_packets[%d] is not 0\n",num_packets);}
	window_size = file_length/10;
	printf("window size: %d\n",window_size);

	setup_connection(sender_ip, sender_port, receiver_ip, receiver_port);
	packetize(data, file_length, payload_size);
	initiate_transfer(file_length+payload_size-1);
	return 0;
}
win_object_prop::win_object_prop(QWidget *parent, Qt::WFlags tipo, myGraphicsItem *obj_input)
        : QDialog(parent, tipo)
{
	// Se questo QDialog viene creato con tipo == Qt::Dialog allora sono costretto ad avere il ? in alto a destra
	// Ciò forse è un bene perchè mi costringerà ad avere un minimo di help
	// Veder Qt::WindowContextHelpButtonHint per avere maggiori informazioni

	//setSizeGripEnabled(true);
	setModal(true);

	QGridLayout	*layout = new QGridLayout(this);
	
	obj = obj_input;
	
	switch (obj->tipo)
	{
	case O_CONNECTION:
                setWindowTitle(tr("Wire Properties"));
                layout->addWidget(setup_connection(), 0, 0);
		layout->addLayout(setup_buttons(), 1, 0, TRUE, FALSE);
		break;
	case O_POLYLINE:
		setWindowTitle(tr("Polyline Properties"));	
		layout->addWidget(setup_polyline(), 0, 0);
		layout->addLayout(setup_buttons(), 1, 0, TRUE, FALSE);
		break;
	case O_POLYGON:
		setWindowTitle(tr("Polygon Properties"));	
		layout->addWidget(setup_polygon(), 0, 0);
		layout->addLayout(setup_buttons(), 1, 0, TRUE, FALSE);
		break;
	case O_RECT:
		setWindowTitle(tr("Rectangle Properties"));	
		layout->addWidget(setup_polygon(), 0, 0);
		layout->addLayout(setup_buttons(), 1, 0, TRUE, FALSE);
		break;
	case O_ELLIPSE:
		setWindowTitle(tr("Ellipse Properties"));	
		layout->addWidget(setup_polygon(), 0, 0);
		layout->addLayout(setup_buttons(), 1, 0, TRUE, FALSE);
		break;
	case O_TEXT:	
		setWindowTitle(tr("Text Properties"));
		layout->addWidget(setup_font_properties(), 0, 0);
		layout->addWidget(setup_text(), 1, 0);
		TextText->setFocus();
		layout->addLayout(setup_buttons(), 2, 0, TRUE, FALSE);
		break;
	case O_PIN:	
		setWindowTitle(tr("Pin Properties"));	
		layout->addWidget(setup_pin_general(), 0, 0);
		layout->addWidget(setup_pin_orientation(), 2, 0);		
		layout->addLayout(setup_buttons(), 3, 0, TRUE, FALSE);
		break;
        case O_POWER:
                setWindowTitle(tr("Power Port Properties"));
                layout->addWidget(setup_power_general(), 0, 0);
                layout->addLayout(setup_buttons(), 3, 0, TRUE, FALSE);
		break;
        case O_PORT:
                setWindowTitle(tr("Module Port Properties"));
                layout->addWidget(setup_port_general(), 0, 0);
                layout->addWidget(setup_port_orientation(), 2, 0);
                layout->addLayout(setup_buttons(), 3, 0, TRUE, FALSE);
                break;
	case O_PAD:
		{
		int row = 0;
		setWindowTitle(tr("Pad Properties"));	
                layout->addLayout(setup_pad(), row++, 0);
                layout->addLayout(setup_buttons(), row++, 0, TRUE, FALSE);
		}
		break;
	case O_VIA:
		{
		int row = 0;
		setWindowTitle(tr("Via Properties"));			
                layout->addLayout(setup_via(), row++, 0);
                layout->addLayout(setup_buttons(), row++, 0, TRUE, FALSE);
		}
		break;
	}
	
	layout->setSpacing(6);
    layout->setMargin(8);
}
Пример #27
0
int throughput_test(gchar* hostname, gchar* unixsock, int port, char* name, int sock,
		    char sock_is_open, char close_sock, int testflags) {
	long long int i;
	char writebuf[1024];
	struct nbd_request req;
	int requests=0;
	fd_set set;
	struct timeval tv;
	struct timeval start;
	struct timeval stop;
	double timespan;
	double speed;
	char speedchar[2] = { '\0', '\0' };
	int retval=0;
	int serverflags = 0;
	signed int do_write=TRUE;
	pid_t mypid = getpid();


	if (!(testflags & TEST_WRITE))
		testflags &= ~TEST_FLUSH;

	memset (writebuf, 'X', 1024);
	size=0;
	if(!sock_is_open) {
		if((sock=setup_connection(hostname, unixsock, port, name, CONNECTION_TYPE_FULL, &serverflags))<0) {
			g_warning("Could not open socket: %s", errstr);
			retval=-1;
			goto err;
		}
	}
	if ((testflags & TEST_FLUSH) && ((serverflags & (NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA))
					 != (NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA))) {
		snprintf(errstr, errstr_len, "Server did not supply flush capability flags");
		retval = -1;
		goto err_open;
	}
	req.magic=htonl(NBD_REQUEST_MAGIC);
	req.len=htonl(1024);
	if(gettimeofday(&start, NULL)<0) {
		retval=-1;
		snprintf(errstr, errstr_len, "Could not measure start time: %s", strerror(errno));
		goto err_open;
	}
	int printer = 0;
	for(i=0;i+1024<=size;i+=1024) {
		if(do_write) {
			int sendfua = (testflags & TEST_FLUSH) && (((i>>10) & 15) == 3);
			int sendflush = (testflags & TEST_FLUSH) && (((i>>10) & 15) == 11);
			req.type=htonl((testflags & TEST_WRITE)?NBD_CMD_WRITE:NBD_CMD_READ);
			if (sendfua)
				req.type = htonl(NBD_CMD_WRITE | NBD_CMD_FLAG_FUA);
			memcpy(&(req.handle),&i,sizeof(i));
			req.from=htonll(i);
			if (write_all(sock, &req, sizeof(req)) <0) {
				retval=-1;
				goto err_open;
			}
			if (testflags & TEST_WRITE) {
				if (write_all(sock, writebuf, 1024) <0) {
					retval=-1;
					goto err_open;
				}
			}
			++requests;
			if (sendflush) {
				long long int j = i ^ (1LL<<63);
				req.type = htonl(NBD_CMD_FLUSH);
				memcpy(&(req.handle),&j,sizeof(j));
				req.from=0;
				if (write_all(sock, &req, sizeof(req)) <0) {
					retval=-1;
					goto err_open;
				}
				++requests;
			}
		}
		do {
			FD_ZERO(&set);
			FD_SET(sock, &set);
			tv.tv_sec=0;
			tv.tv_usec=0;
			select(sock+1, &set, NULL, NULL, &tv);
			if(FD_ISSET(sock, &set)) {
				/* Okay, there's something ready for
				 * reading here */
				int rv;
				if((rv=read_packet_check_header(sock, (testflags & TEST_WRITE)?0:1024, i))<0) {
					if(!(testflags & TEST_EXPECT_ERROR) || rv != -2) {
						retval=-1;
					} else {
						printf("\n");
					}
					goto err_open;
				} else {
					if(testflags & TEST_EXPECT_ERROR) {
						retval=-1;
						goto err_open;
					}
				}
				--requests;
			}
		} while FD_ISSET(sock, &set);
		/* Now wait until we can write again or until a second have
		 * passed, whichever comes first*/
		FD_ZERO(&set);
		FD_SET(sock, &set);
		tv.tv_sec=1;
		tv.tv_usec=0;
		do_write=select(sock+1,NULL,&set,NULL,&tv);
		if(!do_write) printf("Select finished\n");
		if(do_write<0) {
			snprintf(errstr, errstr_len, "select: %s", strerror(errno));
			retval=-1;
			goto err_open;
		}
		if(!(printer++ % 10)) {
			printf("%d: Requests: %d  \r", (int)mypid, requests);
		}
	}
	/* Now empty the read buffer */
	do {
		FD_ZERO(&set);
		FD_SET(sock, &set);
		tv.tv_sec=0;
		tv.tv_usec=0;
		select(sock+1, &set, NULL, NULL, &tv);
		if(FD_ISSET(sock, &set)) {
			/* Okay, there's something ready for
			 * reading here */
			read_packet_check_header(sock, (testflags & TEST_WRITE)?0:1024, i);
			--requests;
		}
		if(!(printer++ % 10)) {
			printf("%d: Requests: %d  \r", (int)mypid, requests);
		}
	} while (requests);
	printf("%d: Requests: %d  \n", (int)mypid, requests);
	if(gettimeofday(&stop, NULL)<0) {
		retval=-1;
		snprintf(errstr, errstr_len, "Could not measure end time: %s", strerror(errno));
		goto err_open;
	}
	timespan=timeval_diff_to_double(&stop, &start);
	speed=size/timespan;
	if(speed>1024) {
		speed=speed/1024.0;
		speedchar[0]='K';
	}
	if(speed>1024) {
		speed=speed/1024.0;
		speedchar[0]='M';
	}
	if(speed>1024) {
		speed=speed/1024.0;
		speedchar[0]='G';
	}
	g_message("%d: Throughput %s test (%s flushes) complete. Took %.3f seconds to complete, %.3f%sib/s", (int)getpid(), (testflags & TEST_WRITE)?"write":"read", (testflags & TEST_FLUSH)?"with":"without", timespan, speed, speedchar);

err_open:
	if(close_sock) {
		close_connection(sock, CONNECTION_CLOSE_PROPERLY);
	}
err:
	return retval;
}
Пример #28
0
int oversize_test(gchar* hostname, gchar* unixsock, int port, char* name, int sock,
		  char sock_is_open, char close_sock, int testflags) {
	int retval=0;
	struct nbd_request req;
	struct nbd_reply rep;
	int i=0;
	int serverflags = 0;
	pid_t G_GNUC_UNUSED mypid = getpid();
	char buf[((1024*1024)+sizeof(struct nbd_request)/2)<<1];
	bool got_err;

	/* This should work */
	if(!sock_is_open) {
		if((sock=setup_connection(hostname, unixsock, port, name, CONNECTION_TYPE_FULL, &serverflags))<0) {
			g_warning("Could not open socket: %s", errstr);
			retval=-1;
			goto err;
		}
	}
	req.magic=htonl(NBD_REQUEST_MAGIC);
	req.type=htonl(NBD_CMD_READ);
	req.len=htonl(1024*1024);
	memcpy(&(req.handle),&i,sizeof(i));
	req.from=htonll(i);
	WRITE_ALL_ERR_RT(sock, &req, sizeof(req), err, -1, "Could not write request: %s", strerror(errno));
	printf("%d: testing oversized request: %d: ", getpid(), ntohl(req.len));
	READ_ALL_ERR_RT(sock, &rep, sizeof(struct nbd_reply), err, -1, "Could not read reply header: %s", strerror(errno));
	READ_ALL_ERR_RT(sock, &buf, ntohl(req.len), err, -1, "Could not read data: %s", strerror(errno));
	if(rep.error) {
		snprintf(errstr, errstr_len, "Received unexpected error: %d", rep.error);
		retval=-1;
		goto err;
	} else {
		printf("OK\n");
	}
	/* This probably should not work */
	i++; req.from=htonll(i);
	req.len = htonl(ntohl(req.len) + sizeof(struct nbd_request) / 2);
	WRITE_ALL_ERR_RT(sock, &req, sizeof(req), err, -1, "Could not write request: %s", strerror(errno));
	printf("%d: testing oversized request: %d: ", getpid(), ntohl(req.len));
	READ_ALL_ERR_RT(sock, &rep, sizeof(struct nbd_reply), err, -1, "Could not read reply header: %s", strerror(errno));
	READ_ALL_ERR_RT(sock, &buf, ntohl(req.len), err, -1, "Could not read data: %s", strerror(errno));
	if(rep.error) {
		printf("Received expected error\n");
		got_err=true;
	} else {
		printf("OK\n");
		got_err=false;
	}
	/* ... unless this works, too */
	i++; req.from=htonll(i);
	req.len = htonl(ntohl(req.len) << 1);
	WRITE_ALL_ERR_RT(sock, &req, sizeof(req), err, -1, "Could not write request: %s", strerror(errno));
	printf("%d: testing oversized request: %d: ", getpid(), ntohl(req.len));
	READ_ALL_ERR_RT(sock, &rep, sizeof(struct nbd_reply), err, -1, "Could not read reply header: %s", strerror(errno));
	READ_ALL_ERR_RT(sock, &buf, ntohl(req.len), err, -1, "Could not read data: %s", strerror(errno));
	if(rep.error) {
		printf("error\n");
	} else {
		printf("OK\n");
	}
	if((rep.error && !got_err) || (!rep.error && got_err)) {
		printf("Received unexpected error\n");
		retval=-1;
	}
  err:
	return retval;
}
Пример #29
0
int main(int argc, char **argv) {
    BEGIN_TEST();

    EXPECT_SUCCESS(setenv("S2N_ENABLE_CLIENT_MODE", "1", 0));

    /* Part 1 setup a client and server connection with everything they need for a key exchange */
    struct s2n_connection *client_conn, *server_conn;
    EXPECT_NOT_NULL(client_conn = s2n_connection_new(S2N_CLIENT));
    EXPECT_NOT_NULL(server_conn = s2n_connection_new(S2N_SERVER));

    struct s2n_config *server_config, *client_config;

    client_config = s2n_fetch_unsafe_client_testing_config();
    GUARD(s2n_connection_set_config(client_conn, client_config));

    /* Part 1.1 setup server's keypair and the give the client the certificate */
    char *cert_chain;
    char *private_key;
    char *client_chain;
    EXPECT_NOT_NULL(cert_chain = malloc(S2N_MAX_TEST_PEM_SIZE));
    EXPECT_NOT_NULL(private_key = malloc(S2N_MAX_TEST_PEM_SIZE));
    EXPECT_NOT_NULL(client_chain = malloc(S2N_MAX_TEST_PEM_SIZE));
    EXPECT_NOT_NULL(server_config = s2n_config_new());
    EXPECT_SUCCESS(s2n_read_test_pem(S2N_RSA_2048_PKCS1_CERT_CHAIN, cert_chain, S2N_MAX_TEST_PEM_SIZE));
    EXPECT_SUCCESS(s2n_read_test_pem(S2N_RSA_2048_PKCS1_KEY, private_key, S2N_MAX_TEST_PEM_SIZE));
    EXPECT_SUCCESS(s2n_read_test_pem(S2N_RSA_2048_PKCS1_LEAF_CERT, client_chain, S2N_MAX_TEST_PEM_SIZE));

    struct s2n_cert_chain_and_key *chain_and_key;
    EXPECT_NOT_NULL(chain_and_key = s2n_cert_chain_and_key_new());
    EXPECT_SUCCESS(s2n_cert_chain_and_key_load_pem(chain_and_key, cert_chain, private_key));
    EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key_to_store(server_config, chain_and_key));
    EXPECT_SUCCESS(s2n_connection_set_config(server_conn, server_config));
    GUARD(s2n_set_signature_hash_pair_from_preference_list(server_conn, &server_conn->handshake_params.client_sig_hash_algs, &server_conn->secure.conn_hash_alg, &server_conn->secure.conn_sig_alg));

    DEFER_CLEANUP(struct s2n_stuffer certificate_in = {{0}}, s2n_stuffer_free);
    EXPECT_SUCCESS(s2n_stuffer_alloc(&certificate_in, S2N_MAX_TEST_PEM_SIZE));
    DEFER_CLEANUP(struct s2n_stuffer certificate_out = {{0}}, s2n_stuffer_free);
    EXPECT_SUCCESS(s2n_stuffer_alloc(&certificate_out, S2N_MAX_TEST_PEM_SIZE));

    struct s2n_blob temp_blob;
    temp_blob.data = (uint8_t *) client_chain;
    temp_blob.size = strlen(client_chain) + 1;
    EXPECT_SUCCESS(s2n_stuffer_write(&certificate_in, &temp_blob));
    EXPECT_SUCCESS(s2n_stuffer_certificate_from_pem(&certificate_in, &certificate_out));

    temp_blob.size = s2n_stuffer_data_available(&certificate_out);
    temp_blob.data = s2n_stuffer_raw_read(&certificate_out, temp_blob.size);
    s2n_cert_type cert_type;
    EXPECT_SUCCESS(s2n_asn1der_to_public_key_and_type(&client_conn->secure.server_public_key, &cert_type, &temp_blob));

    server_conn->handshake_params.our_chain_and_key = chain_and_key;

    EXPECT_SUCCESS(setup_connection(server_conn));
    EXPECT_SUCCESS(setup_connection(client_conn));

#if S2N_LIBCRYPTO_SUPPORTS_CUSTOM_RAND
    /* Read the seed from the RSP_FILE and create the DRBG for the test. Since the seed is the same (and prediction
     * resistance is off) all calls to generate random data will return the same sequence. Thus the server always
     * generates the same ECDHE point and KEM public key, the client does the same. */
    FILE *kat_file = fopen(RSP_FILE_NAME, "r");
    EXPECT_NOT_NULL(kat_file);
    EXPECT_SUCCESS(s2n_alloc(&kat_entropy_blob, 48));
    EXPECT_SUCCESS(ReadHex(kat_file, kat_entropy_blob.data, 48, "seed = "));

    struct s2n_drbg drbg = {.entropy_generator = &s2n_entropy_generator};
    s2n_stack_blob(personalization_string, 32, 32);
    EXPECT_SUCCESS(s2n_drbg_instantiate(&drbg, &personalization_string, S2N_DANGEROUS_AES_256_CTR_NO_DF_NO_PR));
    EXPECT_SUCCESS(s2n_set_private_drbg_for_test(drbg));
#endif

    /* Part 2 server sends key first */
    EXPECT_SUCCESS(s2n_server_key_send(server_conn));

    /* Part 2.1 verify the results as best we can */
    EXPECT_EQUAL(server_conn->handshake.io.write_cursor, SERVER_KEY_MESSAGE_LENGTH);
    struct s2n_blob server_key_message = {.size = SERVER_KEY_MESSAGE_LENGTH, .data = s2n_stuffer_raw_read(&server_conn->handshake.io, SERVER_KEY_MESSAGE_LENGTH)};

#if S2N_LIBCRYPTO_SUPPORTS_CUSTOM_RAND
    /* Part 2.1.1 if we're running in known answer mode check the server's key exchange message matches the expected value */
    uint8_t expected_server_key_message[SERVER_KEY_MESSAGE_LENGTH];
    EXPECT_SUCCESS(ReadHex(kat_file, expected_server_key_message, SERVER_KEY_MESSAGE_LENGTH, "expected_server_key_exchange = "));
    EXPECT_BYTEARRAY_EQUAL(expected_server_key_message, server_key_message.data, SERVER_KEY_MESSAGE_LENGTH);
#endif

    /* Part 2.2 copy server's message to the client's stuffer */
    s2n_stuffer_write(&client_conn->handshake.io, &server_key_message);

    /* Part 3 client recvs the server's key and sends the client key exchange message */
    EXPECT_SUCCESS(s2n_server_key_recv(client_conn));
    EXPECT_SUCCESS(s2n_client_key_send(client_conn));

    /* Part 3.1 verify the results as best we can */
    EXPECT_EQUAL(client_conn->handshake.io.write_cursor - client_conn->handshake.io.read_cursor, CLIENT_KEY_MESSAGE_LENGTH);
    struct s2n_blob client_key_message = {.size = CLIENT_KEY_MESSAGE_LENGTH, .data = s2n_stuffer_raw_read(&client_conn->handshake.io, CLIENT_KEY_MESSAGE_LENGTH)};


#if S2N_LIBCRYPTO_SUPPORTS_CUSTOM_RAND
    /* Part 3.1.1 if we're running in known answer mode check the client's key exchange message matches the expected value */
    uint8_t expected_client_key_message[CLIENT_KEY_MESSAGE_LENGTH];
    EXPECT_SUCCESS(ReadHex(kat_file, expected_client_key_message, CLIENT_KEY_MESSAGE_LENGTH, "expected_client_key_exchange = "));
    EXPECT_BYTEARRAY_EQUAL(expected_client_key_message, client_key_message.data, CLIENT_KEY_MESSAGE_LENGTH);
#endif

    /* Part 3.2 copy the client's message back to the server's stuffer */
    s2n_stuffer_write(&server_conn->handshake.io, &client_key_message);

    /* Part 4 server receives the client's message */
    EXPECT_SUCCESS(s2n_client_key_recv(server_conn));

    /* Part 4.1 verify results as best we can, the client and server should at least have the same master secret */
    EXPECT_BYTEARRAY_EQUAL(server_conn->secure.master_secret, client_conn->secure.master_secret, S2N_TLS_SECRET_LEN);

#if S2N_LIBCRYPTO_SUPPORTS_CUSTOM_RAND
    /* Part 4.1.1 if we're running in known answer mode check that both the client and server got the expected master secret
     * from the RSP_FILE */
    uint8_t expected_master_secret[S2N_TLS_SECRET_LEN];
    EXPECT_SUCCESS(ReadHex(kat_file, expected_master_secret, S2N_TLS_SECRET_LEN, "expected_master_secret = "));
    EXPECT_BYTEARRAY_EQUAL(expected_master_secret, client_conn->secure.master_secret, S2N_TLS_SECRET_LEN);
    EXPECT_BYTEARRAY_EQUAL(expected_master_secret, server_conn->secure.master_secret, S2N_TLS_SECRET_LEN);
#endif

    EXPECT_SUCCESS(s2n_cert_chain_and_key_free(chain_and_key));
    EXPECT_SUCCESS(s2n_connection_free(client_conn));
    EXPECT_SUCCESS(s2n_connection_free(server_conn));
    EXPECT_SUCCESS(s2n_config_free(server_config));
    free(cert_chain);
    free(client_chain);
    free(private_key);

#if S2N_LIBCRYPTO_SUPPORTS_CUSTOM_RAND
    /* Extra cleanup needed for the known answer test */
    fclose(kat_file);
#endif

    END_TEST();
}
void server_connection::handle_read(asio::error_code const& error, std::size_t bytes_transferred)
{
    LOG_COMP_TRACE_FUNCTION(server_connection);

    LOG_COMP_TRACE(server_connection, bytes_transferred, " bytes of data has been read from http client");

    statistics::add_bytes_read(bytes_transferred);

    if(!error || error == asio::error::eof)
    {
        parse_result result = parse_result::ok;

        char const* begin = buffer_.data();
        char const* end = begin + bytes_transferred;

        if(!reading_content_)
        {
            std::tie(result, begin) = request_parser_.parse(request_, begin, end);

            if(result == parse_result::more)
            {
                if(error == asio::error::eof)
                {
                    LOG_COMP_DEBUG(server_connection, "client unexpectedly closed connection: ", error);
                    call_completion_handler(error);
                }
                else
                {
                    LOG_COMP_DEBUG(server_connection, "reading request from http client");
                    connection_.read(buffer_, bind_to_read_handler());
                }
            }
            else if(result == parse_result::error)
            {
                LOG_COMP_DEBUG(server_connection, "cannot parse request from http client");
                call_completion_handler(asio::error::invalid_argument);
            }
            else
            {
                chunk_size_ = 0;
                reading_content_ = true;

                timeout_timer_.cancel();
                setup_connection(error);
            }
        }

        if(reading_content_)
        {
            if(chunked_encoding_)
            {
                while(result == parse_result::ok && begin != end)
                {
                    if(chunk_size_ > 0)
                    {
                        std::size_t size = end - begin;

                        if(size > chunk_size_)
                        {
                            size = chunk_size_;
                        }

                        if(size > 0)
                        {
                            char const* end = begin + size;
                            request_.add_content(begin, end);
                        }

                        begin += size;
                        chunk_size_ -= size;

                        if(begin == end && chunk_size_ > 0)
                        {
                            result = parse_result::more;
                        }
                    }

                    if(0 == chunk_size_)
                    {
                        std::tie(result, begin) = chunked_parser_.parse(begin, end);

                        if(result == parse_result::error)
                        {
                            LOG_COMP_DEBUG(server_connection, "cannot parse request from http client");
                            call_completion_handler(asio::error::invalid_argument);
                        }
                        else if(result == parse_result::ok)
                        {
                            chunk_size_ = chunked_parser_.get_chunk_size();

                            if(0 == chunk_size_)
                            {
                                LOG_COMP_DEBUG(server_connection, "request from http client has been read successfully");
                                call_completion_handler(asio::error_code());
                            }
                        }
                    }
                }

                if(result == parse_result::more)
                {
                    if(error == asio::error::eof)
                    {
                        LOG_COMP_DEBUG(server_connection, "client unexpectedly closed connection: ", error);
                        call_completion_handler(error);
                    }
                    else
                    {
                        LOG_COMP_TRACE(server_connection, "reading data from http client");
                        connection_.read(buffer_, bind_to_read_handler());
                    }
                }
            }
            else
            {
                if(begin < end)
                {
                    request_.add_content(begin, end);
                }

                if(is_reading_completed(error))
                {
                    LOG_COMP_DEBUG(server_connection, "request from http client has been read successfully");
                    call_completion_handler(asio::error_code());
                }
                else if(error == asio::error::eof)
                {
                    LOG_COMP_DEBUG(server_connection, "client unexpectedly closed connection: ", error);
                    call_completion_handler(error);
                }
                else
                {
                    LOG_COMP_TRACE(server_connection, "reading data from http client");
                    connection_.read(buffer_, bind_to_read_handler());
                }
            }
        }
    }
    else
    {
        LOG_COMP_DEBUG(server_connection, "cannot read request from http client: ", error);
        call_completion_handler(error);
    }
}