|
| 1 | +/* |
| 2 | + * Copyright (c) OpenMOQ contributors. |
| 3 | + * This source code is licensed under the Apache 2.0 license found in the |
| 4 | + * LICENSE file in the root directory of this source tree. |
| 5 | + */ |
| 6 | + |
| 7 | +#include "admin/ConnectionLogsHandler.h" |
| 8 | + |
| 9 | +#include <cctype> |
| 10 | +#include <string> |
| 11 | +#include <string_view> |
| 12 | + |
| 13 | +#include <fcntl.h> |
| 14 | +#include <sys/stat.h> |
| 15 | + |
| 16 | +#include <folly/CancellationToken.h> |
| 17 | +#include <folly/File.h> |
| 18 | +#include <folly/FileUtil.h> |
| 19 | +#include <folly/coro/Invoke.h> |
| 20 | +#include <folly/coro/Task.h> |
| 21 | +#include <folly/coro/WithCancellation.h> |
| 22 | +#include <folly/executors/GlobalExecutor.h> |
| 23 | +#include <folly/io/IOBuf.h> |
| 24 | +#include <folly/io/async/EventBaseManager.h> |
| 25 | +#include <folly/logging/xlog.h> |
| 26 | +#include <proxygen/httpserver/ResponseBuilder.h> |
| 27 | +#include <proxygen/lib/http/HTTPMessage.h> |
| 28 | + |
| 29 | +#include "admin/AdminResponse.h" |
| 30 | +#include "admin/AdminServer.h" |
| 31 | + |
| 32 | +namespace openmoq::moqx::admin { |
| 33 | + |
| 34 | +namespace { |
| 35 | + |
| 36 | +constexpr size_t kMaxDownloadBytes = 512ULL * 1024 * 1024; // 512 MB hard cap |
| 37 | + |
| 38 | +// Normalize a raw connection ID string: |
| 39 | +// - strip 0x/0X prefix |
| 40 | +// - lowercase hex digits |
| 41 | +// - validate hex-only, 1–40 chars |
| 42 | +std::optional<std::string> normalizeConnectionId(std::string_view raw) { |
| 43 | + if (raw.size() >= 2 && raw[0] == '0' && (raw[1] == 'x' || raw[1] == 'X')) { |
| 44 | + raw.remove_prefix(2); |
| 45 | + } |
| 46 | + std::string result; |
| 47 | + result.reserve(raw.size()); |
| 48 | + for (char c : raw) { |
| 49 | + if (!std::isxdigit(static_cast<unsigned char>(c))) |
| 50 | + return std::nullopt; |
| 51 | + result += static_cast<char>(std::tolower(static_cast<unsigned char>(c))); |
| 52 | + } |
| 53 | + if (result.empty() || result.size() > 40) |
| 54 | + return std::nullopt; |
| 55 | + return result; |
| 56 | +} |
| 57 | + |
| 58 | +// Read an entire file into an IOBuf. Returns nullptr if the file cannot be |
| 59 | +// opened, is empty, or exceeds maxBytes. |
| 60 | +std::unique_ptr<folly::IOBuf> readFileToIOBuf(const std::string& path, size_t maxBytes) { |
| 61 | + folly::File file; |
| 62 | + try { |
| 63 | + file = folly::File(path, O_RDONLY); |
| 64 | + } catch (const std::exception&) { |
| 65 | + return nullptr; |
| 66 | + } |
| 67 | + |
| 68 | + struct stat st{}; |
| 69 | + if (::fstat(file.fd(), &st) != 0 || !S_ISREG(st.st_mode)) |
| 70 | + return nullptr; |
| 71 | + const auto size = static_cast<size_t>(st.st_size); |
| 72 | + if (size == 0 || size > maxBytes) |
| 73 | + return nullptr; |
| 74 | + |
| 75 | + auto content = std::make_unique<std::string>(); |
| 76 | + if (!folly::readFile(file.fd(), *content, size) || content->size() != size) |
| 77 | + return nullptr; |
| 78 | + |
| 79 | + auto* data = content->data(); |
| 80 | + const auto len = content->size(); |
| 81 | + return folly::IOBuf::takeOwnership( |
| 82 | + data, |
| 83 | + len, |
| 84 | + [](void*, void* userData) { delete static_cast<std::string*>(userData); }, |
| 85 | + content.release() |
| 86 | + ); |
| 87 | +} |
| 88 | + |
| 89 | +} // namespace |
| 90 | + |
| 91 | +void registerConnectionLogsRoutes( |
| 92 | + AdminServer& adminServer, |
| 93 | + const std::optional<config::LoggingConfig>& logging |
| 94 | +) { |
| 95 | + std::string mlogDir, qlogDir; |
| 96 | + if (logging) { |
| 97 | + if (logging->mlog && !logging->mlog->dir.empty()) { |
| 98 | + mlogDir = logging->mlog->dir; |
| 99 | + } |
| 100 | + if (logging->qlog && !logging->qlog->dir.empty()) { |
| 101 | + qlogDir = logging->qlog->dir; |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + // ── GET /logs?connection_id=<hex>&type=mlog|qlog |
| 106 | + // |
| 107 | + // Path is constructed directly as {dir}/{normalized_cid}.{ext} |
| 108 | + adminServer.addRoute( |
| 109 | + "GET", |
| 110 | + "/logs", |
| 111 | + [mlogDir = std::move(mlogDir), qlogDir = std::move(qlogDir)]( |
| 112 | + std::unique_ptr<proxygen::HTTPMessage> req, |
| 113 | + std::unique_ptr<folly::IOBuf> /*body*/, |
| 114 | + proxygen::ResponseHandler* downstream, |
| 115 | + folly::CancellationToken cancelToken |
| 116 | + ) { |
| 117 | + // Resolve type → directory, file extension, Content-Type. |
| 118 | + const auto& typeStr = req->getQueryParam("type"); |
| 119 | + const std::string* dir = nullptr; |
| 120 | + const char* ext = nullptr; |
| 121 | + if (typeStr == "mlog") { |
| 122 | + dir = &mlogDir; |
| 123 | + ext = ".mlog"; |
| 124 | + } else if (typeStr == "qlog") { |
| 125 | + dir = &qlogDir; |
| 126 | + ext = ".qlog"; |
| 127 | + } else { |
| 128 | + sendError(downstream, 400, "type must be 'mlog' or 'qlog'\n"); |
| 129 | + return; |
| 130 | + } |
| 131 | + |
| 132 | + if (dir->empty()) { |
| 133 | + sendError(downstream, 503, "that log type is not configured\n"); |
| 134 | + return; |
| 135 | + } |
| 136 | + |
| 137 | + const auto& rawCid = req->getQueryParam("connection_id"); |
| 138 | + if (rawCid.empty()) { |
| 139 | + sendError(downstream, 400, "missing connection_id\n"); |
| 140 | + return; |
| 141 | + } |
| 142 | + |
| 143 | + auto normCid = normalizeConnectionId(rawCid); |
| 144 | + if (!normCid) { |
| 145 | + sendError(downstream, 400, "invalid connection_id\n"); |
| 146 | + return; |
| 147 | + } |
| 148 | + |
| 149 | + // {dir}/{normalizedCid}.{ext} |
| 150 | + auto filePath = *dir + "/" + *normCid + ext; |
| 151 | + auto fileName = *normCid + ext; |
| 152 | + |
| 153 | + auto* evb = folly::EventBaseManager::get()->getEventBase(); |
| 154 | + folly::coro::co_withCancellation( |
| 155 | + cancelToken, |
| 156 | + folly::coro::co_withExecutor( |
| 157 | + evb, |
| 158 | + [](auto path, auto name, auto* ds, auto token) -> folly::coro::Task<void> { |
| 159 | + if (token.isCancellationRequested()) |
| 160 | + co_return; |
| 161 | + |
| 162 | + // Read the file on the global CPU pool to avoid blocking |
| 163 | + // the admin event-loop thread. |
| 164 | + std::unique_ptr<folly::IOBuf> fileBuf; |
| 165 | + try { |
| 166 | + fileBuf = co_await folly::coro::co_withExecutor( |
| 167 | + folly::getGlobalCPUExecutor(), |
| 168 | + folly::coro::co_invoke( |
| 169 | + [path = std::move(path), maxBytes = kMaxDownloadBytes]( |
| 170 | + ) -> folly::coro::Task<std::unique_ptr<folly::IOBuf>> { |
| 171 | + co_return readFileToIOBuf(path, maxBytes); |
| 172 | + } |
| 173 | + ) |
| 174 | + ); |
| 175 | + } catch (const std::exception& e) { |
| 176 | + XLOG(ERR) << "ConnectionLogsHandler: file read threw: " << e.what(); |
| 177 | + if (!token.isCancellationRequested()) { |
| 178 | + sendError(ds, 500, "internal error\n"); |
| 179 | + } |
| 180 | + co_return; |
| 181 | + } |
| 182 | + |
| 183 | + if (token.isCancellationRequested()) |
| 184 | + co_return; |
| 185 | + |
| 186 | + if (!fileBuf) { |
| 187 | + sendError(ds, 404, "log file not found or exceeds size limit\n"); |
| 188 | + co_return; |
| 189 | + } |
| 190 | + |
| 191 | + proxygen::ResponseBuilder(ds) |
| 192 | + .status(200, proxygen::HTTPMessage::getDefaultReason(200)) |
| 193 | + .header("Content-Type", "application/json") |
| 194 | + .header("Content-Disposition", "attachment; filename=\"" + name + "\"") |
| 195 | + .body(std::move(fileBuf)) |
| 196 | + .sendWithEOM(); |
| 197 | + }(std::move(filePath), std::move(fileName), downstream, cancelToken) |
| 198 | + ) |
| 199 | + ) |
| 200 | + .start(); |
| 201 | + } |
| 202 | + ); |
| 203 | +} |
| 204 | + |
| 205 | +} // namespace openmoq::moqx::admin |
0 commit comments