summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--cfws.c16
-rw-r--r--net.c16
-rw-r--r--net.h2
3 files changed, 27 insertions, 7 deletions
diff --git a/cfws.c b/cfws.c
index f280fe4..2e8eb32 100644
--- a/cfws.c
+++ b/cfws.c
@@ -11,14 +11,24 @@
#define CFWS_DEFAULT_PORT 8080
+static int serverfd;
+
static void handle_request(const struct http_request *, int);
+static void handle_sigint(int signum)
+{
+ (void)signum;
+ shutdown(serverfd, SHUT_RDWR);
+}
+
int main(int argc, char *argv[])
{
int port = CFWS_DEFAULT_PORT;
- int serverfd, clientfd;
+ int clientfd;
struct http_request request;
+ signal(SIGINT, handle_sigint);
+
/* Prevent the program from quitting if it attempts to write to a closed
* socket. */
signal(SIGPIPE, SIG_IGN);
@@ -30,7 +40,9 @@ int main(int argc, char *argv[])
printf("Serving a directory at localhost:%d\n", port);
while (1) {
- request = net_next_request(serverfd, &clientfd);
+ int rc = net_next_request(serverfd, &clientfd, &request);
+ if (rc != 0)
+ break;
handle_request(&request, clientfd);
diff --git a/net.c b/net.c
index 84d713b..438abcb 100644
--- a/net.c
+++ b/net.c
@@ -1,6 +1,7 @@
#include "net.h"
#include <arpa/inet.h>
+#include <errno.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
@@ -50,19 +51,26 @@ int net_init_server(int port)
return sockfd;
}
-struct http_request net_next_request(int serverfd, int *clientfd)
+int net_next_request(int serverfd, int *clientfd, struct http_request *req)
{
int connfd;
char readbuf[CFWS_NET_MAXREAD];
- struct http_request req;
connfd = accept(serverfd, NULL, NULL);
+ if (connfd == -1) {
+ /* EINVAL most likely indicates that the server socket was
+ * closed due to the user pressing Ctrl+C. */
+ if (errno == EINVAL)
+ return 1;
+ perror("cfws: accept");
+ return -1;
+ }
/* Read and parse the HTTP request */
memset(readbuf, 0, CFWS_NET_MAXREAD);
read(connfd, readbuf, CFWS_NET_MAXREAD - 1);
- req = http_parse_request(readbuf);
+ *req = http_parse_request(readbuf);
*clientfd = connfd;
- return req;
+ return 0;
}
diff --git a/net.h b/net.h
index 92f61c4..481f520 100644
--- a/net.h
+++ b/net.h
@@ -7,6 +7,6 @@
#include "http.h"
int net_init_server(int);
-struct http_request net_next_request(int serverfd, int *clientfd);
+int net_next_request(int serverfd, int *clientfd, struct http_request *);
#endif