Read selector from client

This commit is contained in:
Camden Dixie O'Brien 2022-10-13 13:34:29 +01:00
parent 2ab4966773
commit f7583f538e

49
main.c
View File

@ -24,6 +24,8 @@
#include <sys/socket.h> #include <sys/socket.h>
#include <unistd.h> #include <unistd.h>
#define SBUF_SIZE 1024
static bool exit_requested = false; static bool exit_requested = false;
void handle_exit_signal(int signum) void handle_exit_signal(int signum)
@ -82,13 +84,19 @@ int main(int argc, char *argv[])
struct sockaddr_in6 paddr; struct sockaddr_in6 paddr;
socklen_t paddr_size = sizeof(paddr); socklen_t paddr_size = sizeof(paddr);
int cfd; int cfd;
char sbuf[SBUF_SIZE];
ssize_t n, slen;
while (!exit_requested) { while (!exit_requested) {
/* /*
* Accept incoming connection. * Accept incoming connection.
* *
* If accept() returns with an error and errno is EINTR, this * If this is interrupted we go to the next loop iteration
* should not exit the program as it just indicates that a * rather than retrying directly in case the received signal
* signal arrived while waiting for a connection. * 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); cfd = accept(sfd, (struct sockaddr *)&paddr, &paddr_size);
if (cfd == -1) { if (cfd == -1) {
@ -98,7 +106,40 @@ int main(int argc, char *argv[])
return 1; 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); close(cfd);
} }