276 lines
12 KiB
C++
276 lines
12 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 <cctype>
|
||
#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-кодом в последней строке)
|
||
// пишется во временный файл, 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) {
|
||
char tmpl[] = "/tmp/xenith_http_body_XXXXXX";
|
||
char etmp[] = "/tmp/xenith_http_err_XXXXXX";
|
||
const int fd = ::mkstemp(tmpl);
|
||
if (fd < 0) { err = "не удалось создать временный файл"; return -1; }
|
||
::close(fd);
|
||
const int fd2 = ::mkstemp(etmp);
|
||
if (fd2 < 0) { std::remove(tmpl); err = "не удалось создать временный файл"; return -1; }
|
||
::close(fd2);
|
||
|
||
// «; echo $?» — единственное, что приходит в pipe: код возврата процесса.
|
||
const std::string full = "(" + cmd + ") > " + shell_quote(tmpl) +
|
||
" 2> " + shell_quote(etmp) + "; echo $?";
|
||
FILE* pipe = ::popen(full.c_str(), "r");
|
||
if (!pipe) { std::remove(tmpl); std::remove(etmp); err = "popen не удался"; return -1; }
|
||
|
||
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();
|
||
}
|
||
const int rc = ::pclose(pipe);
|
||
|
||
{
|
||
std::ifstream f(tmpl, std::ios::binary);
|
||
if (f) { std::ostringstream ss; ss << f.rdbuf(); out_body = ss.str(); }
|
||
}
|
||
{
|
||
std::ifstream f(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::remove(tmpl);
|
||
std::remove(etmp);
|
||
|
||
if (!last.empty()) return std::atoi(last.c_str());
|
||
return (rc == 0) ? 0 : (rc == -1 ? 1 : 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-код последней строкой.
|
||
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;
|
||
run_capture(build_cmd(tool, url, opt), output, err);
|
||
|
||
// Разделяем тело и 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, ни 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
|