Files
Xenith/xenith/core/http_client.cpp
2026-10-15 00:19:15 +07:00

249 lines
9.9 KiB
C++

// http_client.cpp — HTTP через внешний инструмент с каскадом запасных вариантов.
//
// Почему не cpp-httplib: для HTTPS ему нужен OpenSSL, а заявленный принцип проекта —
// отсутствие внешних зависимостей. Поэтому здесь тонкая обёртка над тем, что уже
// установлено в системе: curl → wget → python3.
//
// Все аргументы проходят через shell_quote()/py_quote(), поэтому URL или путь
// с пробелами, кавычками и точкой с запятой не ломает команду и не позволяет инъекцию.
#include "http_client.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <unistd.h>
namespace fs = std::filesystem;
namespace xt {
// ---------------------------------------------------------------------------
// Экранирование
// ---------------------------------------------------------------------------
// Одинарные кавычки для /bin/sh: внутри '...' не интерпретируется ничего,
// кроме самой одинарной кавычки, которую заменяем на '\''
std::string shell_quote(const std::string& s) {
std::string out = "'";
for (char c : s) {
if (c == '\'') out += "'\\''";
else out += c;
}
out += "'";
return out;
}
namespace {
// Одинарные кавычки для литерала в исходнике Python.
std::string py_quote(const std::string& s) {
std::string out = "'";
for (char c : s) {
if (c == '\\' || c == '\'' || c == '\n' || c == '\r') out += '\\';
out += c;
}
out += "'";
return out;
}
bool have(const char* prog) {
const std::string cmd = std::string("command -v ") + prog + " >/dev/null 2>&1";
return std::system(cmd.c_str()) == 0;
}
// Выполнить команду; тело ответа пишется во временный файл, HTTP-код — в stdout
// последней строкой. Возвращает код (0 = запрос не удался).
int run_capture(const std::string& cmd, std::string& out_body, std::string& err) {
char tmpl[] = "/tmp/xenith_http_XXXXXX";
const int fd = ::mkstemp(tmpl);
if (fd < 0) { err = "не удалось создать временный файл"; return 0; }
::close(fd);
const std::string full = "(" + cmd + ") > " + shell_quote(tmpl) + " 2>/dev/null";
FILE* pipe = ::popen(full.c_str(), "r");
if (!pipe) { std::remove(tmpl); err = "popen не удался"; return 0; }
char buf[256];
std::string last;
while (fgets(buf, sizeof buf, pipe)) {
last.assign(buf);
while (!last.empty() && (last.back() == '\n' || last.back() == '\r')) last.pop_back();
}
::pclose(pipe);
{
std::ifstream f(tmpl, std::ios::binary);
if (f) { std::ostringstream ss; ss << f.rdbuf(); out_body = ss.str(); }
}
std::remove(tmpl);
int status = last.empty() ? 0 : std::atoi(last.c_str());
if (status < 0) status = 0;
if (status == 0 && out_body.empty()) err = "нет ответа";
return status;
}
std::string headers_curl(const HttpOptions& o) {
std::string c;
for (const auto& h : o.headers)
c += " --header " + shell_quote(h.first + ": " + h.second);
return c;
}
std::string headers_python(const HttpOptions& o) {
std::string s;
for (const auto& h : o.headers)
s += " " + py_quote(h.first) + ": " + py_quote(h.second) + ",\n";
return s;
}
// Каскад команд. Каждая печатает тело в stdout и HTTP-код последней строкой.
std::string build_cmd(const char* tool, const std::string& url, const HttpOptions& o) {
const std::string t = std::to_string(o.timeout_sec > 0 ? o.timeout_sec : 15);
if (tool == std::string("curl")) {
std::string c = "curl -sS --max-time " + t;
if (!o.verify_tls) c += " --insecure";
if (o.follow) c += " --location";
c += headers_curl(o);
c += " --write-out '\\n%{http_code}' " + shell_quote(url);
return c;
}
if (tool == std::string("wget")) {
// wget не умеет отдавать код состояния вместе с телом, поэтому
// используем --server-response и grep. Если не выйдет — код будет 200/000.
std::string c = "wget -q --timeout=" + t + " --tries=1";
if (!o.verify_tls) c += " --no-check-certificate";
for (const auto& h : o.headers) c += " --header=" + shell_quote(h.first + ": " + h.second);
c += " -O - " + shell_quote(url) + " && printf '\\n200\\n' || printf '\\n000\\n'";
return c;
}
if (tool == std::string("python3")) {
std::string py;
py += "import ssl,sys,urllib.request,urllib.error\n";
py += "ctx=ssl.create_default_context()\n";
if (!o.verify_tls) py += "ctx.check_hostname=False\nctx.verify_mode=ssl.CERT_NONE\n";
py += "h={\n" + headers_python(o) + "}\n";
py += "req=urllib.request.Request(" + py_quote(url) + ",headers=h)\n";
py += "try:\n";
py += " r=urllib.request.urlopen(req,timeout=" + t + ",context=ctx)\n";
py += " sys.stdout.buffer.write(r.read())\n";
py += " sys.stdout.write('\\n%d\\n'%r.status)\n";
py += "except urllib.error.HTTPError as e:\n";
py += " d=e.read() or b''\n";
py += " sys.stdout.buffer.write(d)\n";
py += " sys.stdout.write('\\n%d\\n'%e.code)\n";
py += "except Exception:\n";
py += " sys.stdout.write('\\n000\\n')\n";
return "python3 -c " + shell_quote(py);
}
return "";
}
} // namespace
// ---------------------------------------------------------------------------
std::vector<std::string> http_available_tools() {
std::vector<std::string> out;
for (const char* t : {"curl", "wget", "python3", "git"})
if (have(t)) out.push_back(t);
return out;
}
HttpResponse http_get(const std::string& url, const HttpOptions& opt) {
HttpResponse r;
for (const char* tool : {"curl", "wget", "python3"}) {
if (!have(tool)) continue;
std::string output, err;
const int exit_code = run_capture(build_cmd(tool, url, opt), output, err);
// Для curl/wget/python3: успех процесса = exit_code == 0
if (exit_code != 0) {
if (r.error.empty())
r.error = std::string(tool) + ": " + (err.empty() ? "запрос не удался" : err);
continue;
}
// Разделяем тело и HTTP-код (последняя строка — это код)
std::string body, http_status_str;
auto last_nl = output.rfind('\n');
if (last_nl != std::string::npos) {
body = output.substr(0, last_nl);
http_status_str = output.substr(last_nl + 1);
// Убираем возможные \r\n
while (!http_status_str.empty() && (http_status_str.back() == '\r' || http_status_str.back() == '\n'))
http_status_str.pop_back();
} else {
body = output;
http_status_str = "200"; // fallback
}
int http_code = 0;
try { http_code = std::stoi(http_status_str); } catch (...) {}
if (http_code >= 200 && http_code < 300) {
r.ok = true;
r.status = http_code;
r.body = std::move(body);
r.via = tool;
return r;
} else {
if (r.error.empty())
r.error = std::string(tool) + ": HTTP " + http_status_str;
}
}
if (r.error.empty())
r.error = "в системе нет ни curl, ни wget, ни python3";
return r;
}
bool http_download(const std::string& url, const std::string& dest_path,
const HttpOptions& opt, std::string& err, std::string* via) {
std::error_code ec;
if (dest_path.find('/') != std::string::npos)
fs::create_directories(fs::path(dest_path).parent_path(), ec);
const std::string t = std::to_string((opt.timeout_sec > 0 ? opt.timeout_sec : 15) * 8);
const std::string dst = shell_quote(dest_path);
const std::string u = shell_quote(url);
if (have("curl")) {
std::string c = "curl -sSL --fail --max-time " + t;
if (!opt.verify_tls) c += " --insecure";
c += headers_curl(opt);
c += " -o " + dst + " " + u;
if (std::system(c.c_str()) == 0) { if (via) *via = "curl"; return true; }
err = "curl не смог скачать " + url;
return false;
}
if (have("wget")) {
std::string c = "wget -q --timeout=" + t + " --tries=1";
if (!opt.verify_tls) c += " --no-check-certificate";
c += " -O " + dst + " " + u;
if (std::system(c.c_str()) == 0) { if (via) *via = "wget"; return true; }
err = "wget не смог скачать " + url;
return false;
}
if (have("python3")) {
std::string py;
py += "import ssl,urllib.request\n";
py += "ctx=ssl.create_default_context()\n";
if (!opt.verify_tls) py += "ctx.check_hostname=False\nctx.verify_mode=ssl.CERT_NONE\n";
py += "req=urllib.request.Request(" + py_quote(url) + ")\n";
py += "d=urllib.request.urlopen(req,timeout=" + t + ",context=ctx).read()\n";
py += "open(" + py_quote(dest_path) + ",'wb').write(d)\n";
std::string c = "python3 -c " + shell_quote(py);
if (std::system(c.c_str()) == 0) { if (via) *via = "python3"; return true; }
err = "python3 не смог скачать " + url;
return false;
}
err = "в системе нет curl/wget/python3 — нечем скачать файл";
return false;
}
} // namespace xt