示例#1
0
void run_ssdp(int port, const char *pFriendlyName, const char * pModelName, const char *pUuid) {
    struct sockaddr sa;
    socklen_t len = sizeof(sa);
    if(pFriendlyName) {
        strncpy(friendly_name, pFriendlyName, sizeof(friendly_name));
        friendly_name[255] = '\0';
    } else {
        strcpy(friendly_name, "DIAL server sample");
    }
    if(pModelName) {
        strncpy(model_name, pModelName, sizeof(model_name));
        uuid[255] = '\0';
    } else {
        strcpy(model_name, "deadbeef-dead-beef-dead-beefdeadbeef");
    }
    if(pUuid) {
        strncpy(uuid, pUuid, sizeof(uuid));
        uuid[255] = '\0';
    } else {
        strcpy(uuid, "deadbeef-dead-beef-dead-beefdeadbeef");
    }
    dial_port = port;
    get_local_address();
    ctx = mg_start(&request_handler, NULL, SSDP_PORT);
    if (mg_get_listen_addr(ctx, &sa, &len)) {
        my_port = ntohs(((struct sockaddr_in *)&sa)->sin_port);
    }
    printf("SSDP listening on %s:%d\n", ip_addr, my_port);
    handle_mcast();
}
SOL_API int
sol_network_init(void)
{
    struct sol_network_link *iface;
    struct sol_network_link_addr *addr;

    iface = sol_vector_append(&links);
    SOL_NULL_CHECK(iface, -ENOMEM);

    sol_vector_init(&iface->addrs, sizeof(struct sol_network_link_addr));

    addr = sol_vector_append(&iface->addrs);
    SOL_NULL_CHECK_GOTO(addr, addr_append_error);

    if (!get_local_address(addr))
        goto get_address_error;

    SOL_SET_API_VERSION(iface->api_version = SOL_NETWORK_LINK_API_VERSION; )
示例#3
0
inline Address get_local_address( SocketPtr const &s )
{
    return get_local_address( s->fd() );
}
示例#4
0
inline Address get_local_address( Socket const &s )
{
    return get_local_address( s.fd() );
}
示例#5
0
/*
 * Initialize state struct to default/empty values
 */
void init_state(state *st)
{
	static const char *filetypes[] = { FILETYPES };
	char buf[BUFSIZE];
	char *c;
	int i;

	/* Request */
	strclear(st->req_selector);
	strclear(st->req_realpath);
	strclear(st->req_query_string);
	strclear(st->req_referrer);
	sstrlcpy(st->req_local_addr, get_local_address());
	sstrlcpy(st->req_remote_addr, get_peer_address());
	/* strclear(st->req_remote_host); */
	st->req_filetype = DEFAULT_TYPE;
	st->req_protocol = PROTO_GOPHER;
	st->req_filesize = 0;

	/* Output */
	st->out_width = DEFAULT_WIDTH;
	st->out_charset = DEFAULT_CHARSET;

	/* Settings */
	sstrlcpy(st->server_root, DEFAULT_ROOT);
	sstrlcpy(st->server_host_default, DEFAULT_HOST);

	if ((c = getenv("HOSTNAME")))
		sstrlcpy(st->server_host, c);
	else if ((gethostname(buf, sizeof(buf))) != ERROR)
		sstrlcpy(st->server_host, buf);

	st->server_port = DEFAULT_PORT;

	st->default_filetype = DEFAULT_TYPE;
	sstrlcpy(st->map_file, DEFAULT_MAP);
	sstrlcpy(st->tag_file, DEFAULT_TAG);
	sstrlcpy(st->cgi_file, DEFAULT_CGI);
	sstrlcpy(st->user_dir, DEFAULT_USERDIR);
	strclear(st->log_file);

	st->hidden_count = 0;
	st->filetype_count = 0;
	strclear(st->filter_dir);
	st->rewrite_count = 0;

	strclear(st->server_description);
	strclear(st->server_location);
	strclear(st->server_platform);
	strclear(st->server_admin);

	/* Session */
	st->session_timeout = DEFAULT_SESSION_TIMEOUT;
	st->session_max_kbytes = DEFAULT_SESSION_MAX_KBYTES;
	st->session_max_hits = DEFAULT_SESSION_MAX_HITS;

	/* Feature options */
	st->opt_vhost = TRUE;
	st->opt_parent = TRUE;
	st->opt_header = TRUE;
	st->opt_footer = TRUE;
	st->opt_date = TRUE;
	st->opt_syslog = TRUE;
	st->opt_magic = TRUE;
	st->opt_iconv = TRUE;
	st->opt_query = TRUE;
	st->opt_caps = TRUE;
	st->opt_shm = TRUE;
	st->opt_root = TRUE;
	st->debug = FALSE;

	/* Load default suffix -> filetype mappings */
	for (i = 0; filetypes[i]; i += 2) {
		if (st->filetype_count < MAX_FILETYPES) {
			sstrlcpy(st->filetype[st->filetype_count].suffix, filetypes[i]);
			st->filetype[st->filetype_count].type = *filetypes[i + 1];
			st->filetype_count++;
		}
	}
}
示例#6
0
int
main(int argc, char **argv)
{
    int i, opt, rc;
    int sock;
    struct timeval now;

    gettime(&now);

    inet_pton(AF_INET6, "ff02::1:6", &babel_group);
    babel_port = 6696;

    srand(now.tv_sec ^ now.tv_usec);

    while(1) {
        opt = getopt(argc, argv, "p:u:h:c:");
        if(opt < 0)
            break;

        switch(opt) {
        case 'p':               /* prefix */
            if(have_prefix)
                goto usage;
            rc = inet_pton(AF_INET6, optarg, &myprefix);
            if(rc != 1)
                goto usage;
            have_prefix = 1;
            break;
        case 'u':               /* update interval */
            update_interval = atoi(optarg);
            if(update_interval <= 0)
                goto usage;
            break;
        case 'h':               /* hello interval */
            hello_interval = atoi(optarg);
            if(hello_interval <= 0)
                goto usage;
            break;
        case 'c':               /* link cost */
            link_cost = atoi(optarg);
            if(link_cost <= 0)
                goto usage;
            break;
        default:
            goto usage;
        }
    }

    if(!have_prefix)
        fprintf(stderr, "Warning: you didn't ask me to announce a prefix.\n");

    if(argc - optind > MAXINTERFACES) {
        fprintf(stderr, "Too many interfaces.\n");
        exit(1);
    }

    for(i = 0; i < argc - optind; i++) {
        int index;

        index = if_nametoindex(argv[optind + i]);
        if(index <= 0) {
            fprintf(stderr, "Unknown interface %s\n", argv[i]);
            exit(1);
        }
        memset(&interfaces[i], 0, sizeof(interfaces[i]));
        interfaces[i].ifindex = index;
        interfaces[i].ifname = argv[optind + i];
        rc = get_local_address(interfaces[i].ifindex, &interfaces[i].address);
        if(rc < 0) {
            perror("get_local_address");
            fprintf(stderr, "Continuing anyway -- "
                    "won't perform reachibility detection "
                    "on interface %s.\n", interfaces[i].ifname);
        }
        interfaces[i].seqno = rand() & 0xFFFF;
    }
    numinterfaces = argc - optind;

    random_eui64(my_router_id);
    myseqno = rand() & 0xFFFF;

    sock = babel_socket(babel_port);
    if(sock < 0) {
        perror("babel_socket");
        exit(1);
    }

    for(i = 0; i < numinterfaces; i++) {
        rc = join_group(sock, interfaces[i].ifindex, &babel_group);
        if(rc < 0) {
            perror("setsockopt(IPV6_JOIN_GROUP)");
            exit(1);
        }
    }

    catch_signals(sigexit);

    while(!exiting) {
        struct sockaddr_in6 sin6;
        unsigned char buf[BUF_SIZE];
        struct timeval tv, update, zerotv = {0, 0};
        fd_set readfds;
        int hello_count = 0;

        /* Compute when to wake up. */
        gettime(&now);
        timeval_add_msec(&tv, &last_hello, hello_interval * 700 + rand() % 300);
        timeval_add_msec(&update, &last_update,
                         update_interval * 700 + rand() % 300);
        timeval_min(&tv, &update);

        if(selected_nexthop_metric < INFINITY) {
            int n = find_neighbour(selected_interface, &selected_nexthop, 0);
            assert(n >= 0);
            timeval_min(&tv, &neighbours[n].timeout);
            timeval_min(&tv, &selected_nexthop_timeout);
        }

        if(timeval_compare(&tv, &now) > 0)
            timeval_minus(&tv, &tv, &now);
        else
            tv = zerotv;

        FD_ZERO(&readfds);
        FD_SET(sock, &readfds);

        rc = select(sock + 1, &readfds, NULL, NULL, &tv);
        if(rc < 0 && errno != EINTR) {
            perror("select");
            nap(1000);
            continue;
        }

        if(rc > 0) {
            /* Oh good, a packet. */
            socklen_t sin6len = sizeof(sin6);
            rc = recvfrom(sock, buf, BUF_SIZE, 0,
                          (struct sockaddr*)&sin6, &sin6len);

            if(rc < 0 || rc >= BUF_SIZE) {
                if(rc < 0 && errno != EAGAIN) {
                    perror("recv");
                    nap(100);
                }
                continue;
            }

            if(sin6.sin6_family != PF_INET6) {
                fprintf(stderr, "Received unexpected packet in family %d.\n",
                        sin6.sin6_family);
                nap(100);
                continue;
            }

            i = find_interface(sin6.sin6_scope_id);
            if(i < 0) {
                fprintf(stderr, "Received packet on unknown interface %d.\n",
                        sin6.sin6_scope_id);
                nap(100);
                continue;
            }
            handle_packet(sock, buf, rc, &interfaces[i], &sin6.sin6_addr);
        }

        gettime(&now);

        if(selected_nexthop_metric < INFINITY) {
            int n = find_neighbour(selected_interface, &selected_nexthop, 0);
            assert(n >= 0);

            if(neighbour_expired(n, &now)) {
                /* Expire neighbour. */
                flush_default_route();
                delete_neighbour(n);
            } else if(timeval_compare(&now, &selected_nexthop_timeout) > 0) {
                /* Expire route. */
                flush_default_route();
            }
            /* Send a request? */
        }

        /* Is it time to send hellos? */
        if(timeval_minus_msec(&now, &last_hello) > hello_interval * 700) {
            for(i = 0; i < numinterfaces; i++)
                send_hello(sock, &interfaces[i]);
            last_hello = now;
            hello_count++;
            /* Make an expiry pass every ten hellos. */
            if(hello_count >= 10) {
                expire_neighbours();
                hello_count = 0;
            }
        }

        /* Is it time to send an update? */
        if(timeval_minus_msec(&now, &last_update) > update_interval * 700) {
            for(i = 0; i < numinterfaces; i++)
                send_update(sock, &interfaces[i], 0);
            last_update = now;
        }
    }

    /* Send a bunch of retractions. */
    for(i = 0; i < numinterfaces; i++)
        send_update(sock, &interfaces[i], 1);

    flush_default_route();

    return 0;

 usage:
    fprintf(stderr,
            "Usage: sbabeld "
            "[-p prefix] [-u interval] [-h interval] [-c cost] interface...\n");
    return 1;
}
示例#7
0
void *net_io_config(void *args) {
	/* Get the args passed from parent thread */
	thread_args_t *targs = (thread_args_t *) args;
	cmd_line_args *cmd_args = targs->cmd_args;
	benchmark_test *bmtest = targs->bmtest;
	result_table_t *res_table = targs->res_table;
	test_results_t *result = NULL;
	int retry = 0;
	int test_status;

	/* Other Local variables of this function */
	int loop = 0, done = 0, count = 0;
	struct timespec start_time, end_time;
	long long time_diff = 0;
	pthread_t server_tid = 0;
	struct sockaddr_in server_det;
	int cl_sock_fd = 0;
	server_arguments_t *serv_args = NULL;
	pthread_attr_t attr;

	/* Use this to set the timeout value for the socket */
	struct timeval t;

	char *msg = NULL;
	int msg_size = DEF_NETIO_SZ;
	int new_iters = bmtest->_iterations;
	double clock_accuracy;
	char retry_status = UNACCEPTABLE_DEVIATIONS;
	char print_flag = FALSE;

	/*
	 * Make sure both client and server threads are running
	 * the right sched policy and priority
	 */

	/* Keep server thread alive with this stay_alive argument variable */
	serv_args = (server_arguments_t *) malloc(sizeof(server_arguments_t));
	if (serv_args == (server_arguments_t *) NULL) {
		RTMB_printf(stderr, "net_io_config: malloc() failed\n");
		abort();
	}
	memset(serv_args, 0, sizeof(server_arguments_t));
	serv_args->stay_alive = 1;
	serv_args-> iterations = new_iters;
	pthread_attr_init(&attr);

	clock_accuracy = get_min_exec_time(res_table);
	if (set_pthreadattr_sched_param(&attr, SCHED_FIFO, HIGH_PRIO_VAL) < 0) {
		targs->ret = ERROR;
		return (void *) NULL;
	}

	/* Start the server thread and let the server get into accept() code */
	if (pthread_create(&server_tid, &attr, net_server_impl, serv_args)
	        != SUCCESS) {
		RTMB_printf(stderr,
		        "net_io_config: Error creating server thread\n");
		perror("net_io_config");
		server_tid = 0;
		cleanup(serv_args, server_tid, msg, cl_sock_fd);
		targs->ret = ERROR;
		return (void *) NULL;
	}

	/* Alloc and init the msg buffer */
	msg = (char *) msg_alloc_init(msg, msg_size);
	if (msg == NULL) {
		RTMB_printf(stderr, "net_io_config: malloc() failed\n");
		abort();
	}

	/* Set the params for the server side stuff */
	server_det.sin_family = AF_INET;

	if (get_local_address(&server_det.sin_addr) < 0) {
		RTMB_printf(stderr,
		        "net_io_config: unable to get local IP \n");
		server_tid = 0;
		cleanup(serv_args, server_tid, msg, cl_sock_fd);
		targs->ret = ERROR;
		return (void *) NULL;
	}

	server_det.sin_port = htons(SERVER_PORT);
	memset(server_det.sin_zero, '\0', sizeof(server_det.sin_zero));

	/* Create the socket fd */
	cl_sock_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (cl_sock_fd == -1) {
		RTMB_printf(stderr,
		        "net_io_config: Error creating client socket\n");
		perror("net_io_config");
		cleanup(serv_args, server_tid, msg, cl_sock_fd);
		targs->ret = ERROR;
		return (void *) NULL;
	}

	/*
	 * We do not want the server thread to indefinitely wait.
	 * Set timeout to some safe value (10 secs).
	 */
	t.tv_sec = 10;
	t.tv_usec = 0;
	if (setsockopt(cl_sock_fd, SOL_SOCKET, SO_RCVTIMEO, (void *) &t,
	        sizeof(struct timeval)) != 0) {
		RTMB_printf(stderr,
		        "net_io_config: Error while setting socket option\n");
		cleanup(serv_args, server_tid, msg, cl_sock_fd);
		targs->ret = ERROR;
		return (void *) NULL;
	}

	/* give some time for the server thread to start */
	sleep(2);

	/* Connect to the server */
	while ((connect(cl_sock_fd, (struct sockaddr *) &server_det,
	        sizeof(server_det)) == -1) && (retry <= 10)) {
		do_nano_sleep(400LL * MS);
		retry++;
		RTMB_verbose_printf(stderr, cmd_args, 1,
		        "net_io_config: Retrying connect to the "
			        "server socket\n");
	}

	/* Connection done. Now, try exchanging some msgs with server */
	result = create_test_result(1, new_iters);
	if (result == NULL) {
		RTMB_printf(stderr,
		        "ERROR: Cannot allocate memory for test_results_t");
		RTMB_printf(stderr, " in net_io_config()\n");
		abort();
	}
	strcpy((char *) result->desc, "Network I/O configuration test");

	RTMB_verbose_printf(stdout, cmd_args, 1, "\nTest Report for %s:\n",
	        (char*) &result->desc);
	RTMB_verbose_printf(stdout, cmd_args, 1,
	        "========================================================="
		        "==\n");
	RTMB_verbose_printf(stdout, cmd_args, 1,
	        "\nnet_io_config : Total number of iterations = %d\n\n",
	        new_iters);

	while (!done) {
		int bytes_remaining;
		char* buffer;

		for (loop = 0; loop < new_iters; loop++) {
			int ret = SUCCESS, retry = 0;
			bytes_remaining = msg_size;
			buffer = msg;

			/* Record start time */
			if (get_cur_time(&start_time) == ERROR) {
				cleanup(serv_args, server_tid, msg, cl_sock_fd);
				free_chain(result, 0);
				targs->ret = ERROR;
				return (void *) NULL;
			}

			/* Send the msg */
			if (send(cl_sock_fd, msg, msg_size, 0) != msg_size) {
				cleanup(serv_args, server_tid, msg, cl_sock_fd);
				free_chain(result, 0);
				targs->ret = ERROR;
				return (void *) NULL;
			}

			/* Wait till you recv response */
			do {
				ret = recv(cl_sock_fd, buffer, bytes_remaining,
				        0);
				retry = 0;
				if (ret == ERROR) {
					if (errno== EINTR) {
						retry = 1;
					}
				} else if (ret > 0 && ret < bytes_remaining) {
					buffer += ret;
					bytes_remaining -= ret;
					retry = 1;

#ifdef TRACE_MSG
					RTMB_printf( stdout, "server: "
						"received = %d   "
						"expected = %d "
						"get_next = %d \n",
						ret,
						bytes_remaining + ret,
						bytes_remaining);

				} else if ( ret> 0 && ret == bytes_remaining
					&& ret != msg_size) {
					RTMB_printf( stdout, "server: "
						"received = %d   "
						"expected = %d "
						"msg_size  = %d \n",
						ret,
						bytes_remaining,
						msg_size);
#endif

				}
			} while (retry != 0);

			/*  Now, record end time */
			if (get_cur_time(&end_time) == ERROR) {
				cleanup(serv_args, server_tid, msg, cl_sock_fd);
				free_chain(result, 0);
				targs->ret = ERROR;
				return (void *) NULL;
			}

			/* If there was error other than EINTR, return fail */
			if ((retry == 0) && (ret == ERROR)) {
				cleanup(serv_args, server_tid, msg, cl_sock_fd);
				free_chain(result, 0);
				targs->ret = ERROR;
				return (void *) NULL;
			}

			/* Get the time difference of start and end times */
			time_diff = get_time_diff(start_time, end_time);
			RTMB_verbose_printf(stdout, cmd_args, 2,
			        "net_io_config: Difference between end"
				        " and start times "
				        "= %.3f us \n", MICROSEC(time_diff));

			fflush(stdout);

			add_entry(result, time_diff, 0);
		}

		if (IS_EXEC_TIME_GRT_THAN_CLK(result, clock_accuracy)) {
			print_flag = TRUE;

			/* Check against the computed median for this test */
			test_status = check_pass_criteria(result, cmd_args,
			        bmtest, 0);

			if (test_status == SUCCESS) {
				retry_status = ACCEPTABLE_DEVIATIONS;
				done = 1;
				break;
			} else {
				if (++count == bmtest->_threshold) {
					RTMB_printf(stderr,
					        "net_io_config: exceeded "
						        "maximum attempts \n");
					break;
				}
			}
		}

		if (print_flag) {
			RTMB_verbose_printf(stdout, cmd_args, 1,
			        "\nnet_io_config: Retrying test ");
			RTMB_verbose_printf(stdout, cmd_args, 1,
			        " with bigger work quantum to get"
				        " lesser variance...\n");
		}
		/*
		 * measured times are not consistent so retry with
		 * larger buffer.
		 */
		free_chain(result, 0);
		if (msg) {
			free(msg);
		}
		msg_size = msg_size * MULTIPLIER_FOR_SUB_ITER;
		msg = (char *) msg_alloc_init(msg, (msg_size));

		if (msg == NULL) {
			abort();
		}
	}

	/*net  IO rate is determined*/
	result->opern_amount = msg_size;

	add_result_to_result_table2(res_table, result, NETIO_CONFIG, bmtest);

	fflush(stdout);
	/* Clean up and leave */
	cleanup(serv_args, server_tid, msg, cl_sock_fd);
	fflush(stdout);
	targs->ret = SUCCESS;
	return (void *) NULL;
}