Skip to content

Instantly share code, notes, and snippets.

@rlapz
Created October 14, 2021 08:59
Show Gist options
  • Save rlapz/200b27ea4ed10105f45841a6c1190120 to your computer and use it in GitHub Desktop.
Save rlapz/200b27ea4ed10105f45841a6c1190120 to your computer and use it in GitHub Desktop.
static int
add_to_pfds(struct server *s, struct sockaddr_storage *addr, const int new_fd)
{
struct pollfd *new_pfd;
struct client *new_cl;
if (s->cl_count > MAX_CLIENTS)
goto err;
/* Resize pdfs and client array */
if (s->fd_count == s->fd_size) {
const uint16_t new_fd_size = s->fd_size * 2;
new_pfd = realloc(s->pfds, sizeof(struct pollfd) * new_fd_size);
if (new_pfd == NULL) {
PERROR("add_to_pfds(): malloc for fds");
goto err;
}
s->pfds = new_pfd;
s->fd_size = new_fd_size;
}
if (s->cl_count == s->cl_size) {
const uint16_t new_cl_size = s->cl_size * 2;
new_cl = realloc(s->clients, sizeof(struct client) * new_cl_size);
if (new_cl == NULL) {
PERROR("add_to_pfds(): malloc for clients");
goto err;
}
s->clients = new_cl;
s->cl_size = new_cl_size;
}
const uint16_t cl = s->cl_count;
const uint16_t pfd = s->fd_count;
/* clearing old values */
memset(&(s->pfds[pfd]), 0, sizeof(struct pollfd));
memset(&(s->clients[cl]), 0, sizeof(struct client));
s->pfds[pfd].fd = new_fd;
s->pfds[pfd].events = POLLIN;
s->clients[cl].got_file_prop = false;
s->clients[cl].sock_fd = new_fd;
s->clients[cl].port = get_port((struct sockaddr *)addr);
if (get_addr(s->clients[cl].addr, (struct sockaddr *)addr) == NULL) {
PERROR("add_to_pfds(): inet_ntop");
goto err;
}
INFO("New connection from \"%s (%d)\" on socket %d\n",
s->clients[cl].addr, s->clients[cl].port, new_fd
);
(s->fd_count)++;
(s->cl_count)++;
return 0;
err:
close(new_fd);
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment