core: client API Majestic, modèles et CLI check
- libopenpu : validation VIN, modèles JSON (getAvailableUpdate, devices), classification ecuType -> type/guide, sélection des mises à jour - couche Transport abstraite + implémentation libcurl (proxy env, redirections, streaming, timeout d'inactivité) - tolérance au EOF TLS sans close_notify de la passerelle Majestic, limitée aux corps délimités par la fermeture (ni Content-Length ni chunked) - openpu-cli : check / raw-devices / raw-updates - tests doctest (VIN, parsing, classification, client API avec faux transport), fixtures dont une capture réelle anonymisée (NAC wave 2) - qualité : presets CMake (debug, asan, tidy), .clang-tidy, tools/check.sh (tests, ASan/UBSan, valgrind, clang-tidy, cppcheck) - validé contre l'API réelle sur 3 véhicules (NAC w4, RCC, NAC w2) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WDASLCiN764v685boRVYar
This commit is contained in:
1 parent
660a420a3e
commit
95704f9882
28 files changed
+1877
-2
No files matched your search
@@ -0,0 +1,3 @@
|
||||
add_executable(openpu-cli main.cpp)
|
||||
target_link_libraries(openpu-cli PRIVATE openpu_core openpu_warnings)
|
||||
install(TARGETS openpu-cli RUNTIME DESTINATION bin)
|
||||
@@ -0,0 +1,109 @@
|
||||
// openpu-cli — command-line front-end of libopenpu.
|
||||
|
||||
#include "openpu/api_client.hpp"
|
||||
#include "openpu/vin.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
void usage()
|
||||
{
|
||||
std::cerr << "usage: openpu-cli [--verbose] <command> [args]\n"
|
||||
"\n"
|
||||
"commands:\n"
|
||||
" check <VIN> identify the head unit and list available updates\n"
|
||||
" raw-devices <VIN> print the raw devices/{VIN} response\n"
|
||||
" raw-updates <VIN> print the raw getAvailableUpdate response (all software types)\n"
|
||||
"\n"
|
||||
"environment: OPENPU_DEVICES_URL, OPENPU_UPDATES_URL, OPENPU_CLIENT_ID,\n"
|
||||
" http_proxy, https_proxy, no_proxy\n";
|
||||
}
|
||||
|
||||
std::string humanSize(std::uint64_t bytes)
|
||||
{
|
||||
const char* units[] = {"B", "KB", "MB", "GB", "TB"};
|
||||
auto value = static_cast<double>(bytes);
|
||||
std::size_t unit = 0;
|
||||
while (value >= 1000.0 && unit + 1 < std::size(units)) {
|
||||
value /= 1000.0;
|
||||
++unit;
|
||||
}
|
||||
char buf[32];
|
||||
(void)std::snprintf(buf, sizeof buf, unit == 0 ? "%.0f %s" : "%.2f %s", value, units[unit]);
|
||||
return buf;
|
||||
}
|
||||
|
||||
void printUpdate(const char* label, const std::optional<openpu::UpdateInfo>& u)
|
||||
{
|
||||
if (!u) {
|
||||
std::cout << label << ": none\n";
|
||||
return;
|
||||
}
|
||||
std::cout << label << ": " << u->version << " (" << u->softwareType << ", " << humanSize(u->size)
|
||||
<< ", " << (u->date.empty() ? "no date" : u->date) << ")\n";
|
||||
}
|
||||
|
||||
int printRaw(const openpu::HttpResponse& r)
|
||||
{
|
||||
std::cerr << "HTTP " << r.status << '\n';
|
||||
std::cout << r.body << '\n';
|
||||
return r.status >= 200 && r.status < 300 ? 0 : 1;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
std::vector<std::string> args(argv + 1, argv + argc);
|
||||
openpu::CurlOptions curlOptions;
|
||||
if (!args.empty() && args.front() == "--verbose") {
|
||||
curlOptions.verbose = true;
|
||||
args.erase(args.begin());
|
||||
}
|
||||
if (args.size() != 2) {
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
const std::string& command = args[0];
|
||||
const std::string vin = openpu::normalizeVin(args[1]);
|
||||
if (!openpu::isValidVin(vin)) {
|
||||
std::cerr << "error: invalid VIN (expected V[FR]3 followed by 14 letters/digits)\n";
|
||||
return 2;
|
||||
}
|
||||
|
||||
auto transport = openpu::makeCurlTransport(curlOptions);
|
||||
openpu::ApiClient api(*transport, openpu::ApiConfig::fromEnvironment());
|
||||
|
||||
try {
|
||||
if (command == "raw-devices")
|
||||
return printRaw(api.rawDevices(vin));
|
||||
if (command == "raw-updates")
|
||||
return printRaw(api.rawUpdates(vin, openpu::software::all()));
|
||||
if (command != "check") {
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
|
||||
const openpu::VehicleCheck check = api.checkVehicle(vin);
|
||||
if (!check.exists) {
|
||||
std::cout << "vehicle not found\n";
|
||||
return 1;
|
||||
}
|
||||
if (check.type == openpu::HeadUnitType::Unknown) {
|
||||
std::cout << "vehicle found, but its head unit is not supported\n";
|
||||
return 1;
|
||||
}
|
||||
std::cout << "head unit: " << openpu::headUnitTypeName(check.type) << "\nguide: " << check.guideKey << '\n';
|
||||
const openpu::AvailableUpdates updates = api.getUpdates(vin, check.type);
|
||||
printUpdate("firmware", updates.firmware);
|
||||
printUpdate("map", updates.map);
|
||||
return 0;
|
||||
} catch (const openpu::ApiError& e) {
|
||||
std::cerr << "error: " << e.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
find_package(CURL REQUIRED)
|
||||
find_package(nlohmann_json 3.2 REQUIRED)
|
||||
|
||||
add_library(openpu_core STATIC
|
||||
vin.cpp
|
||||
models.cpp
|
||||
http.cpp
|
||||
curl_transport.cpp
|
||||
api_client.cpp
|
||||
)
|
||||
target_include_directories(openpu_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
target_link_libraries(openpu_core
|
||||
PUBLIC CURL::libcurl
|
||||
PRIVATE nlohmann_json::nlohmann_json openpu_warnings)
|
||||
target_compile_definitions(openpu_core PRIVATE OPENPU_VERSION="${PROJECT_VERSION}")
|
||||
@@ -0,0 +1,122 @@
|
||||
#include "openpu/api_client.hpp"
|
||||
|
||||
#include "openpu/vin.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace openpu {
|
||||
|
||||
namespace {
|
||||
|
||||
void overrideFromEnv(std::string& field, const char* name)
|
||||
{
|
||||
const char* value = std::getenv(name); // NOLINT(concurrency-mt-unsafe): read once at startup
|
||||
if (value != nullptr && *value != '\0')
|
||||
field = value;
|
||||
}
|
||||
|
||||
std::string withClientId(const std::string& url, const std::string& clientId)
|
||||
{
|
||||
return url + (url.find('?') == std::string::npos ? "?" : "&") + "client_id=" + clientId;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ApiConfig ApiConfig::fromEnvironment()
|
||||
{
|
||||
ApiConfig c;
|
||||
overrideFromEnv(c.devicesUrl, "OPENPU_DEVICES_URL");
|
||||
overrideFromEnv(c.updatesUrl, "OPENPU_UPDATES_URL");
|
||||
overrideFromEnv(c.clientId, "OPENPU_CLIENT_ID");
|
||||
return c;
|
||||
}
|
||||
|
||||
ApiClient::ApiClient(Transport& transport, ApiConfig config) : transport_(transport), config_(std::move(config)) {}
|
||||
|
||||
void ApiClient::requireValidVin(const std::string& vin)
|
||||
{
|
||||
if (!isValidVin(vin))
|
||||
throw ApiError(ApiError::Kind::InvalidVin, 0, "invalid VIN: " + vin);
|
||||
}
|
||||
|
||||
HttpResponse ApiClient::send(HttpRequest request)
|
||||
{
|
||||
request.headers.emplace_back("Accept", "application/json, text/plain, */*");
|
||||
request.stallTimeout = std::chrono::seconds(30);
|
||||
try {
|
||||
return transport_.perform(request);
|
||||
} catch (const NetworkError& e) {
|
||||
throw ApiError(ApiError::Kind::Network, 0, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
HttpResponse ApiClient::rawDevices(const std::string& vin)
|
||||
{
|
||||
requireValidVin(vin);
|
||||
HttpRequest req;
|
||||
req.method = HttpMethod::Get;
|
||||
req.url = withClientId(config_.devicesUrl + vin, config_.clientId);
|
||||
return send(std::move(req));
|
||||
}
|
||||
|
||||
HttpResponse ApiClient::rawUpdates(const std::string& vin, const std::vector<std::string>& softwareTypes)
|
||||
{
|
||||
requireValidVin(vin);
|
||||
HttpRequest req;
|
||||
req.method = HttpMethod::Post;
|
||||
req.url = withClientId(config_.updatesUrl, config_.clientId);
|
||||
req.headers.emplace_back("Content-Type", "application/json");
|
||||
req.body = buildUpdateRequest(vin, softwareTypes);
|
||||
return send(std::move(req));
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
void requireOk(const HttpResponse& r, const char* what)
|
||||
{
|
||||
if (r.status < 200 || r.status >= 300)
|
||||
throw ApiError(ApiError::Kind::Server, r.status,
|
||||
std::string(what) + ": HTTP " + std::to_string(r.status));
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
auto parseOrThrow(F&& parse, const HttpResponse& r, const char* what)
|
||||
{
|
||||
try {
|
||||
return parse(r.body);
|
||||
} catch (const ParseError& e) {
|
||||
throw ApiError(ApiError::Kind::BadResponse, r.status, std::string(what) + ": " + e.what());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
VehicleCheck ApiClient::checkVehicle(const std::string& vin)
|
||||
{
|
||||
// The original application fires both calls in parallel; we serialise them because the
|
||||
// official code notes that concurrent Majestic calls sometimes both fail.
|
||||
const HttpResponse devices = rawDevices(vin);
|
||||
if (devices.status == 404)
|
||||
return {};
|
||||
requireOk(devices, "devices");
|
||||
const DevicesResponse dev = parseOrThrow(parseDevices, devices, "devices");
|
||||
|
||||
const HttpResponse updates = rawUpdates(vin, software::all());
|
||||
requireOk(updates, "getAvailableUpdate");
|
||||
const UpdateListResponse list = parseOrThrow(parseUpdateList, updates, "getAvailableUpdate");
|
||||
|
||||
return classifyVehicle(list, dev);
|
||||
}
|
||||
|
||||
AvailableUpdates ApiClient::getUpdates(const std::string& vin, HeadUnitType type)
|
||||
{
|
||||
const SoftwarePair pair = softwareTypesFor(type);
|
||||
std::vector<std::string> types{pair.firmware};
|
||||
if (pair.map)
|
||||
types.push_back(*pair.map);
|
||||
const HttpResponse updates = rawUpdates(vin, types);
|
||||
requireOk(updates, "getAvailableUpdate");
|
||||
return selectUpdates(parseOrThrow(parseUpdateList, updates, "getAvailableUpdate"), type);
|
||||
}
|
||||
|
||||
} // namespace openpu
|
||||
@@ -0,0 +1,211 @@
|
||||
#include "openpu/http.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <curl/curl.h>
|
||||
#include <mutex>
|
||||
|
||||
#ifndef OPENPU_VERSION
|
||||
#define OPENPU_VERSION "dev"
|
||||
#endif
|
||||
|
||||
namespace openpu {
|
||||
|
||||
namespace {
|
||||
|
||||
void globalInit()
|
||||
{
|
||||
static std::once_flag once;
|
||||
std::call_once(once, [] { curl_global_init(CURL_GLOBAL_DEFAULT); });
|
||||
}
|
||||
|
||||
struct CurlEasyDeleter {
|
||||
void operator()(CURL* c) const { curl_easy_cleanup(c); }
|
||||
};
|
||||
struct CurlSlistDeleter {
|
||||
void operator()(curl_slist* l) const { curl_slist_free_all(l); }
|
||||
};
|
||||
|
||||
struct TransferState {
|
||||
const HttpRequest* request = nullptr;
|
||||
HttpResponse* response = nullptr;
|
||||
CURL* handle = nullptr;
|
||||
bool headersDelivered = false;
|
||||
bool abortedByCallback = false;
|
||||
};
|
||||
|
||||
std::string toLower(std::string s)
|
||||
{
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
|
||||
return s;
|
||||
}
|
||||
|
||||
std::size_t onHeaderLine(char* buffer, std::size_t size, std::size_t nitems, void* userdata)
|
||||
{
|
||||
auto* st = static_cast<TransferState*>(userdata);
|
||||
const std::size_t len = size * nitems;
|
||||
std::string line(buffer, len);
|
||||
while (!line.empty() && (line.back() == '\r' || line.back() == '\n'))
|
||||
line.pop_back();
|
||||
|
||||
if (line.rfind("HTTP/", 0) == 0) {
|
||||
// New response (first one, or the target of a redirect): reset headers.
|
||||
st->response->headers.clear();
|
||||
return len;
|
||||
}
|
||||
const auto colon = line.find(':');
|
||||
if (colon != std::string::npos) {
|
||||
std::string name = toLower(line.substr(0, colon));
|
||||
std::string value = line.substr(colon + 1);
|
||||
const auto first = value.find_first_not_of(" \t");
|
||||
value = first == std::string::npos ? std::string() : value.substr(first);
|
||||
st->response->headers[name] = value;
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
bool deliverHeaders(TransferState* st)
|
||||
{
|
||||
if (st->headersDelivered)
|
||||
return true;
|
||||
st->headersDelivered = true;
|
||||
long status = 0;
|
||||
curl_easy_getinfo(st->handle, CURLINFO_RESPONSE_CODE, &status);
|
||||
st->response->status = status;
|
||||
if (st->request->onHeaders && !st->request->onHeaders(status, st->response->headers)) {
|
||||
st->abortedByCallback = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::size_t onBody(char* ptr, std::size_t size, std::size_t nmemb, void* userdata)
|
||||
{
|
||||
auto* st = static_cast<TransferState*>(userdata);
|
||||
const std::size_t len = size * nmemb;
|
||||
if (!deliverHeaders(st))
|
||||
return 0;
|
||||
if (st->request->onData) {
|
||||
if (!st->request->onData(ptr, len)) {
|
||||
st->abortedByCallback = true;
|
||||
return 0;
|
||||
}
|
||||
} else {
|
||||
st->response->body.append(ptr, len);
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
/// The Majestic gateway ends bodies that have neither Content-Length nor chunked encoding by
|
||||
/// closing the TLS connection without close_notify. OpenSSL 3 reports that as a receive error
|
||||
/// ("unexpected eof while reading"), although the body is complete by HTTP/1.1 rules (the body
|
||||
/// is delimited by the connection close). Browsers accept it, and so do we, but only in this case.
|
||||
bool isCloseDelimitedEof(CURL* h, CURLcode rc, const HttpResponse& response)
|
||||
{
|
||||
if (rc != CURLE_RECV_ERROR)
|
||||
return false;
|
||||
long status = 0;
|
||||
curl_easy_getinfo(h, CURLINFO_RESPONSE_CODE, &status);
|
||||
if (status <= 0)
|
||||
return false;
|
||||
const auto& hd = response.headers;
|
||||
if (hd.count("content-length") != 0)
|
||||
return false;
|
||||
const auto te = hd.find("transfer-encoding");
|
||||
if (te != hd.end() && toLower(te->second).find("chunked") != std::string::npos)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
class CurlTransport final : public Transport {
|
||||
public:
|
||||
explicit CurlTransport(CurlOptions options) : options_(std::move(options))
|
||||
{
|
||||
globalInit();
|
||||
if (options_.userAgent.empty())
|
||||
options_.userAgent = std::string("OpenPU/") + OPENPU_VERSION;
|
||||
}
|
||||
|
||||
HttpResponse perform(const HttpRequest& request) override
|
||||
{
|
||||
std::unique_ptr<CURL, CurlEasyDeleter> handle(curl_easy_init());
|
||||
if (!handle)
|
||||
throw NetworkError("curl_easy_init failed");
|
||||
CURL* h = handle.get();
|
||||
|
||||
HttpResponse response;
|
||||
TransferState st;
|
||||
st.request = &request;
|
||||
st.response = &response;
|
||||
st.handle = h;
|
||||
|
||||
std::unique_ptr<curl_slist, CurlSlistDeleter> headers;
|
||||
for (const auto& [name, value] : request.headers) {
|
||||
std::string line = name;
|
||||
line.append(": ").append(value);
|
||||
headers.reset(curl_slist_append(headers.release(), line.c_str()));
|
||||
}
|
||||
|
||||
char errbuf[CURL_ERROR_SIZE] = {};
|
||||
curl_easy_setopt(h, CURLOPT_ERRORBUFFER, errbuf);
|
||||
curl_easy_setopt(h, CURLOPT_URL, request.url.c_str());
|
||||
curl_easy_setopt(h, CURLOPT_USERAGENT, options_.userAgent.c_str());
|
||||
curl_easy_setopt(h, CURLOPT_FOLLOWLOCATION, request.followRedirects ? 1L : 0L);
|
||||
curl_easy_setopt(h, CURLOPT_MAXREDIRS, 10L);
|
||||
curl_easy_setopt(h, CURLOPT_NOSIGNAL, 1L);
|
||||
curl_easy_setopt(h, CURLOPT_ACCEPT_ENCODING, ""); // enable all supported encodings
|
||||
curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT_MS, static_cast<long>(request.connectTimeout.count()));
|
||||
if (request.stallTimeout.count() > 0) {
|
||||
// Abort when the transfer rate stays below 1 byte/s for the stall period.
|
||||
curl_easy_setopt(h, CURLOPT_LOW_SPEED_LIMIT, 1L);
|
||||
curl_easy_setopt(h, CURLOPT_LOW_SPEED_TIME,
|
||||
std::max(1L, static_cast<long>(request.stallTimeout.count() / 1000)));
|
||||
}
|
||||
curl_easy_setopt(h, CURLOPT_HEADERFUNCTION, &onHeaderLine);
|
||||
curl_easy_setopt(h, CURLOPT_HEADERDATA, &st);
|
||||
curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, &onBody);
|
||||
curl_easy_setopt(h, CURLOPT_WRITEDATA, &st);
|
||||
curl_easy_setopt(h, CURLOPT_VERBOSE, options_.verbose ? 1L : 0L);
|
||||
if (headers)
|
||||
curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers.get());
|
||||
|
||||
switch (request.method) {
|
||||
case HttpMethod::Get: curl_easy_setopt(h, CURLOPT_HTTPGET, 1L); break;
|
||||
case HttpMethod::Head: curl_easy_setopt(h, CURLOPT_NOBODY, 1L); break;
|
||||
case HttpMethod::Post:
|
||||
curl_easy_setopt(h, CURLOPT_POST, 1L);
|
||||
curl_easy_setopt(h, CURLOPT_POSTFIELDS, request.body.c_str());
|
||||
curl_easy_setopt(h, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(request.body.size()));
|
||||
break;
|
||||
}
|
||||
|
||||
const CURLcode rc = curl_easy_perform(h);
|
||||
if (st.abortedByCallback)
|
||||
throw TransferAborted("transfer aborted");
|
||||
if (rc != CURLE_OK && !isCloseDelimitedEof(h, rc, response)) {
|
||||
const std::string detail = errbuf[0] != '\0' ? errbuf : curl_easy_strerror(rc);
|
||||
throw NetworkError(detail);
|
||||
}
|
||||
// Responses without body (HEAD, 204, empty 200) never reached onBody.
|
||||
if (!deliverHeaders(&st))
|
||||
throw TransferAborted("transfer aborted");
|
||||
|
||||
char* effective = nullptr;
|
||||
curl_easy_getinfo(h, CURLINFO_EFFECTIVE_URL, &effective);
|
||||
if (effective != nullptr)
|
||||
response.effectiveUrl = effective;
|
||||
return response;
|
||||
}
|
||||
|
||||
private:
|
||||
CurlOptions options_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<Transport> makeCurlTransport(CurlOptions options)
|
||||
{
|
||||
return std::make_unique<CurlTransport>(std::move(options));
|
||||
}
|
||||
|
||||
} // namespace openpu
|
||||
@@ -0,0 +1,111 @@
|
||||
#include "openpu/http.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
|
||||
namespace openpu {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string trim(std::string s)
|
||||
{
|
||||
const auto notSpace = [](unsigned char c) { return std::isspace(c) == 0; };
|
||||
s.erase(s.begin(), std::find_if(s.begin(), s.end(), notSpace));
|
||||
s.erase(std::find_if(s.rbegin(), s.rend(), notSpace).base(), s.end());
|
||||
return s;
|
||||
}
|
||||
|
||||
int hexValue(char c)
|
||||
{
|
||||
if (c >= '0' && c <= '9')
|
||||
return c - '0';
|
||||
if (c >= 'a' && c <= 'f')
|
||||
return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F')
|
||||
return c - 'A' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
std::string percentDecode(const std::string& s)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(s.size());
|
||||
for (std::size_t i = 0; i < s.size(); ++i) {
|
||||
if (s[i] == '%' && i + 2 < s.size()) {
|
||||
const int hi = hexValue(s[i + 1]);
|
||||
const int lo = hexValue(s[i + 2]);
|
||||
if (hi >= 0 && lo >= 0) {
|
||||
out.push_back(static_cast<char>(hi * 16 + lo));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push_back(s[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Refuses names that could escape the target directory.
|
||||
std::string sanitizeFilename(std::string name)
|
||||
{
|
||||
const auto slash = name.find_last_of("/\\");
|
||||
if (slash != std::string::npos)
|
||||
name = name.substr(slash + 1);
|
||||
if (name == "." || name == "..")
|
||||
return {};
|
||||
name.erase(std::remove_if(name.begin(), name.end(),
|
||||
[](unsigned char c) { return c < 0x20 || c == 0x7f; }),
|
||||
name.end());
|
||||
return name;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string filenameFromContentDisposition(const std::string& header)
|
||||
{
|
||||
// Supports `filename="x"`, `filename=x` and RFC 5987 `filename*=UTF-8''x` (preferred).
|
||||
std::string lower(header);
|
||||
std::transform(lower.begin(), lower.end(), lower.begin(),
|
||||
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
|
||||
|
||||
auto extract = [&](std::size_t valueStart) {
|
||||
std::string value;
|
||||
if (valueStart < header.size() && header[valueStart] == '"') {
|
||||
const auto end = header.find('"', valueStart + 1);
|
||||
value = header.substr(valueStart + 1, end == std::string::npos ? std::string::npos : end - valueStart - 1);
|
||||
} else {
|
||||
const auto end = header.find(';', valueStart);
|
||||
value = trim(header.substr(valueStart, end == std::string::npos ? std::string::npos : end - valueStart));
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const auto star = lower.find("filename*=");
|
||||
if (star != std::string::npos) {
|
||||
std::string v = extract(star + 10);
|
||||
const auto quotes = v.find("''");
|
||||
if (quotes != std::string::npos)
|
||||
v = v.substr(quotes + 2);
|
||||
v = sanitizeFilename(percentDecode(v));
|
||||
if (!v.empty())
|
||||
return v;
|
||||
}
|
||||
const auto plain = lower.find("filename=");
|
||||
if (plain == std::string::npos)
|
||||
return {};
|
||||
return sanitizeFilename(extract(plain + 9));
|
||||
}
|
||||
|
||||
std::string filenameFromUrl(const std::string& url)
|
||||
{
|
||||
std::string path = url.substr(0, url.find_first_of("?#"));
|
||||
const auto schemeEnd = path.find("://");
|
||||
if (schemeEnd != std::string::npos) {
|
||||
const auto pathStart = path.find('/', schemeEnd + 3);
|
||||
path = pathStart == std::string::npos ? std::string() : path.substr(pathStart);
|
||||
}
|
||||
const auto slash = path.find_last_of('/');
|
||||
return sanitizeFilename(percentDecode(slash == std::string::npos ? path : path.substr(slash + 1)));
|
||||
}
|
||||
|
||||
} // namespace openpu
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include "openpu/http.hpp"
|
||||
#include "openpu/models.hpp"
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
namespace openpu {
|
||||
|
||||
/// Backend endpoints. Defaults are those of the Peugeot build of the official application;
|
||||
/// every field can be overridden (other brands, or a local mock server).
|
||||
struct ApiConfig {
|
||||
std::string devicesUrl = "https://api.groupe-psa.com/applications/majesticf/v1/devices/";
|
||||
std::string updatesUrl = "https://api.groupe-psa.com/applications/majesticf/v1/getAvailableUpdate";
|
||||
std::string clientId = "20a4cf7c-f5fb-41d5-9175-a6e23b9880e5";
|
||||
|
||||
/// Defaults overridden by OPENPU_DEVICES_URL, OPENPU_UPDATES_URL and OPENPU_CLIENT_ID when set.
|
||||
static ApiConfig fromEnvironment();
|
||||
};
|
||||
|
||||
class ApiError : public std::runtime_error {
|
||||
public:
|
||||
enum class Kind {
|
||||
Network, ///< no HTTP response (offline, DNS, TLS, timeout)
|
||||
Server, ///< unexpected HTTP status
|
||||
BadResponse, ///< unparsable / unexpected body
|
||||
InvalidVin, ///< rejected locally before any request
|
||||
};
|
||||
ApiError(Kind kind, long status, const std::string& what) : std::runtime_error(what), kind_(kind), status_(status) {}
|
||||
Kind kind() const noexcept { return kind_; }
|
||||
long status() const noexcept { return status_; }
|
||||
|
||||
private:
|
||||
Kind kind_;
|
||||
long status_;
|
||||
};
|
||||
|
||||
class ApiClient {
|
||||
public:
|
||||
ApiClient(Transport& transport, ApiConfig config);
|
||||
|
||||
/// Does the VIN exist, and which head unit does it have?
|
||||
/// A 404 on the devices endpoint yields `exists == false` (not an error).
|
||||
VehicleCheck checkVehicle(const std::string& vin);
|
||||
|
||||
/// Latest firmware / map update for a vehicle whose type is already known.
|
||||
AvailableUpdates getUpdates(const std::string& vin, HeadUnitType type);
|
||||
|
||||
/// Raw calls, exposed for diagnostics (openpu-cli --raw) and tests.
|
||||
HttpResponse rawDevices(const std::string& vin);
|
||||
HttpResponse rawUpdates(const std::string& vin, const std::vector<std::string>& softwareTypes);
|
||||
|
||||
const ApiConfig& config() const noexcept { return config_; }
|
||||
|
||||
private:
|
||||
HttpResponse send(HttpRequest request);
|
||||
static void requireValidVin(const std::string& vin);
|
||||
|
||||
Transport& transport_;
|
||||
ApiConfig config_;
|
||||
};
|
||||
|
||||
} // namespace openpu
|
||||
@@ -0,0 +1,73 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace openpu {
|
||||
|
||||
enum class HttpMethod { Get, Head, Post };
|
||||
|
||||
struct HttpRequest {
|
||||
HttpMethod method = HttpMethod::Get;
|
||||
std::string url;
|
||||
std::vector<std::pair<std::string, std::string>> headers;
|
||||
std::string body;
|
||||
bool followRedirects = true;
|
||||
std::chrono::milliseconds connectTimeout{5000};
|
||||
/// Abort when no data was received for this long (0 = no limit).
|
||||
std::chrono::milliseconds stallTimeout{10000};
|
||||
/// Optional body sink: when set, the body is streamed here instead of being stored in the response.
|
||||
/// Returning false aborts the transfer.
|
||||
std::function<bool(const char* data, std::size_t size)> onData;
|
||||
/// Called once the status line and headers of the final response are known.
|
||||
/// Returning false aborts the transfer before any body is delivered.
|
||||
std::function<bool(long status, const std::map<std::string, std::string>& headers)> onHeaders;
|
||||
};
|
||||
|
||||
struct HttpResponse {
|
||||
long status = 0;
|
||||
std::map<std::string, std::string> headers; ///< lower-cased names, final response only
|
||||
std::string body;
|
||||
std::string effectiveUrl; ///< URL after redirects
|
||||
};
|
||||
|
||||
/// Transport-level failure (DNS, TLS, timeout, connection reset...). Equivalent to HTTP status 0.
|
||||
class NetworkError : public std::runtime_error {
|
||||
public:
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
/// Transfer aborted on purpose (by onData/onHeaders returning false, or cancel()).
|
||||
class TransferAborted : public std::runtime_error {
|
||||
public:
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
class Transport {
|
||||
public:
|
||||
virtual ~Transport() = default;
|
||||
/// Performs the request. Throws NetworkError / TransferAborted; HTTP errors are returned as status.
|
||||
virtual HttpResponse perform(const HttpRequest& request) = 0;
|
||||
};
|
||||
|
||||
struct CurlOptions {
|
||||
std::string userAgent; ///< empty: "OpenPU/<version>"
|
||||
bool verbose = false;
|
||||
};
|
||||
|
||||
/// libcurl-based transport. Honours the standard http_proxy/https_proxy/no_proxy variables.
|
||||
std::unique_ptr<Transport> makeCurlTransport(CurlOptions options = {});
|
||||
|
||||
/// Value of the `filename=` parameter of a Content-Disposition header (empty if none).
|
||||
std::string filenameFromContentDisposition(const std::string& header);
|
||||
|
||||
/// Last path segment of an URL, without query string or fragment, percent-decoded.
|
||||
std::string filenameFromUrl(const std::string& url);
|
||||
|
||||
} // namespace openpu
|
||||
@@ -0,0 +1,105 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace openpu {
|
||||
|
||||
/// Software types understood by the Majestic `getAvailableUpdate` endpoint.
|
||||
namespace software {
|
||||
inline constexpr std::string_view FirmwareNac = "ovip-int-firmware-version";
|
||||
inline constexpr std::string_view FirmwareRcc = "rcc-firmware";
|
||||
inline constexpr std::string_view FirmwareAio = "aio-firmware";
|
||||
inline constexpr std::string_view CronyNav = "crony2-software-nav";
|
||||
inline constexpr std::string_view CronyNonav = "crony2-software-nonav";
|
||||
inline constexpr std::string_view MapEurope = "map-eur";
|
||||
inline constexpr std::string_view MapCrony = "crony2-map-western_europe";
|
||||
|
||||
/// All software types, in the order used when probing a new vehicle.
|
||||
const std::vector<std::string>& all();
|
||||
} // namespace software
|
||||
|
||||
/// Head-unit family. String form matches the `type` field of the original vehicles.json.
|
||||
enum class HeadUnitType { Unknown, Nac, Rcc, Aio, CronyNav, CronyNonav };
|
||||
|
||||
std::string_view headUnitTypeName(HeadUnitType type);
|
||||
HeadUnitType headUnitTypeFromString(std::string_view s);
|
||||
|
||||
/// Thrown when a backend JSON document cannot be interpreted.
|
||||
class ParseError : public std::runtime_error {
|
||||
public:
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
struct UpdateInfo {
|
||||
std::string softwareType;
|
||||
std::string updateId;
|
||||
std::string version;
|
||||
std::string date;
|
||||
std::string url; ///< updateURL (redirects to the CDN)
|
||||
std::string licenseUrl; ///< licenseURL (only meaningful for firmware)
|
||||
std::uint64_t size = 0; ///< bytes, as announced by the backend
|
||||
};
|
||||
|
||||
struct SoftwareEntry {
|
||||
std::string softwareType;
|
||||
std::string requestResult;
|
||||
std::string currentVersion;
|
||||
std::vector<UpdateInfo> updates;
|
||||
};
|
||||
|
||||
struct UpdateListResponse {
|
||||
std::string requestResult;
|
||||
std::string installerUrl;
|
||||
std::string vin;
|
||||
std::vector<SoftwareEntry> software;
|
||||
};
|
||||
|
||||
struct DevicesResponse {
|
||||
std::string vin;
|
||||
std::string requestDate;
|
||||
std::vector<std::string> ecuTypes;
|
||||
};
|
||||
|
||||
struct VehicleCheck {
|
||||
bool exists = false;
|
||||
HeadUnitType type = HeadUnitType::Unknown;
|
||||
std::string guideKey; ///< i18n key of the installation guide (e.g. "path_guide_rcc"), may be empty
|
||||
};
|
||||
|
||||
struct AvailableUpdates {
|
||||
std::optional<UpdateInfo> firmware;
|
||||
std::optional<UpdateInfo> map;
|
||||
};
|
||||
|
||||
/// Firmware and (optional) map software types to request for a given head unit.
|
||||
struct SoftwarePair {
|
||||
std::string firmware;
|
||||
std::optional<std::string> map;
|
||||
};
|
||||
SoftwarePair softwareTypesFor(HeadUnitType type);
|
||||
|
||||
UpdateListResponse parseUpdateList(std::string_view json);
|
||||
DevicesResponse parseDevices(std::string_view json);
|
||||
std::string buildUpdateRequest(std::string_view vin, const std::vector<std::string>& softwareTypes);
|
||||
|
||||
/// Head-unit family from an ECU type string such as "NAC_EU_WAVE4" (Unknown if unsupported).
|
||||
HeadUnitType ecuFamily(std::string_view ecuType);
|
||||
|
||||
/// Reproduces the original vehicle check logic (devices + all-types update probe).
|
||||
VehicleCheck classifyVehicle(const UpdateListResponse& updates, const DevicesResponse& devices);
|
||||
|
||||
/// Usable update of a given software type, if any.
|
||||
std::optional<UpdateInfo> pickUpdate(const UpdateListResponse& response, std::string_view softwareType);
|
||||
|
||||
/// Firmware/map updates for a vehicle of the given type.
|
||||
AvailableUpdates selectUpdates(const UpdateListResponse& response, HeadUnitType type);
|
||||
|
||||
/// Basic absolute http(s) URL check, equivalent to the `is-url` package for our needs.
|
||||
bool isHttpUrl(std::string_view url);
|
||||
|
||||
} // namespace openpu
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace openpu {
|
||||
|
||||
/// Upper-cases and strips whitespace from a user-typed VIN.
|
||||
std::string normalizeVin(std::string_view input);
|
||||
|
||||
/// True when the VIN matches the format accepted by the Majestic backend:
|
||||
/// `^V[FR]3[A-Z0-9]{14}$` (17 characters, PSA/Stellantis WMI).
|
||||
bool isValidVin(std::string_view vin);
|
||||
|
||||
} // namespace openpu
|
||||
@@ -0,0 +1,304 @@
|
||||
#include "openpu/models.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
namespace openpu {
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
namespace software {
|
||||
const std::vector<std::string>& all()
|
||||
{
|
||||
static const std::vector<std::string> types{
|
||||
std::string(FirmwareNac), std::string(FirmwareRcc), std::string(FirmwareAio),
|
||||
std::string(CronyNav), std::string(CronyNonav), std::string(MapEurope),
|
||||
std::string(MapCrony),
|
||||
};
|
||||
return types;
|
||||
}
|
||||
} // namespace software
|
||||
|
||||
std::string_view headUnitTypeName(HeadUnitType type)
|
||||
{
|
||||
switch (type) {
|
||||
case HeadUnitType::Nac: return "nac";
|
||||
case HeadUnitType::Rcc: return "rcc";
|
||||
case HeadUnitType::Aio: return "aio";
|
||||
case HeadUnitType::CronyNav: return "crony_nav";
|
||||
case HeadUnitType::CronyNonav: return "crony_nonav";
|
||||
case HeadUnitType::Unknown: break;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
HeadUnitType headUnitTypeFromString(std::string_view s)
|
||||
{
|
||||
for (auto t : {HeadUnitType::Nac, HeadUnitType::Rcc, HeadUnitType::Aio, HeadUnitType::CronyNav,
|
||||
HeadUnitType::CronyNonav}) {
|
||||
if (headUnitTypeName(t) == s)
|
||||
return t;
|
||||
}
|
||||
return HeadUnitType::Unknown;
|
||||
}
|
||||
|
||||
SoftwarePair softwareTypesFor(HeadUnitType type)
|
||||
{
|
||||
switch (type) {
|
||||
case HeadUnitType::Nac: return {std::string(software::FirmwareNac), std::string(software::MapEurope)};
|
||||
case HeadUnitType::Rcc: return {std::string(software::FirmwareRcc), std::string(software::MapEurope)};
|
||||
case HeadUnitType::CronyNav: return {std::string(software::CronyNav), std::string(software::MapCrony)};
|
||||
case HeadUnitType::CronyNonav: return {std::string(software::CronyNonav), std::nullopt};
|
||||
case HeadUnitType::Aio:
|
||||
case HeadUnitType::Unknown: break;
|
||||
}
|
||||
// Same fallback as the original application (AIO is the default branch).
|
||||
return {std::string(software::FirmwareAio), std::string(software::MapEurope)};
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::string upper(std::string_view s)
|
||||
{
|
||||
std::string out(s);
|
||||
std::transform(out.begin(), out.end(), out.begin(),
|
||||
[](unsigned char c) { return static_cast<char>(std::toupper(c)); });
|
||||
return out;
|
||||
}
|
||||
|
||||
/// String field that may be absent, null, a string or a number.
|
||||
std::string str(const json& obj, const char* key)
|
||||
{
|
||||
auto it = obj.find(key);
|
||||
if (it == obj.end() || it->is_null())
|
||||
return {};
|
||||
if (it->is_string())
|
||||
return it->get<std::string>();
|
||||
if (it->is_number_unsigned())
|
||||
return std::to_string(it->get<std::uint64_t>());
|
||||
if (it->is_number_integer())
|
||||
return std::to_string(it->get<std::int64_t>());
|
||||
return it->dump();
|
||||
}
|
||||
|
||||
std::uint64_t u64(const json& obj, const char* key)
|
||||
{
|
||||
auto it = obj.find(key);
|
||||
if (it == obj.end() || it->is_null())
|
||||
return 0;
|
||||
if (it->is_number_unsigned() || it->is_number_integer())
|
||||
return it->get<std::uint64_t>();
|
||||
if (it->is_number_float())
|
||||
return static_cast<std::uint64_t>(it->get<double>());
|
||||
if (it->is_string()) {
|
||||
const auto s = it->get<std::string>();
|
||||
try {
|
||||
return std::stoull(s);
|
||||
} catch (const std::exception&) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
json parseObject(std::string_view text)
|
||||
{
|
||||
json doc = json::parse(text, nullptr, /*allow_exceptions=*/false);
|
||||
if (doc.is_discarded() || !doc.is_object())
|
||||
throw ParseError("invalid JSON document");
|
||||
return doc;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
UpdateListResponse parseUpdateList(std::string_view text)
|
||||
{
|
||||
const json doc = parseObject(text);
|
||||
UpdateListResponse r;
|
||||
r.requestResult = str(doc, "requestResult");
|
||||
r.installerUrl = str(doc, "installerURL");
|
||||
r.vin = str(doc, "vin");
|
||||
auto sw = doc.find("software");
|
||||
if (sw != doc.end() && sw->is_array()) {
|
||||
for (const auto& s : *sw) {
|
||||
if (!s.is_object())
|
||||
continue;
|
||||
SoftwareEntry e;
|
||||
e.softwareType = str(s, "softwareType");
|
||||
e.requestResult = str(s, "updateRequestResult");
|
||||
e.currentVersion = str(s, "currentSoftwareVersion");
|
||||
auto up = s.find("update");
|
||||
if (up != s.end() && up->is_array()) {
|
||||
for (const auto& u : *up) {
|
||||
if (!u.is_object())
|
||||
continue;
|
||||
UpdateInfo info;
|
||||
info.softwareType = e.softwareType;
|
||||
info.updateId = str(u, "updateId");
|
||||
info.version = str(u, "updateVersion");
|
||||
info.date = str(u, "updateDate");
|
||||
info.url = str(u, "updateURL");
|
||||
info.licenseUrl = str(u, "licenseURL");
|
||||
info.size = u64(u, "updateSize");
|
||||
e.updates.push_back(std::move(info));
|
||||
}
|
||||
}
|
||||
r.software.push_back(std::move(e));
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
DevicesResponse parseDevices(std::string_view text)
|
||||
{
|
||||
const json doc = parseObject(text);
|
||||
DevicesResponse r;
|
||||
r.vin = str(doc, "vin");
|
||||
r.requestDate = str(doc, "requestDate");
|
||||
auto dev = doc.find("devices");
|
||||
if (dev != doc.end() && dev->is_array()) {
|
||||
for (const auto& d : *dev) {
|
||||
if (d.is_object())
|
||||
r.ecuTypes.push_back(str(d, "ecuType"));
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
std::string buildUpdateRequest(std::string_view vin, const std::vector<std::string>& softwareTypes)
|
||||
{
|
||||
json body;
|
||||
body["vin"] = std::string(vin);
|
||||
body["softwareTypes"] = json::array();
|
||||
for (const auto& t : softwareTypes)
|
||||
body["softwareTypes"].push_back({{"softwareType", t}});
|
||||
return body.dump();
|
||||
}
|
||||
|
||||
HeadUnitType ecuFamily(std::string_view ecuType)
|
||||
{
|
||||
const std::string prefix = upper(ecuType.substr(0, ecuType.find('_')));
|
||||
if (prefix == "NAC")
|
||||
return HeadUnitType::Nac;
|
||||
if (prefix == "RCC")
|
||||
return HeadUnitType::Rcc;
|
||||
if (prefix == "AIO")
|
||||
return HeadUnitType::Aio;
|
||||
if (prefix.compare(0, 5, "CRONY") == 0)
|
||||
return HeadUnitType::CronyNav; // nav/nonav is decided from the available software
|
||||
return HeadUnitType::Unknown;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::string guideKeyFor(std::string_view ecuType)
|
||||
{
|
||||
switch (ecuFamily(ecuType)) {
|
||||
case HeadUnitType::Rcc: return "path_guide_rcc";
|
||||
case HeadUnitType::Aio: return "path_guide_aio";
|
||||
case HeadUnitType::Nac: {
|
||||
const std::string last = upper(ecuType.substr(ecuType.rfind('_') + 1));
|
||||
if (last.size() == 5 && last.compare(0, 4, "WAVE") == 0 && last[4] >= '1' && last[4] <= '4')
|
||||
return std::string("path_guide_wave_") + last[4];
|
||||
return "path_guide_wave_default";
|
||||
}
|
||||
case HeadUnitType::CronyNav:
|
||||
case HeadUnitType::CronyNonav: {
|
||||
for (char v : {'1', '2', '3', '4'}) {
|
||||
if (ecuType == std::string("CRONY2_EU_VAR") + v + "_WAVE1")
|
||||
return std::string("path_guide_crony_") + v;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
case HeadUnitType::Unknown: break;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
VehicleCheck classifyVehicle(const UpdateListResponse& updates, const DevicesResponse& devices)
|
||||
{
|
||||
std::vector<std::string> valid;
|
||||
for (const auto& e : devices.ecuTypes) {
|
||||
if (!e.empty() && ecuFamily(e) != HeadUnitType::Unknown)
|
||||
valid.push_back(e);
|
||||
}
|
||||
if (updates.requestResult != "OK" || valid.empty())
|
||||
return {};
|
||||
|
||||
VehicleCheck result;
|
||||
result.exists = true;
|
||||
// A guide link (and therefore a type) is only determined when exactly one valid ECU is present.
|
||||
if (valid.size() != 1)
|
||||
return result;
|
||||
const std::string guide = guideKeyFor(valid.front());
|
||||
if (guide.empty())
|
||||
return result;
|
||||
|
||||
result.guideKey = guide;
|
||||
result.type = ecuFamily(valid.front());
|
||||
if (result.type == HeadUnitType::CronyNav) {
|
||||
const bool hasNonav = std::any_of(updates.software.begin(), updates.software.end(), [](const SoftwareEntry& s) {
|
||||
return s.softwareType == software::CronyNonav && !s.updates.empty() && !s.updates.front().updateId.empty();
|
||||
});
|
||||
if (hasNonav)
|
||||
result.type = HeadUnitType::CronyNonav;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool isHttpUrl(std::string_view url)
|
||||
{
|
||||
std::string_view rest;
|
||||
if (url.substr(0, 8) == "https://")
|
||||
rest = url.substr(8);
|
||||
else if (url.substr(0, 7) == "http://")
|
||||
rest = url.substr(7);
|
||||
else
|
||||
return false;
|
||||
const auto hostEnd = rest.find_first_of("/?#");
|
||||
const auto host = rest.substr(0, hostEnd);
|
||||
if (host.empty())
|
||||
return false;
|
||||
return std::none_of(host.begin(), host.end(), [](char c) { return std::isspace(static_cast<unsigned char>(c)) != 0; });
|
||||
}
|
||||
|
||||
std::optional<UpdateInfo> pickUpdate(const UpdateListResponse& response, std::string_view softwareType)
|
||||
{
|
||||
auto it = std::find_if(response.software.begin(), response.software.end(),
|
||||
[&](const SoftwareEntry& s) { return s.softwareType == softwareType; });
|
||||
if (it == response.software.end() || it->requestResult != "OK" || it->updates.empty())
|
||||
return std::nullopt;
|
||||
|
||||
// The original app's sort is a no-op (it subtracts strings), so it effectively uses update[0].
|
||||
// We keep that, except when every date looks like an ISO-8601 timestamp of the same shape:
|
||||
// then the most recent one is chosen.
|
||||
const auto& ups = it->updates;
|
||||
const UpdateInfo* chosen = &ups.front();
|
||||
const auto isoLike = [&](const UpdateInfo& u) {
|
||||
return u.date.size() >= 10 && u.date.size() == ups.front().date.size() && u.date[4] == '-' && u.date[7] == '-';
|
||||
};
|
||||
if (ups.size() > 1 && std::all_of(ups.begin(), ups.end(), isoLike)) {
|
||||
chosen = &*std::max_element(ups.begin(), ups.end(),
|
||||
[](const UpdateInfo& a, const UpdateInfo& b) { return a.date < b.date; });
|
||||
}
|
||||
if (!isHttpUrl(chosen->url))
|
||||
return std::nullopt;
|
||||
return *chosen;
|
||||
}
|
||||
|
||||
AvailableUpdates selectUpdates(const UpdateListResponse& response, HeadUnitType type)
|
||||
{
|
||||
AvailableUpdates out;
|
||||
if (response.requestResult != "OK" || response.software.empty())
|
||||
return out;
|
||||
const SoftwarePair types = softwareTypesFor(type);
|
||||
out.firmware = pickUpdate(response, types.firmware);
|
||||
if (types.map)
|
||||
out.map = pickUpdate(response, *types.map);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace openpu
|
||||
@@ -0,0 +1,35 @@
|
||||
#include "openpu/vin.hpp"
|
||||
|
||||
#include <cctype>
|
||||
|
||||
namespace openpu {
|
||||
|
||||
std::string normalizeVin(std::string_view input)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(input.size());
|
||||
for (char c : input) {
|
||||
const auto uc = static_cast<unsigned char>(c);
|
||||
if (std::isspace(uc) != 0)
|
||||
continue;
|
||||
out.push_back(static_cast<char>(std::toupper(uc)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool isValidVin(std::string_view vin)
|
||||
{
|
||||
if (vin.size() != 17)
|
||||
return false;
|
||||
if (vin[0] != 'V' || (vin[1] != 'F' && vin[1] != 'R') || vin[2] != '3')
|
||||
return false;
|
||||
for (std::size_t i = 3; i < vin.size(); ++i) {
|
||||
const char c = vin[i];
|
||||
const bool ok = (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||
if (!ok)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace openpu
|
||||
Reference in new issue
Block a user