tvote.c: use err() for error handling and exit - vote - simple cgi voting system for web and gopher
(HTM) git clone git://src.adamsgaard.dk/vote
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
(DIR) commit 3934b097745f258d593dc8eaf39073e60e1872fc
(DIR) parent 5190a3453c2755d07cb5e6afeb9689d27275d4da
(HTM) Author: Anders Damsgaard <anders@adamsgaard.dk>
Date: Sun, 27 Sep 2020 09:12:16 +0200
vote.c: use err() for error handling and exit
Diffstat:
M vote.c | 32 ++++++++++++++++----------------
1 file changed, 16 insertions(+), 16 deletions(-)
---
(DIR) diff --git a/vote.c b/vote.c
t@@ -3,9 +3,10 @@
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
-#include <errno.h>
+#include <err.h>
#include <fcntl.h>
#include <limits.h>
+
#include "util.h"
#define OUT(s) (fputs((s), stdout))
t@@ -14,7 +15,7 @@
static char poll[1024];
void
-die(int statuscode)
+http_status(int statuscode)
{
switch(statuscode) {
case 401:
t@@ -27,11 +28,9 @@ die(int statuscode)
OUT("Status: 500 Internal Server Error\r\n\r\n");
break;
default:
- fprintf(stderr, "unknown status code %d\n", statuscode);
+ err(1, "unknown status code %d\n", statuscode);
OUT("Status: 500 Internal Server Error\r\n\r\n");
}
-
- exit(statuscode);
}
void
t@@ -60,13 +59,13 @@ show_poll(const char *poll_name)
strlcpy(buf, poll_name, sizeof(buf));
escapechars(buf);
if (snprintf(fname, sizeof(fname), "%s/%s", POLLS_DIR, buf) < 0) {
- fprintf(stderr, "snprintf fname %s/%s\n", POLLS_DIR, buf);
- die(500);
+ http_status(500);
+ err(1, "snprintf fname %s/%s", POLLS_DIR, buf);
}
if (!(fd = fopen(fname, "r"))) {
- fprintf(stderr, "poll_open %s: %s\n", poll, strerror(errno));
- die(404);
+ http_status(404);
+ err(1, "poll_open fopen %s", poll);
} else {
fclose(fd);
}
t@@ -84,7 +83,8 @@ parse_query()
if ((p = getparam(query, "poll"))) {
if (decodeparam(poll, sizeof(poll), p) == -1) {
- die(401);
+ http_status(401);
+ exit(1);
}
}
}
t@@ -95,19 +95,19 @@ main()
struct stat sb;
if (unveil(getenv("PWD"), NULL) == -1 || unveil(NULL, NULL) == -1) {
- fprintf(stderr, "unveil: %s\n", strerror(errno));
- die(500);
+ http_status(500);
+ err(1, "unveil");
}
if (pledge("stdio cpath rpath", NULL) == -1) {
- fprintf(stderr, "pledge: %s\n", strerror(errno));
- die(500);
+ http_status(500);
+ err(1, "pledge");
}
if (stat(POLLS_DIR, &sb) == -1) {
if (mkdir(POLLS_DIR, 0755) == -1) {
- fprintf(stderr, "mkdir polls/ failed: %s\n", strerror(errno));
- die(500);
+ http_status(500);
+ err(1, "mkdir '%s' failed", POLLS_DIR);
}
}