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:
yann64andClaude Opus 5.5 committed 2026-11-28 17:45:27 +01:00
1 parent 660a420a3e
commit 95704f9882
28 files changed
+1877 -2

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
---
Checks: >
-*,
bugprone-*,
-bugprone-easily-swappable-parameters,
cert-*,
-cert-err58-cpp,
clang-analyzer-*,
concurrency-*,
modernize-*,
-modernize-use-trailing-return-type,
-modernize-use-nodiscard,
-modernize-avoid-c-arrays,
performance-*,
-performance-enum-size,
readability-container-size-empty,
readability-redundant-*,
readability-else-after-return,
misc-unused-*
WarningsAsErrors: ''
HeaderFilterRegex: '.*/src/.*'
FormatStyle: none
...
+46
View File
@@ -0,0 +1,46 @@
cmake_minimum_required(VERSION 3.20)
project(openpu VERSION 0.1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
option(OPENPU_BUILD_CLI "Build openpu-cli" ON)
option(OPENPU_BUILD_TESTS "Build unit tests" ON)
option(OPENPU_UI_GTK "Build the GTK4 user interface" OFF)
option(OPENPU_UI_HAIKU "Build the Haiku user interface" OFF)
option(OPENPU_WERROR "Treat warnings as errors" OFF)
option(OPENPU_CLANG_TIDY "Run clang-tidy while compiling" OFF)
option(OPENPU_SANITIZE "Build with ASan + UBSan" OFF)
if(CMAKE_SYSTEM_NAME STREQUAL "Haiku")
set(OPENPU_UI_HAIKU_DEFAULT ON)
endif()
add_library(openpu_warnings INTERFACE)
target_compile_options(openpu_warnings INTERFACE -Wall -Wextra -Wpedantic -Wshadow -Wconversion -Wno-sign-conversion)
if(OPENPU_WERROR)
target_compile_options(openpu_warnings INTERFACE -Werror)
endif()
if(OPENPU_SANITIZE)
add_compile_options(-fsanitize=address,undefined -fno-omit-frame-pointer)
add_link_options(-fsanitize=address,undefined)
endif()
if(OPENPU_CLANG_TIDY)
find_program(CLANG_TIDY_EXE NAMES clang-tidy REQUIRED)
set(CMAKE_CXX_CLANG_TIDY ${CLANG_TIDY_EXE})
endif()
add_subdirectory(src/core)
if(OPENPU_BUILD_CLI)
add_subdirectory(src/cli)
endif()
if(OPENPU_BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()
+39
View File
@@ -0,0 +1,39 @@
{
"version": 6,
"configurePresets": [
{
"name": "debug",
"displayName": "Debug (warnings as errors)",
"generator": "Ninja",
"binaryDir": "${sourceParentDir}/build-openpu/${presetName}",
"cacheVariables": { "CMAKE_BUILD_TYPE": "Debug", "OPENPU_WERROR": "ON" }
},
{
"name": "release",
"inherits": "debug",
"cacheVariables": { "CMAKE_BUILD_TYPE": "RelWithDebInfo", "OPENPU_WERROR": "OFF" }
},
{
"name": "asan",
"displayName": "Debug + AddressSanitizer + UBSan",
"inherits": "debug",
"cacheVariables": { "OPENPU_SANITIZE": "ON" }
},
{
"name": "tidy",
"displayName": "Debug + clang-tidy",
"inherits": "debug",
"cacheVariables": { "OPENPU_CLANG_TIDY": "ON", "OPENPU_BUILD_TESTS": "OFF" }
}
],
"buildPresets": [
{ "name": "debug", "configurePreset": "debug" },
{ "name": "release", "configurePreset": "release" },
{ "name": "asan", "configurePreset": "asan" },
{ "name": "tidy", "configurePreset": "tidy" }
],
"testPresets": [
{ "name": "debug", "configurePreset": "debug", "output": { "outputOnFailure": true } },
{ "name": "asan", "configurePreset": "asan", "output": { "outputOnFailure": true } }
]
}
+11 -1
View File
@@ -10,7 +10,8 @@ C'est une alternative à l'application officielle « Peugeot Update » (Windows/
## État
- [x] Analyse de l'application existante : voir [`docs/analysis/`](docs/analysis/)
- [ ] Cœur C++ (`libopenpu`) et CLI
- [x] Cœur C++ : VIN, API Majestic, modèles, CLI `check`
- [ ] Cœur C++ : téléchargement avec reprise, tar, USB, Job
- [ ] UI GTK4 (Linux)
- [ ] UI Haiku
- [ ] Paquets `.deb`, Flatpak et `.hpkg`
@@ -26,3 +27,12 @@ src/ui-haiku interface BeAPI
## Outils
- `tools/asar_extract.py` : extracteur asar minimal, en lecture seule, pour étudier l'app de référence.
Les sources extraites restent **hors du dépôt**.
## Compiler (Linux / WSL)
```sh
sudo apt install build-essential cmake ninja-build pkg-config libcurl4-openssl-dev \
libarchive-dev nlohmann-json3-dev doctest-dev
cmake --preset debug && cmake --build --preset debug && ctest --preset debug
../build-openpu/debug/src/cli/openpu-cli check VF3XXXXXXXXXXXXXX
tools/check.sh # tests + ASan/UBSan + valgrind + clang-tidy + cppcheck
```
+16 -1
View File
@@ -144,6 +144,21 @@ La licence est téléchargée **sans reprise** (`electron-dl`). Si le fichier ex
`<install>/proxy.json` : `{http_proxy, https_proxy, no_proxy}`. OpenPU utilise les variables
d'environnement standard (libcurl les gère nativement).
## 4. Mise à jour de l'application elle-même
## 4. Observations sur l'API réelle (capture du 2026-11-28)
- **Passerelle** (`X-Global-Transaction-ID`, de type IBM DataPower) : les réponses n'ont **pas de
`Content-Length`**, et la passerelle ferme la connexion TLS **sans `close_notify`**. OpenSSL 3
signale alors `unexpected eof while reading` (curl : code 56), alors que le corps est complet. Chromium
tolère ce cas, et OpenPU aussi, mais uniquement pour un corps délimité par la fermeture de la connexion.
- Le JSON échappe `=` et `&` en `=` / `&` dans les URL. Il faut donc toujours décoder avant d'analyser.
- `ecuType` réels : `NAC_EUR_WAVE2`, `NAC_EUR_WAVE4`, RCC (voir les fixtures).
- `updateDate` est au format `yyyy-MM-dd HH:mm:ss.S`. `updateSize` est une chaîne.
- **Cartographie NAC** : `updateURL` pointe directement vers le CDN TomTom
(`https://download-cde.tomtom.com/OEM/PSA/MAP/PSA_map-eur_<ver>-NAC_EUR_WAVE2.tar`), et `licenseURL` est vide.
- `installerURL` est présent au niveau racine (une URL `UpdateDownload` sur `majestic.mpsa.com`). Son rôle est inconnu
et l'app d'origine ne l'utilise pas.
- Un VIN inexistant renvoie **404** avec un corps HTML.
- Aucun en-tête particulier n'est requis : le User-Agent est libre, et HTTP/1.1 suffit (pas de négociation h2).
## 5. Mise à jour de l'application elle-même
electron-updater, fournisseur générique `https://d1tik0o5ahgjm.cloudfront.net/peugeot/latest.yml`.
Hors périmètre pour OpenPU.
+3
View File
@@ -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)
+109
View File
@@ -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;
}
}
+15
View File
@@ -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}")
+122
View File
@@ -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
+211
View File
@@ -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
+111
View File
@@ -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
+64
View File
@@ -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
+73
View File
@@ -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
+105
View File
@@ -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
+15
View File
@@ -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
+304
View File
@@ -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
+35
View File
@@ -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
+16
View File
@@ -0,0 +1,16 @@
find_package(doctest QUIET)
add_executable(openpu_tests
main.cpp
test_vin.cpp
test_models.cpp
test_http.cpp
test_api_client.cpp
)
target_link_libraries(openpu_tests PRIVATE openpu_core openpu_warnings)
if(TARGET doctest::doctest)
target_link_libraries(openpu_tests PRIVATE doctest::doctest)
endif()
target_compile_definitions(openpu_tests PRIVATE OPENPU_FIXTURES_DIR="${CMAKE_CURRENT_SOURCE_DIR}/fixtures")
add_test(NAME openpu_tests COMMAND openpu_tests)
+8
View File
@@ -0,0 +1,8 @@
{
"vin": "VR3XXXXXXXXXXXXXX",
"requestDate": "2026-11-28T17:00:00Z",
"devices": [
{ "ecuType": "BSI_X" },
{ "ecuType": "RCC_EU_W3" }
]
}
+9
View File
@@ -0,0 +1,9 @@
{
"devices": [
{
"ecuType": "NAC_EUR_WAVE2"
}
],
"requestDate": "2026-11-28T18:43:48+0100",
"vin": "VF3XXXXXXXXXXXXXX"
}
+37
View File
@@ -0,0 +1,37 @@
{
"installerURL": "https://majestic.mpsa.com/mjf00-web/rest/UpdateDownload?updateId=005000000000000001&uin=00000000000000000000&type=fw",
"requestResult": "OK",
"software": [
{
"currentSoftwareVersion": "4.0.2-r0",
"softwareType": "map-eur",
"update": [
{
"licenseURL": "",
"updateDate": "2026-07-27 07:52:53.0",
"updateId": "005000000000000002",
"updateSize": "10475161600",
"updateURL": "https://download-cde.tomtom.com/OEM/PSA/MAP/PSA_map-eur_31.0.0-r0-NAC_EUR_WAVE2.tar",
"updateVersion": "31.0.0-r0"
}
],
"updateRequestResult": "OK"
},
{
"currentSoftwareVersion": "21.05.90.42_NAC-r0",
"softwareType": "ovip-int-firmware-version",
"update": [
{
"licenseURL": "https://majestic-web.mpsa.com/mjf00-web/rest/LicenseDownload?mediaVersion=005000000000000003&uin=00000000000000000000",
"updateDate": "2026-06-30 12:48:06.0",
"updateId": "005000000000000003",
"updateSize": "2728908800",
"updateURL": "https://majestic-web.mpsa.com/mjf00-web/rest/UpdateDownload?updateId=005000000000000003&uin=00000000000000000000&type=fw",
"updateVersion": "21.08.90.52_NAC-r0"
}
],
"updateRequestResult": "OK"
}
],
"vin": "VF3XXXXXXXXXXXXXX"
}
+28
View File
@@ -0,0 +1,28 @@
{
"requestResult": "OK",
"installerURL": "https://example.invalid/installer",
"vin": "VR3XXXXXXXXXXXXXX",
"software": [
{
"softwareType": "rcc-firmware",
"updateRequestResult": "OK",
"currentSoftwareVersion": "22-1X00-0",
"update": [
{
"updateId": "005000000000000001",
"updateSize": "8390000000",
"updateVersion": "23-2I44-1",
"updateDate": "2024-03-12",
"updateURL": "https://majestic-web.mpsa.com/mjf00-web/rest/UpdateDownload?updateId=005000000000000001&uin=00000000000000000000&type=fw",
"licenseURL": "https://majestic-web.mpsa.com/mjf00-web/rest/LicenseDownload?mediaVersion=005000000000000001&uin=00000000000000000000"
}
]
},
{
"softwareType": "map-eur",
"updateRequestResult": "KO",
"currentSoftwareVersion": "",
"update": []
}
]
}
+2
View File
@@ -0,0 +1,2 @@
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest/doctest.h>
+153
View File
@@ -0,0 +1,153 @@
#include "openpu/api_client.hpp"
#include <deque>
#include <doctest/doctest.h>
using namespace openpu;
namespace {
/// Replays canned responses and records the requests it received.
class FakeTransport final : public Transport {
public:
std::deque<HttpResponse> responses;
std::vector<HttpRequest> requests;
bool failNetwork = false;
HttpResponse perform(const HttpRequest& request) override
{
requests.push_back(request);
if (failNetwork)
throw NetworkError("could not resolve host");
REQUIRE_FALSE(responses.empty());
HttpResponse r = responses.front();
responses.pop_front();
return r;
}
};
HttpResponse ok(std::string body)
{
HttpResponse r;
r.status = 200;
r.body = std::move(body);
return r;
}
HttpResponse status(long code)
{
HttpResponse r;
r.status = code;
return r;
}
const char* const kVin = "VR3ABCDEFGH123456";
ApiConfig testConfig()
{
ApiConfig c;
c.devicesUrl = "https://api.test/v1/devices/";
c.updatesUrl = "https://api.test/v1/getAvailableUpdate";
c.clientId = "cid";
return c;
}
const char* const kUpdates = R"({"requestResult":"OK","software":[
{"softwareType":"rcc-firmware","updateRequestResult":"OK","update":[
{"updateId":"1","updateSize":"100","updateVersion":"v2","updateDate":"2024-01-01",
"updateURL":"https://dl.test/UpdateDownload?updateId=1","licenseURL":"https://dl.test/LicenseDownload?mediaVersion=1"}]},
{"softwareType":"map-eur","updateRequestResult":"OK","update":[
{"updateId":"2","updateSize":"50","updateVersion":"m9","updateURL":"https://dl.test/UpdateDownload?updateId=2"}]}]})";
} // namespace
TEST_CASE("checkVehicle issues devices then getAvailableUpdate with client_id")
{
FakeTransport t;
t.responses.push_back(ok(R"({"devices":[{"ecuType":"RCC_EU_W3"}]})"));
t.responses.push_back(ok(kUpdates));
ApiClient api(t, testConfig());
const VehicleCheck c = api.checkVehicle(kVin);
CHECK(c.exists);
CHECK(c.type == HeadUnitType::Rcc);
REQUIRE(t.requests.size() == 2);
CHECK(t.requests[0].method == HttpMethod::Get);
CHECK(t.requests[0].url == std::string("https://api.test/v1/devices/") + kVin + "?client_id=cid");
CHECK(t.requests[1].method == HttpMethod::Post);
CHECK(t.requests[1].url == "https://api.test/v1/getAvailableUpdate?client_id=cid");
CHECK(t.requests[1].body.find("\"crony2-map-western_europe\"") != std::string::npos); // all 7 types
bool hasContentType = false;
for (const auto& [k, v] : t.requests[1].headers)
hasContentType |= (k == "Content-Type" && v == "application/json");
CHECK(hasContentType);
}
TEST_CASE("checkVehicle: 404 on devices means unknown VIN, no second call")
{
FakeTransport t;
t.responses.push_back(status(404));
ApiClient api(t, testConfig());
CHECK_FALSE(api.checkVehicle(kVin).exists);
CHECK(t.requests.size() == 1);
}
TEST_CASE("errors are mapped to ApiError kinds")
{
FakeTransport t;
ApiClient api(t, testConfig());
SUBCASE("server error")
{
t.responses.push_back(status(503));
try {
api.checkVehicle(kVin);
FAIL("expected ApiError");
} catch (const ApiError& e) {
CHECK(e.kind() == ApiError::Kind::Server);
CHECK(e.status() == 503);
}
}
SUBCASE("network error")
{
t.failNetwork = true;
try {
api.getUpdates(kVin, HeadUnitType::Rcc);
FAIL("expected ApiError");
} catch (const ApiError& e) {
CHECK(e.kind() == ApiError::Kind::Network);
}
}
SUBCASE("bad body")
{
t.responses.push_back(ok("<html>maintenance</html>"));
try {
api.getUpdates(kVin, HeadUnitType::Rcc);
FAIL("expected ApiError");
} catch (const ApiError& e) {
CHECK(e.kind() == ApiError::Kind::BadResponse);
}
}
SUBCASE("invalid VIN never reaches the network")
{
CHECK_THROWS_AS(api.checkVehicle("VF3SHORT"), ApiError);
CHECK(t.requests.empty());
}
}
TEST_CASE("getUpdates requests the pair of types of the head unit")
{
FakeTransport t;
t.responses.push_back(ok(kUpdates));
ApiClient api(t, testConfig());
const AvailableUpdates u = api.getUpdates(kVin, HeadUnitType::Rcc);
REQUIRE(u.firmware.has_value());
CHECK(u.firmware->version == "v2");
CHECK(u.firmware->size == 100);
REQUIRE(u.map.has_value());
CHECK(u.map->version == "m9");
CHECK(t.requests[0].body ==
std::string(R"({"softwareTypes":[{"softwareType":"rcc-firmware"},{"softwareType":"map-eur"}],"vin":")") +
kVin + "\"}");
}
+26
View File
@@ -0,0 +1,26 @@
#include "openpu/http.hpp"
#include <doctest/doctest.h>
using namespace openpu;
TEST_CASE("filename from Content-Disposition")
{
CHECK(filenameFromContentDisposition("attachment; filename=license_ABC.key") == "license_ABC.key");
CHECK(filenameFromContentDisposition("attachment; filename=\"licenses_1_20240101.tar\"") ==
"licenses_1_20240101.tar");
CHECK(filenameFromContentDisposition("attachment;filename=a.key; size=3") == "a.key");
CHECK(filenameFromContentDisposition("attachment; filename*=UTF-8''l%C3%A9.key; filename=x.key") == "l\xC3\xA9.key");
CHECK(filenameFromContentDisposition("inline") == "");
CHECK(filenameFromContentDisposition("attachment; filename=../../etc/passwd") == "passwd");
CHECK(filenameFromContentDisposition("attachment; filename=\"..\"") == "");
}
TEST_CASE("filename from URL")
{
CHECK(filenameFromUrl("https://ds4emloty3shq.cloudfront.net/BOSCH/RCC_EU/rcc-firmware/PSA_rcc.tar") == "PSA_rcc.tar");
CHECK(filenameFromUrl("https://h/a/b.tar?sig=1&x=2#frag") == "b.tar");
CHECK(filenameFromUrl("https://h/a/my%20file.tar") == "my file.tar");
CHECK(filenameFromUrl("https://h") == "");
CHECK(filenameFromUrl("https://h/") == "");
}
+230
View File
@@ -0,0 +1,230 @@
#include "openpu/models.hpp"
#include <doctest/doctest.h>
#include <fstream>
#include <sstream>
using namespace openpu;
namespace {
std::string fixture(const std::string& name)
{
std::ifstream in(std::string(OPENPU_FIXTURES_DIR) + "/" + name);
REQUIRE_MESSAGE(in.good(), "missing fixture " << name);
std::stringstream ss;
ss << in.rdbuf();
return ss.str();
}
DevicesResponse devices(std::initializer_list<const char*> ecus)
{
DevicesResponse d;
for (const char* e : ecus)
d.ecuTypes.emplace_back(e);
return d;
}
UpdateListResponse okList()
{
UpdateListResponse r;
r.requestResult = "OK";
return r;
}
} // namespace
TEST_CASE("head unit type string round-trip matches vehicles.json values")
{
for (auto t : {HeadUnitType::Nac, HeadUnitType::Rcc, HeadUnitType::Aio, HeadUnitType::CronyNav,
HeadUnitType::CronyNonav})
CHECK(headUnitTypeFromString(headUnitTypeName(t)) == t);
CHECK(headUnitTypeName(HeadUnitType::Nac) == "nac");
CHECK(headUnitTypeName(HeadUnitType::CronyNonav) == "crony_nonav");
CHECK(headUnitTypeFromString("bogus") == HeadUnitType::Unknown);
}
TEST_CASE("ECU family is the prefix before the first underscore")
{
CHECK(ecuFamily("NAC_EU_WAVE4") == HeadUnitType::Nac);
CHECK(ecuFamily("nac_eu_wave2") == HeadUnitType::Nac);
CHECK(ecuFamily("RCC_EU") == HeadUnitType::Rcc);
CHECK(ecuFamily("AIO") == HeadUnitType::Aio);
CHECK(ecuFamily("CRONY2_EU_VAR1_WAVE1") == HeadUnitType::CronyNav);
CHECK(ecuFamily("BSI_X") == HeadUnitType::Unknown);
CHECK(ecuFamily("") == HeadUnitType::Unknown);
}
TEST_CASE("vehicle classification")
{
SUBCASE("NAC waves map to guide keys")
{
CHECK(classifyVehicle(okList(), devices({"NAC_EU_WAVE1"})).guideKey == "path_guide_wave_1");
CHECK(classifyVehicle(okList(), devices({"NAC_EU_WAVE4"})).guideKey == "path_guide_wave_4");
const auto c = classifyVehicle(okList(), devices({"NAC_EU"}));
CHECK(c.exists);
CHECK(c.type == HeadUnitType::Nac);
CHECK(c.guideKey == "path_guide_wave_default");
}
SUBCASE("RCC and AIO")
{
auto c = classifyVehicle(okList(), devices({"BSI", "RCC_EU_W3"}));
CHECK(c.exists);
CHECK(c.type == HeadUnitType::Rcc);
CHECK(c.guideKey == "path_guide_rcc");
c = classifyVehicle(okList(), devices({"AIO_X"}));
CHECK(c.type == HeadUnitType::Aio);
CHECK(c.guideKey == "path_guide_aio");
}
SUBCASE("Crony nav vs nonav depends on available software")
{
auto list = okList();
CHECK(classifyVehicle(list, devices({"CRONY2_EU_VAR2_WAVE1"})).type == HeadUnitType::CronyNav);
CHECK(classifyVehicle(list, devices({"CRONY2_EU_VAR2_WAVE1"})).guideKey == "path_guide_crony_2");
SoftwareEntry nonav;
nonav.softwareType = std::string(software::CronyNonav);
nonav.updates.push_back(UpdateInfo{});
list.software.push_back(nonav);
// An entry without updateId does not count.
CHECK(classifyVehicle(list, devices({"CRONY2_EU_VAR2_WAVE1"})).type == HeadUnitType::CronyNav);
list.software.back().updates.front().updateId = "1";
CHECK(classifyVehicle(list, devices({"CRONY2_EU_VAR2_WAVE1"})).type == HeadUnitType::CronyNonav);
}
SUBCASE("unknown Crony variant: exists but no type")
{
const auto c = classifyVehicle(okList(), devices({"CRONY3_XX"}));
CHECK(c.exists);
CHECK(c.type == HeadUnitType::Unknown);
}
SUBCASE("several valid ECUs: exists but no type")
{
const auto c = classifyVehicle(okList(), devices({"NAC_EU_WAVE2", "RCC_EU"}));
CHECK(c.exists);
CHECK(c.type == HeadUnitType::Unknown);
CHECK(c.guideKey.empty());
}
SUBCASE("no supported ECU or failed request: does not exist")
{
CHECK_FALSE(classifyVehicle(okList(), devices({"BSI"})).exists);
CHECK_FALSE(classifyVehicle(okList(), devices({})).exists);
UpdateListResponse ko;
ko.requestResult = "KO";
CHECK_FALSE(classifyVehicle(ko, devices({"RCC_EU"})).exists);
}
}
TEST_CASE("software types requested per head unit")
{
CHECK(softwareTypesFor(HeadUnitType::Nac).firmware == software::FirmwareNac);
CHECK(softwareTypesFor(HeadUnitType::Rcc).firmware == software::FirmwareRcc);
CHECK(*softwareTypesFor(HeadUnitType::Rcc).map == software::MapEurope);
CHECK(*softwareTypesFor(HeadUnitType::CronyNav).map == software::MapCrony);
CHECK_FALSE(softwareTypesFor(HeadUnitType::CronyNonav).map.has_value());
CHECK(softwareTypesFor(HeadUnitType::Unknown).firmware == software::FirmwareAio);
}
TEST_CASE("request body")
{
CHECK(buildUpdateRequest("VF3ABCDEFGH123456", {"rcc-firmware", "map-eur"}) ==
R"({"softwareTypes":[{"softwareType":"rcc-firmware"},{"softwareType":"map-eur"}],"vin":"VF3ABCDEFGH123456"})");
}
TEST_CASE("parse getAvailableUpdate response (fixture)")
{
const auto r = parseUpdateList(fixture("updates_rcc.json"));
CHECK(r.requestResult == "OK");
REQUIRE(r.software.size() == 2);
CHECK(r.software[0].softwareType == "rcc-firmware");
REQUIRE(r.software[0].updates.size() == 1);
const auto& u = r.software[0].updates[0];
CHECK(u.updateId == "005000000000000001");
CHECK(u.size == 8390000000ULL); // given as a string by the backend
CHECK(u.url.rfind("https://majestic-web.mpsa.com/", 0) == 0);
const auto sel = selectUpdates(r, HeadUnitType::Rcc);
REQUIRE(sel.firmware.has_value());
CHECK(sel.firmware->version == "23-2I44-1");
CHECK(sel.firmware->licenseUrl.find("LicenseDownload") != std::string::npos);
CHECK_FALSE(sel.map.has_value()); // map-eur entry is not OK
}
TEST_CASE("parse devices response (fixture)")
{
const auto d = parseDevices(fixture("devices_rcc.json"));
REQUIRE(d.ecuTypes.size() == 2);
CHECK(d.ecuTypes[1] == "RCC_EU_W3");
}
TEST_CASE("parser robustness")
{
CHECK_THROWS_AS(parseUpdateList("not json"), ParseError);
CHECK_THROWS_AS(parseUpdateList("[1,2]"), ParseError);
CHECK_THROWS_AS(parseDevices(""), ParseError);
const auto r = parseUpdateList(R"({"requestResult":"OK","software":[{"softwareType":"x","update":null},7]})");
REQUIRE(r.software.size() == 1);
CHECK(r.software[0].updates.empty());
const auto n = parseUpdateList(
R"({"requestResult":"OK","software":[{"softwareType":"x","updateRequestResult":"OK","update":[{"updateId":5,"updateSize":12}]}]})");
CHECK(n.software[0].updates[0].updateId == "5");
CHECK(n.software[0].updates[0].size == 12);
}
TEST_CASE("update selection")
{
auto make = [](std::vector<std::pair<std::string, std::string>> dateUrl) {
UpdateListResponse r = okList();
SoftwareEntry e;
e.softwareType = "rcc-firmware";
e.requestResult = "OK";
for (auto& [d, u] : dateUrl) {
UpdateInfo i;
i.date = d;
i.url = u;
i.version = d;
e.updates.push_back(i);
}
r.software.push_back(e);
return r;
};
SUBCASE("first entry when dates are not comparable (original behaviour)")
{
const auto r = make({{"", "https://a/x"}, {"2024-01-01", "https://a/y"}});
CHECK(pickUpdate(r, "rcc-firmware")->url == "https://a/x");
}
SUBCASE("most recent ISO date wins")
{
const auto r = make({{"2023-05-01T00:00:00Z", "https://a/old"}, {"2024-02-01T00:00:00Z", "https://a/new"}});
CHECK(pickUpdate(r, "rcc-firmware")->url == "https://a/new");
}
SUBCASE("invalid URL is rejected")
{
CHECK_FALSE(pickUpdate(make({{"", "not-an-url"}}), "rcc-firmware").has_value());
CHECK_FALSE(pickUpdate(make({{"", "https://"}}), "rcc-firmware").has_value());
}
SUBCASE("unknown type")
{
CHECK_FALSE(pickUpdate(make({{"", "https://a/x"}}), "map-eur").has_value());
}
}
TEST_CASE("real NAC wave 2 response (anonymised capture, 2026-11-28)")
{
const auto list = parseUpdateList(fixture("real_nac_updates.json"));
const auto dev = parseDevices(fixture("real_nac_devices.json"));
const VehicleCheck check = classifyVehicle(list, dev);
CHECK(check.exists);
CHECK(check.type == HeadUnitType::Nac);
CHECK(check.guideKey == "path_guide_wave_2");
const AvailableUpdates sel = selectUpdates(list, HeadUnitType::Nac);
REQUIRE(sel.firmware.has_value());
CHECK(sel.firmware->version == "21.08.90.52_NAC-r0");
CHECK(sel.firmware->size == 2728908800ULL);
CHECK_FALSE(sel.firmware->licenseUrl.empty());
REQUIRE(sel.map.has_value());
CHECK(sel.map->version == "31.0.0-r0");
CHECK(sel.map->licenseUrl.empty()); // maps come without a license
CHECK(sel.map->url.rfind("https://download-cde.tomtom.com/", 0) == 0);
}
+26
View File
@@ -0,0 +1,26 @@
#include "openpu/vin.hpp"
#include <doctest/doctest.h>
using openpu::isValidVin;
using openpu::normalizeVin;
TEST_CASE("VIN validation follows ^V[FR]3[A-Z0-9]{14}$")
{
CHECK(isValidVin("VF3ABCDEFGH123456"));
CHECK(isValidVin("VR3UPHNKSKT000001"));
CHECK_FALSE(isValidVin(""));
CHECK_FALSE(isValidVin("VF3ABCDEFGH12345")); // 16 chars
CHECK_FALSE(isValidVin("VF3ABCDEFGH1234567")); // 18 chars
CHECK_FALSE(isValidVin("VX3ABCDEFGH123456")); // bad 2nd char
CHECK_FALSE(isValidVin("VF1ABCDEFGH123456")); // Renault WMI
CHECK_FALSE(isValidVin("WF3ABCDEFGH123456"));
CHECK_FALSE(isValidVin("vf3abcdefgh123456")); // must be normalised first
CHECK_FALSE(isValidVin("VF3ABCDEFGH12345-"));
}
TEST_CASE("VIN normalisation upper-cases and strips blanks")
{
CHECK(normalizeVin(" vf3 abcd efgh 123456\n") == "VF3ABCDEFGH123456");
CHECK(isValidVin(normalizeVin("vr3uphnksk t000001")));
}
+40
View File
@@ -0,0 +1,40 @@
#!/bin/sh
# Full local quality gate: build + tests, ASan/UBSan tests, valgrind, clang-tidy, cppcheck.
# usage: tools/check.sh [build-root] (default: ~/build/openpu-check)
set -eu
SRC=$(cd "$(dirname "$0")/.." && pwd)
OUT=${1:-"$HOME/build/openpu-check"}
step() { printf '\n==> %s\n' "$*"; }
step "debug build + tests"
cmake -S "$SRC" -B "$OUT/debug" -G Ninja -DCMAKE_BUILD_TYPE=Debug -DOPENPU_WERROR=ON >/dev/null
cmake --build "$OUT/debug"
ctest --test-dir "$OUT/debug" --output-on-failure
step "ASan + UBSan tests"
cmake -S "$SRC" -B "$OUT/asan" -G Ninja -DCMAKE_BUILD_TYPE=Debug -DOPENPU_SANITIZE=ON >/dev/null
cmake --build "$OUT/asan"
UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 ctest --test-dir "$OUT/asan" --output-on-failure
if command -v valgrind >/dev/null; then
step "valgrind memcheck"
valgrind --quiet --error-exitcode=1 --leak-check=full --errors-for-leak-kinds=definite \
"$OUT/debug/tests/openpu_tests" >/dev/null
fi
if command -v clang-tidy >/dev/null; then
step "clang-tidy"
# Only our sources; compile_commands.json comes from the debug build.
find "$SRC/src" -name '*.cpp' -print0 |
xargs -0 clang-tidy -p "$OUT/debug" --quiet --warnings-as-errors='*'
fi
if command -v cppcheck >/dev/null; then
step "cppcheck"
cppcheck --quiet --error-exitcode=1 --std=c++17 --enable=warning,performance,portability \
--inline-suppr --suppress=missingIncludeSystem -I "$SRC/src/core/include" "$SRC/src"
fi
step "all checks passed"