396 lines
17 KiB
C++
396 lines
17 KiB
C++
// http_client.cpp — HTTP через внешний инструмент с каскадом запасных вариантов.
|
||
//
|
||
// Почему не cpp-httplib: для HTTPS ему нужен OpenSSL, а заявленный принцип проекта —
|
||
// отсутствие внешних зависимостей. Поэтому здесь тонкая обёртка над тем, что уже
|
||
// установлено в системе: curl → wget → python3.
|
||
//
|
||
// Все аргументы проходят через shell_quote()/py_quote(), поэтому URL или путь
|
||
// с пробелами, кавычками и точкой с запятой не ломает команду и не позволяет инъекцию.
|
||
#include "http_client.h"
|
||
#include "platform.h"
|
||
|
||
#include <cstdio>
|
||
#include <cstdlib>
|
||
#include <cstring>
|
||
#include <filesystem>
|
||
#include <fstream>
|
||
#include <cctype>
|
||
#include <sstream>
|
||
#include <random>
|
||
|
||
#ifdef _WIN32
|
||
# define WIN32_LEAN_AND_MEAN
|
||
# define NOMINMAX
|
||
# include <windows.h>
|
||
# include <io.h>
|
||
# define XT_POPEN _popen
|
||
# define XT_PCLOSE _pclose
|
||
#else
|
||
# include <unistd.h>
|
||
# include <sys/wait.h>
|
||
# define XT_POPEN ::popen
|
||
# define XT_PCLOSE ::pclose
|
||
#endif
|
||
|
||
namespace fs = std::filesystem;
|
||
|
||
namespace xt {
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Экранирование
|
||
// ---------------------------------------------------------------------------
|
||
std::string shell_quote(const std::string& s) {
|
||
#ifdef _WIN32
|
||
// Правила разбора argv в MSVCRT (curl/git/python на Windows): аргумент с
|
||
// пробелами заключается в двойные кавычки, внутренние двойные кавычки и
|
||
// предшествующие им обратные слэши удваиваются/экранируются.
|
||
std::string out = "\"";
|
||
size_t backslashes = 0;
|
||
for (char c : s) {
|
||
if (c == '\\') { ++backslashes; out += c; continue; }
|
||
if (c == '"') {
|
||
for (size_t i = 0; i < backslashes; ++i) out += '\\';
|
||
backslashes = 0;
|
||
out += "\\\"";
|
||
continue;
|
||
}
|
||
backslashes = 0;
|
||
out += c;
|
||
}
|
||
for (size_t i = 0; i < backslashes; ++i) out += '\\';
|
||
out += "\"";
|
||
return out;
|
||
#else
|
||
// Одинарные кавычки для /bin/sh: внутри '...' не интерпретируется ничего,
|
||
// кроме самой одинарной кавычки, которую заменяем на '\''
|
||
std::string out = "'";
|
||
for (char c : s) {
|
||
if (c == '\'') out += "'\\''";
|
||
else out += c;
|
||
}
|
||
out += "'";
|
||
return out;
|
||
#endif
|
||
}
|
||
|
||
namespace {
|
||
|
||
#ifdef _WIN32
|
||
// Уникальный путь во временном каталоге (замена mkstemp).
|
||
std::string make_temp_path(const char* prefix) {
|
||
std::error_code ec;
|
||
fs::path base = fs::temp_directory_path(ec);
|
||
if (ec) base = fs::path(".");
|
||
static std::mt19937_64 rng(std::random_device{}());
|
||
std::string name = std::string(prefix) + "_" +
|
||
std::to_string(::GetCurrentProcessId()) + "_" +
|
||
std::to_string(rng());
|
||
return path_to_utf8(base / name);
|
||
}
|
||
#endif
|
||
|
||
// Имя python-интерпретатора: python3 на POSIX, python/py на Windows.
|
||
const char* py_tool() {
|
||
#ifdef _WIN32
|
||
static const char* found = [] {
|
||
for (const char* cand : {"python", "py", "python3"}) {
|
||
const std::string probe = std::string("where ") + cand + " >NUL 2>&1";
|
||
if (std::system(probe.c_str()) == 0) return cand;
|
||
}
|
||
return (const char*)nullptr;
|
||
}();
|
||
return found;
|
||
#else
|
||
return "python3";
|
||
#endif
|
||
}
|
||
|
||
// Одинарные кавычки для литерала в исходнике 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) {
|
||
#ifdef _WIN32
|
||
const std::string cmd = std::string("where ") + prog + " >NUL 2>&1";
|
||
#else
|
||
const std::string cmd = std::string("command -v ") + prog + " >/dev/null 2>&1";
|
||
#endif
|
||
return std::system(cmd.c_str()) == 0;
|
||
}
|
||
|
||
// Выполнить команду. Тело ответа (вместе с HTTP-кодом в последней строке)
|
||
// пишется во временный файл, stderr — во второй временный файл и попадает в err.
|
||
// Возвращает КОД ВОЗВРАТА САМОГО ПРОЦЕССА (0 = команда отработала).
|
||
//
|
||
// Раньше здесь было две ошибки, из-за которых каскад curl → wget → python3
|
||
// фактически работал только с curl:
|
||
// 1) stdout команды уходил во временный файл, поэтому в pipe не попадало
|
||
// ничего и функция всегда возвращала 0 (HTTP-код не возвращался никогда);
|
||
// 2) stderr глушился «2>/dev/null», так что текст ошибки был пустым
|
||
// («не удалось получить версию: python3: HTTP »).
|
||
int run_capture(const std::string& cmd, std::string& out_body, std::string& err) {
|
||
#ifdef _WIN32
|
||
const std::string tmpl = make_temp_path("xenith_http_body");
|
||
const std::string etmp = make_temp_path("xenith_http_err");
|
||
#else
|
||
char tbuf[] = "/tmp/xenith_http_body_XXXXXX";
|
||
char ebuf[] = "/tmp/xenith_http_err_XXXXXX";
|
||
const int fd = ::mkstemp(tbuf);
|
||
if (fd < 0) { err = "не удалось создать временный файл"; return -1; }
|
||
::close(fd);
|
||
const int fd2 = ::mkstemp(ebuf);
|
||
if (fd2 < 0) { std::remove(tbuf); err = "не удалось создать временный файл"; return -1; }
|
||
::close(fd2);
|
||
const std::string tmpl = tbuf, etmp = ebuf;
|
||
#endif
|
||
|
||
// Тело — в один временный файл, stderr — в другой. Код возврата берём из
|
||
// pclose (на POSIX декодируем WEXITSTATUS): прежняя конструкция
|
||
// «; echo $?» завязана на sh и на Windows не работает.
|
||
const std::string full = "(" + cmd + ") > " + shell_quote(tmpl) +
|
||
" 2> " + shell_quote(etmp);
|
||
FILE* pipe = XT_POPEN(full.c_str(), "r");
|
||
if (!pipe) { std::remove(tmpl.c_str()); std::remove(etmp.c_str()); err = "popen не удался"; return -1; }
|
||
char buf[256];
|
||
while (fgets(buf, sizeof buf, pipe)) { /* stdout команды уходит в файл */ }
|
||
const int rc_raw = XT_PCLOSE(pipe);
|
||
#ifdef _WIN32
|
||
const int rc = rc_raw;
|
||
#else
|
||
const int rc = WIFEXITED(rc_raw) ? WEXITSTATUS(rc_raw) : 1;
|
||
#endif
|
||
|
||
{
|
||
std::ifstream f(path_from_utf8(tmpl), std::ios::binary);
|
||
if (f) { std::ostringstream ss; ss << f.rdbuf(); out_body = ss.str(); }
|
||
}
|
||
{
|
||
std::ifstream f(path_from_utf8(etmp), std::ios::binary);
|
||
if (f) {
|
||
std::ostringstream ss; ss << f.rdbuf();
|
||
std::string e = ss.str();
|
||
while (!e.empty() && (e.back() == '\n' || e.back() == '\r' || e.back() == ' ')) e.pop_back();
|
||
if (e.size() > 300) e = e.substr(0, 300) + "…";
|
||
if (!e.empty()) err = e;
|
||
}
|
||
}
|
||
{
|
||
std::error_code ec_rm;
|
||
std::filesystem::remove(path_from_utf8(tmpl), ec_rm);
|
||
std::filesystem::remove(path_from_utf8(etmp), ec_rm);
|
||
}
|
||
return rc;
|
||
}
|
||
|
||
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-код последней строкой.
|
||
// cleanup: сюда попадают временные файлы (Windows-скрипт python), которые
|
||
// вызывающий обязан удалить после выполнения команды.
|
||
std::string build_cmd(const char* tool, const std::string& url, const HttpOptions& o,
|
||
std::vector<std::string>& cleanup) {
|
||
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 " + shell_quote("\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") || tool == std::string("python")) {
|
||
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";
|
||
#ifdef _WIN32
|
||
// cmd.exe не передаёт многострочный аргумент в -c: пишем скрипт во
|
||
// временный файл и запускаем его. Файл удаляет вызывающий (cleanup).
|
||
const std::string script = make_temp_path("xenith_http") + ".py";
|
||
{ std::ofstream f(path_from_utf8(script), std::ios::binary); f << py; }
|
||
cleanup.push_back(script);
|
||
return std::string(py_tool()) + " " + shell_quote(script);
|
||
#else
|
||
return std::string(py_tool()) + " -c " + shell_quote(py);
|
||
#endif
|
||
}
|
||
return "";
|
||
}
|
||
|
||
} // namespace
|
||
|
||
// ---------------------------------------------------------------------------
|
||
std::vector<std::string> http_available_tools() {
|
||
std::vector<std::string> out;
|
||
#ifdef _WIN32
|
||
for (const char* t : {"curl", "git"})
|
||
if (have(t)) out.push_back(t);
|
||
if (py_tool()) out.push_back(py_tool());
|
||
#else
|
||
for (const char* t : {"curl", "wget", "git"})
|
||
if (have(t)) out.push_back(t);
|
||
if (have("python3")) out.push_back("python3");
|
||
#endif
|
||
return out;
|
||
}
|
||
|
||
HttpResponse http_get(const std::string& url, const HttpOptions& opt) {
|
||
HttpResponse r;
|
||
#ifdef _WIN32
|
||
const char* tools[] = {"curl", "python"}; // "python" условно: реальный интерпретатор ищет py_tool()
|
||
#else
|
||
const char* tools[] = {"curl", "wget", "python3"};
|
||
#endif
|
||
for (const char* tool : tools) {
|
||
if (tool == std::string("python")) { if (!py_tool()) continue; }
|
||
else if (!have(tool)) continue;
|
||
std::string output, err;
|
||
std::vector<std::string> cleanup;
|
||
run_capture(build_cmd(tool, url, opt, cleanup), output, err);
|
||
for (const std::string& f : cleanup) {
|
||
std::error_code ec_rm;
|
||
fs::remove(path_from_utf8(f), ec_rm);
|
||
}
|
||
|
||
// Разделяем тело и HTTP-код. Код — ПОСЛЕДНЯЯ НЕПУСТАЯ строка: curl
|
||
// печатает его без завершающего перевода (--write-out '\n%{http_code}'),
|
||
// а wget и python3 — с переводом ('\n200\n'). Прежний разбор брал
|
||
// подстроку после последнего '\n', то есть для wget/python3 всегда
|
||
// получал пустую строку, код становился нулевым, и запрос считался
|
||
// проваленным с бессодержательным «python3: HTTP ».
|
||
std::string body = output, http_status_str;
|
||
while (!body.empty() && (body.back() == '\n' || body.back() == '\r')) body.pop_back();
|
||
const auto last_nl = body.rfind('\n');
|
||
if (last_nl != std::string::npos) {
|
||
http_status_str = body.substr(last_nl + 1);
|
||
body = body.substr(0, last_nl);
|
||
}
|
||
int http_code = 0;
|
||
bool status_looks_valid = !http_status_str.empty() && http_status_str.size() <= 3;
|
||
for (char c : http_status_str) if (!std::isdigit((unsigned char)c)) status_looks_valid = false;
|
||
if (status_looks_valid) {
|
||
try { http_code = std::stoi(http_status_str); } catch (...) { http_code = 0; }
|
||
} else {
|
||
// последняя строка — не код (например, wget не смог и напечатал только тело)
|
||
http_code = 0;
|
||
body = output;
|
||
while (!body.empty() && (body.back() == '\n' || body.back() == '\r')) body.pop_back();
|
||
}
|
||
|
||
if (http_code >= 200 && http_code < 300) {
|
||
r.ok = true;
|
||
r.status = http_code;
|
||
r.body = std::move(body);
|
||
r.via = tool;
|
||
return r;
|
||
}
|
||
r.status = http_code;
|
||
std::string why = http_code > 0 ? ("HTTP " + std::to_string(http_code))
|
||
: "нет ответа";
|
||
if (!err.empty()) why += " (" + err + ")";
|
||
if (r.error.empty()) r.error = std::string(tool) + ": " + why;
|
||
}
|
||
if (r.error.empty())
|
||
r.error = "в системе нет ни curl, ни wget, ни python";
|
||
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 || dest_path.find('\\') != std::string::npos)
|
||
fs::create_directories(path_from_utf8(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 (py_tool()) {
|
||
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";
|
||
#ifdef _WIN32
|
||
const std::string script = make_temp_path("xenith_dl") + ".py";
|
||
{ std::ofstream f(path_from_utf8(script), std::ios::binary); f << py; }
|
||
std::string c = std::string(py_tool()) + " " + shell_quote(script);
|
||
const int rc = std::system(c.c_str());
|
||
std::error_code ec_rm;
|
||
std::filesystem::remove(path_from_utf8(script), ec_rm);
|
||
#else
|
||
std::string c = std::string(py_tool()) + " -c " + shell_quote(py);
|
||
const int rc = std::system(c.c_str());
|
||
#endif
|
||
if (rc == 0) { if (via) *via = py_tool(); return true; }
|
||
err = std::string(py_tool()) + " не смог скачать " + url;
|
||
return false;
|
||
}
|
||
err = "в системе нет curl/wget/python — нечем скачать файл";
|
||
return false;
|
||
}
|
||
|
||
} // namespace xt
|