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

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "httpServer.h"
  2. #include <arpa/inet.h>
  3. #include <cerrno>
  4. #include <chrono>
  5. #include <cstring>
  6. #include <netdb.h>
  7. #include <netinet/in.h>
  8. #include <netinet/tcp.h>
  9. #include <poll.h>
  10. #include <sys/socket.h>
  11. #include <unistd.h>
  12. #include <algorithm>
  13. #include "../../conf/conf.h"
  14. namespace mtx {
  15. namespace {
  16. const size_t MAX_HEADER_SIZE = 16 * 1024;
  17. const size_t MAX_BODY_SIZE = 1024 * 1024;
  18. const int IDLE_TIMEOUT_MS = 15000;
  19. } // namespace
  20. const char * httpStatusText(int status)
  21. {
  22. switch (status)
  23. {
  24. case 200: return "OK";
  25. case 201: return "Created";
  26. case 204: return "No Content";
  27. case 301: return "Moved Permanently";
  28. case 400: return "Bad Request";
  29. case 403: return "Forbidden";
  30. case 404: return "Not Found";
  31. case 405: return "Method Not Allowed";
  32. case 409: return "Conflict";
  33. case 413: return "Payload Too Large";
  34. case 415: return "Unsupported Media Type";
  35. case 500: return "Internal Server Error";
  36. case 503: return "Service Unavailable";
  37. default: return "Status";
  38. }
  39. }
  40. static std::string urlDecode(const std::string & s)
  41. {
  42. std::string tOut;
  43. for (size_t i = 0; i < s.size(); i++)
  44. {
  45. if (s[i] == '%' && i + 2 < s.size() && isxdigit((unsigned char) s[i + 1]) && isxdigit((unsigned char) s[i + 2]))
  46. {
  47. tOut.push_back((char) strtol(s.substr(i + 1, 2).c_str(), nullptr, 16));
  48. i += 2;
  49. }
  50. else
  51. {
  52. tOut.push_back(s[i]);
  53. }
  54. }
  55. return tOut;
  56. }
  57. bool HttpServer::start(const std::string & address, Handler handler, std::string & err)
  58. {
  59. std::string tHost;
  60. uint16_t tPort = 0;
  61. if (! splitHostPort(address, tHost, tPort))
  62. {
  63. err = "bad address " + address;
  64. return false;
  65. }
  66. struct addrinfo tHints;
  67. memset(&tHints, 0, sizeof(tHints));
  68. tHints.ai_family = AF_UNSPEC;
  69. tHints.ai_socktype = SOCK_STREAM;
  70. tHints.ai_flags = AI_PASSIVE;
  71. struct addrinfo * tRes = nullptr;
  72. std::string tPortS = std::to_string(tPort);
  73. if (getaddrinfo(tHost.empty() ? nullptr : tHost.c_str(), tPortS.c_str(), &tHints, &tRes) != 0 || tRes == nullptr)
  74. {
  75. err = "cannot resolve " + address;
  76. return false;
  77. }
  78. // with an empty host prefer IPv6 any (dual stack); fall back to the other results (no IPv6 support)
  79. std::vector<struct addrinfo *> tOrder;
  80. for (struct addrinfo * a = tRes; a != nullptr; a = a->ai_next)
  81. {
  82. if (tHost.empty() && a->ai_family == AF_INET6)
  83. {
  84. tOrder.insert(tOrder.begin(), a);
  85. }
  86. else
  87. {
  88. tOrder.push_back(a);
  89. }
  90. }
  91. err.clear();
  92. for (struct addrinfo * a : tOrder)
  93. {
  94. m_nListenFd = socket(a->ai_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
  95. if (m_nListenFd < 0)
  96. {
  97. err = std::string("socket: ") + strerror(errno);
  98. continue;
  99. }
  100. int tOne = 1;
  101. setsockopt(m_nListenFd, SOL_SOCKET, SO_REUSEADDR, &tOne, sizeof(tOne));
  102. if (a->ai_family == AF_INET6)
  103. {
  104. int tZero = 0;
  105. setsockopt(m_nListenFd, IPPROTO_IPV6, IPV6_V6ONLY, &tZero, sizeof(tZero));
  106. }
  107. if (bind(m_nListenFd, a->ai_addr, a->ai_addrlen) == 0 && listen(m_nListenFd, 64) == 0)
  108. {
  109. err.clear();
  110. break;
  111. }
  112. err = "listen on " + address + ": " + strerror(errno);
  113. close(m_nListenFd);
  114. m_nListenFd = -1;
  115. }
  116. if (m_nListenFd < 0)
  117. {
  118. freeaddrinfo(tRes);
  119. return false;
  120. }
  121. freeaddrinfo(tRes);
  122. if (pipe(m_aWake) != 0)
  123. {
  124. err = "pipe failed";
  125. close(m_nListenFd);
  126. m_nListenFd = -1;
  127. return false;
  128. }
  129. m_handler = std::move(handler);
  130. m_bRun = true;
  131. m_thread = std::thread(&HttpServer::acceptLoop, this);
  132. return true;
  133. }
  134. void HttpServer::stop()
  135. {
  136. if (! m_bRun.exchange(false))
  137. {
  138. return;
  139. }
  140. if (write(m_aWake[1], "x", 1) < 0)
  141. {
  142. // the accept loop also wakes up on its poll timeout
  143. }
  144. if (m_thread.joinable())
  145. {
  146. m_thread.join();
  147. }
  148. {
  149. std::lock_guard<std::mutex> lock(m_connMutex);
  150. for (int fd : m_vConnFds)
  151. {
  152. shutdown(fd, SHUT_RDWR);
  153. }
  154. }
  155. // connection threads are detached: wait until they are gone
  156. for (int i = 0; i < 500 && m_nConnections > 0; i++)
  157. {
  158. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  159. }
  160. close(m_nListenFd);
  161. close(m_aWake[0]);
  162. close(m_aWake[1]);
  163. m_nListenFd = -1;
  164. }
  165. void HttpServer::acceptLoop()
  166. {
  167. while (m_bRun)
  168. {
  169. struct pollfd tP[2] = {{m_nListenFd, POLLIN, 0}, {m_aWake[0], POLLIN, 0}};
  170. int tN = poll(tP, 2, 1000);
  171. if (tN <= 0 || ! m_bRun)
  172. {
  173. continue;
  174. }
  175. if (tP[0].revents & POLLIN)
  176. {
  177. struct sockaddr_storage tAddr;
  178. socklen_t tLen = sizeof(tAddr);
  179. int fd = accept4(m_nListenFd, (struct sockaddr *) &tAddr, &tLen, SOCK_CLOEXEC);
  180. if (fd < 0)
  181. {
  182. continue;
  183. }
  184. char tHost[INET6_ADDRSTRLEN] = "?";
  185. if (tAddr.ss_family == AF_INET)
  186. {
  187. inet_ntop(AF_INET, &((struct sockaddr_in *) &tAddr)->sin_addr, tHost, sizeof(tHost));
  188. }
  189. else if (tAddr.ss_family == AF_INET6)
  190. {
  191. inet_ntop(AF_INET6, &((struct sockaddr_in6 *) &tAddr)->sin6_addr, tHost, sizeof(tHost));
  192. if (strncmp(tHost, "::ffff:", 7) == 0)
  193. {
  194. memmove(tHost, tHost + 7, strlen(tHost + 7) + 1);
  195. }
  196. }
  197. int tOne = 1;
  198. setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &tOne, sizeof(tOne));
  199. {
  200. std::lock_guard<std::mutex> lock(m_connMutex);
  201. m_vConnFds.push_back(fd);
  202. }
  203. m_nConnections++;
  204. std::thread(&HttpServer::serveConnection, this, fd, std::string(tHost)).detach();
  205. }
  206. }
  207. }
  208. static bool sendAll(int fd, const std::string & data)
  209. {
  210. size_t tOff = 0;
  211. while (tOff < data.size())
  212. {
  213. ssize_t n = send(fd, data.data() + tOff, data.size() - tOff, MSG_NOSIGNAL);
  214. if (n <= 0)
  215. {
  216. if (n < 0 && errno == EINTR)
  217. {
  218. continue;
  219. }
  220. return false;
  221. }
  222. tOff += (size_t) n;
  223. }
  224. return true;
  225. }
  226. void HttpServer::serveConnection(int fd, std::string remote)
  227. {
  228. std::string tBuf;
  229. bool tKeep = true;
  230. while (tKeep && m_bRun)
  231. {
  232. // read the header
  233. size_t tHdrEnd;
  234. while ((tHdrEnd = tBuf.find("\r\n\r\n")) == std::string::npos)
  235. {
  236. if (tBuf.size() > MAX_HEADER_SIZE)
  237. {
  238. tKeep = false;
  239. break;
  240. }
  241. struct pollfd tP = {fd, POLLIN, 0};
  242. if (poll(&tP, 1, IDLE_TIMEOUT_MS) <= 0)
  243. {
  244. tKeep = false;
  245. break;
  246. }
  247. char tChunk[4096];
  248. ssize_t n = recv(fd, tChunk, sizeof(tChunk), 0);
  249. if (n <= 0)
  250. {
  251. tKeep = false;
  252. break;
  253. }
  254. tBuf.append(tChunk, (size_t) n);
  255. }
  256. if (! tKeep)
  257. {
  258. break;
  259. }
  260. HttpRequest tReq;
  261. tReq.remoteAddr = remote;
  262. std::string tHead = tBuf.substr(0, tHdrEnd);
  263. tBuf.erase(0, tHdrEnd + 4);
  264. size_t tEol = tHead.find("\r\n");
  265. std::string tLine = tHead.substr(0, tEol);
  266. size_t s1 = tLine.find(' '), s2 = tLine.rfind(' ');
  267. if (s1 == std::string::npos || s2 == s1)
  268. {
  269. break;
  270. }
  271. tReq.method = tLine.substr(0, s1);
  272. std::string tUri = tLine.substr(s1 + 1, s2 - s1 - 1);
  273. std::string tVer = tLine.substr(s2 + 1);
  274. size_t tQ = tUri.find('?');
  275. tReq.path = urlDecode(tQ == std::string::npos ? tUri : tUri.substr(0, tQ));
  276. tReq.query = (tQ == std::string::npos) ? std::string() : tUri.substr(tQ + 1);
  277. size_t tPos = (tEol == std::string::npos) ? tHead.size() : tEol + 2;
  278. while (tPos < tHead.size())
  279. {
  280. size_t tE = tHead.find("\r\n", tPos);
  281. std::string h = tHead.substr(tPos, (tE == std::string::npos ? tHead.size() : tE) - tPos);
  282. tPos = (tE == std::string::npos) ? tHead.size() : tE + 2;
  283. size_t tC = h.find(':');
  284. if (tC == std::string::npos)
  285. {
  286. continue;
  287. }
  288. std::string k = h.substr(0, tC);
  289. std::transform(k.begin(), k.end(), k.begin(), ::tolower);
  290. size_t tV = h.find_first_not_of(" \t", tC + 1);
  291. tReq.headers[k] = (tV == std::string::npos) ? std::string() : h.substr(tV);
  292. }
  293. std::string tConn = tReq.header("connection");
  294. std::transform(tConn.begin(), tConn.end(), tConn.begin(), ::tolower);
  295. tKeep = (tVer == "HTTP/1.1") ? (tConn != "close") : (tConn == "keep-alive");
  296. HttpResponse tRes;
  297. size_t tLen = (size_t) strtoul(tReq.header("content-length").c_str(), nullptr, 10);
  298. if (! tReq.header("transfer-encoding").empty())
  299. {
  300. tRes.status = 400;
  301. tKeep = false;
  302. }
  303. else if (tLen > MAX_BODY_SIZE)
  304. {
  305. tRes.status = 413;
  306. tKeep = false;
  307. }
  308. else
  309. {
  310. while (tBuf.size() < tLen)
  311. {
  312. struct pollfd tP = {fd, POLLIN, 0};
  313. if (poll(&tP, 1, IDLE_TIMEOUT_MS) <= 0)
  314. {
  315. tKeep = false;
  316. break;
  317. }
  318. char tChunk[8192];
  319. ssize_t n = recv(fd, tChunk, sizeof(tChunk), 0);
  320. if (n <= 0)
  321. {
  322. tKeep = false;
  323. break;
  324. }
  325. tBuf.append(tChunk, (size_t) n);
  326. }
  327. if (tBuf.size() < tLen)
  328. {
  329. break;
  330. }
  331. tReq.body = tBuf.substr(0, tLen);
  332. tBuf.erase(0, tLen);
  333. try
  334. {
  335. m_handler(tReq, tRes);
  336. }
  337. catch (const std::exception & e)
  338. {
  339. if (m_pParent)
  340. {
  341. m_pParent->log(LogLevel::Error, "HTTP handler: %s", e.what());
  342. }
  343. tRes = HttpResponse();
  344. tRes.status = 500;
  345. }
  346. }
  347. std::string tOut = "HTTP/1.1 " + std::to_string(tRes.status) + " " + httpStatusText(tRes.status) + "\r\n";
  348. bool tHasType = false;
  349. for (auto & h : tRes.headers)
  350. {
  351. tOut += h.first + ": " + h.second + "\r\n";
  352. if (strcasecmp(h.first.c_str(), "Content-Type") == 0)
  353. {
  354. tHasType = true;
  355. }
  356. }
  357. if (! tHasType && ! tRes.body.empty())
  358. {
  359. tOut += "Content-Type: text/plain\r\n";
  360. }
  361. tOut += "Server: MediaMtx\r\nContent-Length: " + std::to_string(tRes.body.size()) + "\r\n";
  362. tOut += tKeep ? "Connection: keep-alive\r\n\r\n" : "Connection: close\r\n\r\n";
  363. if (tReq.method != "HEAD")
  364. {
  365. tOut += tRes.body;
  366. }
  367. if (! sendAll(fd, tOut))
  368. {
  369. break;
  370. }
  371. }
  372. {
  373. std::lock_guard<std::mutex> lock(m_connMutex);
  374. m_vConnFds.erase(std::remove(m_vConnFds.begin(), m_vConnFds.end(), fd), m_vConnFds.end());
  375. }
  376. close(fd);
  377. m_nConnections--;
  378. }
  379. } // namespace mtx