Example #1
0
krb5_error_code
krb5_ldap_db_single_init(krb5_ldap_context *ldap_context)
{
    krb5_error_code             st=0;
    int                         cnt=0;
    krb5_ldap_server_info       *server_info=NULL;

    while (ldap_context->server_info_list[cnt] != NULL) {
        server_info = ldap_context->server_info_list[cnt];
        if ((server_info->server_status == NOTSET || server_info->server_status == ON)) {
            if (server_info->num_conns < ldap_context->max_server_conns-1) {
                st = initialize_server(ldap_context, server_info);
                if (st == LDAP_SUCCESS)
                    goto cleanup;
            }
        }
        ++cnt;
    }

    /* If we are here, try to connect to all the servers */

    cnt = 0;
    while (ldap_context->server_info_list[cnt] != NULL) {
        server_info = ldap_context->server_info_list[cnt];
        st = initialize_server(ldap_context, server_info);
        if (st == LDAP_SUCCESS)
            goto cleanup;
        ++cnt;
    }
cleanup:
    return (st);
}
int main(void)
{

	int fd;
	
	pid_t child_pid;
	child_pid = fork ();
	if (child_pid != 0) {
	//parent ID
	exit(0); //the parent needs to die so the child can leave
	}else{
	//child process executing
	setsid();
	for (child_pid=getdtablesize();child_pid>=0;--child_pid) close(child_pid);
		
			fd = open(LOCK_FILE,O_RDWR|O_CREAT,0777);
			
			if (fd<0){
			write_to_log(" :Fatal Error: couldnot read/create lock file. permission reasons");
			exit(1); /* can not open */
			}
		
			if (lockf(fd,F_TLOCK,0) < 0){
			write_to_log(" :Another Instance of Video Server is already running\n");
			fprintf(stderr,"See *.log for details\n");
			exit(0); /* can not lock */
			}
		
		initialize_server();
	}

return 0;
}
Example #3
0
int main(int argc,char *argv[])
{	
	strategy_t server_operation;
	int sfd;
	server_operation = (strategy_t)configure_server(argc,argv);		
	sfd              = initialize_server();
	server_operation(sfd);  				//start server
	if(close(sfd)==-1)					//close server
		print_log(WARNING,"\nError while closing");

	return 0;
}
Example #4
0
krb5_error_code
krb5_ldap_db_init(krb5_context context, krb5_ldap_context *ctx)
{
    krb5_error_code ret;
    int i, version = LDAP_VERSION3;
    unsigned int conns;
    krb5_ldap_server_info *info;
    struct timeval local_timelimit = { 10, 0 };

    ret = validate_context(context, ctx);
    if (ret)
        return ret;

#ifdef LDAP_OPT_DEBUG_LEVEL
    ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &ctx->ldap_debug);
#endif
    ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &version);
#ifdef LDAP_OPT_NETWORK_TIMEOUT
    ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &local_timelimit);
#elif defined LDAP_X_OPT_CONNECT_TIMEOUT
    ldap_set_option(NULL, LDAP_X_OPT_CONNECT_TIMEOUT, &local_timelimit);
#endif

    HNDL_LOCK(ctx);
    for (i = 0; ctx->server_info_list[i] != NULL; i++) {
        info = ctx->server_info_list[i];
        if (info->server_status == NOTSET) {
            krb5_clear_error_message(context);

#ifdef LDAP_MOD_INCREMENT
            info->modify_increment = has_modify_increment(context,
                                                          info->server_name);
#else
            info->modify_increment = 0;
#endif

            for (conns = 0; conns < ctx->max_server_conns; conns++) {
                ret = initialize_server(ctx, info);
                if (ret)
                    break;
            }

            /* If we opened a connection, don't try any more servers. */
            if (info->server_status == ON)
                break;
        }
    }
    HNDL_UNLOCK(ctx);

    return ret;
}
Example #5
0
int start_server()
{
    int r;
    int pid;


    r = initialize_server();
    if (r < 0)
	{
	    LOG("Initialazing failed ... code %d\n",r);
	    return -1;
	}
    //we start the 6 processes:
    // 4 listen on udp, one on TLS and one is a timer
    for (r=0;r<MAX_PROCESSES;r++)
    {
                pid = fork();
		if (pid<0)
		    {
			LOG("start_server:cannot fork\n");
			return -2;
		    }
		    else
			if (pid == 0) //child
			    {
				child_function(r+1);
			    }
			    else //dad
			    {
				//LOG("Child %d started[%d]\n",r+1,pid);
				pids[r] = pid;
			    }
    }
	if (dont_fork == 1)
	{
	    for(;;)
    	        pause();
	}
	else
	{
	    sleep(10);//to be sure
	    cleanup(1);
	    while(wait(0)>0);
	    return 0;
	}


    //LOG("starting server ... ok\n");

    return 0;
}
Example #6
0
int main(int argc, char *argv[])
{
    evutil_socket_t listener;
    struct sockaddr_in sin;
    struct event_base *base;
    struct event *listener_event;
    log_init(L_TRACEV, "./poopymonster.txt");
    SquealConfig *config = squeal_config_init(INI_FILE);

    LOG_WARN("Unable to poop");
    initialize_server(config);

    base = event_base_new();

    if (!base)
        return EXIT_FAILURE;

    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = 0;
    sin.sin_port = htons(server->server_info.port);

    listener = socket(AF_INET, SOCK_STREAM, 0);
    evutil_make_socket_nonblocking(listener);

#ifndef WIN32
    {
        int one = 1;
        setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    }
#endif

    if (bind(listener, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
        perror("bind");
        return EXIT_FAILURE;
    }

    if (listen(listener, server->server_info.max_connections ) < 0) {
        perror("listen");
        return EXIT_FAILURE;
    }

    listener_event = event_new(base, listener, EV_READ | EV_PERSIST, on_accept, (void *) base);
    event_add(listener_event, NULL);

    event_base_dispatch(base);
}
int
main (int argc, char *argv[])
{
    char* load_filename;

    /* Initialize some global variables */
    initialize_server ();

    /* Set up the paths to certain files and directories */
    init_path_strings ();

#ifndef CS_PROFILE
#ifdef SEED_RAND
    srand (time (0));
#endif
#endif

    init_types ();
    initialize_tax_rates ();

    reset_start_time ();

    load_filename = parse_server_args (argc, argv);
    if (load_filename && file_exists(load_filename)) {
	printf ("Server is trying to load: %s\n", load_filename);
	load_city (load_filename);
	zoom_originx = main_screen_originx;
	zoom_originy = main_screen_originy;
    } else {
	engine_new_city (&zoom_originx, &zoom_originy, 1);
    }

    printf ("Server starting main loop!\n");
    while (1) {
	sniff_packets ();
	engine_do_time_step ();
	get_real_time ();
	send_periodic_messages ();
	if (total_time % 1000 == 0) {
	    debug_print_stats ();
	}
    }

    return 0;
}
Example #8
0
int main(int argc, char *argv[])
{
  puts("Starting server.");

  fd_set file_descriptors;

  connection_info server_info;

  int i;


  if (argc != 4)
  {
    fprintf(stderr, "Usage:./%s <server_ip> <server_port> <max_client> \n", argv[0]);
    exit(1);
  }
  MAX_CLIENTS=atoi(argv[3]);
  //check the max clients
  //printf("%d",MAX_CLIENTS);

  connection_info *clients=(connection_info*)malloc(MAX_CLIENTS*sizeof(connection_info));
  
  
  for(i = 0; i < MAX_CLIENTS; i++)
  {
    clients[i].socket = 0;
  }
  
  
  initialize_server(&server_info, atoi(argv[2]));

  while(true)
  {
    int max_fd = construct_fd_set(&file_descriptors, &server_info, clients);

    if(select(max_fd+1, &file_descriptors, NULL, NULL, NULL) < 0)
    {
      perror("Select Failed");
      stop_server(clients);
    }

    if(FD_ISSET(STDIN_FILENO, &file_descriptors))
    {
      handle_user_input(clients);
    }

    if(FD_ISSET(server_info.socket, &file_descriptors))
    {
      handle_new_connection(&server_info, clients);
    }

    for(i = 0; i < MAX_CLIENTS; i++)
    {
      if(clients[i].socket > 0 && FD_ISSET(clients[i].socket, &file_descriptors))
      {
        handle_client_message(clients, i);
      }
    }
  }

  return 0;
}
int main(int argc, char* argv[]){   

    //Use info flag to show useful output about program
    options.info_flag = false;
    
    //Set default options 
    set_default_server_options(options);


    char option;
    while((option = getopt(argc,argv,"hdl:p:r:t:n:s:"))!=-1){
      switch(option){
        case 'h':
          show_help();
          return 0;
          break;
        case 'd':
          options.debug_flag = true;
          break;
        case 'l':
          options.file = optarg;
          options.logging_enabled = true;
          break;
        case 'p':   
          options.port = std::stoi(optarg, nullptr, 10);
          break;
        case 'r':
          options.dir = optarg;
          chdir(optarg);
        break;     
        case 't':  
          options.time = std::stoi(optarg, nullptr, 10); 
          break;     
        case 'n':
          options.threadnum = std::stoi(optarg, nullptr, 10);   
          break;        
        case 's': 
          options.sched = optarg;  
          break;
        default:
        break;
      }
    }
  
    if (options.debug_flag == false){
        daemon(1, 0);  
    }
  
    
    //At this point options struct contains all options to be used in program.          
    if(options.info_flag == true) show_server_info(options);
    
    //Initialize server
    int server_socket_fd = initialize_server(options);
        
    //Main thread creates queueing thread
    std::thread queue_thread(http_request_handler, std::cref(server_socket_fd));
        
    //Create the scheduling thread (the producer)
    //if(options.info_flag == true) std::cout <<"(Main thread): Creating scheduling thread\n";
    std::thread scheduler_thread(http_request_scheduler);
    
                             
    //Create worker threads (the consumers) from -n option
    //if(options.info_flag == true) std::cout << "(Main thread): Creating worker threads\n";
    std::vector<std::thread> threads;
    threads.reserve(options.threadnum); 
    
    for(int thread_id = 1 ; thread_id <= options.threadnum; thread_id++ ) {
      threads.emplace_back(process_queue_block, thread_id);
      std::this_thread::sleep_for (std::chrono::seconds(1));
    }
    

    queue_thread.join();
    scheduler_thread.join();
    for(auto &thread : threads){
      thread.detach();
    }

    return 0;
}
Example #10
0
int main(int argc, char *argv[])
{
	status_t error;

	server_t server;
	error = initialize_server(&server);
	if (error)
	{
		goto exit0;
	}

	char start_up_message[] = "Config file read. Starting rest of server up.\n";
	error = write_log(server.log, start_up_message, sizeof start_up_message);
	if (error)
	{
		goto exit0;
	}

	uint16_t port;
	error = parse_command_line(argc, argv, &port);
	if (error)
	{
		goto exit0;
	}

	char socket_message[] = "Setting up socket.\n";
	error = write_log(server.log, socket_message, sizeof socket_message);
	if (error)
	{
		goto exit0;
	}
	int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
	if (listen_sock < 0)
	{
		error = SOCKET_OPEN_ERROR;
		goto exit0;
	}

	struct sockaddr_in sad;
	memset(&sad, 0, sizeof sad);
	sad.sin_family = AF_INET;
	sad.sin_addr.s_addr = INADDR_ANY;
	sad.sin_port = htons(port);

	if (bind(listen_sock, (struct sockaddr *) &sad, sizeof sad) < 0)
	{
		error = BIND_ERROR;
		goto exit1;
	}

	if (listen(listen_sock, MAX_USERS) < 0)
	{
		error = LISTEN_ERROR;
		goto exit1;
	}

	struct sockaddr_in cad;
	socklen_t clilen = sizeof cad;
	while (1)
	{
		int connection_sock = accept(listen_sock, (struct sockaddr *) &cad, &clilen);
		if (connection_sock < 0)
		{
			char *error_str = get_error_message(ACCEPT_ERROR);
			write_log(server.log, error_str, strlen(error_str));
			printf("%s", error_str);
		}
		else
		{
			char join_message[] = "Client joined.\n";
			write_log(server.log, join_message, sizeof join_message);
			printf("%s", join_message);

			//use calloc to make sure the state flags are all set to 0.
			user_session_t *args = calloc(1, sizeof *args);
			args->command_sock = connection_sock;
			args->server = &server;

			pthread_t thread;
			if (pthread_create(&thread, NULL, client_handler, args) != 0)
			{
				error = send_response(connection_sock, SERVICE_NOT_AVAILABLE, "Could not establish a session.", server.log, 0);

				char *error_str = get_error_message(PTHREAD_CREATE_ERROR);
				write_log(server.log, error_str, strlen(error_str));
				printf("%s", error_str);
			}
			else
				pthread_detach(thread);
		}
	}

	char closing_message[] = "Server closing down.\n";
exit1:
	write_log(server.log, closing_message, sizeof closing_message);
	close(listen_sock);
exit0:
	free_server(&server);
	print_error_message(error);
	return error;
}
Example #11
0
int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        fprintf(stderr, "%s [server name] [log file] ([config file]...)\n", argv[0]);
        return 1;
    }

    set_initial_id(); /*NOTE: must be before log file for su servers*/
    set_log_file(argv[2]);

    /*setup~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    if (!set_program_name(argv[0])) return 1;
    if (!change_server_name(argv[1]))
    {
        fprintf(stderr, "%s: invalid server name '%s'\n", argv[0], argv[1]);
        return 1;
    }

    /*use 'clean_server_exit' below here (after initialization)*/

    if (!initialize_server())
    {
        fprintf(stderr, "%s: couldn't initialize server (check log file)\n", argv[0]);
        clean_server_exit(1);
    }


    /*NOTE: stop using standard error here and use logging only because of daemonizing*/


    start_server();


    int current_pid = getpid();


#ifndef PARAM_NO_DAEMON
    if (getsid(0) != getpid())
    {
        notify_parent = current_pid;

        pid_t daemon = fork();

        if (daemon < 0)
        {
            log_server_daemon_error(strerror(errno));
            fprintf(stderr, "%s: daemon error (check log file)\n", argv[0]);
            clean_server_exit(1);
        }

        if (daemon == 0)
        {
            log_server_daemon(current_pid, getpid());
#ifndef PARAM_NO_SESSION

            if (getpid() == setsid())
                /*NOTE: leave 'getpid' first here in case of error*/
                log_server_session_set();

            else
            {
                log_server_session_error(strerror(errno));
                fprintf(stderr, "%s: session error (check log file)\n", argv[0]);
                clean_server_exit(1);
            }
#else
            setpgid(0, 0);
#endif

            raise(SIGSTOP);
        }

        else
        {
            setpgid(0, 0);

            signal(SIGUSR1, &parent_signal);
            signal(SIGUSR2, &parent_signal);

            int error = 0, status = 0;

            while ( ((error = waitpid(daemon, &status, WUNTRACED)) < 0 && errno == EINTR) ||
                    (!WIFSTOPPED(status) && !WIFEXITED(status)) );

            if (error < 0 || WIFEXITED(status))
            {
                fprintf(stderr, "%s: internal error: %s\n", argv[0],
                        (error < 0)? strerror(errno) : "unknown error");
                partial_server_exit(1);
            }

            kill(daemon, SIGCONT);

            struct timespec register_wait = server_register_all_wait();
            nanosleep(&register_wait, NULL);

            partial_server_exit(1);
        }
    }

    else
        log_server_session_leader();
#endif


    set_env_pid();

    if (set_terminal())
        log_server_terminal();

    set_controlling_pid(getpid());
    /*END setup~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    /*scheduling setup~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    struct sched_param parameters =
    { sched_priority: sched_get_priority_max(SCHED_RR) };
Example #12
0
int
main(int argc, char * argv[])
{
	fd_set	all_fds;		
	fd_set	read_fds;
	int nfds; /* The highest-numbered file descriptor in the set */
	int listener;
	int yes = 1;
	int i, j, rv;
	struct addrinfo hints, *ai, *servIter;
	struct server_info *sInfo;
	unsigned char outBuf[1024];
	unsigned char inBuf[3];
	char playerBuf[1024];
	unsigned char **map;
	int idCount = 0;
    char str[256];
	int sd, n, player_loc;
	socklen_t client_len;
	unsigned char udpbuf[MAX_LEN];
	struct sockaddr_in udpserver, udpclient;
	struct sockaddr_in clientIP[8];
	u_long lttl;

	if(argc != 2)
	{
		printf("Usage: %s [player limit]\n", argv[0]);
		exit(0);
	}
	
	printf("------------------------------\n");
	printf("Tux Bomber v1.0\n");
	printf("Data Comm 0x131B\n");
	printf("April 2009\n");
	printf("------------------------------\n");
	
	expectedClients = atoi(argv[1]);
	playerCount = expectedClients;

	for(i = 0; i < expectedClients; i++)
		player_array[i] = new DPlaya();

    /* Initialize client table */
	for (i = 0; i < expectedClients; i++)
	{
	    memset(&clientIP[i], 0, sizeof(clientIP[i]));
        //clientIP[i].sin_addr.s_addr = 0;
		clientIP[i].sin_family = AF_INET;
		clientIP[i].sin_port = htons(8000);
	}
	 
	FD_ZERO(&all_fds);
	FD_ZERO(&read_fds);
	
	printf("Initializing server settings...");
	
	// initialize server settings
	if(!initialize_server(sInfo))
	{
		perror("ERROR: Unable to initialize server settings!\n");
		exit(1);
	}
	
	printf(" Success!\n");
	
	/* Clear and set family attributes! */
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;

	if((rv = getaddrinfo(NULL, PORT, &hints, &ai)) != 0)
	{
		fprintf(stderr, "server: %s\n", gai_strerror(rv));
		exit(1);
	}

    printf("Creating TCP socket...");
    
	// Set up the listening socket
	for (servIter = ai; servIter != NULL; servIter = servIter->ai_next)
	{
		listener = socket(servIter->ai_family, servIter->ai_socktype, servIter->ai_protocol);
		if (listener < 0)
			continue;
		setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

		/* Close the socket & continue if it's already being used, else bind it */
		if (bind(listener, servIter->ai_addr, servIter->ai_addrlen) < 0)
		{
			close(listener);
			continue;
		}
		
		break;
	}
    
	/* Exit if bind was unsuccessful.  If it was, start listening. */
	if (servIter == NULL)
	{
		fprintf(stderr, "server: failed to bind\n");
		exit(2);
	}

	if (listen(listener, 8) == -1)
	{
		perror("listen");
		exit(3);
	}
	
    printf(" Success!\n");

	/* Add new client to the set of all clients & make it the new nfds  */
	FD_SET(listener, &all_fds);
	nfds = listener;
	
	printf("Generating map...");
	
	map = genRandomMap(17,18);
	
	for(int y = 0; y < 17; y++)
		for(int x = 0; x < 18; x++)
			grid[y][x] = map[y][x];
	
	for (i = 0; i < 17; ++i)
		for (j = 0; j < 18; ++j)
			outBuf[i * 17 + j] = map[i][j];
			
	printf(" Success!\n");
	printf("Waiting for clients...\n");
	
	/* Loop, waiting for client connections until we have all of them. */
	while (idCount < expectedClients)
	{
		read_fds = all_fds;
		if (select(nfds + 1, &read_fds, NULL, NULL, NULL) == -1)
		{
			perror("select");
			exit(4);
		}
		
		/* Check each connection for input */
		for (i = 3; i <= nfds; i++)
		{
			if (FD_ISSET(i, &read_fds))
			{
				if (i == listener) /* New client connection */
				{   
					nfds = new_client(nfds, listener, &all_fds, player_array[idCount], &clientIP[idCount]);
					
					printf("Client %d connected\n", idCount);
					
					if (idCount == 0) 
					{
						player_array[idCount]->setX(35);
						player_array[idCount]->setY(35);
					}
					else if (idCount == 1)
					{
						player_array[idCount]->setX(15 * 35 - 1);
						player_array[idCount]->setY(15 * 35 - 1);
					}
					else if (idCount == 2)
					{
						player_array[idCount]->setX(35);
						player_array[idCount]->setY(15 * 35 - 1);
					}
					else if (idCount == 3)
					{
						player_array[idCount]->setX(15 * 35 - 1);
						player_array[idCount]->setY(35);
					}
					sprintf(str, "resources/img/models/in_game/%d.png\0", idCount);
					player_array[idCount]->setImageName(str);
					player_array[idCount]->setID(idCount);
					player_array[idCount]->setNumBombs(5);
					idCount++;
					
					break;
				}
			}
		}
	}
	
	printf("Sending out map and client information...");
	
	for (j = 3; j <= nfds; j++)
	{
		if (FD_ISSET(j, &all_fds))
		{
			if(j == listener)
				continue;

			if (send(j, outBuf, MAX_LEN, 0) == -1)
				perror("send");
		}
	}
	
	for (j = 3; j <= nfds; j++)
	{
		if (FD_ISSET(j, &all_fds))
		{
			if(j == listener)
				continue;

			if (send(j, argv[1], 1024, 0) == -1)
				perror("send");
		}
	}
	
	/* Copy all players and send them out */
	for(i = 0; i < expectedClients; i++)
	{
		memcpy(playerBuf, player_array[i], 1024);
		
		for(j = 3; j <= nfds; j++)
		{
			if(FD_ISSET(j, &all_fds))
			{
				if(j == listener)
					continue;
				if(send(j, playerBuf, MAX_LEN, 0) == -1)
					perror("send");
			}
		}
	}
	
	printf(" Success!\n");
	printf("Creating UDP socket...");
	
	/* Create udp listen socket */
	if((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
	{
		perror("Socket Creation");
		exit(EXIT_FAILURE);
	}

    /* initialize sockaddr struct */
	bzero((char *)&udpserver, sizeof(udpserver));
	udpserver.sin_family = AF_INET;
	udpserver.sin_port = htons(8000);
	udpserver.sin_addr.s_addr = htonl(INADDR_ANY);

    /* bind socket to address */
	if(bind(sd, (struct sockaddr *)&udpserver, sizeof(udpserver)) == -1)
	{
		perror("Binding Socket");
		exit(EXIT_FAILURE);
	}
	
	/* create what looks like an ordinary UDP socket */
    if ((fd=socket(AF_INET,SOCK_DGRAM,0)) < 0) {
        perror("socket");
        exit(1);
    }
    
    /* set up destination address */
    memset(&addr,0,sizeof(addr));
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=inet_addr(MULTI_ADDR);
    addr.sin_port=htons(MULTI_PORT);
    
    lttl = 10;
    
    setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, (char *)lttl, sizeof(lttl));
    
    printf(" Success!\n");
	
	printf("Starting game. HAVE FUN! :D\n");
	/*********************** GAME STARTED HERE! ************************/
	while(playerCount > 1) 
	{
	    memset(udpbuf, 0, sizeof(udpbuf));
	    memset(outBuf, 0, sizeof(outBuf));
	    client_len = sizeof(udpclient);

		/* listen for connection */
	    if((n = recvfrom(sd, inBuf, 3, 0, (struct sockaddr *)&udpclient, &client_len)) <= 0)
	    {
	        /* socket closed */
			if(n == 0)
			{
				fprintf(stderr,"Connection closed on socket: %d\n", sd);
				continue;
			}
			else /* error */
			{
				perror("Recv From");
				exit(EXIT_FAILURE);
			}
	    }

        if((player_loc = get_player_loc(udpclient.sin_addr.s_addr)) >= 0 && player_loc < MAX_PLAYERS)
        {
            clientIP[player_loc].sin_port = udpclient.sin_port;
        
		    if(inBuf[0] - '0'== MOVE_UP)
			player_array[player_loc]->move(grid, MOVE_UP);
		    else if(inBuf[0] - '0' == MOVE_DOWN) 
			player_array[player_loc]->move(grid, MOVE_DOWN);
		    else if(inBuf[0] - '0' == MOVE_RIGHT)
			player_array[player_loc]->move(grid, MOVE_RIGHT);
		    else if(inBuf[0] - '0' == MOVE_LEFT)
			player_array[player_loc]->move(grid, MOVE_LEFT);
		    else if(inBuf[0] - '0' == PLANT_BOMB)
			plant_bomb(player_loc);
		   
		    outBuf[0] = 'P';
		    outBuf[1] = 'P';
		    
		    memcpy(outBuf + 2, player_array[player_loc], 1024);
		    
	        if (sendto(fd,outBuf,sizeof(outBuf),0,(struct sockaddr *) &addr, sizeof(addr)) < 0) {
	            perror("sendto");
	            exit(1);
	        }
    	}
	}
	
    outBuf[0] = 'G';

    if (sendto(fd,outBuf,sizeof(outBuf),0,(struct sockaddr *) &addr, sizeof(addr)) < 0) {
        perror("sendto");
        exit(1);
    }
    sleep(2);
    shutdown(fd, 2);
    close(fd);
    
	printf("Game over!\n");
	
	free(map);

	return 0;
}
Example #13
0
int main(int argc, char *argv[]){

	//Check if valid format
	if(argc != 4){
		printf("\n\nUsage: ./server <certificate> <key> <port number>\n\n");
		exit(1);
	}

	//Initialization
	SSL_CTX *ctx;
	int server;
	char *port;
	SSL_library_init();

	//Get the port from the argument
	port = argv[3];

	//Initialize the OpenSSL (page 1)
	ctx = initialize_server();

	//Load and validate the certificate and key (page 1)
	if(SSL_CTX_use_certificate_file(ctx, argv[1], SSL_FILETYPE_PEM) <= 0){
		printf("\n\nERROR: SSL_CTX_use_certificate_file failed (server.c - main)\n");
		printf("Could not find the certificate file.\n\n");
		exit(1);
	}
	if(SSL_CTX_use_PrivateKey_file(ctx,  argv[2], SSL_FILETYPE_PEM) <= 0){
		printf("\n\nERROR: SSL_CTX_use_PrivateKey_file failed (server.c - main)\n");
		printf("Could not find the private key file or incorrect key.\n\n");
		exit(1);
	}
	if(!SSL_CTX_check_private_key(ctx)){
		printf("\n\nERROR: SSL_CTX_check_private_key failed (server.c -main)\n");
		printf("Private key does not match the public certificate\n\n");
		exit(1);
	}	

	//create server socket
	server = server_socket(atoi(port));	

	//Continue listening
	while(1){
		struct sockaddr_in addr;
		socklen_t addrLen = sizeof(addr);
		SSL *ssl;

		//If client connects
		int client = accept(server, (struct sockaddr*) &addr, &addrLen);
		if(client < 0){
			printf("\n\nERROR: accept() failed (server.c - main).\n\n");
			printf("Couldn't create socket.\n\n");
			exit(1);
		}

		//creates a new SSL structure to hold the data for SSL connection
		ssl = SSL_new(ctx);
		if(ssl == NULL){
			printf("\n\nERROR: SSL_new() failed (server.c - main).\n\n");
			printf("Couldn't create new SSL structure.\n\n");
			exit(1);
		}

		//Sets the file descriptor client as the input/output facility for the SSL (encrypted) side of ssl
		SSL_set_fd(ssl, client);

		//Start talking
		ssl_handshake(ssl);	
	}

	//close and exit
	close(server);	
	SSL_CTX_free(ctx);
	return 0;
}
Example #14
0
int main(int argc, char* argv[]){
  //Pass in config file by using cmdline args
	if(argc > 1){
    //initialize variables for file read
    char *path = argv[1];
    int bytes_read, fd, i;
    char *file_type;
  	char *send_data = malloc(BUFFER_SIZE);

  	for(i = 0; i < MAX_SUPPORTED_FILE_TYPES; i++){
  		supported_file_types[i] = "";
  	}

    int n = 0;
    //Open the file
  	if((fd = open(path, O_RDONLY))!=-1){
      //Read from the file and store in send_data
  		 while((bytes_read = read(fd, send_data, BUFFER_SIZE)) > 0){
         //create tokens
  		 	char *tok = strtok(send_data, " \t\n");
  		 	while(tok != NULL){
           //Save the PORT number
  		 		if(strcmp(tok, "Listen") == 0){
  		 			tok = strtok(NULL, " \t\n");
  		 			PORT = tok;
  		 		}
           //Save the file extentions from the config file
  		 		else if(tok[0] == '.'){
  		 			char tok_copy[strlen(tok)];
            strcpy(tok_copy, tok);

  		 			char file_ext[strlen(tok) - 1];
  		 			int i, j;

  		 			for(i = 1, j = 0;i < strlen(tok);i++, j++){
  		 				file_ext[j] = tok_copy[i];
  		 			}

  		 			file_type = file_ext;
  		 			supported_file_types[n] = file_type;
  		 			n++;
  		 		}

  		 		tok = strtok(NULL, " \t\n");
  		 	}
  		 }
  	}
    //Exit if there is no config file found
  	else{
  		printf("Not Found: Configuration File\n");
  		exit(EXIT_FAILURE);
  	}

    //After Config file is processed,
    //initialize the server
		initialize_server(PORT);

    //exit with success
		return 0;
	}
  //if there are no cmdline args, give the user instructions
	else{
		printf("Run Command: ./server <input user config file>\n");
	}
}