You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

393 lines
9.3 KiB

#include "httpServer.h"
#include <arpa/inet.h>
#include <cerrno>
#include <chrono>
#include <cstring>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#include <algorithm>
#include "../../conf/serverConf.h"
namespace mtx {
namespace {
const size_t MAX_HEADER_SIZE = 16 * 1024;
const size_t MAX_BODY_SIZE = 1024 * 1024;
const int IDLE_TIMEOUT_MS = 15000;
} // namespace
const char * httpStatusText(int status)
{
switch (status)
{
case 200: return "OK";
case 201: return "Created";
case 204: return "No Content";
case 301: return "Moved Permanently";
case 400: return "Bad Request";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 409: return "Conflict";
case 413: return "Payload Too Large";
case 415: return "Unsupported Media Type";
case 500: return "Internal Server Error";
case 503: return "Service Unavailable";
default: return "Status";
}
}
static std::string urlDecode(const std::string & s)
{
std::string tOut;
for (size_t i = 0; i < s.size(); i++)
{
if (s[i] == '%' && i + 2 < s.size() && isxdigit((unsigned char) s[i + 1]) && isxdigit((unsigned char) s[i + 2]))
{
tOut.push_back((char) strtol(s.substr(i + 1, 2).c_str(), nullptr, 16));
i += 2;
}
else
{
tOut.push_back(s[i]);
}
}
return tOut;
}
bool HttpServer::start(const std::string & address, Handler handler, std::string & err)
{
std::string tHost;
uint16_t tPort = 0;
if (! splitHostPort(address, tHost, tPort))
{
err = "bad address " + address;
return false;
}
struct addrinfo tHints;
memset(&tHints, 0, sizeof(tHints));
tHints.ai_family = AF_UNSPEC;
tHints.ai_socktype = SOCK_STREAM;
tHints.ai_flags = AI_PASSIVE;
struct addrinfo * tRes = nullptr;
std::string tPortS = std::to_string(tPort);
if (getaddrinfo(tHost.empty() ? nullptr : tHost.c_str(), tPortS.c_str(), &tHints, &tRes) != 0 || tRes == nullptr)
{
err = "cannot resolve " + address;
return false;
}
// with an empty host prefer IPv6 any (dual stack); fall back to the other results (no IPv6 support)
std::vector<struct addrinfo *> tOrder;
for (struct addrinfo * a = tRes; a != nullptr; a = a->ai_next)
{
if (tHost.empty() && a->ai_family == AF_INET6)
{
tOrder.insert(tOrder.begin(), a);
}
else
{
tOrder.push_back(a);
}
}
err.clear();
for (struct addrinfo * a : tOrder)
{
m_nListenFd = socket(a->ai_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (m_nListenFd < 0)
{
err = std::string("socket: ") + strerror(errno);
continue;
}
int tOne = 1;
setsockopt(m_nListenFd, SOL_SOCKET, SO_REUSEADDR, &tOne, sizeof(tOne));
if (a->ai_family == AF_INET6)
{
int tZero = 0;
setsockopt(m_nListenFd, IPPROTO_IPV6, IPV6_V6ONLY, &tZero, sizeof(tZero));
}
if (bind(m_nListenFd, a->ai_addr, a->ai_addrlen) == 0 && listen(m_nListenFd, 64) == 0)
{
err.clear();
break;
}
err = "listen on " + address + ": " + strerror(errno);
close(m_nListenFd);
m_nListenFd = -1;
}
if (m_nListenFd < 0)
{
freeaddrinfo(tRes);
return false;
}
freeaddrinfo(tRes);
if (pipe(m_aWake) != 0)
{
err = "pipe failed";
close(m_nListenFd);
m_nListenFd = -1;
return false;
}
m_handler = std::move(handler);
m_bRun = true;
m_thread = std::thread(&HttpServer::acceptLoop, this);
return true;
}
void HttpServer::stop()
{
if (! m_bRun.exchange(false))
{
return;
}
if (write(m_aWake[1], "x", 1) < 0)
{
// the accept loop also wakes up on its poll timeout
}
if (m_thread.joinable())
{
m_thread.join();
}
{
std::lock_guard<std::mutex> lock(m_connMutex);
for (int fd : m_vConnFds)
{
shutdown(fd, SHUT_RDWR);
}
}
// connection threads are detached: wait until they are gone
for (int i = 0; i < 500 && m_nConnections > 0; i++)
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
close(m_nListenFd);
close(m_aWake[0]);
close(m_aWake[1]);
m_nListenFd = -1;
}
void HttpServer::acceptLoop()
{
while (m_bRun)
{
struct pollfd tP[2] = {{m_nListenFd, POLLIN, 0}, {m_aWake[0], POLLIN, 0}};
int tN = poll(tP, 2, 1000);
if (tN <= 0 || ! m_bRun)
{
continue;
}
if (tP[0].revents & POLLIN)
{
struct sockaddr_storage tAddr;
socklen_t tLen = sizeof(tAddr);
int fd = accept4(m_nListenFd, (struct sockaddr *) &tAddr, &tLen, SOCK_CLOEXEC);
if (fd < 0)
{
continue;
}
char tHost[INET6_ADDRSTRLEN] = "?";
if (tAddr.ss_family == AF_INET)
{
inet_ntop(AF_INET, &((struct sockaddr_in *) &tAddr)->sin_addr, tHost, sizeof(tHost));
}
else if (tAddr.ss_family == AF_INET6)
{
inet_ntop(AF_INET6, &((struct sockaddr_in6 *) &tAddr)->sin6_addr, tHost, sizeof(tHost));
if (strncmp(tHost, "::ffff:", 7) == 0)
{
memmove(tHost, tHost + 7, strlen(tHost + 7) + 1);
}
}
int tOne = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &tOne, sizeof(tOne));
{
std::lock_guard<std::mutex> lock(m_connMutex);
m_vConnFds.push_back(fd);
}
m_nConnections++;
std::thread(&HttpServer::serveConnection, this, fd, std::string(tHost)).detach();
}
}
}
static bool sendAll(int fd, const std::string & data)
{
size_t tOff = 0;
while (tOff < data.size())
{
ssize_t n = send(fd, data.data() + tOff, data.size() - tOff, MSG_NOSIGNAL);
if (n <= 0)
{
if (n < 0 && errno == EINTR)
{
continue;
}
return false;
}
tOff += (size_t) n;
}
return true;
}
void HttpServer::serveConnection(int fd, std::string remote)
{
std::string tBuf;
bool tKeep = true;
while (tKeep && m_bRun)
{
// read the header
size_t tHdrEnd;
while ((tHdrEnd = tBuf.find("\r\n\r\n")) == std::string::npos)
{
if (tBuf.size() > MAX_HEADER_SIZE)
{
tKeep = false;
break;
}
struct pollfd tP = {fd, POLLIN, 0};
if (poll(&tP, 1, IDLE_TIMEOUT_MS) <= 0)
{
tKeep = false;
break;
}
char tChunk[4096];
ssize_t n = recv(fd, tChunk, sizeof(tChunk), 0);
if (n <= 0)
{
tKeep = false;
break;
}
tBuf.append(tChunk, (size_t) n);
}
if (! tKeep)
{
break;
}
HttpRequest tReq;
tReq.remoteAddr = remote;
std::string tHead = tBuf.substr(0, tHdrEnd);
tBuf.erase(0, tHdrEnd + 4);
size_t tEol = tHead.find("\r\n");
std::string tLine = tHead.substr(0, tEol);
size_t s1 = tLine.find(' '), s2 = tLine.rfind(' ');
if (s1 == std::string::npos || s2 == s1)
{
break;
}
tReq.method = tLine.substr(0, s1);
std::string tUri = tLine.substr(s1 + 1, s2 - s1 - 1);
std::string tVer = tLine.substr(s2 + 1);
size_t tQ = tUri.find('?');
tReq.path = urlDecode(tQ == std::string::npos ? tUri : tUri.substr(0, tQ));
tReq.query = (tQ == std::string::npos) ? std::string() : tUri.substr(tQ + 1);
size_t tPos = (tEol == std::string::npos) ? tHead.size() : tEol + 2;
while (tPos < tHead.size())
{
size_t tE = tHead.find("\r\n", tPos);
std::string h = tHead.substr(tPos, (tE == std::string::npos ? tHead.size() : tE) - tPos);
tPos = (tE == std::string::npos) ? tHead.size() : tE + 2;
size_t tC = h.find(':');
if (tC == std::string::npos)
{
continue;
}
std::string k = h.substr(0, tC);
std::transform(k.begin(), k.end(), k.begin(), ::tolower);
size_t tV = h.find_first_not_of(" \t", tC + 1);
tReq.headers[k] = (tV == std::string::npos) ? std::string() : h.substr(tV);
}
std::string tConn = tReq.header("connection");
std::transform(tConn.begin(), tConn.end(), tConn.begin(), ::tolower);
tKeep = (tVer == "HTTP/1.1") ? (tConn != "close") : (tConn == "keep-alive");
HttpResponse tRes;
size_t tLen = (size_t) strtoul(tReq.header("content-length").c_str(), nullptr, 10);
if (! tReq.header("transfer-encoding").empty())
{
tRes.status = 400;
tKeep = false;
}
else if (tLen > MAX_BODY_SIZE)
{
tRes.status = 413;
tKeep = false;
}
else
{
while (tBuf.size() < tLen)
{
struct pollfd tP = {fd, POLLIN, 0};
if (poll(&tP, 1, IDLE_TIMEOUT_MS) <= 0)
{
tKeep = false;
break;
}
char tChunk[8192];
ssize_t n = recv(fd, tChunk, sizeof(tChunk), 0);
if (n <= 0)
{
tKeep = false;
break;
}
tBuf.append(tChunk, (size_t) n);
}
if (tBuf.size() < tLen)
{
break;
}
tReq.body = tBuf.substr(0, tLen);
tBuf.erase(0, tLen);
try
{
m_handler(tReq, tRes);
}
catch (const std::exception & e)
{
if (m_pParent)
{
m_pParent->log(LogLevel::Error, "HTTP handler: %s", e.what());
}
tRes = HttpResponse();
tRes.status = 500;
}
}
std::string tOut = "HTTP/1.1 " + std::to_string(tRes.status) + " " + httpStatusText(tRes.status) + "\r\n";
bool tHasType = false;
for (auto & h : tRes.headers)
{
tOut += h.first + ": " + h.second + "\r\n";
if (strcasecmp(h.first.c_str(), "Content-Type") == 0)
{
tHasType = true;
}
}
if (! tHasType && ! tRes.body.empty())
{
tOut += "Content-Type: text/plain\r\n";
}
tOut += "Server: MediaMtx\r\nContent-Length: " + std::to_string(tRes.body.size()) + "\r\n";
tOut += tKeep ? "Connection: keep-alive\r\n\r\n" : "Connection: close\r\n\r\n";
if (tReq.method != "HEAD")
{
tOut += tRes.body;
}
if (! sendAll(fd, tOut))
{
break;
}
}
{
std::lock_guard<std::mutex> lock(m_connMutex);
m_vConnFds.erase(std::remove(m_vConnFds.begin(), m_vConnFds.end(), fd), m_vConnFds.end());
}
close(fd);
m_nConnections--;
}
} // namespace mtx