#include "webrtcServer.h" #include namespace mtx { namespace { const char * PLAYER_PAGE = R"HTML( MediaMtx
)HTML"; std::string newSecret() { static std::mutex s_mutex; static std::random_device s_rd; static std::mt19937_64 s_gen(((uint64_t) s_rd() << 32) ^ s_rd()); std::lock_guard lock(s_mutex); char tB[40]; snprintf(tB, sizeof(tB), "%016llx%016llx", (unsigned long long) s_gen(), (unsigned long long) s_gen()); return tB; } std::vector splitPath(const std::string & p) { std::vector tOut; size_t i = 0; while (i < p.size()) { size_t j = p.find('/', i); if (j == std::string::npos) { j = p.size(); } if (j > i) { tOut.push_back(p.substr(i, j - i)); } i = j + 1; } return tOut; } } // namespace WebrtcServer::WebrtcServer(const Conf & global, PathManager * paths) : LogParent("[WebRTC] "), m_global(global), m_pPaths(paths), m_http(this) {} WebrtcServer::~WebrtcServer() { stop(); } bool WebrtcServer::start(std::string & err) { rtc::InitLogger(rtc::LogLevel::Warning, [](rtc::LogLevel level, std::string message) { Logger::instance().log(level <= rtc::LogLevel::Error ? LogLevel::Error : (level == rtc::LogLevel::Warning ? LogLevel::Warn : LogLevel::Debug), "[WebRTC] [libdatachannel] %s", message.c_str()); }); if (! m_http.start(m_global.webrtcAddress, [this](const HttpRequest & q, HttpResponse & r) { handle(q, r); }, err)) { return false; } m_bRun = true; m_janitor = std::thread(&WebrtcServer::janitor, this); log(LogLevel::Info, "listener opened on %s (HTTP)", m_global.webrtcAddress.c_str()); return true; } void WebrtcServer::stop() { { std::lock_guard lock(m_stopMutex); if (! m_bRun) { return; } m_bRun = false; } m_stopCond.notify_all(); if (m_janitor.joinable()) { m_janitor.join(); } m_http.stop(); std::map> tAll; { std::lock_guard lock(m_mutex); tAll.swap(m_sessions); } for (auto & s : tAll) { s.second->close(); } rtc::Cleanup(); } size_t WebrtcServer::sessionCount() const { std::lock_guard lock(m_mutex); return m_sessions.size(); } void WebrtcServer::janitor() { while (true) { { std::unique_lock lock(m_stopMutex); m_stopCond.wait_for(lock, std::chrono::seconds(1), [this] { return ! m_bRun; }); if (! m_bRun) { return; } } std::vector> tClose; int64_t tNow = nowMs(); { std::lock_guard lock(m_mutex); for (auto it = m_sessions.begin(); it != m_sessions.end();) { if (it->second->isClosing() || it->second->connectTimedOut(tNow)) { tClose.push_back(it->second); it = m_sessions.erase(it); } else { ++it; } } } for (auto & s : tClose) { s->close(); } } } void WebrtcServer::handle(const HttpRequest & req, HttpResponse & res) { res.setHeader("Access-Control-Allow-Origin", m_global.webrtcAllowOrigin); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader("Access-Control-Expose-Headers", "ETag, ID, Accept-Patch, Link, Location"); if (req.method == "OPTIONS") { res.status = 204; res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PATCH, DELETE"); res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, If-Match"); return; } std::vector tParts = splitPath(req.path); // GET / or // -> player page if (req.method == "GET" && tParts.size() == 1) { if (req.path.back() != '/') { res.status = 301; res.setHeader("Location", req.path + "/"); return; } res.status = 200; res.setHeader("Content-Type", "text/html; charset=utf-8"); res.body = PLAYER_PAGE; return; } if (tParts.size() < 2 || tParts[1] != "whep") { res.status = 404; res.body = "not found"; return; } const std::string & tPathName = tParts[0]; if (tParts.size() == 2) { if (req.method != "POST") { res.status = 405; return; } std::string tType = req.header("content-type"); if (tType.compare(0, 15, "application/sdp") != 0) { res.status = 415; res.body = "invalid Content-Type"; return; } std::shared_ptr tPath = m_pPaths->find(tPathName); if (! tPath) { res.status = 404; res.body = "path '" + tPathName + "' is not configured"; log(LogLevel::Info, "%s: path '%s' is not configured", req.remoteAddr.c_str(), tPathName.c_str()); return; } std::string tSecret = newSecret(); auto tSession = std::make_shared(tSecret, tPath, m_global, req.remoteAddr); std::string tAnswer, tErr; int tStatus = 500; if (! tSession->create(req.body, tAnswer, tStatus, tErr)) { tSession->log(LogLevel::Info, "closed: %s", tErr.c_str()); tSession->close(); res.status = tStatus; res.body = tErr; return; } { std::lock_guard lock(m_mutex); m_sessions[tSecret] = tSession; } res.status = 201; res.setHeader("Content-Type", "application/sdp"); res.setHeader("ETag", "*"); res.setHeader("ID", tSecret); res.setHeader("Accept-Patch", "application/trickle-ice-sdpfrag"); res.setHeader("Location", "/" + tPathName + "/whep/" + tSecret); for (const std::string & s : m_global.webrtcICEServers) { res.setHeader("Link", "<" + s + ">; rel=\"ice-server\""); } res.body = tAnswer; return; } // //whep/ std::shared_ptr tSession; { std::lock_guard lock(m_mutex); auto it = m_sessions.find(tParts[2]); if (it != m_sessions.end() && it->second->pathName() == tPathName) { tSession = it->second; } } if (! tSession) { res.status = 404; res.body = "session not found"; return; } if (req.method == "PATCH") { std::string tErr; if (! tSession->addRemoteCandidates(req.body, tErr)) { res.status = 400; res.body = tErr; return; } res.status = 204; } else if (req.method == "DELETE") { { std::lock_guard lock(m_mutex); m_sessions.erase(tParts[2]); } tSession->log(LogLevel::Info, "deleted by the client"); tSession->close(); res.status = 200; } else { res.status = 405; } } } // namespace mtx