Exemple #1
0
int	check_lvl_up(t_desc *serv, t_play *player)
{
  int	id;
  t_map	*tmp;

  tmp = serv->map;
  id = 0;
  while (tmp && id == 0)
    {
      if ((tmp->x == player->x) && (tmp->y == player->y))
	id = 1;
      else
	tmp = tmp->next;
    }
  id = player->lvl - 1;
  if (tmp && (cmp_ressources(levels[id], tmp->res) == 0) &&
      get_players_on_map(serv->players, player->x, player->y) == levels[id][6])
    {
      add_sto_buffer(serv, "elevation en cours\n");
      write_to_client(serv, player->cs);
      return (0);
    }
  else
    {
      add_sto_buffer(serv, "ko\n");
      write_to_client(serv, player->cs);
      return (-1);
    }
}
Exemple #2
0
void		ft_msg(char *buff, t_client *client, t_server *server)
{
	int		i;
	char	**tmp;
	char	*message;

	tmp = ft_strsplit(buff, ' ');
	i = 0;
	if (tmp[3])
	{
		write_to_client(client->sock, "Usage : /msg <name> <message>");
		return ;
	}
	while (i < MAX_CLIENTS)
	{
		if (server->clients[i].name != NULL
			&& ft_strcmp(tmp[1], server->clients[i].name) == 0)
		{
			message = ft_strdup(tmp[2]);
			message = ft_strjoin(client->name, " : ");
			message = ft_strjoin(message, tmp[2]);
			write_to_client(server->clients[i].sock, message);
			free(message);
		}
		i++;
	}
}
Exemple #3
0
int		handle_client(t_selfd *fd, t_server *serv)
{
  char		*cmd;
  int		r;
  ssize_t      	swr;

  if (ISREADABLE(fd))
    {
      if (((r = read_from_client(fd)) < 0 && errno != EINTR) || (r == 0))
        {
          log_connection(((t_client *)fd->data)->sock,
                         "Client disconnected from:");
          return (destroy_connection(serv, fd));
        }
    }
  if (ISWRITEABLE(fd) && (r = write_to_client(fd)) < 0 && errno != EINTR)
    return (destroy_connection(serv, fd));
  while ((cmd = get_command(fd)))
    handle_add_cmd(serv, fd, cmd);
  swr = ring_buffer_left_read(fd->wbuff);
  if (!swr && fd->to_close)
    return (destroy_connection(serv, fd));
  if (swr)
    CHECKWRITE(fd);
  CHECKREAD(fd);
  push_instruction(serv, fd);
  return (0);
}
int		new_clients(t_server *server, int *actual_client, char *buff)
{
	int					cs;
	unsigned int		cslen;
	struct sockaddr_in	csin;

	cs = accept(server->sock, (struct sockaddr *)&csin, &cslen);
	if (cs == -1)
	{
		ft_putstr("Error: accept, new_clients\n");
		exit(-1);
	}
	if (read_to_client(cs, buff) == -1)
		return (-1);
	while (check_name(server, buff) == -1)
	{
		write_to_client(cs, "Name is already used !");
		if (read_to_client(cs, buff) == -1)
			return (-1);
	}
	FD_SET(cs, &(server->groupfd));
	server->max = cs > server->max ? cs : server->max;
	define_client(server, actual_client, buff, cs);
	(*actual_client)++;
	return (cs);
}
Exemple #5
0
void		lvl_up(t_desc *serv, t_play *player, t_env *e, char **cmd)
{
  int		id;
  t_map		*tmp;

  tmp = serv->map;
  id = 0;
  if (e->team && cmd[0])
    while (tmp && id == 0)
      {
	if ((tmp->x == player->x) && (tmp->y == player->y))
	  id = 1;
	else
	  tmp = tmp->next;
      }
  id = player->lvl - 1;
  if (tmp && (cmp_ressources(levels[id], tmp->res) == 0) &&
      get_players_on_map(serv->players, player->x, player->y) == levels[id][6])
    {
      player->lvl++;
      add_sto_buffer(serv, "niveau actuel : ");
      add_nto_buffer(serv, player->lvl);
      add_cto_buffer(serv, '\n');
    }
  else
    add_sto_buffer(serv, "ko\n");
  write_to_client(serv, player->cs);
}
Exemple #6
0
apr_status_t serf__process_client(serf_incoming_t *client, apr_int16_t events)
{
    apr_status_t rv;
    if ((events & APR_POLLIN) != 0) {
        rv = read_from_client(client);
        if (rv) {
            return rv;
        }
    }

    if ((events & APR_POLLHUP) != 0) {
        return APR_ECONNRESET;
    }

    if ((events & APR_POLLERR) != 0) {
        return APR_EGENERAL;
    }

    if ((events & APR_POLLOUT) != 0) {
        rv = write_to_client(client);
        if (rv) {
            return rv;
        }
    }

    return APR_SUCCESS;
}
void		add_channel(char *name, t_client *client)
{
	int		i;

	i = 0;
	while (client->channel[i])
		i++;
	if (client->n_channel + 1 == MAX_CHANNEL)
	{
		write_to_client(client->sock, "/join => limit of channel !");
		return ;
	}
	client->channel[i] = ft_strdup(name);
	client->n_channel++;
	write_to_client(client->sock, "channel join !");
}
Exemple #8
0
void session::on_http2_connect_server(const boost::system::error_code& error, tcp::resolver::iterator endpoint_iterator)
{
	if (error)
	{
		BOOST_LOG_TRIVIAL(debug) << "[" << session_id << "] " << error.message();
		BOOST_LOG_TRIVIAL(error) << "[" << session_id << "] open " << endpoint_iterator->host_name() << " fail";

		stop();
		return;
	}

	BOOST_LOG_TRIVIAL(debug) << "[" << session_id << "] open " << endpoint_iterator->host_name();

	std::string ack = "HTTP/1.1 200 Connection Established\r\n\r\n";
	write_to_client(ack.c_str(), ack.size(), true);

	boost::asio::streambuf::mutable_buffers_type buf = read_client_buf.prepare(SOCKET_RECV_BUF_LEN);
	client_socket.async_read_some(buf,
		strand_.wrap(
			boost::bind(&session::on_read_client_data, shared_from_this(),
				boost::asio::placeholders::error,
				boost::asio::placeholders::bytes_transferred
			)
		)
	);

	server_socket.async_read_some(boost::asio::buffer(server_buf, SOCKET_RECV_BUF_LEN),
		strand_.wrap(boost::bind(&session::on_read_server_data, shared_from_this(),
			boost::asio::placeholders::error,
			boost::asio::placeholders::bytes_transferred)
		)
	);
}
void print_header(int sock, int number_of_threads, long file_size){
	char n_threads_string[255], file_size_string[255];
	sprintf(n_threads_string, "%d\n", number_of_threads);
	sprintf(file_size_string, "%lu\n", file_size);
	int size = strlen(n_threads_string) + strlen(file_size_string);
	char *header = malloc(size*sizeof(char));
	strcat(header, n_threads_string);
	strcat(header, file_size_string);
	write_to_client(sock, header, size);
	fprintf(stderr, "%s\n", header);
	free(header);
}
Exemple #10
0
void		ft_nick(char *buff, t_client *client, t_server *server)
{
	char		**tmp;

	tmp = ft_strsplit(buff, ' ');
	if (check_name(server, tmp[1]) == -1)
	{
		write_to_client(client->sock, "/nick => name is already used !\n");
		return ;
	}
	free(client->name);
	client->name = ft_strdup(tmp[1]);
}
Exemple #11
0
void	send_to_all(t_server *server, t_client client,
	int *actual_client, char *buff)
{
	int		i;

	i = 0;
	while (i < *actual_client)
	{
		if (client.sock != server->clients[i].sock)
			write_to_client(server->clients[i].sock, buff);
		i++;
	}
}
Exemple #12
0
void		ft_who(char *buff, t_client *client, t_server *server)
{
	int		i;

	(void)buff;
	i = 0;
	while (i < MAX_CLIENTS)
	{
		if (server->clients[i].name != NULL
			&& server->clients[i].n_channel == client->n_channel
			&& ft_strcmp(client->name, server->clients[i].name) != 0)
		{
			write_to_client(client->sock, server->clients[i].name);
		}
		i++;
	}
}
Exemple #13
0
void		ft_leave(char *buff, t_client *client, t_server *server)
{
	int		i;

	(void)server;
	i = 0;
	if (ft_strlen(buff) > 6)
	{
		delete_channel(buff, client);
	}
	else
	{
		while (i < MAX_CHANNEL)
			client->channel[i++] = NULL;
		client->n_channel = 0;
		write_to_client(client->sock, "leave with success !");
	}
}
void	define_client(t_server *server, int *actual_client, char *buff, int cs)
{
	int		i;
	char	*welcome;

	i = 0;
	server->clients[(*actual_client)].sock = cs;
	server->clients[(*actual_client)].name = ft_strdup(buff);
	server->clients[(*actual_client)].n_channel = 0;
	while (i < MAX_CHANNEL)
	{
		server->clients[(*actual_client)].channel[i] = NULL;
		i++;
	}
	welcome = ft_strjoin("Welcome #", server->clients[(*actual_client)].name);
	write_to_client(server->clients[(*actual_client)].sock, welcome);
	ft_putstr("Welcome #");
	ft_putendl(server->clients[(*actual_client)].name);
}
Exemple #15
0
void	send_to_by_channel(t_server *server, t_client client,
	int *actual_client, char *buff)
{
	int		i;
	char	*message;

	i = 0;
	message = ft_strdup(buff);
	message = ft_strjoin(client.name, " : ");
	message = ft_strjoin(message, buff);
	while (i < *actual_client)
	{
		if (client.sock != server->clients[i].sock
			&& client.n_channel == server->clients[i].n_channel)
		{
			write_to_client(server->clients[i].sock, message);
		}
		i++;
	}
}
Exemple #16
0
void	check_fdset(fd_set *rfds, fd_set *wfds, t_mgs_context *context)
{
  t_mgs_client	*tmp;

  if (FD_ISSET(context->fd, rfds))
    accept_mgs_new_client(context);
  tmp = context->clients;
  while (tmp)
    {
      if (tmp->fd >= 0)
	{
	  if (FD_ISSET(tmp->fd, rfds))
	    if (read_from_client(tmp))
	      return ;
	  if (tmp->buffout != NULL && FD_ISSET(tmp->fd, wfds))
	    write_to_client(tmp);
	}
      tmp = tmp->next;
    }
  return ;
}
Exemple #17
0
void		connect_nbr(t_desc *serv, t_play *player, t_env *e, char **cmd)
{
  t_team	*tmp;
  int		flag;

  flag = 0;
  tmp = e->team;
  if (cmd[0] && serv->map)
    {
      while (tmp && (flag == 0))
	{
	  if (my_strcmp(player->team, tmp->name) == 0)
	    {
	      add_nto_buffer(serv, tmp->place);
	      add_cto_buffer(serv, '\n');
	      flag = 1;
	    }
	  tmp = tmp->next;
	}
      write_to_client(serv, player->cs);
    }
}
void		delete_channel(char *buff, t_client *client)
{
	int		i;
	char	**tmp;

	tmp = ft_strsplit(buff, ' ');
	i = 0;
	while (i < MAX_CHANNEL)
	{
		if (client->channel[i] && tmp[1])
		{
			if (ft_strcmp(client->channel[i], tmp[1]) == 0)
			{
				client->channel[i] = NULL;
				client->n_channel--;
				write_to_client(client->sock, "leave with success !");
				return ;
			}
		}
		i++;
	}
}
Exemple #19
0
void
free_node(char *nodename)
{
    int sock;
    char *buf;
    struct sockaddr_in name;
    struct hostent *hostinfo;

    /* create socket */
    sock = socket(PF_INET, SOCK_STREAM, 0);
    if (sock < 0)
	bailout();

    name.sin_family = AF_INET;
    name.sin_port = htons(iportnum);
    hostinfo = gethostbyname(jsd_host);

    if (hostinfo == NULL) {
	(void)fprintf(stderr, "Unknown host %s.\n", jsd_host);
	exit(EXIT_FAILURE);
    }

    name.sin_addr = *(struct in_addr *)hostinfo->h_addr;

    if (connect(sock, (struct sockaddr *)&name, sizeof(name)) < 0)
	bailout();

    if (debug)
	printf("Freeing node %s\n", nodename);
    read_from_client(sock, &buf);
    /* we just ignore the contents, so free it */
    free(buf);
    if (write_to_client(sock, nodename) != 0)
	bailout();
    if (debug)
	printf("freed node %s\n", nodename);
    (void)close(sock);
}
Exemple #20
0
void		ft_join(char *buff, t_client *client, t_server *server)
{
	int		i;
	char	**tmp;

	(void)server;
	tmp = ft_strsplit(buff, ' ');
	i = 0;
	while (i < MAX_CHANNEL)
	{
		if (client->channel[i] && tmp[1])
		{
			if (ft_strcmp(client->channel[i], tmp[1]) == 0)
			{
				write_to_client(client->sock,
					"/join => channel already joined !");
				return ;
			}
		}
		i++;
	}
	add_channel(tmp[1], client);
}
Exemple #21
0
/* send error msg to client in case the input msg could not be parsed */
int notify_parse_error(command_t *cmd, char *input)
{
    /* lookup client */
    client_data_t *client = registration_lookup(cmd->key);

    if(client == NULL) {
        fprintf(stderr, "Error -- no client found\n");
        return -1;
    }


    if(cmd->answer_exp) {
        char buffer[BABBLE_BUFFER_SIZE];

        snprintf(buffer, BABBLE_BUFFER_SIZE,"%s[%ld]: ERROR -> %s\n", client->client_name, time(NULL)-server_start, input);

        if(write_to_client(cmd->key, strlen(buffer)+1, buffer)) {
            fprintf(stderr,"Error -- could not send error msg: %s\n", buffer);
            return -1;
        }
    }

    return 0;
}
Exemple #22
0
void parseMessage (struct team *teams, int nbTeams, int sendingTeam, const unsigned char *buf, int nbbytes) {
    debug (KNRM, "[");
    debug (COL(sendingTeam),"%" STR(MAXNAMESIZE) "s", teams[sendingTeam].name);
    debug (KNRM, "] ");

    if (nbbytes < 5) {
        debug (KRED, "*** header is too short (%d bytes) ***\n", nbbytes);
        return;
    }

    if (buf[2] != sendingTeam) {
        debug (KRED, "*** mediocre spoofing attempt detected ***\n");
        return;
    }

    if (buf[3] >= nbTeams || !teams[buf[3]].active) {
        debug (KRED, "*** unkown or inactive receiver (%d) ***\n", buf[3]);
        return;
    }

    if (!teams[buf[3]].connected) {
        debug (KRED, "*** Team ");
        debug (COL(buf[3]), "%s", teams[buf[3]].name);
        debug (KRED, " is not connected. Message discarded ***\n");
        return;
    }

    uint16_t id = *((uint16_t *) buf);

    switch (buf[4]) {
        case MSG_ACTION:
            // ACTION
            if (nbbytes < 10) {
                debug (KRED, "*** ACTION message is too short (%d bytes) ***\n", nbbytes);
                return;
            }

            if (teams[buf[3]].rank != teams[sendingTeam].rank+1) {
                debug (KRED, "*** Can't send ACTION message to team ");
                debug (COL(buf[3]), "%s", teams[buf[3]].name);
                debug (KRED, " ***\n");
                return;
            }

            uint16_t angle = *((uint16_t *) &buf[5]);
            uint16_t speed = *((uint16_t *) &buf[8]);

            debug (KNRM, "id=%d dest=", id);
            debug (COL(buf[3]), "%s\n", teams[buf[3]].name);
            debug (KNRM, "         ACTION   angle=%d dist=%d speed=%d\n", angle, buf[7], speed);

            write_to_client (&teams[buf[3]], (char *) buf, 10);

            break;
        case MSG_ACK:
            // ACK
            if (nbbytes < 8) {
                debug (KRED, "*** ACK message is too short (%d bytes) ***\n", nbbytes);
                return;
            }

            if (teams[buf[3]].rank != teams[sendingTeam].rank+1 && teams[buf[3]].rank != teams[sendingTeam].rank-1) {
                debug (KRED, "*** Can't send ACK message to team ");
                debug (COL(buf[3]), "%s", teams[buf[3]].name);
                debug (KRED, " ***\n");
                return;
            }

            uint16_t idAck = *((uint16_t *) &buf[5]);

            debug (KNRM, "id=%d dest=", id);
            debug (COL(buf[3]), "%s\n", teams[buf[3]].name);
            debug (KNRM, "          ACK      idAck=%d status=%d\n", idAck, buf[7]);

            write_to_client (&teams[buf[3]], (char *) buf, 8);

            break;
        case MSG_LEAD:
            // LEAD
            if (teams[buf[3]].rank != teams[sendingTeam].rank+1) {
                debug (KRED, "*** Can't send LEAD message to team ");
                debug (COL(buf[3]), "%s", teams[buf[3]].name);
                debug (KRED, " ***\n");
                return;
            }

            debug (KNRM, "id=%d dest=", id);
            debug (COL(buf[3]), "%s\n", teams[buf[3]].name);
            debug (KNRM, "          LEAD\n");

            write_to_client (&teams[buf[3]], (char *) buf, 5);

            break;
        case MSG_START:
            // START
            debug (KRED, "*** Tried to START the game ***\n");
            return;
        case MSG_STOP:
            // STOP
            debug (KRED, "*** Tried to STOP the game ***\n");
            return;
        case MSG_WAIT:
            // WAIT
            if (nbbytes < 6) {
                debug (KRED, "*** WAIT message is too short (%d bytes) ***\n", nbbytes);
                return;
            }

            if (teams[buf[3]].rank != teams[sendingTeam].rank-1) {
                debug (KRED, "*** Can't send WAIT message to team ");
                debug (COL(buf[3]), "%s", teams[buf[3]].name);
                debug (KRED, " ***\n");
                return;
            }

            debug (KNRM, "id=%d dest=", id);
            debug (COL(buf[3]), "%s\n", teams[buf[3]].name);
            debug (KNRM, "          WAIT     seconds=%d\n", buf[5]);

            write_to_client (&teams[buf[3]], (char *) buf, 6);

            break;
        case MSG_CUSTOM:
            // CUSTOM
            if (teams[buf[3]].rank != teams[sendingTeam].rank+1 && teams[buf[3]].rank != teams[sendingTeam].rank-1) {
                debug (KRED, "*** Can't send CUSTOM message to team ");
                debug (COL(buf[3]), "%s", teams[buf[3]].name);
                debug (KRED, " ***\n");
                return;
            }

            debug (KNRM, "id=%d dest=", id);
            debug (COL(buf[3]), "%s\n", teams[buf[3]].name);
            debug (KNRM, "          CUSTOM   content=");
            int i;
            for (i=5; i<nbbytes; i++) {
                debug (KNRM, "%02X", (unsigned char) buf[i]);
                if ((i-5) % 4 == 3)
                    debug (KNRM, " ");
            }
            debug (KNRM, "\n");

            write_to_client (&teams[buf[3]], (char *) buf, nbbytes);

            break;
        default:
            debug (KRED, "*** unkown message type 0x%02X ***\n", (unsigned char) buf[4]);
            return;
    }
}
void print_init_transmission(int sock){
	char init[] = "init";
	write_to_client(sock, init, strlen(init));
}
Exemple #24
0
int main (int argc, char **argv) {

    struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
    int serverSock, fdmax, i;
    socklen_t opt = sizeof(rem_addr);
    fd_set read_fd_set;

    char buf[MAXMSG+1] = { 0 };

    struct team teams [MAXTEAM];
    memset(teams, 0, MAXTEAM * sizeof(struct team));

    if (argc < 2 || argc > 3) {
        fprintf (stderr, "Usage: %s teamFile [ouputFile]\n", argv[0]);
        exit (EXIT_FAILURE);
    }

    if (argc == 3) {
        out = fopen (argv[2], "w");
        
        if (out == NULL) {
            fprintf (stderr, "Could not open file %s.\n", argv[2]);
            exit (EXIT_FAILURE);
        }
    }

    srand(time(NULL));

    printf ("\n\n");
    printf (KRED    "                                           )  (      (                            \n");
    printf (        "                                        ( /(  )\\ )   )\\ )                         \n");
    printf (        "       (     (  (     (           )     )\\())(()/(  (()/(   (  (    )     (  (    \n");
    printf (        "       )\\   ))\\ )(   ))\\ (  (    (     ((_)\\  /(_))  /(_)) ))\\ )(  /((   ))\\ )(   \n");
    printf (        "      ((_) /((_|()\\ /((_))\\ )\\   )\\  '   ((_)(_))   (_))  /((_|()\\(_))\\ /((_|()\\  \n");
    printf (RESET   "      | __" KRED "(_))( ((_|_)) ((_|(_)_((_))   " RESET "/ _ \\/ __|  / __|" KRED "(_))  ((_))((_|_))  ((_) \n");
    printf (RESET   "      | _|| || | '_/ -_) _/ _ \\ '  \\" KRED "() " RESET "| (_) \\__ \\  \\__ \\/ -_)| '_\\ V // -_)| '_| \n");
    printf (        "      |___|\\_,_|_| \\___\\__\\___/_|_|_|   \\___/|___/  |___/\\___||_|  \\_/ \\___||_|  \n");
    printf ("\n\n");

    // create server socket
    printf ("Creating server socket...                                                    ");
    fflush (stdout);
    serverSock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

    // bind socket to port 1 of the first available local bluetooth adapter
    loc_addr.rc_family = AF_BLUETOOTH;
    loc_addr.rc_bdaddr = *BDADDR_ANY;
    loc_addr.rc_channel = (uint8_t) 1;
    bind(serverSock, (struct sockaddr *) &loc_addr, sizeof (loc_addr)); 

    // put socket into listening mode
    listen(serverSock, MAXTEAM);
    printf ("[" KGRN "OK" RESET "]\n");

    // load teams from file
    int nbTeams = load_teams_file (argv[1], teams, MAXTEAM);
    debug (KNRM, "  ... %d teams have been loaded...\n", nbTeams);

    // connect to server
    connect(teams[0].sock, (struct sockaddr *)&rem_addr, sizeof(rem_addr));

    // catch SIGINT to stop game
    if (signal (SIGINT, intHandler) == SIG_ERR) {
        fprintf (stderr, "Couldn't catch SIGINT.\n");
        exit (EXIT_FAILURE);
    }

    // start the contest
    while (running) {

        // print all teams
        printf ("   +--------------------------------------------+\n");
        printf ("   |" KRED " TEAMS " RESET "                                     |\n");
        printf ("   +--------------------------------------------+\n");
        for (i=0; i<nbTeams; i++)
            if (teams[i].robotType != RBT_MISS)
                printf ("   | %2d: %s%-" STR(MAXNAMESIZE) "s " RESET " (%3s) |\n", 
                        i,
                        COL(i),
                        teams[i].name,
                        teams[i].robotType == RBT_EV3 ? "EV3" : "NXT");
        printf ("   +--------------------------------------------+\n");

        // prompt for game composition
        printf ("Which teams are going to participate? (^D to end the contest)\n");

        char invalidInput;
        int rankCmp;

        do {
            for (i=0; i<nbTeams; i++) {
                teams[i].active = 0;
                teams[i].rank = 0;
                if (teams[i].robotType == RBT_NXT) {
                    teams[i].mailbox->messagesReady = 0;
                    teams[i].mailbox->nextMessage = 0;
                }
            }

            invalidInput = 0;

            printf ("> ");
            fflush (stdout);
            char *p = fgets (buf, MAXTEAM * 3 + 2, stdin);

            if (p == NULL)
                running = 0;
            else {
                rankCmp = 0;
                // get participating teams
                for (i=-1; *p && *p != '\n'; p++) {
                    if (*p == ' ') {
                        if (i != -1) {
                            if (i < nbTeams && teams[i].robotType != RBT_MISS && !teams[i].active) {
                                teams[i].active = 1;
                                teams[i].rank = rankCmp++;
                            } else {
                                invalidInput = 1;
                                printf ("Invalid team number: %d\n", i);
                            }
                            i = -1;
                        }
                    } else {
                        if (*p < '0' || *p > '9') {
                            invalidInput = 1;
                            printf ("Invalid input number: '%c'\n", *p);
                            break;
                        }

                        if (i == -1)
                            i = *p - '0';
                        else
                            i = i*10 + *p - '0';
                    }
                }

                if (i != -1) {
                    if (i < nbTeams && teams[i].robotType != RBT_MISS && !teams[i].active) {
                        teams[i].active = 1;
                        teams[i].rank = rankCmp++;
                    } else {
                        invalidInput = 1;
                        printf ("Invalid team number: %d\n", i);
                    }
                }

                if (rankCmp == 0)
                    invalidInput = 1;
            }
        } while (invalidInput);

        if (running) {
            int rep = 0;
            while (rep != '0') {
                printf ("Rank is:\n");
                int j;
                for (i=0; i<rankCmp; i++)
                    for (j=0; j<nbTeams; j++)
                        if (teams[j].active && teams[j].rank == i) {
                            printf ("%d: %s%s" RESET "\n", i, COL(j), teams[j].name);
                            break;
                        }
                printf ("What do you want to do?   (default: 0)\n");
                printf ("      0: keep that\n");
                printf ("      1: randomize all\n");
                printf ("      2: randomize all but leader\n");
                printf ("> ");
                fflush (stdout);
                char *p = fgets (buf, 2, stdin);
                if (p == NULL || buf[0] == '\n')
                    break;
                if (p[0] < '0' || p[0] > '2')
                    continue;

                rep = p[0];

                if (rep == '1') {
                    for (i=0; i<nbTeams; i++)
                        if (teams[i].active) {
                            char found;
                            unsigned char rnd;
                            do {
                                rnd = (unsigned char) (rand () % rankCmp);
                                found = 0;
                                for (j=0; j<i; j++)
                                    if (teams[j].active && teams[j].rank == rnd) {
                                        found = 1;
                                        break;
                                    }
                            } while (found);

                            teams[i].rank = rnd;
                        }
                } else if (rep == '2') {
                    for (i=0; i<nbTeams; i++)
                        if (teams[i].active && teams[i].rank != 0) {
                            char found;
                            unsigned char rnd;
                            do {
                                rnd = (unsigned char) (rand () % (rankCmp-1)) + 1;
                                found = 0;
                                for (j=0; j<i; j++)
                                    if (teams[j].active && teams[j].rank == rnd) {
                                        found = 1;
                                        break;
                                    }
                            } while (found);

                            teams[i].rank = rnd;
                        }
                }
            }

            debug (KRED, "Starting game with teams ");
            int j;
            for (i=0; i<rankCmp; i++)
                for (j=0; j<nbTeams; j++)
                    if (teams[j].active && teams[j].rank == i) {
                        if (i != 0)
                            debug (KRED, ", ");
                        debug (COL(j), "%s", teams[j].name);
                        break;
                    }
            debug (KRED, ".\n");
        } else
            break;

        time_t startTime = time (NULL) + CONNECT_DELAY;
        char state = GAM_CONNECTING;

        while (running) {

            fdmax = serverSock;
            FD_ZERO (&read_fd_set);
            FD_SET (serverSock, &read_fd_set);

            for (i=0; i<nbTeams; i++)
                if (teams[i].connected) {
                    FD_SET (teams[i].sock, &read_fd_set);
                    if (teams[i].sock > fdmax)
                        fdmax = teams[i].sock;
                }

            int selectRet;
            time_t now = time (NULL);

            if (now >= startTime && state == GAM_CONNECTING) {
                printf (KRED "Game starts NOW !\n" RESET);

                buf[0] = 0x00;                      // ID of start message
                buf[1] = 0x00;                      // is 0000
                buf[2] = 0xFF;                      // server ID is 0xFF
                buf[4] = MSG_START;                 // This is a START message
                buf[6] = (char) (0xFF & rankCmp);   // length of the snake

                char first = 1;
                for (i=0; i<nbTeams; i++) {
                    if (teams[i].active) {
                        if (teams[i].connected) {
                            buf[3] = (char) (0xFF & i);             // receiver
                            buf[5] = teams[i].rank;                 // rank
                            buf[7] = 0xFF;
                            buf[8] = 0xFF;
                            int j;
                            for (j=0; j<nbTeams; j++)
                                if (teams[j].active) {
                                    if (teams[j].rank == teams[i].rank - 1)
                                        buf[7] = (char) (0xFF & j); // previous
                                    if (teams[j].rank == teams[i].rank + 1)
                                        buf[8] = (char) (0xFF & j); // next
                                }

                            write_to_client (&teams[i], buf, 9);
                        } else {
                            if (first)
                                first = 0;
                            else
                                printf (KRED ", " RESET);
                            printf ("%s%s" RESET, COL(i), teams[i].name);
                        }
                    }
                }

                if (!first)
                    printf (KRED " failed to connect.\n" RESET);

                state = GAM_RUNNING;
            }
            
            if (now < startTime) {
                struct timeval tv;
                tv.tv_sec = startTime - now;
                tv.tv_usec = 0;
                selectRet = select (fdmax+1, &read_fd_set, NULL, NULL, &tv);
            } else
                selectRet = select (fdmax+1, &read_fd_set, NULL, NULL, NULL);

            if (selectRet < 0) {
                if (running) {
                    fprintf (stderr, "Error when select.\n");
                    exit (EXIT_FAILURE);
                }
            } else {

                if (FD_ISSET (serverSock, &read_fd_set)) {
                    // accept one connection
                    int client = accept(serverSock, (struct sockaddr *)&rem_addr, &opt);


                    for (i=0; i<nbTeams; i++)
                        if (memcmp (&teams[i].address, &rem_addr.rc_bdaddr, sizeof (bdaddr_t)) == 0) {
                            if (teams[i].active) {
                                teams[i].sock = client;
                                teams[i].connected = 1;
                                debug (KRED, "Team ");
                                debug (COL(i), "%s", teams[i].name);
                                debug (KRED, " is now connected.\n");
                                if (state == GAM_RUNNING) {
                                    buf[0] = 0x00;                          // ID of start message
                                    buf[1] = 0x00;                          // is 0000
                                    buf[2] = 0xFF;                          // server ID is 0xFF
                                    buf[3] = (char) (0xFF & i);             // receiver
                                    buf[4] = MSG_START;                     // This is a START message
                                    buf[5] = teams[i].rank;                 // rank
                                    buf[6] = (char) (0xFF & rankCmp);       // length of the snake
                                    buf[7] = 0xFF;
                                    buf[8] = 0xFF;
                                    int j;
                                    for (j=0; j<nbTeams; j++)
                                        if (teams[j].active) {
                                            if (teams[j].rank == teams[i].rank - 1)
                                                buf[7] = (char) (0xFF & j); // previous
                                            if (teams[j].rank == teams[i].rank + 1)
                                                buf[8] = (char) (0xFF & j); // next
                                        }
                                    write_to_client (&teams[i], buf, 9);
                                }
                            } else {
                                debug (KRED, "Team ");
                                debug (COL(i), "%s", teams[i].name);
                                debug (KRED, " tried to connect while not taking part in this game!\n");
                                close (client);
                            }

                            break;
                        }

                    if (i == nbTeams) {
                        ba2str(&rem_addr.rc_bdaddr, buf );
                        debug (KRED, "Unknown connection from address %s.\n", buf);
                        close (client);
                    }
                }

                for (i = 0; i <= nbTeams; ++i)
                    if (teams[i].connected && FD_ISSET (teams[i].sock, &read_fd_set)) {
                        memset(buf, 0, sizeof(buf));
                        int nbbytes;
                        if ((nbbytes = read_from_client (&teams[i], buf, MAXMSG)) < 0) {
                            close (teams[i].sock);
                            teams[i].connected = 0;
                            debug (KRED, "Team ");
                            debug (COL(i), "%s", teams[i].name);
                            debug (KRED, " has disconnected.\n");
                        } else if (nbbytes != 0 && state == GAM_RUNNING)
                            parseMessage (teams, nbTeams, i, (unsigned char *) buf, nbbytes);
                    }
            }
        }

        printf ("\n");
        debug (KRED, "End of this game.\n\n");
        running = 1;

        buf[0] = 0x01;                      // ID of stop message
        buf[1] = 0x00;                      // is 0001
        buf[2] = 0xFF;                      // server ID is 0xFF
        buf[4] = MSG_STOP;                  // This is a STOP message


        for (i = 0; i < nbTeams; i++) {
            if (teams[i].connected) {
                buf[3] = (char) (0xFF & i);             // receiver
                write_to_client (&teams[i], buf, 5);

                close (teams[i].sock);
                teams[i].connected = 0;
            }

            if (teams[i].active)
                teams[i].active = 0;
        }
    }

    printf ("\n");
    debug (KRED, "End of the contest.\n");

    for (i=0; i<nbTeams; i++)
        if (teams[i].robotType == RBT_NXT)
            free (teams[i].mailbox);

    if (out)
        fclose (out);

    close(serverSock);
    return 0;
}
int main(int argc , char *argv[])
{
    Maintainer* maintainer = mymalloc(sizeof(Maintainer));
    init_maintainer(maintainer);
    logger("<Server><main>maintainer initialized\n");
    int opt = TRUE;

    if((maintainer->master_socket=socket(AF_INET, SOCK_STREAM, 0))==0) {
        logger("<Server><main>failed at master socket creation\n");
        myfree(maintainer);
        exit(EXIT_FAILURE);
    }

    fcntl(maintainer->master_socket, F_SETFL, O_NONBLOCK);

    if(setsockopt(maintainer->master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0) {
        logger("<Server><main>failed at master socket reuse\n");
        myfree(maintainer);
        exit(EXIT_FAILURE);
    }

    if(bind(maintainer->master_socket, (struct sockaddr *)&(maintainer->address), sizeof(maintainer->address)) < 0) {
        logger("<Server><main>failed at master socket binding\n");
        myfree(maintainer);
        exit(EXIT_FAILURE);
    }

    if (listen(maintainer->master_socket, 10) < 0) {
        logger("<Server><main>failed at master socket listen");
        exit(EXIT_FAILURE);
    }

    FD_SET(maintainer->master_socket, &(maintainer->fd_read_set));
    FD_SET(maintainer->master_socket, &(maintainer->fd_exception_set));
    maintainer->max_sd = maintainer->master_socket;

    while(TRUE) {
        maintainer->fd_read_set_select = maintainer->fd_read_set;
        maintainer->fd_write_set_select = maintainer->fd_write_set;
        maintainer->fd_exception_set_select = maintainer->fd_exception_set;
        if ((select(maintainer->max_sd+1, &(maintainer->fd_read_set_select),
                    &(maintainer->fd_write_set_select),
                    &(maintainer->fd_exception_set_select), NULL) < 0))
            logger("<Server><main>error at select\n");
        if (FD_ISSET(maintainer->master_socket, &(maintainer->fd_read_set_select)))
            handle_new_client(maintainer);
        if (FD_ISSET(maintainer->master_socket, &(maintainer->fd_exception_set_select)))
            handle_server_exception(maintainer);
        struct Nodes_ll* prev = maintainer->clients;
        struct Nodes_ll* iterator = maintainer->clients;
        while(iterator != NULL) {
            int current_socket = iterator->node->socket_fd;
            if(FD_ISSET(current_socket, &(maintainer->fd_exception_set_select)))
                close_client_connection(maintainer, current_socket, iterator->node, TRUE);
            else if(FD_ISSET(current_socket, &(maintainer->fd_read_set_select)))
                if(!read_from_client(maintainer, current_socket, iterator->node))
                    if(FD_ISSET(current_socket, &(maintainer->fd_write_set_select)))
                        write_to_client(maintainer, current_socket, iterator->node);
                    else if(FD_ISSET(current_socket, &(maintainer->fd_write_set_select)))
                        write_to_client(maintainer, current_socket, iterator->node);
            if(iterator != maintainer->clients) {
                if(iterator->node->socket_fd == -1) {
                    prev->next = iterator->next;
                    myfree(iterator->node);
                    struct Nodes_ll* tmp = iterator;
                    iterator = iterator->next;
                    myfree(tmp);
                }
                else {
                    prev = prev->next;
                    iterator = iterator->next;
                }
            } else if(iterator->node->socket_fd == -1) { /*marked for deletation*/
                maintainer->clients = iterator->next;
                myfree(iterator->node);
                struct Nodes_ll* tmp = iterator;
                iterator = iterator->next;
                myfree(tmp);
            } else
                iterator = iterator->next;
        }
    }
    myfree(maintainer);
    return 0;
}
Exemple #26
0
void baby_server_read(int client_pid){
    FILE* read_from;
    char reader[BUFFER], writer[BUFFER];
    char* buffer = NULL;
    CREATE_CLIENT_READER_NAME(reader, client_pid);
    CREATE_CLIENT_WRITER_NAME(writer, client_pid);

    if((read_from = fopen(writer, "r+")) == NULL)
        fprintf(stderr,"%s\n", strerror(errno));
    size_t len;
    ssize_t read;

    while((read=getline(&buffer, &len, read_from)) != -1){
        if(strstr(buffer, "cd")){
            if(strlen(buffer) >=4){
                char cwd[BUFFER];
                buffer[strlen(buffer)-1] = '\0';
                fprintf(stderr, "%s\n", &buffer[3]);
                if(chdir(&buffer[3]) != 0)
                    fprintf(stderr, "%s\n", strerror(errno));
                sprintf(cwd, "Changed directory to %s\nexit\n", &buffer[3]); 
                write_to_client(cwd, reader);
            }
            else{
                char cwd[BUFFER];
                chdir(getenv("HOME"));
                sprintf(cwd, "Changed directory to %s\nexit\n", getenv("HOME")); 
                write_to_client(cwd, reader);
            }
        }
        if(strstr(buffer, "dir")){
            char* little;
            FILE* dir = popen(CMD_LS_POPEN, "r");
            size_t l_len = 0;
            ssize_t l_read;
            while((l_read=getline(&little, &l_len, dir)) != -1 && !feof(dir)){
                write_to_client(little, reader);
            }
            write_to_client("exit\n", reader);
            fclose(dir);
        }
        if(strstr(buffer, "pwd")){
            char cwd[BUFFER];
            if(getcwd(cwd, sizeof(cwd)) != NULL){
                write_to_client(cwd, reader);
                write_to_client("\n", reader);
                write_to_client("exit\n", reader);
            }
        }
        if(strstr(buffer, "help")){
            write_to_client("Server-client:"
                    "You are currently on a server spawned especially to help you!\n"
                    "To restart the server, ctrl+c in the server's terminal\n"
                    "To kill the client, ctrl+c in the client's terminal\n", 
                    reader);
        }
        if(strstr(buffer, "put")){
        }
        if(strstr(buffer, "get")){
        }
        if(strstr(buffer, "Terminate")){
            fclose(read_from);
            exit(0);
        }
    }
}