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.

74 lines
1.9 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. MediaMtx (C++) - small HTTP/1.1 server (MediaMTX: internal/protocols/httpp)
  3. Used by the WebRTC (WHEP) server and the control API. One thread per connection, keep-alive,
  4. Content-Length bodies only (no chunked uploads), small requests (signalling / API).
  5. */
  6. #pragma once
  7. #include <atomic>
  8. #include <functional>
  9. #include <map>
  10. #include <mutex>
  11. #include <string>
  12. #include <thread>
  13. #include <utility>
  14. #include <vector>
  15. #include "../../logger/logger.h"
  16. namespace mtx {
  17. struct HttpRequest
  18. {
  19. std::string method;
  20. std::string path; // decoded, without the query
  21. std::string query;
  22. std::map<std::string, std::string> headers; // lower case names
  23. std::string body;
  24. std::string remoteAddr;
  25. std::string header(const std::string & lowerName) const
  26. {
  27. auto it = headers.find(lowerName);
  28. return it == headers.end() ? std::string() : it->second;
  29. }
  30. };
  31. struct HttpResponse
  32. {
  33. int status = 200;
  34. std::vector<std::pair<std::string, std::string>> headers;
  35. std::string body;
  36. void setHeader(const std::string & name, const std::string & value) { headers.emplace_back(name, value); }
  37. };
  38. class HttpServer
  39. {
  40. public:
  41. typedef std::function<void(const HttpRequest &, HttpResponse &)> Handler;
  42. explicit HttpServer(const LogParent * parent) : m_pParent(parent) {}
  43. ~HttpServer() { stop(); }
  44. bool start(const std::string & address, Handler handler, std::string & err);
  45. void stop();
  46. private:
  47. void acceptLoop();
  48. void serveConnection(int fd, std::string remote);
  49. const LogParent * m_pParent;
  50. Handler m_handler;
  51. int m_nListenFd = -1;
  52. int m_aWake[2] = {-1, -1};
  53. std::atomic<bool> m_bRun{false};
  54. std::atomic<int> m_nConnections{0};
  55. std::thread m_thread;
  56. std::mutex m_connMutex;
  57. std::vector<int> m_vConnFds;
  58. };
  59. const char * httpStatusText(int status);
  60. } // namespace mtx