src/server/daemon/error.c

changeset 47
ce9790523346
parent 44
3da1f7b6847f
child 70
4e6e812c1d97
--- a/src/server/daemon/error.c	Sat Jan 12 14:00:47 2013 +0100
+++ b/src/server/daemon/error.c	Sun Jan 13 14:16:45 2013 +0100
@@ -30,13 +30,16 @@
 
 #include "../ucx/string.h"
 #include "../util/pblock.h"
+#include "../util/strbuf.h"
 
 // macro for creating an error string (ucx sstr_t)
 #define ERRMSG(s) { s, sizeof(s)-1 }
 
+static sstr_t error_400 = ERRMSG("<html><body>bad request</body></html>");
 static sstr_t error_403 = ERRMSG("<html><body>forbidden</body></html>");
 static sstr_t error_404 = ERRMSG("<html><body>not found</body></html>");
 static sstr_t error_500 = ERRMSG("<html><body>server error</body></html>");
+static sstr_t error_503 = ERRMSG("<html><body>service unavailable</body></html>");
 
 static sstr_t error_std = ERRMSG("<html><body>error</body></html>");
 
@@ -67,3 +70,42 @@
     
     return REQ_PROCEED;
 }
+
+void fatal_error(HTTPRequest *req, int status) {
+    sstr_t msg = error_500;
+    char *statusmsg = "Internal Server Error";
+    switch(status) {
+        case 400: {
+            msg = error_400;
+            statusmsg = "Bad request";
+            break;
+        }
+        case 500: {
+            msg = error_500;
+            statusmsg = "Internal Server Error";
+            break;
+        }
+        case 503: {
+            msg = error_503;
+            statusmsg = "Service Unavailable";
+            break;
+        }
+    }
+    
+    char buf[512];
+    int len = snprintf(buf, 512, "HTTP/1.1 %d %s\r\nServer: webserver\r\nContent-type: text/html\r\nContent-length: %d\r\n\r\n", status, statusmsg, msg.length);
+    
+    // set socket blocking
+    int flags;
+    if (-1 == (flags = fcntl(req->connection->fd, F_GETFL, 0))) {
+        flags = 0;
+    }
+    if (fcntl(req->connection->fd, F_SETFL, flags & ~O_NONBLOCK) != 0) {
+        // error
+    }
+    
+    write(req->connection->fd, buf, len);
+    write(req->connection->fd, msg.ptr, msg.length);
+    
+    close(req->connection->fd);
+}

mercurial