Exemplo n.º 1
0
static const char *run_case(struct Worker *client, struct Worker *server)
{
	struct event_base *base = NULL;
	int spair[2];
	const char *res = "huh";
	bool done = false;

	ignore_sigpipe();

	base = event_init();
	client->evbase = base;
	server->evbase = base;

	tt_assert(socketpair(AF_UNIX, SOCK_STREAM, 0, spair) == 0);
	tt_assert(socket_setup(spair[0], true));
	tt_assert(socket_setup(spair[1], true));

	str_check(start_worker(client, spair[1]), "OK");
	str_check(start_worker(server, spair[0]), "OK");

	while (client->ctx || server->ctx)
		tt_assert(event_base_loop(base, EVLOOP_ONCE) == 0);

	done = true;
end:
	res = check_errors(client, server);
	free_worker(client);
	free_worker(server);
	event_base_free(base);
	return done ? res : "fail";
}
Exemplo n.º 2
0
    int main(int argc, char **argv) {

        initiate(argc, argv); /* initialize executor */
        #ifndef BASIC
        socket_setup();
        network_socket = socket_connect();
        #endif
        runsys(); /* initialize running system */
        if (has_network_socket()) {
            request_id();
            GraphRes = get_graph_res();
            graph_setstatus();
            if (GraphRes < 0) exit(12);
            if (remote) send_ready();
        }

        setjmp (contenv); /* set label for continue long jump */
        while (TRUE) { /* repeat until exit() is called */
            get_internal();
            schedule(); /* reschedule current process */
            if (ready != 0) {
                decode(); /* fetch instruction */
                execute(); /* and execute it */
            }
        }
        return 0;
    } /* end main */
Exemplo n.º 3
0
int socket_init(void)
{
    s8 rc = eat_gprs_bearer_open("CMNET", NULL, NULL, bear_notify_cb);
    if (rc == CBM_WOULDBLOCK)
    {
        LOG_DEBUG("opening bearer...");
    }
    else if (rc == CBM_OK)
    {
        LOG_DEBUG("open bearer success.");

        rc = eat_gprs_bearer_hold();
        if (rc == CBM_OK)
        {
            LOG_DEBUG("hold bearer success.");

            return socket_setup();
        }
        else
        {
            LOG_ERROR("hold bearer failed!");
            return ERR_HOLD_BEARER_FAILED;
        }
    }
    else
    {
        LOG_ERROR("open bearer failed: rc = %d", rc);

        return ERR_OPEN_BEARER_FAILED;
    }

    return SUCCESS;
}
Exemplo n.º 4
0
int main(void)
{
	int s;
	int i;
	int ret;
        fd_set fds;
	struct clients cli;

	client_init(&cli);
	s = socket_setup(SOCK_PATH);
	cli.self = s;
	client_add(&cli, s);

	for (;;) {
		fds = cli.set;
		if (select(cli.max + 1, &fds, NULL, NULL, NULL) == -1) {
		    perror("select");
		    exit(1);
		}

		for (i = 0; i <= cli.max; i++) {
			if (!FD_ISSET(i, &fds))
				continue;

			if (i == cli.self) {
				client_accept(&cli, s);
				continue;
			}
			client_handle_request(&cli, i);
		}
	}

	return 0;
}
Exemplo n.º 5
0
int
server_start(struct server *s) {

	int i, ret;

	/* initialize libevent */
	s->base = event_base_new();

	if(s->cfg->daemonize) {
		server_daemonize(s->cfg->pidfile);

		/* sometimes event mech gets lost on fork */
		if(event_reinit(s->base) != 0) {
			fprintf(stderr, "Error: event_reinit failed after fork");
		}
	}

	/* ignore sigpipe */
#ifdef SIGPIPE
	signal(SIGPIPE, SIG_IGN);
#endif

	slog_init(s);

	/* install signal handlers */
	server_install_signal_handlers(s);

	/* start worker threads */
	for(i = 0; i < s->cfg->http_threads; ++i) {
		worker_start(s->w[i]);
	}

	/* create socket */
	s->fd = socket_setup(s, s->cfg->http_host, s->cfg->http_port);
	if(s->fd < 0) {
		return -1;
	}
	
	/*set keepalive socket option to do with half connection*/
        int keep_alive = 1;
        setsockopt(s->fd , SOL_SOCKET, SO_KEEPALIVE, (void*)&keep_alive, sizeof(keep_alive));

	/* start http server */
	event_set(&s->ev, s->fd, EV_READ | EV_PERSIST, server_can_accept, s);
	event_base_set(s->base, &s->ev);
	ret = event_add(&s->ev, NULL);

	if(ret < 0) {
		slog(s, WEBDIS_ERROR, "Error calling event_add on socket", 0);
		return -1;
	}

	slog(s, WEBDIS_INFO, "Webdis " WEBDIS_VERSION " up and running", 0);
	event_base_dispatch(s->base);

	return 0;
}
Exemplo n.º 6
0
int server_start(struct server *s) {
    int i, ret;


    /* setrlimit */
    server_setrlimit(8192);

    /* daemonize */
    if (s->cfg->daemonize) {
        server_daemonize(s->cfg->pid);

        /* sometimes event mech gets lost on fork */
        if (event_reinit(s->base) != 0) {
            fprintf(stderr, "Error: event_reinit failed after fork");
        }
    }

    /* ignore sigpipe */
#ifdef SIGPIPE
    signal(SIGPIPE, SIG_IGN);
#endif

    /* lose root privileges if we have them */
    /*ret = server_setuid(s->cfg->user);
    if(ret < 0) {
        return -1;
    }*/

    /* slog init */
    slog_init(s);

    /* install signal handlers */
    server_install_signal_handlers(s);

    /* initialize libevent */
    s->base = event_base_new();

    /* start worker threads */
    for (i = 0; i < s->cfg->worker_processes; ++i) {
        worker_start(s->w[i]);
    }

    /* create socket */
	ret = socket_setup(s, s->cfg->http.servers);
    if(ret < 0) {
		return -1;
	}

    /* dispatch */
    slog(s, LOG_INFO, "pbiws " PBIWS_VERSION " up and running", 0);
    event_base_dispatch(s->base);

    return 0;
}
Exemplo n.º 7
0
/* set needed socket options */
bool tune_socket(int sock, bool is_unix)
{
	int res;
	int val;
	bool ok;

	/*
	 * Generic stuff + nonblock.
	 */
	ok = socket_setup(sock, true);
	if (!ok)
		goto fail;

	/*
	 * Following options are for network sockets
	 */
	if (is_unix)
		return true;

	/*
	 * TCP Keepalive
	 */
	ok = socket_set_keepalive(sock, cf_tcp_keepalive, cf_tcp_keepidle,
				  cf_tcp_keepintvl, cf_tcp_keepcnt);
	if (!ok)
		goto fail;

	/*
	 * set in-kernel socket buffer size
	 */
	if (cf_tcp_socket_buffer) {
		val = cf_tcp_socket_buffer;
		res = setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &val, sizeof(val));
		if (res < 0)
			goto fail;
		val = cf_tcp_socket_buffer;
		res = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &val, sizeof(val));
		if (res < 0)
			goto fail;
	}

	/*
	 * Turn off kernel buffering, each send() will be one packet.
	 */
	val = 1;
	res = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
	if (res < 0)
		goto fail;
	return true;
fail:
	log_warning("tune_socket(%d) failed: %s", sock, strerror(errno));
	return false;
}
Exemplo n.º 8
0
int
temp11(int argc, char *argv[]) {
    int o;
    int sock;
    while ((o = getopt(argc, argv, "dstS")) != -1) {
        switch (o) {
        case 'S':
            do_sleep = 1;
            break;
        case 'd':
            do_debug = 1;
            break;
        case 's':
            do_stdin = 1;
            break;
        case 't':
            do_thread = 1;
            break;
        }
    }

    if (do_stdin) {
        struct sockets s;
        s.local = 1;
        s.in = stdin;
        s.out = stdout;
        if (do_thread) {
            pthread_t p;
            pthread_create(&p, NULL, roll_dice, (void *) &s);
        } else {
            roll_dice(&s);
            exit(0);
        }
    }

    sock = socket_setup();
    while (1) {
        struct sockets *s = get_sockets(sock);
        if (s) {
            if (do_thread) {
                pthread_t p;
                pthread_create(&p, NULL, roll_dice, (void *) s);
            } else {
                roll_dice(s);
                exit(0);
            }
        }
    }
    return 0;
}
Exemplo n.º 9
0
int
server_start(struct server *s) {

	int i, ret;

	/* initialize libevent */
	s->base = event_base_new();

	if(s->cfg->daemonize) {
		server_daemonize();

		/* sometimes event mech gets lost on fork */
		if(event_reinit(s->base) != 0) {
			fprintf(stderr, "Error: event_reinit failed after fork");
		}
	}

	/* ignore sigpipe */
#ifdef SIGPIPE
	signal(SIGPIPE, SIG_IGN);
#endif

	slog_init(s);

	/* start worker threads */
	for(i = 0; i < s->cfg->http_threads; ++i) {
		worker_start(s->w[i]);
	}

	/* create socket */
	s->fd = socket_setup(s->cfg->http_host, s->cfg->http_port);
	if(s->fd < 0) {
		return -1;
	}

	/* start http server */
	event_set(&s->ev, s->fd, EV_READ | EV_PERSIST, server_can_accept, s);
	event_base_set(s->base, &s->ev);
	ret = event_add(&s->ev, NULL);

	if(ret < 0) {
		slog(s, WEBDIS_ERROR, "Error calling event_add on socket", 0);
		return -1;
	}

	event_base_dispatch(s->base);

	return 0;
}
Exemplo n.º 10
0
int __cdecl main( int argc, char* argv[] )
{
    
    ShowWindow(GetConsoleWindow(),SW_HIDE);
    
    int iResult;
    
    WSADATA wsaData;
    SOCKET sListenSocket = INVALID_SOCKET;  // listen socket
    
    GetLocalTime(&localTime);
    
    g_hLog = create_log_file( NULL );
    if (g_hLog == INVALID_HANDLE_VALUE) {
        display_error("main - CreateFile - log file", FALSE);
        return 1;
    }

    // Initialize Winsock using Windows socket API version 2.2
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        display_error("main - WSAStartup", FALSE);
        return 2;
    }

    // Server socket setup
    sListenSocket = socket_setup();
    if (sListenSocket == -1) {
        display_error("main - socket_setup", FALSE);
        return 3;
    }

    // Giving welcom message
    sprintf_s(g_sLogMessage, SZ_MAX_LOG, "================ Welcome to MBA Agent ================\r\n");
    write_log();

    // Server infinite loop
    server_mainloop( sListenSocket );

    // Cleanup
    WSACleanup();
    closesocket(sListenSocket);
    CloseHandle(g_hLog);

    return 0;
}
Exemplo n.º 11
0
int main(int args, char **argv){
    
	 if(args != 4){
		printf("USAGE: pop3 [port] [maildir path] [log file]\n");
		printf("NOTE: the maildir path must end with an '/'\n");
		exit(1);
	}
	
	int sockfd, newSockfd; 	
	
	//Process command line arguments
	int c;
	for (c = 1; c < args; c++){
		if (c == 1){
			sockfd = socket_setup(atoi(argv[c])); 
		}
		else if (c == 2){
			dir_set_path(argv[c]); 
		}
		else if (c == 3){
			log_setUp (argv[c]); 
		}
	}
    
	//Creation of thread 
    pthread_t thread_id[100];
    int c_tnum = 0;
 
	//Listen for new connections and create a new thread for every new 
	//connection 
    log_write("Main" ,"POP3 Server Started" , "", "");
    while(1){
        newSockfd = socket_get_new_connection(sockfd);
        int rc;
        rc = pthread_create(&thread_id[c_tnum], NULL, 
                            (void *)pop_protocol, (void *)newSockfd);
        
        log_write("Main" ,"New Connection" , "", "");
        c_tnum++;
    }
		
}
Exemplo n.º 12
0
void server_update(network net)
{
    int fd = socket_setup(1);
    int counter = 18000;
    listen(fd, 64);
    struct sockaddr_in client;     /* remote address */
    socklen_t client_size = sizeof(client);   /* length of addresses */
    time_t t=0;
    while(1){
        connection_info *info = calloc(1, sizeof(connection_info));
        info->net = net;
        info->counter = counter;
        pthread_t worker;
        int connection = accept(fd, (struct sockaddr *) &client, &client_size);
        if(!t) t=time(0);
        info->fd = connection;
        pthread_create(&worker, NULL, (void *) &handle_connection, info);
        ++counter;
        printf("%d\n", counter);
        //if(counter == 1024) break;
    }
    close(fd);
}
Exemplo n.º 13
0
int main(int args, char **argv){
	
	int portno, sockfd, newsockfd;
	char *maildir;
	char *logfile;

	if(args != 4){
		printf("USAGE: pop3 [port] [maildir path] [log file]\n");
		printf("NOTE: the maildir path must end with an '/'\n");
		exit(1);
	} 
	
	portno = atoi(argv[1]);
	maildir = argv[2];
	logfile = argv[3];	
	
	//initial setup
	log_setUp(logfile);
	dir_set_path(maildir);

	//we need to initialise our struct of threads
	
	int i;
	for(i=0; i<MAX_THREADS; i++)
	{
		thread_list[i].thread = malloc(sizeof(pthread_t));
		thread_list[i].used = 0;
		hand_list[i].threadid = i;
		hand_list[i].newsocket = 0;
	}

	//setup our listener socket
	sockfd = socket_setup(portno);
	log_write("Main", "POP3 Server Started", "", "");
	
	while(1)
	{
	//	fprintf(stderr, "new thread\n");
		newsockfd = socket_get_new_connection(sockfd);
		//pthread_t *t;
		//t = malloc(sizeof(pthread_t));

		//we must find a free process.
		//this is a very bad linear search for now
		i = 0;
		while(i<MAX_THREADS)
		{
			if(thread_list[i].used == 0)
			{
				fprintf(stderr, "Handing off thread %i\n", i);
				thread_list[i].used = 1;
				//this is a struct that we handover which contains required info
				hand_list[i].newsocket = newsockfd;
				hand_list[i].threadid = i;		
				pthread_create(thread_list[i].thread, NULL, work_function,
				&hand_list[i]);
				break;
			}
			
			i++;
		}
		//no free connection, close connection

		if(i>=MAX_THREADS)
		{
			socket_write(newsockfd, "\nServer is overcapacity.\nPlease try again later\n\n");
			fprintf(stderr, "connection rejected, tubes clogged\n");
			close_connection(newsockfd);
		}	

	}
	//closes listener socket
	close_socket(sockfd);
	fprintf(stderr,"DONE!\n");
	
	return 0;
}
Exemplo n.º 14
0
	int
main ( int argc, char *argv[] )
{	

	if(argc !=2){
		fprintf(stderr, "usage: snowcast_server tcpport\n");
		exit(1);
	}

	/*<-SET UP PASSSIVE TCP SOCKET->*/
	struct addrinfo hints;
	
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE; 
	tcp_sourcefd = socket_setup(hints,argv[1], NULL);
	printf("tcp socket (fd %d) on port %d setup successful!\n",tcp_sourcefd, atoi(argv[1]));

	/*<-SET UP PASSIVE UDP SOCKET->*/
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC; 
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_flags = AI_PASSIVE; 
	udp_sourcefd = socket_setup(hints, argv[1], NULL);
	printf("udp socket (fd %d) on port %d setup successful!\n", udp_sourcefd, atoi(argv[1]));

	/*<-SET UP STREAMING THREADS->*/
	int i;
	for(i=0;i<STATIONNUM;i++){

	}
	struct station_info *station_0;
	spawn_stream_thread("test.text", &station_0);
	struct station_info *station_1;
	spawn_stream_thread("a.text", &station_1);
	station_0->si_next = station_1;

	/*<-MISC DECLARATION->*/
	struct station_info *s;
	struct client_info *pending_clients = NULL;

	
	/*<-INITIATE SERVICE->*/ 
	//for select()
	fd_set masterfds, readfds;
	FD_ZERO(&masterfds);
	FD_SET(0, &masterfds);
	FD_SET(tcp_sourcefd, &masterfds);
	struct timeval tv, tvcop;
	tv.tv_sec = 1;

	int maxfd = tcp_sourcefd;

	//for accepting new clients
	struct sockaddr_storage their_addr;
	socklen_t ss_size = sizeof their_addr;
	char addr_str[INET6_ADDRSTRLEN];
	if(listen(tcp_sourcefd, 10) == -1){
		perror("program: error on listen");
		exit(1);
	}

	//for talking to clients
	uint16_t numStations = 1, udpPort;
	unsigned char request[512];
	int request_bytes, response_bytes, packetSize;
	struct client_info *c;
	uint8_t commandType;

	//for talking to the user
	char command[512];
	ssize_t command_bytes;

	while(1){
		/* <-CLEAN UP FOR ANOTHER SELECT-> */
		printf("waiting...\n");
		readfds = masterfds;
		tvcop = tv;
	

		/*<-SELECT-> */
		if(select(maxfd+1, &readfds, NULL, NULL, &tvcop) == -1){
			perror("program: error on select()");
			close(tcp_sourcefd);
			//close(newfd);
			exit(1);
		}

		/*<-ACTIVE TCP SOCKET CHECK for ACTIVE CLIENTS-> */
		//expects setStation: 8 +16

		for(s=station_0;s!=NULL;s=s->si_next){
			printf("1\n");
		for(c=s->client_list;c!=NULL;c=c->ci_next){
			//did you say something, i?
			printf("checking active client %d\n",c->ci_fd);
			if(FD_ISSET(c->ci_fd, &readfds)){
				printf("new message from active client %d\n", c->ci_fd);
				if((request_bytes = recv(c->ci_fd, request, sizeof request, 0)) == -1){
					perror("recv()");
					continue;
				}

				if(!request_bytes){
					printf("client quits\n");
					//TODO get rid of the client from the active list
					//TODO how to get the next highest fd number?
					if(c->ci_fd == maxfd) maxfd = maxfd-1;
					FD_CLR(c->ci_fd, &masterfds);
					close(c->ci_fd);
					continue; 
				}

				unpack(request, "ch", &commandType, &udpPort);
				printf("bytes_received: %d \n commandType: %hd\n udpPort: %d\n", request_bytes, commandType, udpPort);
			}

		}
		}
	
		/*<-PASSIVE TCP: New Client connect()-> */	
		if (FD_ISSET(tcp_sourcefd, &readfds)){
			client_count++;
			printf("new client!\n");

			int clientfd = accept(tcp_sourcefd, (struct sockaddr *)&their_addr, &ss_size);
			if ( clientfd == -1 ) {
				perror("program: error on accept()\n");
				close(tcp_sourcefd);
				exit(1);
			}

			//announce new connection
			inet_ntop(their_addr.ss_family,
				get_in_addr( (struct sockaddr *)&their_addr),
				addr_str, sizeof addr_str);
			printf("connection accepted from: %s\n", addr_str);

			//make client_info struct 
			struct client_info *newclient = (struct client_info *) malloc(sizeof(struct client_info));
			newclient->ci_family = their_addr.ss_family;
			newclient->ci_addr = addr_str;
			newclient->ci_next = NULL;
			newclient->ci_fd = clientfd;

			//add client to the pending list
			printf("new connection fd: %d\n",clientfd);
			clist_add(newclient, &pending_clients);
			clist_display(&pending_clients);
			FD_SET(clientfd, &masterfds);
			if(maxfd<clientfd)maxfd= clientfd;
		}

	

		/*<-ACTIVE TCP SOCKET CHECK for PENDING CLIENTS-> */
		//expects hello: 8 + 16
		for(c=pending_clients;c!= NULL;c=c->ci_next){
			printf("checking pending client %d\n", c->ci_fd);
			if(FD_ISSET(c->ci_fd, &readfds)){
				printf("new message from pending client %d\n", c->ci_fd);
				if((request_bytes = recv(c->ci_fd, request, sizeof request, 0)) == -1){
					perror("recv()");
					continue;
				}
				if(!request_bytes){
					printf("client quits\n");
					//TODO get rid of the client from the pending list
					//-----unfortunately, this client has not been able to provide us with his
					//-----UDP port. He passed away too early.
					//TODO how to get the next highest fd number?
					if(c->ci_fd == maxfd) maxfd = maxfd-1;
					FD_CLR(c->ci_fd, &masterfds);
					close(c->ci_fd);
					continue; 
				}	

				unpack(request, "ch", &commandType, &udpPort);
				printf("bytes_received: %d \n commandType: %hd\n udpPort: %d\n", request_bytes, commandType, udpPort);
 
				//was that a hello?
				if(commandType == 0){
					printf("hello received\n");

					//send back welcome
					int welcomesize = sizeof(uint8_t) + sizeof(uint16_t);
					unsigned char response[welcomesize];
					packetSize = pack(response, "ch", (uint8_t)0, (uint16_t)numStations);

					if( (response_bytes = send(c->ci_fd, response, sizeof response, 0)) == -1){
						perror("send() failed");
						exit(1);
					}
					if(packetSize != response_bytes){
						printf("%d bytes have been packed, but %d bytes have been sent\n", packetSize, response_bytes);
						exit(1);
					}

					//complete client's struct info
					c->ci_udp = udpPort;
					struct sockaddr_in *addr = malloc(sizeof(struct sockaddr_in));
					addr->sin_family = c->ci_family;
					addr->sin_port = htons(c->ci_udp);
					addr->sin_addr = *((struct in_addr *) gethostbyname(c->ci_addr)->h_addr);
					c->ci_udp_addr = (struct sockaddr *) addr;

					//add client to default stations client list
					printf("i->ci_fd: %d\n", c->ci_fd);
					if(client_count==1)clist_add(c,&station_0->client_list);
					if(client_count==2)clist_add(c,&station_1->client_list);
					clist_remove(c,&pending_clients);
					printf("pending list: ");
					clist_display(&pending_clients);
					printf("active list: ");
					clist_display(&station_0->client_list);
				} else {
					//invalid command
					clist_remove(c, &pending_clients);
					FD_CLR(c->ci_fd, &masterfds);
				}
			}
		}


		/*<-STDIN CHECK-> */	
		if(FD_ISSET(0, &readfds)){
			printf("new command!\n");
			command_bytes = read(0, command, sizeof command);
			if(command_bytes == -1){
				perror("read()");
				exit(1);
			}
			command[command_bytes] = '\0';
			printf("server admin command: %s\n", command);	
		}
	}
	
	return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */ 
Exemplo n.º 15
0
int __cdecl main( int argc, CHAR* argv[] )
{
    
    ShowWindow(GetConsoleWindow(),SW_HIDE);
    
    int iResult;
    CHAR sLogMessage[SZ_MAX_LOG];
    
    WSADATA wsaData;
    SOCKET sListenSocket = INVALID_SOCKET;  // listen socket
    
    LUID pv;
    TOKEN_PRIVILEGES tp;
    HANDLE hProc;
    HMODULE ntdll;
    
    // Raise up the privilege
    LookupPrivilegeValue( NULL, "SeProfileSingleProcessPrivilege", &pv );
    OpenProcessToken( GetCurrentProcess(), TOKEN_WRITE, &hProc );
        
    tp.PrivilegeCount            = 1;
    tp.Privileges[0].Luid        = pv;
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    AdjustTokenPrivileges(    hProc,
                            FALSE,
                            &tp,
                            sizeof(TOKEN_PRIVILEGES),
                            (PTOKEN_PRIVILEGES)NULL,
                            (PDWORD)NULL );
    ntdll = LoadLibrary("ntdll.dll");
    NtSetSystemInformation = (NTSTATUS (WINAPI *)(INT, PVOID, ULONG))GetProcAddress(ntdll, "NtSetSystemInformation");    
    
    GetLocalTime(&localTime);
    
    g_hLog = create_log_file( NULL );
    if (g_hLog == INVALID_HANDLE_VALUE) {
        write_agent_log("main - CreateFile - log file", TRUE);
        return 1;
    }

    // Initialize Winsock using Windows socket API version 2.2
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        write_agent_log("main - WSAStartup", TRUE);
        return 2;
    }

    // Server socket setup
    sListenSocket = socket_setup();
    if (sListenSocket == -1) {
        write_agent_log("main - socket_setup", TRUE);
        return 3;
    }

    // Giving welcom message
    sprintf_s(sLogMessage, SZ_MAX_LOG, "================ Welcome to MBA Agent ================\r\n");
    write_agent_log(sLogMessage, FALSE);

    // Server infinite loop
    server_mainloop( sListenSocket );

    // Cleanup
    WSACleanup();
    closesocket(sListenSocket);
    CloseHandle(g_hLog);

    return 0;
}
Exemplo n.º 16
0
// setup an agent and get its file descriptors
void setup_agent(int bot, struct agent_t* agent, char* filename)
{
	if (!strcmp(filename, "HUMAN"))
	{
		socket_setup();
		
		socklen_t clen;
		struct sockaddr_in cli_addr;
		int nsockfd;

		agent->status = ERROR;
		clen = sizeof cli_addr;

		if (DEBUG) fprintf(stderr, "Accepting connections"
				" for bot #%d\n", bot+1);

		nsockfd = accept(sockfd, 
				(struct sockaddr *) &cli_addr, &clen);
		if (nsockfd < 0) return;

		if (DEBUG) fprintf(stderr, "...bot #%d connected"
				" successfully!\n", bot+1);

		agent->status = RUNNING;
		agent->fds[READ] = agent->fds[WRITE] = nsockfd;
		agent->timeout = TIMEOUT_MS_HMN;
		return;
	}
	else
	{
		int i, pid, c2p[2], p2c[2];
		agent->timeout = TIMEOUT_MS_BOT;

		char *p, *arglist[100];
		for (i = 0, p = strtok(filename, " "); p; 
			++i, p = strtok(NULL, " ")) arglist[i] = strdup(p);
		arglist[i] = NULL;

		// setup anonymous pipes to replace child's stdin/stdout
		if (pipe(c2p) || pipe(p2c))
		{
			// the pipes were not properly set up (perhaps no more file descriptors)
			fprintf(stderr, "Couldn't set up communication for bot%d\n", bot+1);
			exit(1);
		}

		// fork here!
		switch (pid = fork())
		{
		case -1: // error forking
			agent->status = ERROR;
			fprintf(stderr, "Could not fork process to run bot%d: '%s'\n", bot+1, filename);
			exit(1);

		case 0: // child process
			close(p2c[WRITE]); close(c2p[READ]);
			
			if (STDIN_FILENO != dup2(p2c[READ], STDIN_FILENO))
				fprintf(stderr, "Could not replace stdin on bot%d\n", bot+1);
			
			if (STDOUT_FILENO != dup2(c2p[WRITE], STDOUT_FILENO))
				fprintf(stderr, "Could not replace stdout on bot%d\n", bot+1);

			close(p2c[0]); close(c2p[1]);
			agent->status = RUNNING;
			execvp(arglist[0], arglist);
			
			agent->status = ERROR;
			fprintf(stderr, "Could not exec bot%d: [%d] %s\n", 
				bot, errno, strerror(errno));

			exit(1);
			break;

		default: // parent process
			agent->pid = pid;
			close(p2c[READ]); close(c2p[WRITE]);

			agent->fds[READ ] = c2p[READ ]; // save the file descriptors in the
			agent->fds[WRITE] = p2c[WRITE]; // returned parameter
			
			return;
		}
	}
}
Exemplo n.º 17
0
void client_update(network net, char *address)
{
    int fd = socket_setup(0);

    struct hostent *hp;     /* host information */
    struct sockaddr_in server;    /* server address */

    /* fill in the server's address and data */
    bzero((char*)&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(SERVER_PORT);

    /* look up the address of the server given its name */
    hp = gethostbyname(address);
    if (!hp) {
        perror("no such host");
        fprintf(stderr, "could not obtain address of %s\n", "localhost");
    }

    /* put the host's address into the server address structure */
    memcpy((void *)&server.sin_addr, hp->h_addr_list[0], hp->h_length);
    if (connect(fd, (struct sockaddr *) &server, sizeof(server)) < 0) {
        error("error connecting");
    }

    /* send a message to the server */
    int i;
    //printf("Sending\n");
    for(i = 0; i < net.n; ++i){
        if(net.layers[i].type == CONVOLUTIONAL){
            convolutional_layer layer = net.layers[i];
            write_all(fd, (char*) layer.bias_updates, layer.n*sizeof(float));
            int num = layer.n*layer.c*layer.size*layer.size;
            write_all(fd, (char*) layer.filter_updates, num*sizeof(float));
            memset(layer.bias_updates, 0, layer.n*sizeof(float));
            memset(layer.filter_updates, 0, num*sizeof(float));
        }
        if(net.layers[i].type == CONNECTED){
            connected_layer layer = net.layers[i];
            write_all(fd, (char *)layer.bias_updates, layer.outputs*sizeof(float));
            write_all(fd, (char *)layer.weight_updates, layer.outputs*layer.inputs*sizeof(float));
            memset(layer.bias_updates, 0, layer.outputs*sizeof(float));
            memset(layer.weight_updates, 0, layer.inputs*layer.outputs*sizeof(float));
        }
    }
    //printf("Sent\n");

    for(i = 0; i < net.n; ++i){
        if(net.layers[i].type == CONVOLUTIONAL){
            convolutional_layer layer = net.layers[i];

            read_all(fd, (char*) layer.biases, layer.n*sizeof(float));
            int num = layer.n*layer.c*layer.size*layer.size;
            read_all(fd, (char*) layer.filters, num*sizeof(float));

#ifdef GPU
            push_convolutional_layer(layer);
            #endif
        }
        if(net.layers[i].type == CONNECTED){
            connected_layer layer = net.layers[i];

            read_all(fd, (char *)layer.biases, layer.outputs*sizeof(float));
            read_all(fd, (char *)layer.weights, layer.outputs*layer.inputs*sizeof(float));

#ifdef GPU
            push_connected_layer(layer);
            #endif
        }
    }
    //printf("Updated\n");
    close(fd);
}