#include #include #include #include #include #include #include #include #include #include #include #include "utils.h" #define ASSERT assert // #define ASSERT #define LISTEN_QUEUE 2 // #define MAX_CLIENT_COUNT (FD_SETSIZE - 5) // stdin, stdout, stderr, listener, reserved #define MAX_CLIENT_COUNT 4 #define MAX_NICK_LENGTH 9 #define MAX_MESSAGE_SIZE 512 #define BUFFER_SIZE (1 + MAX_NICK_LENGTH + 2 + MAX_MESSAGE_SIZE) // " msg" #define NICK_INDEX_SIZE FD_SETSIZE #define HASH djb2 #define HASHN djb2n #define HASHV djb2v #define INITIAL_CLIENT_CAPACITY 1 typedef uint16_t client_id; typedef uint16_t buffer_index; // arena with free list, socket luts and nick indexing struct clients { struct client { char nick[MAX_NICK_LENGTH + 1]; client_id prev; // prev in hash map bucket client_id next; // next in hash map bucket / free list client_id socket_index; buffer_index buffer_message_beg; buffer_index buffer_message_end; char buffer[BUFFER_SIZE]; // only for reading from socket } *items; client_id count; client_id capacity; client_id free_list_head; int socket_count; int socket_index_to_socket[MAX_CLIENT_COUNT]; client_id socket_to_id [FD_SETSIZE ]; client_id nick_index[NICK_INDEX_SIZE]; // hash map bucket heads } clients = {0}; int max_fd = 0; fd_set active_fds; int listener = -1; client_id djb2 (const char *str) { client_id hash = 5381; while (*str) hash = ((hash << 5) + hash) + *str++; return hash; } client_id djb2n (const char *str, int n) { client_id hash = 5381; while (n && *str) { hash = ((hash << 5) + hash) + *str++; n -= 1; } return hash; } client_id djb2v (const char *str, const char *end) { client_id hash = 5381; while (str < end && *str) hash = ((hash << 5) + hash) + *str++; return hash; } bool clients__server_vprintf (int sock, const char *template, va_list ap) { static char buffer[513]; int len = 0; len += snprintf (buffer + len, 513 - len, " "); len += vsnprintf (buffer + len, 513 - len, template, ap); len += snprintf (buffer + len, 513 - len, "\n"); if (write (sock, buffer, len) == -1) { ERROR ("write: %s", strerror (errno)); return false; } return true; } bool clients__server_printf_to (int sock, const char *template, ...) { va_list ap; va_start (ap, template); bool ret = clients__server_vprintf (sock, template, ap); va_end (ap); return ret; } bool clients__server_printf_except (int except, const char *template, ...) { va_list ap; bool ret = true; for (client_id i = 0; i < clients.socket_count; ++i) { int sock = clients.socket_index_to_socket[i]; if (sock == except) continue; va_start (ap, template); if (!clients__server_vprintf (sock, template, ap)) ret = false; va_end (ap); } return ret; } bool clients__server_printf_all (const char *template, ...) { va_list ap; bool ret = true; for (client_id i = 0; i < clients.socket_count; ++i) { int sock = clients.socket_index_to_socket[i]; va_start (ap, template); if (!clients__server_vprintf (sock, template, ap)) ret = false; va_end (ap); } return ret; } bool clients__add_client (int sock) { ASSERT (sock < FD_SETSIZE); ASSERT (!FD_ISSET (sock, &active_fds)); FD_SET (sock, &active_fds); if (sock > max_fd) max_fd = sock; client_id id; if (clients.free_list_head) { id = clients.free_list_head - 1; clients.free_list_head = clients.items[id].next; } else { id = clients.count++; if (clients.count > clients.capacity) { if (clients.count == MAX_CLIENT_COUNT) { // TODO(cmmm): disconnect with error } clients.capacity *= 2; if (clients.capacity > MAX_CLIENT_COUNT) clients.capacity = MAX_CLIENT_COUNT; clients.items = realloc (clients.items, clients.capacity*sizeof (*clients.items)); } } struct client *client = &clients.items[id]; snprintf (client->nick, sizeof (client->nick), "guest%d", id); client->buffer_message_end = client->buffer_message_beg = snprintf (client->buffer, BUFFER_SIZE, "<%s> ", client->nick); client_id *entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE]; client->prev = 0; client->next = *entry; if (client->next) clients.items[client->next - 1].prev = id + 1; *entry = id + 1; clients__server_printf_to (sock, "your nick is <%s>, " "use '/nick ' to change it", client->nick); clients__server_printf_all ("client <%s> connected", client->nick); client->socket_index = clients.socket_count++; clients.socket_index_to_socket[client->socket_index] = sock; clients.socket_to_id[sock] = id; INFO ("added client <%s>", client->nick); return true; } bool clients__accept_connection (void) { ASSERT (listener != -1); struct sockaddr_in addr; socklen_t length = sizeof (addr); int sock = accept (listener, (struct sockaddr *) &addr, &length); if (sock == -1) { if (errno == EWOULDBLOCK) return false; ERROR ("accept: %s", strerror (errno)); exit (EXIT_FAILURE); } INFO ("accepted connection: %hhu.%hhu.%hhu.%hhu:%hu", ntohl (addr.sin_addr.s_addr) >> 3*8, ntohl (addr.sin_addr.s_addr) >> 2*8, ntohl (addr.sin_addr.s_addr) >> 1*8, ntohl (addr.sin_addr.s_addr) >> 0*8, ntohs (addr.sin_port)); if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) { ERROR ("fcntl: %s", strerror (errno)); if (close (sock) == -1) ERROR ("close: %s", strerror (errno)); return true; } clients__add_client (sock); return true; } bool clients__remove_client (int sock) { ASSERT (sock < FD_SETSIZE); ASSERT (FD_ISSET (sock, &active_fds)); FD_CLR (sock, &active_fds); if (sock == max_fd) { do max_fd -= 1; while (!FD_ISSET (max_fd, &active_fds)); } client_id id = clients.socket_to_id[sock]; struct client *client = &clients.items[id]; clients.socket_index_to_socket[client->socket_index] = clients.socket_index_to_socket[--clients.socket_count]; if (close (sock) == -1) ERROR ("close: %s", strerror (errno)); client->next = clients.free_list_head; clients.free_list_head = id + 1; if (client->next) clients.items[client->next - 1].prev = client->prev; if (client->prev) clients.items[client->prev - 1].next = client->next; else clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE] = client->next; clients__server_printf_all ("client <%s> disconnected", client->nick); INFO ("removed client <%s>", client->nick); return true; } int clients__nick_to_socket (const char *nick_beg, const char *nick_end) { ASSERT (nick_beg < nick_end); ASSERT (nick_end - nick_beg <= MAX_NICK_LENGTH); client_id recepient_id = clients.nick_index[HASHV (nick_beg, nick_end) % NICK_INDEX_SIZE]; while (recepient_id) { const struct client *recepient = &clients.items[recepient_id - 1]; if (strlen (recepient->nick) == (size_t) (nick_end - nick_beg) && strncmp (recepient->nick, nick_beg, nick_end - nick_beg) == 0) { return clients.socket_index_to_socket[recepient->socket_index]; } recepient_id = recepient->next; } return -1; } bool clients__set_nick (int sock, const char *nick_beg, const char *nick_end) { ASSERT (sock < FD_SETSIZE); ASSERT (FD_ISSET (sock, &active_fds)); client_id id = clients.socket_to_id[sock]; struct client *client = &clients.items[id]; if (isalnum (*nick_end)) { clients__server_printf_to (sock, "nick too long"); return false; } if (clients__nick_to_socket (nick_beg, nick_end) != -1) { clients__server_printf_to (sock, "nick already occupied"); return false; } client_id *entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE]; if (*entry == id + 1) *entry = client->next; clients__server_printf_except (sock, "client <%s> changed it's nick to <%.*s>", client->nick, (int) (nick_end - nick_beg), nick_beg); memcpy (client->nick, nick_beg, nick_end - nick_beg); client->nick[nick_end - nick_beg] = '\0'; client->buffer_message_beg = sprintf (client->buffer, "<%.*s> ", (int) (nick_end - nick_beg), nick_beg); if (client->prev) clients.items[client->prev - 1].next = client->next; if (client->next) clients.items[client->next - 1].prev = client->prev; entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE]; client->prev = 0; client->next = *entry; if (client->next) clients.items[client->next - 1].prev = id + 1; *entry = id + 1; clients__server_printf_to (sock, "your new nick is <%s>", client->nick); return true; } bool clients__message_received (int sock, const char *message_end) { ASSERT (sock < FD_SETSIZE); ASSERT (FD_ISSET (sock, &active_fds)); client_id id = clients.socket_to_id[sock]; struct client *client = &clients.items[id]; char *message_beg = &client->buffer[client->buffer_message_beg]; if (*message_beg == '/') { if (strncmp (message_beg + 1, "nick ", 5) == 0) { char *nick_beg = message_beg + 6; while (*nick_beg == ' ') nick_beg += 1; char *nick_end = nick_beg; do { *nick_end = tolower (*nick_end); nick_end += 1; } while (nick_end < nick_beg + MAX_NICK_LENGTH && isalnum (*nick_end)); clients__set_nick (sock, nick_beg, nick_end); } else { clients__server_printf_to (sock, "unsupported command"); } } else if (*message_beg == '!') { const char *nick_beg = message_beg + 1; const char *nick_end = nick_beg; do nick_end += 1; while (nick_end < nick_beg + MAX_NICK_LENGTH && isalnum (*nick_end)); int recepient = clients__nick_to_socket (nick_beg, nick_end); if (recepient == -1) { clients__server_printf_to (sock, "nick not found: <%.*s>", (int) (nick_end - nick_beg), nick_beg); goto cleanup; } if (recepient == sock) { clients__server_printf_to (sock, "you may not send message to yourself"); goto cleanup; } if (write (recepient, client->buffer, client->buffer_message_end) == -1) { ERROR ("write: %s", strerror (errno)); goto cleanup; } } else { for (client_id i = 0; i < clients.socket_count; ++i) { int recepient = clients.socket_index_to_socket[i]; if (recepient == sock) continue; if (write (recepient, client->buffer, client->buffer_message_end) == -1) { ERROR ("write: %s", strerror (errno)); } } } cleanup: client->buffer_message_end = client->buffer_message_beg; return true; } bool clients__read_from_client (int sock) { ASSERT (sock < FD_SETSIZE); ASSERT (FD_ISSET (sock, &active_fds)); client_id id = clients.socket_to_id[sock]; struct client *client = &clients.items[id]; ssize_t bytes_read = read (sock, &client->buffer[client->buffer_message_end], BUFFER_SIZE - client->buffer_message_end); if (bytes_read <= 0) { if (bytes_read == -1) ERROR ("read: %s", strerror (errno)); clients__remove_client (sock); return false; } const char *head = &client->buffer[client->buffer_message_end]; client->buffer_message_end += bytes_read; const char *end = &client->buffer[client->buffer_message_end]; while (head < end) { if (*head == '\n') return clients__message_received (sock, head); head += 1; } return true; } int main (int argc, char *argv[]) { listener = socket (AF_INET, SOCK_STREAM, 0); if (listener == -1) DIE (EXIT_FAILURE, "socket: %s", strerror (errno)); max_fd = listener; int reuseaddr = 1; setsockopt (listener, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof (reuseaddr)); if (fcntl (listener, F_SETFL, O_NONBLOCK) == -1) DIE (EXIT_FAILURE, "fcntl: %s", strerror (errno)); struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons (3422), .sin_addr.s_addr = htonl (INADDR_ANY), }; if (bind (listener, (struct sockaddr *) &addr, sizeof (addr)) == -1) DIE (EXIT_FAILURE, "bind: %s", strerror (errno)); INFO ("listening on: %hhu.%hhu.%hhu.%hhu:%hu", ntohl (addr.sin_addr.s_addr) >> 3*8, ntohl (addr.sin_addr.s_addr) >> 2*8, ntohl (addr.sin_addr.s_addr) >> 1*8, ntohl (addr.sin_addr.s_addr) >> 0*8, ntohs (addr.sin_port)); if (listen (listener, LISTEN_QUEUE)) DIE (EXIT_FAILURE, "listen: %s", strerror (errno)); FD_ZERO (&active_fds); FD_SET (listener, &active_fds); clients.items = malloc (INITIAL_CLIENT_CAPACITY*sizeof (*clients.items)); clients.capacity = INITIAL_CLIENT_CAPACITY; for (;;) { fd_set read_fds; memcpy (&read_fds, &active_fds, sizeof (fd_set)); struct timeval timeout = { .tv_sec = 15 }; if (select (max_fd + 1, &read_fds, NULL, NULL, &timeout) == -1) DIE (EXIT_FAILURE, "select: %s", strerror (errno)); if (FD_ISSET (listener, &read_fds)) while (clients__accept_connection ()); for (int i = 0; i < clients.socket_count; ++i) { int sock = clients.socket_index_to_socket[i]; if (!FD_ISSET (sock, &read_fds)) continue; if (!clients__read_from_client (sock)) sock -= 1; } } return EXIT_SUCCESS; }