#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "utils.h" // TODO(cmmm): Could save some space by offseting, N first sockets // won't be clients, but finding N is not trivial. #define SOCKET_TO_CLIENT_ID(SOCK ) (SOCK ) #define CLIENT_ID_TO_SOCKET(CLIENT) (CLIENT) #define MAX_CLIENT_COUNT SOCKET_TO_CLIENT_ID (FD_SETSIZE - 2) #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 PROGRAM_ARGUMENTS \ PROGRAM_ARGUMENT_BOOL (help, 'h', "help", "Show this help message" ) \ PROGRAM_ARGUMENT_BOOL (daemonize, 'd', "daemonize", "Daemonize process on startup" ) \ PROGRAM_ARGUMENT_UINT (log_upto, 'l', "log-upto", "Log up to this Syslog priority", LOG_NOTICE ) \ PROGRAM_ARGUMENT_STRING (archive, 'x', "archive", "Filename of broadcast message archive", "/var/log/chat-server-archive.log") \ PROGRAM_ARGUMENT_STRING (addr, 'a', "addr", "IP address to listen on", "0.0.0.0" ) \ PROGRAM_ARGUMENT_UINT (port, 'p', "port", "Port to listen on", 6666 ) #include "program-arguments.h" #define MOTD "Welcome, your nick is <%s>, " \ "use `/nick NAME' to change it, use `/help' to show help", client->nick #define COMMAND_HELP_OFFSET 20 #define COMMAND_FIGLET_MAX_MSG_LEN 23 #define COMMANDS \ COMMAND (HELP, "help", "", "Show this help message" ) \ COMMAND (NICK, "nick", "NAME", "Set nickname to NAME" ) \ COMMAND (USERS, "users", "", "List users nicknames and ip addresses") \ COMMAND (UPTIME, "uptime", "", "Show chat's age" ) \ COMMAND (LALU, "lalu", "", "Lalu's personal command" ) \ COMMAND (FIGLET, "figlet", "MSG...", "Send MSG... in large characters" ) #define COMMAND(SYM, ...) COMMAND_##SYM, enum command { COMMANDS COMMAND_COUNT }; #undef COMMAND #define COMMAND(SYM, STR, ...) [COMMAND_##SYM] = STR, const char *command_to_str[COMMAND_COUNT] = { COMMANDS }; #undef COMMAND #define COMMAND(SYM, STR, ...) [COMMAND_##SYM] = (uint8_t) sizeof (STR) - 1, uint8_t command_to_strlen[COMMAND_COUNT] = { COMMANDS }; #undef COMMAND #define COMMAND(SYM, STR, ARGS, ...) [COMMAND_##SYM] = ARGS, const char *command_to_args[COMMAND_COUNT] = { COMMANDS }; #undef COMMAND #define COMMAND(SYM, STR, ARGS, HELP) [COMMAND_##SYM] = HELP, const char *command_to_help[COMMAND_COUNT] = { COMMANDS }; #undef COMMAND typedef uint16_t client_id; typedef uint16_t buffer_index; struct client { char nick[MAX_NICK_LENGTH + 1]; client_id prev; // prev in hash map bucket client_id next; // next in hash map bucket client_id socket_index; uint8_t addr[4]; uint16_t port; buffer_index buffer_message_beg; buffer_index buffer_message_end; char buffer[BUFFER_SIZE]; // only for reading from socket } clients[MAX_CLIENT_COUNT]; client_id nick_index[NICK_INDEX_SIZE] = {0}; // hash map bucket heads int client_sockets[MAX_CLIENT_COUNT]; int *client_sockets_end = client_sockets; #define FOREACH_CLIENT_SOCKET(SOCK) \ for (int *SOCK = client_sockets; SOCK < client_sockets_end; ++SOCK) int max_fd = 0; fd_set active_fds; int listener = -1; struct program_arguments pa; volatile bool should_stop = false; FILE *archive; int archive_fd; time_t startup_time; uint64_t accepted_messages; uint64_t accepted_connections; void signal_handler (int sig) { int serrno = errno; switch (sig) { case SIGINT: DEBUG ("Received SIGINT"); should_stop = true; break; case SIGTERM: DEBUG ("Received SIGTERM"); should_stop = true; break; default: DEBUG ("Received unhandled %s", strsignal (sig)); } errno = serrno; } 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) { DEBUG ("write: %s", strerror (errno)); return false; } return true; } bool clients__server_printf_to (int recepient, const char *template, ...) { va_list ap; va_start (ap, template); bool ret = clients__server_vprintf (recepient, template, ap); va_end (ap); return ret; } bool clients__server_printf_except (int except, const char *template, ...) { va_list ap; va_start (ap, template); fprintf (archive, " "); vfprintf (archive, template, ap); fprintf (archive, "\n"); va_end (ap); fflush (archive); bool ret = true; FOREACH_CLIENT_SOCKET (recepient) { if (*recepient == except) continue; va_start (ap, template); if (!clients__server_vprintf (*recepient, template, ap)) ret = false; va_end (ap); } return ret; } bool clients__server_printf_all (const char *template, ...) { va_list ap; va_start (ap, template); fprintf (archive, " "); vfprintf (archive, template, ap); fprintf (archive, "\n"); va_end (ap); fflush (archive); bool ret = true; FOREACH_CLIENT_SOCKET (recepient) { va_start (ap, template); if (!clients__server_vprintf (*recepient, template, ap)) ret = false; va_end (ap); } return ret; } bool clients__add_client (int sock, uint32_t addr, uint16_t port) { 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 = SOCKET_TO_CLIENT_ID (sock); struct client *client = &clients[id]; snprintf (client->nick, sizeof (client->nick), "guest%d", id); *((uint32_t *) &client->addr) = addr; client->port = port; client->buffer_message_end = client->buffer_message_beg = snprintf (client->buffer, BUFFER_SIZE, "<%s> ", client->nick); client_id *entry = &nick_index[HASH (client->nick) % NICK_INDEX_SIZE]; client->prev = 0; client->next = *entry; if (client->next) clients[client->next - 1].prev = id + 1; *entry = id + 1; clients__server_printf_to (sock, MOTD); clients__server_printf_all ("Client <%s> connected from %hhu.%hhu.%hhu.%hhu", client->nick, client->addr[3], client->addr[2], client->addr[1], client->addr[0]); client->socket_index = client_sockets_end - client_sockets; *client_sockets_end++ = sock; INFO ("Added client <%s> %hhu.%hhu.%hhu.%hhu:%hu", client->nick, client->addr[3], client->addr[2], client->addr[1], client->addr[0], client->port); 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 ("Failed to accept connection: %s", strerror (errno)); exit (EXIT_FAILURE); } NOTICE ("Accepted connection: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr)); accepted_connections += 1; if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) { ERROR ("Failed to set nonblocking mode for client socket: %s", strerror (errno)); if (close (sock) == -1) WARNING ("close: %s", strerror (errno)); return true; } clients__add_client (sock, ntohl (addr.sin_addr.s_addr), ntohs (addr.sin_port)); 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)); } if (close (sock) == -1) WARNING ("close: %s", strerror (errno)); client_id id = SOCKET_TO_CLIENT_ID (sock); struct client *client = &clients[id]; client_sockets_end -= 1; clients[SOCKET_TO_CLIENT_ID (*client_sockets_end)].socket_index = client->socket_index; client_sockets[client->socket_index] = *client_sockets_end; if (client->next) clients[client->next - 1].prev = client->prev; if (client->prev) clients[client->prev - 1].next = client->next; else nick_index[HASH (client->nick) % NICK_INDEX_SIZE] = client->next; clients__server_printf_all ("Client <%s> from %hhu.%hhu.%hhu.%hhu disconnected", client->nick, client->addr[3], client->addr[2], client->addr[1], client->addr[0]); INFO ("Removed client <%s> %hhu.%hhu.%hhu.%hhu:%hu", client->nick, client->addr[3], client->addr[2], client->addr[1], client->addr[0], client->port); 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 = nick_index[HASHV (nick_beg, nick_end) % NICK_INDEX_SIZE]; while (recepient_id) { const struct client *recepient = &clients[recepient_id - 1]; if (strlen (recepient->nick) == (size_t) (nick_end - nick_beg) && strncmp (recepient->nick, nick_beg, nick_end - nick_beg) == 0) { return CLIENT_ID_TO_SOCKET (recepient - clients); } 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 = SOCKET_TO_CLIENT_ID (sock); struct client *client = &clients[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 = &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); INFO ("Client <%s> %hhu.%hhu.%hhu.%hhu:%hu changed it's nick to <%.*s>", client->nick, client->addr[3], client->addr[2], client->addr[1], client->addr[0], client->port, (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[client->prev - 1].next = client->next; if (client->next) clients[client->next - 1].prev = client->prev; entry = &nick_index[HASH (client->nick) % NICK_INDEX_SIZE]; client->prev = 0; client->next = *entry; if (client->next) clients[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, char *message_end) { ASSERT (sock < FD_SETSIZE); ASSERT (FD_ISSET (sock, &active_fds)); accepted_messages += 1; client_id id = SOCKET_TO_CLIENT_ID (sock); struct client *client = &clients[id]; char *message_beg = &client->buffer[client->buffer_message_beg]; if (*message_beg == '/') { enum command command = COMMAND_COUNT; char *command_beg = message_beg + 1; char *command_end = command_beg; for (enum command c = 0; c < COMMAND_COUNT; ++c) { if (strncmp (command_beg, command_to_str[c], command_to_strlen[c]) == 0 && strchr (" \t\n", command_beg[command_to_strlen[c]])) { command = c; command_end += command_to_strlen[c]; break; } } switch (command) { case COMMAND_HELP: { #define COMMAND(SYM, STR, ARGS, HELP) clients__server_printf_to ( \ sock, "/"STR" %-*s"HELP, (int) (COMMAND_HELP_OFFSET - sizeof (STR)), ARGS); COMMANDS; #undef COMMAND } goto cleanup; case COMMAND_NICK: { char *nick_beg = command_end; if (*nick_beg == '\n') { clients__server_printf_to (sock, "No nickname provided"); goto cleanup; } while (nick_beg < message_end && strchr (" \t", *nick_beg)) nick_beg += 1; if (*nick_beg == '\n') { clients__server_printf_to (sock, "No nickname provided"); goto cleanup; } char *nick_end = nick_beg; while (nick_end < message_end && nick_end < nick_beg + MAX_NICK_LENGTH && isalnum (*nick_end)) { *nick_end = tolower (*nick_end); nick_end += 1; } if (nick_end - nick_beg == 0) { clients__server_printf_to (sock, "Invalid nickname"); goto cleanup; } clients__set_nick (sock, nick_beg, nick_end); } goto cleanup; case COMMAND_USERS: { FOREACH_CLIENT_SOCKET (user_sock) { const struct client *user = &clients[SOCKET_TO_CLIENT_ID (*user_sock)]; clients__server_printf_to (sock, "%*hhu.%hhu.%hhu.%hhu <%s>%s", 4*3 - log10u8 (user->addr[3]) - log10u8 (user->addr[2]) - log10u8 (user->addr[1]) - log10u8 (user->addr[0]), user->addr[3], user->addr[2], user->addr[1], user->addr[0], user->nick, *user_sock == sock ? " (you)" : ""); } } goto cleanup; case COMMAND_UPTIME: { double uptime = difftime (time (NULL), startup_time); uint8_t seconds = (uint8_t) (uptime ) % 60; uint8_t minutes = (uint8_t) (uptime/60 ) % 60; uint8_t hours = (uint8_t) (uptime/60/60) % 24; double days = uptime/60/60/24; struct rusage usage; getrusage (RUSAGE_SELF, &usage); clients__server_printf_to (sock, "Up %.0lf day%s %02hhu:%02hhu:%02hhu, " "accepted %lu connection%s and %lu message%s", days, 1 <= days && days < 2 ? "s" : "", hours, minutes, seconds, accepted_connections, accepted_connections != 1 ? "s" : "", accepted_messages, accepted_messages != 1 ? "s" : ""); } goto cleanup; case COMMAND_LALU: { clients__server_printf_all ("Chaau from lu"); clients__remove_client (sock); } goto cleanup; case COMMAND_FIGLET: { char line_buffer[6][72]; char line_lengths[6] = {0}; if (message_end - command_end > COMMAND_FIGLET_MAX_MSG_LEN) strcpy (command_end + COMMAND_FIGLET_MAX_MSG_LEN, " 2>/dev/null"); else strcpy (message_end, " 2>/dev/null"); INFO ("Running command %s", command_beg); FILE *figlet = popen (command_beg, "r"); int c = getc (figlet); if (c == EOF) { pclose (figlet); clients__server_printf_to (sock, "Something went wrong"); goto cleanup; } ungetc (c, figlet); for (int i = 0; i < 6; ++i) { char *head = &line_buffer[i][0]; while (head < &line_buffer[i][0] + sizeof (line_buffer[i]) - 1) { int c = getc (figlet); if (c == EOF) { pclose (figlet); clients__server_printf_to (sock, "Something went wrong"); goto cleanup; } *head++ = c; line_lengths[i] += 1; if (c == '\n') break; } } pclose (figlet); for (int i = 0; i < 6; ++i) { memcpy (client->buffer + client->buffer_message_beg, &line_buffer[i][0], line_lengths[i]); client->buffer_message_end = client->buffer_message_beg + line_lengths[i]; if (write (archive_fd, client->buffer, client->buffer_message_end) == -1) DEBUG ("write: %s", strerror (errno)); FOREACH_CLIENT_SOCKET (recepient) { if (write (*recepient, client->buffer, client->buffer_message_end) == -1) { DEBUG ("write: %s", strerror (errno)); goto cleanup; } } } } goto cleanup; case COMMAND_COUNT: { clients__server_printf_to (sock, "Unknown command"); } goto cleanup; default: { clients__server_printf_to (sock, "Sorry, command not implemented("); } goto cleanup; } } 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) { DEBUG ("write: %s", strerror (errno)); goto cleanup; } } else { if (write (archive_fd, client->buffer, client->buffer_message_end) == -1) DEBUG ("write: %s", strerror (errno)); FOREACH_CLIENT_SOCKET (recepient) { if (*recepient == sock) continue; if (write (*recepient, client->buffer, client->buffer_message_end) == -1) DEBUG ("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 = SOCKET_TO_CLIENT_ID (sock); struct client *client = &clients[id]; ssize_t bytes_read; if (client->buffer_message_end == BUFFER_SIZE) { bytes_read = read (sock, &client->buffer[client->buffer_message_beg], BUFFER_SIZE); if (bytes_read == -1) { DEBUG ("read: %s", strerror (errno)); clients__remove_client (sock); return false; } char *head = &client->buffer[client->buffer_message_beg]; char *end = &client->buffer[client->buffer_message_beg + bytes_read]; while (head < end && *head != '\n') head += 1; if (head == end) return true; clients__server_printf_to (sock, "Message too long"); head += 1; if (head == end) { client->buffer_message_end = client->buffer_message_beg; return true; } bytes_read = end - head; memmove (&client->buffer[client->buffer_message_beg], head, bytes_read); client->buffer_message_end = client->buffer_message_beg; } else { bytes_read = read (sock, &client->buffer[client->buffer_message_end], BUFFER_SIZE - client->buffer_message_end); if (bytes_read < 1) { if (bytes_read == -1) DEBUG ("read: %s", strerror (errno)); clients__remove_client (sock); return false; } } char *head = &client->buffer[client->buffer_message_end]; client->buffer_message_end += bytes_read; 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[]) { pa = parse_program_arguments (argc, argv); if (pa.help) { print_help (pa.program_name); exit (EXIT_SUCCESS); } setlogmask (LOG_UPTO (pa.log_upto)); openlog (basename (pa.program_name), LOG_PID | (pa.daemonize ? 0 : LOG_PERROR), LOG_DAEMON); if (pa.daemonize) { close (STDIN_FILENO); close (STDOUT_FILENO); close (STDERR_FILENO); DEBUG ("Closed standard file descriptors"); } archive = fopen (pa.archive, "a"); if (!archive) { EMERGENCY ("Unable to open message archive `%s' for append access: %s", pa.archive, strerror (errno)); exit (EXIT_FAILURE); } NOTICE ("Opened message archive `%s' for append access", pa.archive); archive_fd = fileno (archive); struct sigaction sa = { .sa_handler = signal_handler }; sigaction (SIGINT, &sa, NULL); sigaction (SIGTERM, &sa, NULL); DEBUG ("Registered signal handlers"); if (pa.daemonize) { pid_t pid = fork (); if (pid == -1) { EMERGENCY ("Unable to fork: %s", strerror (errno)); exit (EXIT_FAILURE); } if (pid > 0) exit (EXIT_SUCCESS); DEBUG ("Forked"); pid_t sid = setsid (); if (sid == -1) { EMERGENCY ("Unable to set SID: %s", strerror (errno)); exit (EXIT_FAILURE); } DEBUG ("Set sid to %d", sid); } umask (0); if (chdir ("/") == -1) { EMERGENCY ("Unable to chdir to /: %s", strerror (errno)); exit (EXIT_FAILURE); } DEBUG ("Changed directory to /"); listener = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listener == -1) { EMERGENCY ("Failed to create socket: %s", strerror (errno)); exit (EXIT_FAILURE); } DEBUG ("Created socket"); max_fd = listener; int reuseaddr = 1; setsockopt (listener, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof (reuseaddr)); if (fcntl (listener, F_SETFL, O_NONBLOCK) == -1) { EMERGENCY ("Failed to set nonblocking mode for listener socket: %s", strerror (errno)); exit (EXIT_FAILURE); } DEBUG ("Set nonblocking mode for listener socket"); struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons (pa.port), }; if (!inet_aton (pa.addr, &addr.sin_addr)) { EMERGENCY ("Failed to convert address %s", pa.addr); exit (EXIT_FAILURE); } DEBUG ("Converted address %s: %s", pa.addr, inet_ntoa (addr.sin_addr)); if (bind (listener, (struct sockaddr *) &addr, sizeof (addr)) == -1) { EMERGENCY ("Failed to bind address "SOCKADDR_IN_FMT" to listener socket: %s", SOCKADDR_IN_SPLIT (addr), strerror (errno)); exit (EXIT_FAILURE); } DEBUG ("Bound address "SOCKADDR_IN_FMT" to listener socket", SOCKADDR_IN_SPLIT (addr)); if (listen (listener, 2)) { EMERGENCY ("Failed to listen on "SOCKADDR_IN_FMT": %s", SOCKADDR_IN_SPLIT (addr), strerror (errno)); exit (EXIT_FAILURE); } NOTICE ("Listening on: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr)); FD_ZERO (&active_fds); FD_SET (listener, &active_fds); NOTICE ("Server started"); startup_time = time (NULL); while (!should_stop) { 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) { DEBUG ("select: %s", strerror (errno)); continue; } if (FD_ISSET (listener, &read_fds)) while (clients__accept_connection ()); FOREACH_CLIENT_SOCKET (client) { if (!FD_ISSET (*client, &read_fds)) continue; if (!clients__read_from_client (*client)) client -= 1; } } NOTICE ("Server stopped"); return EXIT_SUCCESS; }