Ejemplo n.º 1
0
int init_sock(struct addrinfo *ai) {

	const 	int on = 1;
	int	 fd;
	int ret;

	if (ai == NULL)
		return(-1);

	if ( (fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0 ) {
		fd = init_sock(ai->ai_next);
		return fd;
	}

	ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
	check("setsockopts", ret);


	if (bind(fd, ai->ai_addr, ai->ai_addrlen) == 0) {
		if(ai->ai_socktype == SOCK_STREAM) {
			ret = listen(fd, LISTENQ);
			check("listen", ret);
		}
		return fd;
	}
	else {
		ret = close(fd);
		check("close", ret);
		fd = init_sock(ai->ai_next);
		return fd;
	}
}
Ejemplo n.º 2
0
//part2
int send_data(char *send_buf, int send_len)
{
	int n = 0;

	if (init_conf() < 0)
		return -1;
		
	int s_socket = init_sock(sc.s_ip, sc.s_port);
	if (s_socket < 0) 
	{
		printf("connect socket failed\n");
		return -1;
	}
    
	n = send(s_socket, send_buf, send_len, 0);
	printf("send len is:%d\n", n);
	if (n < 0)
	{
		printf("send failed\n");
		return -1;
	}

	close(s_socket);
	return 1;
}
Ejemplo n.º 3
0
static int setup(int argc, char *argv[])
{
	int ret = 0, sockfd;
	FILE *logfile = NULL;

	if (parse_opts(argc, argv))
		usage();

	if (test_flags & DSCV_TEST) {

		sockfd = init_sock(lsnr_addr, port);
		if (sockfd < 0) {
			fprintf(stderr, "init socket failed.\n");
			return sockfd;
		}

		log.socket_log = sockfd;	

	} else {
		ret = open_logfile(&logfile, log_path);
		if (ret)
			return ret;

		log.stream_log = logfile;
	}

	child_pid_list = (pid_t *)malloc(sizeof(pid_t) * num_children);

	return ret;
}
Ejemplo n.º 4
0
Archivo: noxref.c Proyecto: mth/noxref
static void* process_connection(void *arg) {
	struct pollfd fds[2];
	char buf[BUF_SIZE];
	int i = CLIENT, res;

	init_sock(fds[CLIENT].fd = (long) arg);
	fds[CLIENT].events = POLLIN | POLLERR | POLLHUP;
	fds[SERVER].fd = -1;
	fds[SERVER].events = POLLIN | POLLERR | POLLHUP;
	fds[SERVER].fd = res = prepare_http(fds[CLIENT].fd, buf);
	while (res >= 0) {
		i = SERVER;
		if (!(res = poll(fds, 2, inactivity_timeout * 1000)))
			break;
		for (i = 0; res > 0 && i < 2; ++i)
			if ((fds[i].revents & POLL_IN))
				res = send_data(buf, i, fds + i, fds[i ^ 1].fd);
			else if ((fds[i].revents & (POLLERR | POLLHUP)))
				res = ERR_IO;
	}
	if (res < 0 && (i == SERVER || res != ERR_IO))
		write_error(buf, fds[CLIENT].fd, res);
	if (fds[SERVER].fd >= 0)
		close(fds[SERVER].fd);
	close(fds[CLIENT].fd);
	return NULL;
}
Ejemplo n.º 5
0
Archivo: audioc.c Proyecto: ricann/lab
int main(int argc, char *argv[])
{
	//init ip and port
	if (argc == 3) {
		strncpy(ip, argv[1], strlen(argv[1]));
		port = atoi(argv[2]);
	} else {
		strncpy(ip, IP_DEFAULT, strlen(IP_DEFAULT));
		port = PORT_DEFAULT;
	}

	//init alsa, open device and set parameters
	if (init_alsa() != 0) {
		return -1;
	}

	//init socket
	if (init_sock() != 0) {
		return -1;
	}

	//capture and transfer audio
	if (cap_audio() != 0) {
		return -1;
	}

	return 0;
}
Ejemplo n.º 6
0
int insert_aodv_dev(struct net_device *dev) {
	aodv_dev *new_dev;
	int error=0;

	char netmask[16];

	new_dev = create_aodv_dev(dev);
	if (new_dev == NULL){
		printk("Error during creation of socket; terminating, %d\n", error);
		return 1;
	}
	strcpy(netmask, inet_ntoa(new_dev->netmask & new_dev->ip));

	printk(
			"Adding interface: %s  Interface Index: %d  IP: %s Subnet: %s\n",
			dev->name, dev->ifindex, inet_ntoa(g_mesh_ip), netmask);
		                                 
		error = sock_create(PF_INET, SOCK_DGRAM, 0, &(new_dev->sock));
		if (error < 0) {
			kfree(new_dev);
			printk("Error during creation of socket; terminating, %d\n", error);
			return 1;
		}
		init_sock(new_dev->sock, new_dev->ip, dev->name);
	
	g_mesh_dev = new_dev;
	return 0;
}
Ejemplo n.º 7
0
int main(int argc, char **argv)
{
	struct sockaddr iodAddr;
	struct cas_options cas_options = {
doInstrumentation:0,
use_sockets:0,
	};

	parse_args(argc, argv);
	if (optind < argc) {
		usage(argc, argv);
	}
	cas_options.use_sockets = use_sockets;
	clnt_init(&cas_options, 1, CAPFS_CHUNK_SIZE);
	if (init_sock(&iodAddr, host, port_nr) < 0) {
		fprintf(stderr, "No such host : %s? %s\n", host, strerror(errno));
		goto oops;
	}
	if (clnt_ping(TRY_TCP, &iodAddr) == 0) {
		goto oops;
	}
	clnt_finalize();
	printf("CAPFS I/O server on %s:%d is up and listening.\n", host, port_nr);
	exit(0);
oops:
	clnt_finalize();
	printf("CAPFS I/O server on %s:%d is down.\n", host, port_nr);
	exit(1);
}
Ejemplo n.º 8
0
Archivo: noxref.c Proyecto: mth/noxref
static int connect_host(char *host) {
	struct addrinfo hint, *addr;
	char *port;
	int fd;

	if ((port = strchr(host, ':')))
		*port = 0;
	memset(&hint, 0, sizeof hint);
	hint.ai_family = AF_UNSPEC;
	hint.ai_socktype = SOCK_STREAM;
	hint.ai_flags = AI_ADDRCONFIG;
	if (getaddrinfo(host, port ? port + 1 : "http", &hint, &addr))
		return ERR_RESOLV;
	if (port)
		*port = ':';
	fd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
	init_sock(fd);
	if (fd < 0)
		goto free;
	if (connect(fd, addr->ai_addr, addr->ai_addrlen)) {
		close(fd);
		fd = ERR_CONNECT;
	}
free:
	freeaddrinfo(addr);
	return fd;
}
Ejemplo n.º 9
0
int
main(int argc, char **argv)
{
	thread thread_obj;

	/* Allocate the room */
	req = (REQ *) MALLOC(sizeof (REQ));

	/* Command line parser */
	if (!parse_cmdline(argc, argv, req)) {
		FREE(req);
		exit(0);
	}

	/* Check minimum configuration need */
	if (!req->addr_ip && !req->addr_port && !req->url) {
		FREE(req);
		exit(0);
	}

	/* Init the reference timer */
	req->ref_time = timer_tol(timer_now());
	DBG("Reference timer = %lu\n", req->ref_time);

	/* Init SSL context */
	init_ssl();

	/* Signal handling initialization  */
	signal_init();

	/* Create the master thread */
	master = thread_make_master();

	/* Register the GET request */
	init_sock();

	/*
	 * Processing the master thread queues,
	 * return and execute one ready thread.
	 * Run until error, used for debuging only.
	 * Note that not calling launch_scheduler() does
	 * not activate SIGCHLD handling, however, this
	 * is no issue here.
	 */
	while (thread_fetch(master, &thread_obj))
		thread_call(&thread_obj);

	/* Finalize output informations */
	if (req->verbose)
		printf("Global response time for [%s] =%lu\n",
		       req->url, req->response_time - req->ref_time);

	/* exit cleanly */
	SSL_CTX_free(req->ctx);
	free_sock(sock);
	FREE(req);
	exit(0);
}
Ejemplo n.º 10
0
/* accept a socket (creates a new fd) */
static struct sock *accept_socket( obj_handle_t handle )
{
    struct sock *acceptsock;
    struct sock *sock;
    int	acceptfd;

    sock = (struct sock *)get_handle_obj( current->process, handle, FILE_READ_DATA, &sock_ops );
    if (!sock)
        return NULL;

    if ( sock->deferred )
    {
        acceptsock = sock->deferred;
        sock->deferred = NULL;
    }
    else
    {
        if ((acceptfd = accept_new_fd( sock )) == -1)
        {
            release_object( sock );
            return NULL;
        }
        if (!(acceptsock = alloc_object( &sock_ops )))
        {
            close( acceptfd );
            release_object( sock );
            return NULL;
        }

        init_sock( acceptsock );
        /* newly created socket gets the same properties of the listening socket */
        acceptsock->state  = FD_WINE_CONNECTED|FD_READ|FD_WRITE;
        if (sock->state & FD_WINE_NONBLOCKING)
            acceptsock->state |= FD_WINE_NONBLOCKING;
        acceptsock->mask    = sock->mask;
        acceptsock->proto   = sock->proto;
        acceptsock->type    = sock->type;
        acceptsock->family  = sock->family;
        acceptsock->window  = sock->window;
        acceptsock->message = sock->message;
        if (sock->event) acceptsock->event = (struct event *)grab_object( sock->event );
        acceptsock->flags = sock->flags;
        if (!(acceptsock->fd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj,
                                                    get_fd_options( sock->fd ) )))
        {
            release_object( acceptsock );
            release_object( sock );
            return NULL;
        }
    }
    clear_error();
    sock->pmask &= ~FD_ACCEPT;
    sock->hmask &= ~FD_ACCEPT;
    sock_reselect( sock );
    release_object( sock );
    return acceptsock;
}
Ejemplo n.º 11
0
int main(int argc, char **argv) {
    struct pollfd fds[POLL_MAX];
    int sockfd, clifd, polled=0, i;
    struct serv_conf conf;
    struct mime * mime_tbl;
    struct cgi * cgi_tbl;
    struct addrinfo *info;
    struct sockaddr_storage cli_addr;
    socklen_t addr_size;

    init_conf(&conf);
    init_info(conf.port, &info);
    mime_tbl = init_mime_table();
    cgi_tbl = init_cgi_table();

    sockfd = init_sock(info);
    if(sockfd==-1) return -1;

    memset(fds, 0, sizeof(struct pollfd)*POLL_MAX);
    for(i=0;i<POLL_MAX;i++) fds[i].fd = -1;
    fds[0].fd = sockfd;
    fds[0].events = POLLRDNORM;


    while(1) {
        polled = poll(fds, POLL_MAX, -1);
        if(polled==-1) {
            fprintf(stderr, "poll() error\n");
            continue;
        }

        if(fds[0].revents & POLLRDNORM) {
            /* Handle new connection */
            clifd = accept(sockfd, (struct sockaddr *) &cli_addr, &addr_size);
            for(i=1;i<POLL_MAX;i++) {
                if(fds[i].fd==-1) {
                    fds[i].fd = clifd;
                    fds[i].events = POLLRDNORM;
                    break;
                }
            }
        }

        for(i=1;i<POLL_MAX;i++) {
            if(fds[i].fd!=-1&&(fds[i].revents & POLLRDNORM)) {
                handle_request(mime_tbl, cgi_tbl, conf.pub_dir, fds[i].fd);
                close(fds[i].fd);
                fds[i].fd = -1;
                --polled;
            }
            if(polled==0) break;
        }
    }
    return 0;
}
Ejemplo n.º 12
0
Archivo: sockio.c Proyecto: Goon83/SALB
int connect_sock(int sockd, char *name, int service)
{
	struct sockaddr saddr;

	if (init_sock(&saddr, name, service) != 0) return(-1);
connect_sock_restart:
	if (connect(sockd,(struct sockaddr *)&saddr,sizeof(saddr)) < 0) {
		if (errno == EINTR) goto connect_sock_restart;
		return(-1);
	}
	return(sockd);
}
Ejemplo n.º 13
0
void	init_serv(t_env *e)
{
	int		i;

	e->srv.glst = NULL;
	i = init_sock(e->opt.port, e);
	e->repop = ft_usec_time() + ((126 * 1000000) / e->opt.time);
	e->srv.time = 2000000000000;
	e->users[i]->fct_read = create_clt;
	e->users[i]->fct_write = client_write;
	e->users[i]->type = FD_SRV;
	e->end = 0;
}
Ejemplo n.º 14
0
Archivo: init.c Proyecto: amapig/ipmsg
void init_ipmsg()
{
    get_user_info();
    //encode
    utf8 = 0;
    if (setlocale(LC_CTYPE, "")) {
        if (!strcmp(nl_langinfo(CODESET), "UTF-8")) {
            utf8 = 1;
        }
    }

    init_mlist();
    init_ulist();
    init_sock();
    sem_init(&msg_empty, 0, 0);
    login();
}
Ejemplo n.º 15
0
int main(int argc, char* argv[])
{
	char *data = "Let's begin to communicate!";
	char buf[100];
	char c;
	
        FILE *file;
        //初始化
        int ret1,ret2;
	int i = 3;
	init_sock();
	
	/*开始通信之前需要将用户进程ID发送给内核*/
	//ret1 = send_to_kernel(skfd,data); 
	/*发送白名单*/
        file = fopen("etc_white","r");
	ret1 = setProfile(file,'W');
	/*发送黑名单*/	
	file = fopen("etc_black","r");
	ret1 = setProfile(file,'B');

	if(!ret1){
           	perror("send pid:");
           	exit(-1);
	}
	signal(SIGINT,sig_init);//退出信号
       while(1)
	{
		bzero(buf,sizeof(buf));
		 //接受内核态确认信息
                ret2 = receive_message(skfd,buf);
                if(!ret2){
                        perror("recv form kerner:");
                        exit(-1);
                }
                //printf("->from kernel:%s\n",buf);

	} 
	close(skfd);
        return 0;
}
Ejemplo n.º 16
0
t_cli		handle_pasv(t_env env, t_cli cli, char *str)
{
	struct sockaddr_in6	sin;
	socklen_t			len;
	char				ip[16];
	unsigned short		port;

	(void)env;
	(void)str;
	port = 0;
	if (cli.istransferable)
		close(cli.env.data_fd);
	cli.env.data_fd = init_sock(cli.env);
	cli.env = bind_sock(cli.env, &cli.env.data_fd, &port);
	len = sizeof(sin);
	getsockname(cli.fd, (struct sockaddr*)&sin, &len);
	if (IN6_IS_ADDR_V4MAPPED(&sin.sin6_addr))
	{
		ft_memcpy(ip, sin.sin6_addr.s6_addr + 12, 4);
		S_MESSAGE(227, cli.fd, (int)ip[0], (int)ip[1], (int)ip[2],
				(int)ip[3], (port >> 8) & 0xFF, port & 0xFF);
		cli.istransferable = TRUE;
	}
Ejemplo n.º 17
0
/* create a new and unconnected socket */
static struct object *create_socket( int family, int type, int protocol, unsigned int flags )
{
    struct sock *sock;
    int sockfd;

    sockfd = socket( family, type, protocol );
    if (debug_level)
        fprintf(stderr,"socket(%d,%d,%d)=%d\n",family,type,protocol,sockfd);
    if (sockfd == -1)
    {
        sock_set_error();
        return NULL;
    }
    fcntl(sockfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
    if (!(sock = alloc_object( &sock_ops )))
    {
        close( sockfd );
        return NULL;
    }
    init_sock( sock );
    sock->state  = (type != SOCK_STREAM) ? (FD_READ|FD_WRITE) : 0;
    sock->flags  = flags;
    sock->proto  = protocol;
    sock->type   = type;
    sock->family = family;

    if (!(sock->fd = create_anonymous_fd( &sock_fd_ops, sockfd, &sock->obj,
                            (flags & WSA_FLAG_OVERLAPPED) ? 0 : FILE_SYNCHRONOUS_IO_NONALERT )))
    {
        release_object( sock );
        return NULL;
    }
    sock_reselect( sock );
    clear_error();
    return &sock->obj;
}
Ejemplo n.º 18
0
void do_work(int ac, char **av)
{
    int     serv_sock, clnt_sock;
    int     strcnt, loop;
    int     epfd, event_cnt;
    char    buf[BUF_SIZE], respond[BUF_SIZE];
    socklen_t adrsz = sizeof(struct sockaddr);

    struct  sockaddr  serv_adr, clnt_adr;
    struct  epoll_event *ep_events, event;

    if(2 != ac){
        printf("Usage: %s <port>\n", av[0]);
        exit(1);
    }

    serv_sock = init_sock((struct sockaddr_in*)&serv_adr, NULL, atoi(av[1]));
    return_if_fail(-1 != serv_sock);
    return_if_fail(-1 != bind(serv_sock, &serv_adr, adrsz));
    return_if_fail(-1 != listen(serv_sock, 5));

    epfd = epoll_create(EPOLL_SIZE);
    ep_events = calloc(sizeof(struct epoll_event), EPOLL_SIZE);

    event.events    = EPOLLIN;
    event.data.fd   = serv_sock;
    epoll_ctl(epfd, EPOLL_CTL_ADD, serv_sock, &event);

    while(RUN_FLAG){
        event_cnt = epoll_wait(epfd, ep_events, EPOLL_SIZE, -1);
        if(-1 == event_cnt){
            break;
        }
        fputs("event_wait\n", stdout);
        for(loop = 0; loop < event_cnt; loop++){
            //Get new client
            if(ep_events[loop].data.fd == serv_sock){
                clnt_sock = accept(serv_sock, &clnt_adr, &adrsz);
                event.events = EPOLLIN;
                event.data.fd = clnt_sock;
#ifdef UPDATE
                strcpy(respond, "ALBERT SAY HELO TO YOU:\n");
                write(clnt_sock, respond, strlen(respond));
#endif
                epoll_ctl(epfd, EPOLL_CTL_ADD, clnt_sock, &event);
            }else{
                strcnt = read(ep_events[loop].data.fd, buf, BUF_SIZE);
                printf("read %d bytes\n", strcnt);
                write(1, buf, strcnt);
                if(0 == strcnt || !strncmp("@exit", buf, 5)){
                    write(ep_events[loop].data.fd, "Bye\n", 4);
                    epoll_ctl(epfd, EPOLL_CTL_DEL, ep_events[loop].data.fd, NULL);
                    close(ep_events[loop].data.fd);
                }else{
#ifdef UPDATE
                    sprintf(respond, "%s[%d bytes] %s", ALBERT, strcnt, buf);
                    strcnt = strnlen(respond, BUF_SIZE);
                    write(ep_events[loop].data.fd, respond, strcnt);
#else
                    write(ep_events[loop].data.fd, buf, strcnt);
#endif
                    //write(1, respond, strcnt);
                }
            }
        }//end for
    }//end while
    close(serv_sock);
    close(epfd);
}
Ejemplo n.º 19
0
int recv_data()
{
	struct sockaddr_in   client_addr;  
    socklen_t length = sizeof(client_addr);  

	int server_socket = init_sock();	
	if (server_socket < 0)
	{
		printf("create socket failed!\n");
		return -1;
	}

	while (1)
	{
		int new_server_socket = accept(server_socket, (struct sockaddr*)&client_addr, &length);  
        if (new_server_socket < 0)  
        {  
            printf("Server Accept Failed!\n");  
            break;  
        }  

		int recv_len = 0;
		int total_len = 0;
		int tmp_len = 0;
		char buffer[BUFFER_SIZE] = {0};  
		char file_buf[4096] = {0};

        length = recv(new_server_socket, buffer, sizeof(int), 0);  
        if (length < 0)  
        {  
            printf("Server Recieve Data Failed!\n");  
            break;  
        }  
		printf("length:%d\n", length);
		memcpy(&total_len, buffer, 4);
		total_len -= 4;
		printf("total_len:%d\n", total_len);

		while (tmp_len != total_len)
		{	
			recv_len = recv(new_server_socket, buffer, BUFFER_SIZE , 0);  
			if (recv_len < 0)  
			{  
				printf("Server Recieve Data Failed!\n");  
				break;  
			}  
			
			memcpy(file_buf + tmp_len, buffer, recv_len);
			tmp_len = tmp_len + recv_len;	
			printf("tmp_len is :%d\n", tmp_len);
		}

		puts("===================================");
		puts("recv:");
		t_disbuf(file_buf, total_len);
		puts("===================================");

		write_new_file(file_buf, total_len);
		close(new_server_socket);
	}

	close(server_socket);
}
Ejemplo n.º 20
0
/*
 * Create the resolver.
 */
PJ_DEF(pj_status_t) pj_dns_resolver_create( pj_pool_factory *pf,
					    const char *name,
					    unsigned options,
					    pj_timer_heap_t *timer,
					    pj_ioqueue_t *ioqueue,
					    pj_dns_resolver **p_resolver)
{
    pj_pool_t *pool;
    pj_dns_resolver *resv;
    pj_status_t status;

    /* Sanity check */
    PJ_ASSERT_RETURN(pf && p_resolver, PJ_EINVAL);

    if (name == NULL)
	name = THIS_FILE;

    /* Create and initialize resolver instance */
    pool = pj_pool_create(pf, name, 4000, 4000, NULL);
    if (!pool)
	return PJ_ENOMEM;

    /* Create pool and name */
    resv = PJ_POOL_ZALLOC_T(pool, struct pj_dns_resolver);
    resv->pool = pool;
    resv->udp_sock = PJ_INVALID_SOCKET;
    pj_strdup2_with_null(pool, &resv->name, name);
    
    /* Create the mutex */
    status = pj_mutex_create_recursive(pool, name, &resv->mutex);
    if (status != PJ_SUCCESS)
	goto on_error;

    /* Timer, ioqueue, and settings */
    resv->timer = timer;
    resv->ioqueue = ioqueue;
    resv->last_id = 1;

    pj_dns_settings_default(&resv->settings);
    resv->settings.options = options;

    /* Create the timer heap if one is not specified */
    if (resv->timer == NULL) {
	status = pj_timer_heap_create(pool, TIMER_SIZE, &resv->timer);
	if (status != PJ_SUCCESS)
	    goto on_error;
    }

    /* Create the ioqueue if one is not specified */
    if (resv->ioqueue == NULL) {
	status = pj_ioqueue_create(pool, MAX_FD, &resv->ioqueue);
	if (status != PJ_SUCCESS)
	    goto on_error;
    }

    /* Response cache hash table */
    resv->hrescache = pj_hash_create(pool, RES_HASH_TABLE_SIZE);

    /* Query hash table and free list. */
    resv->hquerybyid = pj_hash_create(pool, Q_HASH_TABLE_SIZE);
    resv->hquerybyres = pj_hash_create(pool, Q_HASH_TABLE_SIZE);
    pj_list_init(&resv->query_free_nodes);

    /* Initialize the UDP socket */
    status = init_sock(resv);
    if (status != PJ_SUCCESS)
	goto on_error;

    /* Looks like everything is okay */
    *p_resolver = resv;
    return PJ_SUCCESS;

on_error:
    pj_dns_resolver_destroy(resv, PJ_FALSE);
    return status;
}
Ejemplo n.º 21
0
int main(int argc, char **argv) {

	int 	fd;
	//time_t	ticks;
	//char	buff[MAXLINE];
	struct addrinfo	*ai;
	int socktype;
	char port[5];
	/*char *filename;
	out = FALSE;
	verbose = 0; */

	char *server_name = argv[1];


	time_record_tail = &time_record_head; /* tail points to the first element,
						 i.e. the head of the list */
	seqlist_tail = &seqlist_head;
	seqlist_tail->next = NULL;

	/* default values for port and socktype */
	strncpy(port, "5001", 4);
	socktype = SOCK_STREAM;

	if (argc < 2) {
		usage();
	}



	argc--; argv++; /* skip program name */
	argc--; argv++; /* skip source address or name */

	while( argc > 0 && argv[0][0] == '-' )  {
		switch (argv[0][1]) {
			case 'u': socktype = SOCK_DGRAM;
				break;
			case 't': socktype = SOCK_STREAM;
				break;
			case 'p': strncpy(port, &argv[0][2], 5);
				break;
			case 'l': //strncpy(port, &argv[0][2], 5);
				buflen = atoi(&argv[0][2]);
				break;
			/*
			case 'v': verbose++;
				break;
			case 'o': // next string specifies a filename
				strncpy(filename,&argv[1][0] , MAXFILENAME);
				argv++; argc--; // skip filename
				out = TRUE;
				break;*/
			default:
				usage();
		};
		argv++; argc--;
	}

	/* open output file if specified */
	/*
	if(out) {
		output = fopen(filename, "w");
		if(!output) {
			fprintf(stderr, "Failed opening file for output %s: ", filename);
			perror("");
		}

	}*/

	ai = getaddrlist(server_name, port, AI_PASSIVE, AF_UNSPEC, socktype);


	fd = init_sock(ai);
	check("init_socket", fd);


	if(socktype == SOCK_STREAM) {
		printf("Waiting for TCP connection on port %s\n", port);
		read_tcp(fd);
	}
	else if(socktype == SOCK_DGRAM) {
		printf("Waiting for UDP connection on port %s\n", port);
		read_udp(fd);
	}



	/*
	if(output) {
		if(fclose(output)) {
			fprintf(stderr, "Failed closing file %s\n", filename);
			perror("");
		}
	}*/

	if(time_record_head.next != NULL)
		free_time_record(time_record_head.next);
	if(seqlist_head.next != NULL)
		free_seqlist(seqlist_head.next);

	return 0;
}
Ejemplo n.º 22
0
/* capfs_detect() - given a file name, attempts to determine if the given
 * file is a CAPFS one
 *
 * Returns -1 on error.
 * Returns 0 if file name does not appear to refer to a CAPFS file.
 * Returns 1 if file name refers to an existing CAPFS file OR if it
 *   refers to a file that does not yet exist but that would exist
 *   on a CAPFS file system.
 * Returns 2 if file name refers to an existing CAPFS directory.
 *
 * IF the name refers to a CAPFS file, we return a pointer to our static
 * region holding the canonicalized file name.  This isn't too
 * thread-safe <smile>, but neither are a lot of other things in this
 * version of the library...
 */
int capfs_detect(const char *fn, char **sname_p, struct sockaddr **saddr_p,
int64_t *fs_ino_p, int64_t *fino_p, int to_follow)
{
	struct mntent *ent;
	int len;
	char *remainder, *fsdir;
	mreq req;
	mack ack;
	static struct sockaddr saddr;
	static char snambuf[MAXPATHLEN+1];
	u_int16_t port;
	char host[1024];
	struct capfs_options opt;
	
	opt.tcp = MGR_USE_TCP;
	opt.use_hcache = 0;

	memset(&req, 0, sizeof(req));
	memset(&ack, 0, sizeof(req));
	/* canonicalize the filename, result in canonicalize_outbuf */
	if (!canonicalize(fn)) return(-1);


	LOG(stderr, DEBUG_MSG, SUBSYS_LIB,  "canonicalize: %s\n", canonicalize_outbuf);

	/* check for capfs fstab match, return 0 if no match */
	if (!(ent = search_fstab(canonicalize_outbuf))) {
		LOG(stderr, INFO_MSG, SUBSYS_LIB,  "search_fstab didn't find a match\n");
		return(0);
	}

	/* piece together the filename at the server end
	 *
	 * Steps:
	 * 1) skip over hostname and ':' in fsname
	 * 2) replace directory name in filename with one on server
	 *
	 * Assumption: unless mnt_dir refers to the root directory, there
	 * will be no trailing /.
	 */
	if (!(fsdir = strchr(ent->mnt_fsname, ':'))) return(-1);
	fsdir++;
	len = strlen(ent->mnt_dir);
	remainder = canonicalize_outbuf + len;
	snprintf(snambuf, MAXPATHLEN, "%s/%s", fsdir, remainder);
	LOG(stderr, DEBUG_MSG, SUBSYS_LIB,  "capfs name: %s\n", snambuf);

	/* ideally we would like to hit the manager here to see if this is a
	 * directory or a file, but we don't want to use stat because it
	 * causes traffic to the iods.
	 *
	 * So instead we do an access call, which now returns the file stats
	 * too (except for size).  This way we can check to see if we're
	 * looking at a file or directory.
	 */
	req.uid = getuid();
	req.gid = getgid();
	req.type = MGR_ACCESS;
	req.dsize = strlen(snambuf); /* null terminated at other end */
	req.req.access.mode = F_OK;
	req.req.access.to_follow = to_follow;
	ack.majik_nr = 0;

	/* piece together host and port for server */
	if (!(remainder = strchr(ent->mnt_fsname, ':'))) return(-1);
	if (!(len = remainder - ent->mnt_fsname)) return(-1);
	strncpy(host, ent->mnt_fsname, len);
	*(host + len) = '\0';

	if (!(remainder = strstr(ent->mnt_opts, "port="))) return(-1);
	remainder += 5; /* strlen("port=") */
	port = atoi(remainder);

	/* send the request; don't return an error just because we get -1
	 * back from send_mreq_saddr; file might have just not existed
	 */
	if (init_sock(&saddr, host, port)) {
		return(-1);
	}
	/* send_mreq_saddr < 0 means mgr is down or something */
	if (send_mreq_saddr(&opt, &saddr, &req, snambuf, &ack, NULL) < 0) {
		PERROR(SUBSYS_LIB,"capfs_detect: send_mreq_saddr -");
		return -1;
	}

	*saddr_p = &saddr;
	*sname_p = snambuf;
	if (ack.status == 0) {
		*fs_ino_p = ack.ack.access.meta.fs_ino;
		if(fino_p) *fino_p = ack.ack.access.meta.u_stat.st_ino;
		if (S_ISDIR(ack.ack.access.meta.u_stat.st_mode)) 
			return(2);
	}
	else {
		if (ack.eno == ENOENT) {
			return(1);
		}
	}

	/* fill in dmeta structure */
	return(1);
}
Ejemplo n.º 23
0
int dim_tcpip_init(int thr_flag)
{
#ifdef WIN32
	int addr, flags = 1;
/*
    void tcpip_task();
*/
	void create_io_thread(void);
#else
	struct sigaction sig_info;
	sigset_t set;
	void io_sig_handler();
	void dummy_io_sig_handler();
	void tcpip_pipe_sig_handler();
#endif
	extern int get_write_tmout();

	if(init_done) 
		return(1);

	dim_get_write_timeout();
#ifdef WIN32
	init_sock();
	Threads_on = 1;
#else
	if(thr_flag)
	{
		Threads_on = 1;
	}
	else
	{
		sigemptyset(&set);

		sigaddset(&set,SIGALRM);
	    sig_info.sa_handler = io_sig_handler;
	    sig_info.sa_mask = set;
#ifndef LYNXOS
	    sig_info.sa_flags = SA_RESTART;
#else
	    sig_info.sa_flags = 0;
#endif
  
		if( sigaction(SIGIO, &sig_info, 0) < 0 ) 
		{
			perror( "sigaction(SIGIO)" );
			exit(1);
		}
	      
	    sigemptyset(&set);
	    sig_info.sa_handler = tcpip_pipe_sig_handler;
	    sig_info.sa_mask = set;
#ifndef LYNXOS 
	    sig_info.sa_flags = SA_RESTART;
#else
	    sig_info.sa_flags = 0;
#endif

	    if( sigaction(SIGPIPE, &sig_info, 0) < 0 ) {
			perror( "sigaction(SIGPIPE)" );
			exit(1);
	    }
	  
	}
#endif
	if(Threads_on)
	{
#ifdef WIN32
		if(DIM_IO_path[0] == -1)
		{
			if( (DIM_IO_path[0] = (int)socket(AF_INET, SOCK_STREAM, 0)) == -1 ) 
			{
				perror("socket");
				return(0);
			}
		
			DIM_sockname.sin_family = PF_INET;
			addr = 0;
			DIM_sockname.sin_addr = *((struct in_addr *) &addr);
			DIM_sockname.sin_port = htons((ushort) 2000); 
			ioctl(DIM_IO_path[0], FIONBIO, &flags);
		}
#else
		if(DIM_IO_path[0] == -1)
		{
			pipe(DIM_IO_path);
		}
#endif
	}
	if(!queue_id)
		queue_id = dtq_create();

#ifdef WIN32
/*
#ifndef STDCALL
	tid = _beginthread((void *)(void *)tcpip_task,0,NULL);
#else
	tid = _beginthreadex(NULL, NULL,
			tcpip_task,0,0,NULL);
#endif
*/
	create_io_thread();
#endif
	init_done = 1;
	return(1);
}
Ejemplo n.º 24
0
int main(int argc, char **argv)
{
    int ch = 0;
    char *ifname = NULL, *ip = NULL;;
    int type = 0, broadcast = 0, demon = 0;
    int ret = 0, len = 0;

    while((ch = getopt(argc,argv,"i:gbdh"))!= -1)
    {
        switch(ch) {
        case 'i':
            ifname = optarg;
            break;
        case 'g':
            type = 1;
            break;
        case 'b':
            broadcast = 1;
            break;
        case 'd':
            demon = 1;
            break;
        case 'h':
            usage();
            exit(0);
            break;
        default:
            fprintf (stderr, "invaild option: %c \n", ch);
            exit(0);
            break;
        }
    }
    if(optind < argc) {
        ip = argv[optind];
    }

    if(!ifname) {
        printf("error: no ifname \n");
        exit(0);
    }

    if(!type) {
        if(!ip) {
            printf("error: no ip \n");
            exit(0);
        }

        if(!ip_check(ip)) {
            printf("invaild ip: %s \n", ip);
            exit(0);
        }

        if( inet_aton(ip, (struct in_addr *)&cheat_ip) == 0 ) {
            printf("ip addr error \n");
            exit(0);
        }
    }

    if( get_info(ifname) < 0 ) {
        printf("get info failed \n");
        exit(0);
    }

    len = put_data(broadcast, type);

    if(demon)
        wf_demon(arp_exit_system);
    else
        wf_registe_exit_signal(arp_exit_system);

    if( init_sock(ifname) < 0) {
        printf("socket failed \n");
        exit(0);
    }

    while(1)
    {
        sleep(1);
        ret = send(sockfd, arp_data, len, 0);
        if(!demon)
            printf("ret of send: %d,  %s \n", ret, strerror(errno));
    }

    arp_exit_system();
    return 0;
}
Ejemplo n.º 25
0
/* Note: adjust rlimit if needed for more allowed open fd */
int main(int argc, char **argv)
{
	int i;
	int rc;
	void *thread_retval;
	int retry;

	if (argc > 1) {
		target_addr = strtoul(argv[1], NULL, 0);
	}
	fprintf(stderr, "target_addr = %p\n", (void *)target_addr);

	setfdlimit();
	init_sock();
	init_mmap();

redo:
	retry = 0;
	init_pipes();

	for (i = 0; i < NR_SOCKS; i++) {
		rc = pthread_create(&sendmmsg_threads[i], NULL,
			sendmmsg_thread_func, NULL);

		if (rc) {
			perror("sendmmsg_threads failed");

			exit(2);
		}
	}

	sleep(3);
	kill_switch = 1;
	for (i = 0; i < NR_SOCKS; i++) {
		pthread_join(sendmmsg_threads[i], &thread_retval);
	}
	kill_switch = 0;
	sleep(1);

	rc = pthread_create(&mmap_thread, NULL, mmap_thread_func, NULL);
	if (rc) {
		perror("mmap_thread failed");
	}

	for (i = 0; i < NR_PIPES; i++) {
		rc = pthread_create(&pipe_write_threads[i], NULL,
		                    pipe_write_func, (void *)pipes[i].fd[1]);
		if (rc) {
			perror("pipe_write_thread failed");
			exit(2);
		}

		rc = pthread_create(&pipe_read_threads[i], NULL,
		                    pipe_read_func, (void *)pipes[i].fd[0]);
		if (rc) {
			perror("pipe_read_thread failed");
			exit(2);
		}
	}

	for (i = 0; i < NR_PIPES; i++) {
		fprintf(stderr, "join read thread %d...\n", i);
		pthread_join(pipe_read_threads[i], &thread_retval);
		if (thread_retval == (void *)-1) {
			retry = 1;
		}
		fprintf(stderr, "done\n");
	}

	kill_switch = 1;
	fprintf(stderr, "kill others\n");
	fprintf(stderr, "join mmap thread...\n");
	pthread_join(mmap_thread, &thread_retval);
	fprintf(stderr, "done\n");

	for (i = 0; i < NR_PIPES; i++) {
		for(;;) {
			if (close(pipes[i].fd[0])) {
				perror("close write pipe failed");
				continue;
			}

			if (close(pipes[i].fd[1])) {
				perror("close read pipe failed");
				continue;
			}
			break;
		}
	}
	fprintf(stderr, "pipe closed\n");

	if (retry) {
		goto redo;
	}

	exit(0);

	return 0;
}
Ejemplo n.º 26
0
Archivo: sws.c Proyecto: 01zhou/sws
int
main(int argc, char* argv[])
{
	int sockfd, newsockfd;
	int port;
	int i,j;
	socklen_t clilen;
	struct sockaddr_in cli_addr;
	char root_path[MAX_URI_LEN];

	root_path[0]=0;
	ROOT_PATH = root_path;
	PROGRAM_NAME = argv[0];

	global_option.l = 0;
	global_option.d = 0;
	global_option.c = 0;


	signal(SIGCHLD, SIG_IGN);

	port=PORT;
	for(i=1; i<argc; i++)
	{
		if(argv[i][0]=='-')
		{
			for(j=1; j>0 && argv[i][j]!=0; j++)
			{
				switch(argv[i][j])
				{
				case 'h':
					print_usage();
					break;
				case 'd':
					global_option.d = 1;
					break;
				case 'p':
					i++;
					j=-1;
					if(i<argc)
					{
						port= atoi(argv[i]);
					}
					else
					{
						print_usage();
					}
				break;
				case 'l':
					global_option.l = 1;
					i++;
					j=-1;
					if(i<argc)
					{
						strcpy(global_option.lfile, argv[i]);
					}
					else
					{
						print_usage();
					}
					break;
				case 'c':
					global_option.c = 1;
					i++;
					j=-1;
					if(i<argc)
					{
						if(argv[i][0]=='.' && argv[i][1]=='/')
						{
							strcpy(global_option.cdir, argv[i]);
						}
						else if(argv[i][0]!='/')
						{
							sprintf(global_option.cdir, "./%s", argv[i]);
						}
						else
						{
							sprintf(global_option.cdir, "%s", argv[i]);
						}
						if(global_option.cdir[strlen(global_option.cdir)-1] == '/')
						{
							global_option.cdir[strlen(global_option.cdir)-1] = 0;
						}
					}
					else
					{
						print_usage();
					}
					break;
				default:
					print_usage();
					break;
				}
			}
		}
		else
		{
			if(argv[i][0]=='.' && argv[i][1]=='/')
			{
				strcpy(ROOT_PATH, argv[i]);
			}
			else if(argv[i][0]!='/')
			{
				sprintf(ROOT_PATH, "./%s", argv[i]);
			}
			else
			{
				sprintf(ROOT_PATH, "%s", argv[i]);
			}
			if(ROOT_PATH[strlen(ROOT_PATH)-1] == '/')
			{
				ROOT_PATH[strlen(ROOT_PATH)-1] = 0;
			}
		}
	}

	if(ROOT_PATH[0] == 0)
		strcpy(ROOT_PATH, ".");


	if(global_option.d == 0)
	{
		/*daemonize*/
		if(fork()>0)
			return 0;

	}


	sockfd = init_sock(port);
	listen(sockfd, BACKLOG);
	clilen = sizeof(cli_addr);

	while(1)
	{
		newsockfd = accept(sockfd, (struct sockaddr*) &cli_addr, &clilen);
#ifndef DEBUG
		if(global_option.d == 1)
		{
#endif
			handle(newsockfd, &cli_addr);
#ifndef DEBUG
		}
		else
		{
			if(fork()==0)
			{
				/*child*/
				handle(newsockfd, &cli_addr);
				close(newsockfd);
				return 0;
			}
			close(newsockfd);
		}
#endif
	}
	/* shutdown(sockfd, SHUT_RDWR); */
	close(sockfd);
	return 0;

}