12 #ifdef HAVE_HTTP_DEBUG
15 # define LOG_TRACE(x, ...) printf(x "\n", __VA_ARGS__)
19 #ifndef HTTP_SERVER_NS
20 # define HTTP_SERVER_NS testing
36 std::map<std::string, std::string>
headers;
44 std::map<std::string, std::string>
headers;
48 using CallbackFunction = std::function<int(HttpRequest
const &request, HttpResponse &response)>;
50 class HttpRequestCallback
120 class HttpRequestHandler :
public std::pair<std::string, HttpRequestCallback *>
138 second = other.second;
173 std::ostringstream os;
174 os << serverHost <<
":" << port;
217 LOG_INFO(
"HttpServer: Added handler for %s", root.c_str());
225 LOG_INFO(
"HttpServer: Added handler for %s", root.c_str());
231 LOG_INFO(
"HttpServer: Added handler for %s", other.first.c_str());
249 if (socket.
accept(csocket, caddr))
253 conn.socket = csocket;
255 conn.request.client = caddr.
toString();
257 LOG_TRACE(
"HttpServer: [%s] accepted", conn.request.client.c_str());
276 char buffer[2048] = {0};
277 int received = socket.
recv(buffer,
sizeof(buffer));
278 LOG_TRACE(
"HttpServer: [%s] received %d", conn.request.client.c_str(), received);
284 conn.receiveBuffer.append(buffer, buffer + received);
329 if (conn.sendBuffer.empty())
334 int sent = conn.socket.send(conn.sendBuffer.data(),
static_cast<int>(conn.sendBuffer.size()));
335 LOG_TRACE(
"HttpServer: [%s] sent %d", conn.request.client.c_str(), sent);
340 conn.sendBuffer.erase(0, sent);
342 if (!conn.sendBuffer.empty())
355 LOG_TRACE(
"HttpServer: [%s] closed", conn.request.client.c_str());
358 LOG_WARN(
"HttpServer: [%s] connection closed unexpectedly", conn.request.client.c_str());
372 conn.response.code = 0;
374 LOG_TRACE(
"HttpServer: [%s] receiving headers", conn.request.client.c_str());
380 size_t ofs = conn.receiveBuffer.find(
"\r\n\r\n");
381 if (ofs == std::string::npos)
384 ofs = conn.receiveBuffer.find(
"\n\n");
386 size_t headersLen = (ofs != std::string::npos) ? ofs : conn.receiveBuffer.length();
389 LOG_WARN(
"HttpServer: [%s] headers too long - %u", conn.request.client.c_str(),
390 static_cast<unsigned>(headersLen));
391 conn.response.code = 431;
392 conn.keepalive =
false;
396 if (ofs == std::string::npos)
403 LOG_WARN(
"HttpServer: [%s] invalid headers", conn.request.client.c_str());
404 conn.response.code = 400;
405 conn.keepalive =
false;
409 LOG_INFO(
"HttpServer: [%s] %s %s %s", conn.request.client.c_str(),
410 conn.request.method.c_str(), conn.request.uri.c_str(),
411 conn.request.protocol.c_str());
412 conn.receiveBuffer.erase(0, ofs + (lfOnly ? 2 : 4));
414 conn.keepalive = (conn.request.protocol ==
"HTTP/1.1");
415 auto const connection = conn.request.headers.find(
"Connection");
416 if (connection != conn.request.headers.end())
420 conn.keepalive =
true;
424 conn.keepalive =
false;
428 auto const contentLength = conn.request.headers.find(
"Content-Length");
429 if (contentLength != conn.request.headers.end())
431 conn.contentLength = atoi(contentLength->second.c_str());
435 conn.contentLength = 0;
439 LOG_WARN(
"HttpServer: [%s] content too long - %u", conn.request.client.c_str(),
440 static_cast<unsigned>(conn.contentLength));
441 conn.response.code = 413;
442 conn.keepalive =
false;
447 auto const expect = conn.request.headers.find(
"Expect");
448 if (expect != conn.request.headers.end() && conn.request.protocol ==
"HTTP/1.1")
452 LOG_WARN(
"HttpServer: [%s] unknown expectation - %s", conn.request.client.c_str(),
453 expect->second.c_str());
454 conn.response.code = 417;
455 conn.keepalive =
false;
459 conn.sendBuffer =
"HTTP/1.1 100 Continue\r\n\r\n";
461 LOG_TRACE(
"HttpServer: [%s] sending \"100 Continue\"", conn.request.client.c_str());
466 LOG_TRACE(
"HttpServer: [%s] receiving body", conn.request.client.c_str());
477 LOG_TRACE(
"HttpServer: [%s] receiving body", conn.request.client.c_str());
482 if (conn.receiveBuffer.length() < conn.contentLength)
487 if (conn.receiveBuffer.length() == conn.contentLength)
489 conn.request.content =
std::move(conn.receiveBuffer);
490 conn.receiveBuffer.clear();
494 conn.request.content.assign(conn.receiveBuffer, 0, conn.contentLength);
495 conn.receiveBuffer.erase(0, conn.contentLength);
499 LOG_TRACE(
"HttpServer: [%s] processing request", conn.request.client.c_str());
506 std::ostringstream os;
507 os << conn.request.protocol <<
' ' << conn.response.code <<
' ' << conn.response.message
509 for (
auto const &header : conn.response.headers)
511 os << header.first <<
": " << header.second <<
"\r\n";
515 conn.sendBuffer = os.str();
517 LOG_TRACE(
"HttpServer: [%s] sending headers", conn.request.client.c_str());
527 conn.sendBuffer =
std::move(conn.response.body);
529 LOG_TRACE(
"HttpServer: [%s] sending body", conn.request.client.c_str());
546 LOG_TRACE(
"HttpServer: [%s] idle (keep-alive)", conn.request.client.c_str());
547 if (conn.receiveBuffer.empty())
557 LOG_TRACE(
"HttpServer: [%s] closing", conn.request.client.c_str());
571 char const *begin = conn.receiveBuffer.c_str();
572 char const *ptr = begin;
573 while (*ptr && *ptr !=
' ' && *ptr !=
'\r' && *ptr !=
'\n')
581 conn.request.method.assign(begin, ptr);
589 while (*ptr && *ptr !=
' ' && *ptr !=
'\r' && *ptr !=
'\n')
597 conn.request.uri.assign(begin, ptr);
605 while (*ptr && *ptr !=
' ' && *ptr !=
'\r' && *ptr !=
'\n')
609 if (*ptr !=
'\r' && *ptr !=
'\n')
613 conn.request.protocol.assign(begin, ptr);
625 conn.request.headers.clear();
626 while (*ptr !=
'\r' && *ptr !=
'\n')
630 while (*ptr && *ptr !=
':' && *ptr !=
' ' && *ptr !=
'\r' && *ptr !=
'\n')
647 while (*ptr && *ptr !=
'\r' && *ptr !=
'\n')
651 if (!conn.request.headers[name].empty())
653 conn.request.headers[name] =
654 conn.request.headers[name].append(
",").append(std::string(begin, ptr));
658 conn.request.headers[name] = std::string(begin, ptr);
686 char const *ptr = str.c_str();
687 while (*ptr && *mask && ::tolower(*ptr) == *mask)
692 return !*ptr && !*mask;
697 std::string result(begin,
end);
699 for (
char &ch : result)
703 ch =
static_cast<char>(::toupper(ch));
712 ch =
static_cast<char>(::tolower(ch));
720 conn.response.message.clear();
721 conn.response.headers.clear();
722 conn.response.body.clear();
724 if (conn.response.code == 0)
726 conn.response.code = 404;
729 if (conn.request.uri.length() >= handler.first.length() &&
730 strncmp(conn.request.uri.c_str(), handler.first.c_str(), handler.first.length()) == 0)
732 LOG_TRACE(
"HttpServer: [%s] using handler for %s", conn.request.client.c_str(),
733 handler.first.c_str());
736 int result = handler.second->onHttpRequest(conn.request, conn.response);
739 conn.response.code = result;
745 if (conn.response.code == -1)
747 LOG_TRACE(
"HttpServer: [%s] closing by request", conn.request.client.c_str());
752 if (conn.response.message.empty())
758 conn.response.headers[
"Connection"] = (conn.keepalive ?
"keep-alive" :
"close");
760 conn.response.headers[
"Content-Length"] = std::to_string(conn.response.body.size());
767 gmtime_s(&tm, &time);
769 gmtime_r(&time, &tm);
772 strftime(buf,
sizeof(buf),
"%a, %d %b %Y %H:%M:%S GMT", &tm);
785 return "Switching Protocols";
793 return "Non-Authoritative Information";
797 return "Reset Content";
799 return "Partial Content";
801 return "Multiple Choices";
803 return "Moved Permanently";
809 return "Not Modified";
813 return "Switch Proxy";
815 return "Temporary Redirect";
817 return "Permanent Redirect";
819 return "Bad Request";
821 return "Unauthorized";
823 return "Payment Required";
829 return "Method Not Allowed";
831 return "Not Acceptable";
833 return "Proxy Authentication Required";
835 return "Request Timeout";
841 return "Length Required";
843 return "Precondition Failed";
845 return "Payload Too Large";
847 return "URI Too Long";
849 return "Unsupported Media Type";
851 return "Range Not Satisfiable";
853 return "Expectation Failed";
855 return "Misdirected Request";
857 return "Upgrade Required";
859 return "Precondition Required";
861 return "Too Many Requests";
863 return "Request Header Fields Too Large";
865 return "Internal Server Error";
867 return "Not Implemented";
869 return "Bad Gateway";
871 return "Service Unavailable";
873 return "Gateway Timeout";
875 return "HTTP Version Not Supported";
877 return "Variant Also Negotiates";
879 return "Not Extended";
881 return "Network Authentication Required";