From f7583f538ee6e33c1f1a0d8b386f202cc540a020 Mon Sep 17 00:00:00 2001 From: Camden Dixie O'Brien Date: Thu, 13 Oct 2022 13:34:29 +0100 Subject: [PATCH] Read selector from client --- main.c | 49 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/main.c b/main.c index 077cc26..74ce543 100644 --- a/main.c +++ b/main.c @@ -24,6 +24,8 @@ #include #include +#define SBUF_SIZE 1024 + static bool exit_requested = false; void handle_exit_signal(int signum) @@ -82,13 +84,19 @@ int main(int argc, char *argv[]) struct sockaddr_in6 paddr; socklen_t paddr_size = sizeof(paddr); int cfd; + char sbuf[SBUF_SIZE]; + ssize_t n, slen; while (!exit_requested) { /* * Accept incoming connection. * - * If accept() returns with an error and errno is EINTR, this - * should not exit the program as it just indicates that a - * signal arrived while waiting for a connection. + * If this is interrupted we go to the next loop iteration + * rather than retrying directly in case the received signal + * was requesting that the server exits. + * + * System calls after this point should be retried before + * checking if we need to exit, as we don't want to leave the + * client hanging. */ cfd = accept(sfd, (struct sockaddr *)&paddr, &paddr_size); if (cfd == -1) { @@ -98,7 +106,40 @@ int main(int argc, char *argv[]) return 1; } - printf("Accepted connection\n"); + /* + * Read selector from client socket. + * + * For now, assuming that the selector is less than RDBUF + * bytes long. + */ + do { + errno = 0; + n = read(cfd, sbuf, SBUF_SIZE); + } while (errno == EINTR); + if (n == -1) { + fprintf(stderr, "Error reading selector from client\n"); + return 1; + } + + /* + * Locate the end of the selector. + * + * The end of the selector string is indicated with CRLF. Most + * of the time this will be at the end of the received data, + * so might as well start from there. + */ + slen = n; + for (unsigned i = n - 2; i < n; --i) { + if (sbuf[i] == 0x0d && sbuf[i + 1] == 0x0a) + slen = i; + } + if (slen == n) { + fprintf(stderr, "Received invalid selector (no CRLF)\n"); + return 1; + } + + sbuf[slen] = '\0'; + printf("Received selector: \"%s\"\n", sbuf); close(cfd); }