#include "http.h" #include #include #include #include #include const char * status_str[] = { [STATUS_OK] = "200 OK", [STATUS_BAD_REQUEST] = "400 Bad Request", [STATUS_METHOD_NOT_ALLOWED] = "405 Method Not Allowed", [STATUS_REQUEST_TIMEOUT] = "408 Request Timeout", [STATUS_INTERNAL_SERVER_ERROR] = "500 Internal Server Error", [STATUS_NOT_IMPLEMENTED] = "501 Not Implemented", [STATUS_VERSION_NOT_SUPPORTED] = "505 Version Not Supported", }; /// Sends a simple response only with a status to the client. /// \param fd File descriptor of the client socket /// \param status HTTP response status code /// \return Negative value if an error was encountered; numbers of bytes written otherwise int respond_only_status(const int fd, const enum status status) { static const char * pattern = "HTTP/1.1 %s\r\n" "Connection: close\r\n" "\r\n"; return dprintf(fd, pattern, status_str[status]); } /// Sends a response with a status and a body to the client. /// \param fd File descriptor of the client socket /// \param status HTTP response status code /// \param body Content that will be sent /// \param size Size of the content in bytes /// \return Negative value if an error was encountered; numbers of bytes written otherwise int respond_with_body(const int fd, const enum status status, const char * body, const int size) { static const char * pattern = "HTTP/1.1 %s\r\n" "Connection: close\r\n" "Content-Type: application/json\r\n" "Content-Size: %d\r\n" "\r\n"; if (0 > dprintf(fd, pattern, status_str[status], size)) { return -1; // TODO: Handle errors properly } return write(fd, body, size); } /// Collects request between calls to `poll`. /// \param fd Client socket /// \param request Buffer with the request content /// \return Number of bytes parsed, -1 if an error occured or 0 if expects more data int collect_request(const int fd, char ** request) { static const int size = 4096; if (NULL == *request) { *request = malloc(size); if (NULL == *request) { return -1; } } // TODO: Expand buffer until EAGAIN or arbitrary limit int length = read(fd, *request, size - 1); if (0 == length || (-1 == length && EWOULDBLOCK != errno && EAGAIN != errno)) { return -1; // TODO: Handle errors properly } (*request)[length] = 0; return length; }