Clavem

Software update checks and downloads in a C++ app

GET /v1/releases/<product id>/latest with the key in an X-License-Key header, parse it with nlohmann/json, compare semantic versions, and stream the file with CURLOPT_RESUME_FROM_LARGE. Set no total timeout on the download, only a connect timeout and a low-speed limit.

Clavem stores your builds and answers GET /v1/releases/:productId/latest. A license that is valid for the product gets release notes and files with signed download links. Any other key gets only version and published_at. The release docs list the fields. This page is the C++ side: the check, a semantic version comparison, a download that resumes, and what to do with the result. The post-style helpers, json and text come from license key validation in C++.

Check

#include <cstdio>
#include <filesystem>
#include <functional>

struct Version {
  int major = 0, minor = 0, patch = 0;
  std::string pre;   // "" for a release

  static std::optional<Version> parse(const std::string& s) {
    Version v;
    char dash[64] = {0};
    if (std::sscanf(s.c_str(), "%d.%d.%d-%63s", &v.major, &v.minor, &v.patch, dash) < 3) return std::nullopt;
    v.pre = dash;
    return v;
  }
  bool operator>(const Version& o) const {   // SemVer order: a pre-release sorts below its release
    if (major != o.major) return major > o.major;
    if (minor != o.minor) return minor > o.minor;
    if (patch != o.patch) return patch > o.patch;
    if (pre.empty() != o.pre.empty()) return pre.empty();
    return pre > o.pre;
  }
};

struct ReleaseFile { int64_t id; std::string filename; int64_t size; std::string url; };
enum class UpdateState { UpToDate, Available, Locked, Failed };
struct Update { UpdateState state; std::string version, notes, reason; std::optional<ReleaseFile> file; };

Update check_for_update(const std::string& base, int64_t product_id, const std::string& current,
                        const std::string& license_key, const std::string& platform) {
  std::unique_ptr<CURL, CurlDeleter> curl(curl_easy_init());
  std::string raw;
  std::unique_ptr<char, decltype(&curl_free)> label(curl_easy_escape(curl.get(), platform.c_str(), 0), curl_free);
  const std::string url = base + "/v1/releases/" + std::to_string(product_id) + "/latest?platform=" + label.get();
  std::unique_ptr<curl_slist, SlistDeleter> headers;
  if (!license_key.empty()) headers.reset(curl_slist_append(nullptr, ("X-License-Key: " + license_key).c_str()));

  curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  if (headers) curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers.get());   // a header keeps the key out of logs
  curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, 8L);
  curl_easy_setopt(curl.get(), CURLOPT_NOSIGNAL, 1L);
  curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, append);
  curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &raw);
  if (curl_easy_perform(curl.get()) != CURLE_OK) return {UpdateState::Failed, "", "", "offline", std::nullopt};

  long status = 0;
  curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &status);
  if (status == 404) return {UpdateState::UpToDate, "", "", "", std::nullopt};   // nothing published yet
  if (status == 429) return {UpdateState::Failed, "", "", "rate limited, retry in a minute", std::nullopt};
  if (status != 200) return {UpdateState::Failed, "", "", "HTTP " + std::to_string(status), std::nullopt};

  json release = json::parse(raw, nullptr, false);
  auto latest = release.is_object() ? Version::parse(text(release, "version")) : std::nullopt;
  auto now = Version::parse(current);
  if (!latest || !now) return {UpdateState::Failed, "", "", "version is not semver", std::nullopt};
  if (!(*latest > *now)) return {UpdateState::UpToDate, "", "", "", std::nullopt};

  for (const auto& f : release.value("files", json::array()))
    if (f.contains("url") && f["url"].is_string())
      return {UpdateState::Available, text(release, "version"), text(release, "notes"), "",
              ReleaseFile{f.value("id", int64_t{0}), text(f, "filename"), f.value("size", int64_t{0}), text(f, "url")}};
  return {UpdateState::Locked, text(release, "version"), "", "", std::nullopt};   // newer, but the key is missing or not valid
}

Locked is the useful middle case: a lapsed customer learns that a newer version exists and can be sent to renew. Run against a local stub with release 3.2.1 and the app on 3.2.0, plus one live call, the function returned:

with key: state=1 version=3.2.1 file=inkwell-3.2.1.zip
without key: state=2 version=3.2.1 file=-
app 3.10.0: state=0
app 3.2.1-rc.1: state=1 version=3.2.1
other product: state=0
live demo product: state=0

State 1 is Available, 2 is Locked and 0 is UpToDate. The live demo product has no published release, so the real API answers 404 with not_found, which the code treats as nothing to offer. A program on 3.2.1-rc.1 is offered 3.2.1, because the comparison sorts a pre-release below its release. Only the unlabelled .zip came back for darwin-arm64, because the stub’s other files were labelled macos and windows. Request the label you used at upload.

Download, resume and progress

Request the link when the customer clicks, not when the check ran, because it lasts one hour. The write callback reads the status on its first call. A 206 means the server honoured the range and the file is appended. A 200 means it ignored the range, so the file is rewritten. Anything else aborts:

struct Sink { CURL* curl; std::filesystem::path part; int64_t have; std::FILE* out = nullptr; long status = 0; };

static size_t sink_write(char* data, size_t size, size_t n, void* user) {
  auto* s = static_cast<Sink*>(user);
  if (!s->out) {
    curl_easy_getinfo(s->curl, CURLINFO_RESPONSE_CODE, &s->status);
    if (s->status != 200 && s->status != 206) return 0;          // abort: nothing worth saving
    if (s->status == 200) s->have = 0;                           // Range ignored: start over
    s->out = std::fopen(s->part.string().c_str(), s->status == 206 ? "ab" : "wb");
    if (!s->out) return 0;
  }
  s->have += static_cast<int64_t>(size * n);
  return std::fwrite(data, size, n, s->out);
}

std::string download(const ReleaseFile& file, const std::filesystem::path& dest, std::function<void(int)> on_percent = {}) {
  std::filesystem::path part = dest;
  part += ".part";
  std::error_code ec;
  int64_t have = std::filesystem::exists(part, ec) ? static_cast<int64_t>(std::filesystem::file_size(part, ec)) : 0;
  if (have > file.size) { std::filesystem::remove(part, ec); have = 0; }

  if (have < file.size) {
    std::unique_ptr<CURL, CurlDeleter> curl(curl_easy_init());
    Sink sink{curl.get(), part, have};
    curl_easy_setopt(curl.get(), CURLOPT_URL, file.url.c_str());
    curl_easy_setopt(curl.get(), CURLOPT_CONNECTTIMEOUT, 10L);     // no CURLOPT_TIMEOUT: it caps the whole transfer
    curl_easy_setopt(curl.get(), CURLOPT_LOW_SPEED_LIMIT, 1024L);  // give up below 1 KB/s ...
    curl_easy_setopt(curl.get(), CURLOPT_LOW_SPEED_TIME, 30L);     // ... for 30 seconds
    curl_easy_setopt(curl.get(), CURLOPT_NOSIGNAL, 1L);
    if (have > 0) curl_easy_setopt(curl.get(), CURLOPT_RESUME_FROM_LARGE, static_cast<curl_off_t>(have));
    curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, sink_write);
    curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &sink);
    CURLcode rc = curl_easy_perform(curl.get());
    if (sink.out) std::fclose(sink.out);
    curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &sink.status);
    if (sink.status == 403) return "The download link expired. Check for updates again.";
    if (rc != CURLE_OK) return std::string("download failed: ") + curl_easy_strerror(rc);
  }
  if (static_cast<int64_t>(std::filesystem::file_size(part, ec)) != file.size) return "Size does not match. Keep the .part file and resume.";
  std::filesystem::rename(part, dest, ec);
  return ec ? ec.message() : "";
}

The on_percent callback is wired through CURLOPT_XFERINFOFUNCTION and CURLOPT_NOPROGRESS, which is omitted here for length. Run with 1 MiB already in the .part file of a 3 MiB download, the function resumed, returned no error and left 3,145,728 bytes. A link with a bad signature returned the expired-link message, which is the 403 path, and a file declared 10 bytes too large returned the size message. The response has no checksum field, so size is the only integrity check the API gives. Sign what you ship, and let the operating system verify the signature.

Install

  • macOS. Open the DMG with open, through posix_spawn or NSWorkspace, and the customer drags the new app over the old one.
  • Windows. A running executable cannot be overwritten. Start the downloaded installer with ShellExecuteW and exit.
  • Linux. For an AppImage, std::filesystem::rename the new file over the old one and chmod +x it. For a package, hand it to the package manager.

Limits and timing

The releases endpoint allows 120 requests a minute per IP address, counted apart from validation. Check once at launch or once a day, on a worker thread. “Latest” is the most recently published release, not the highest version number: a backport published after 3.2.1 becomes the answer.

Doing this with Clavem

Upload each installer in the dashboard, give it a platform label and publish. The same key that turns the app on fetches the download, and licenses imported from Lemon Squeezy, which have no order page, get their builds through this endpoint. See the release docs for limits.

Questions

Why does my libcurl download stop after a few seconds?

CURLOPT_TIMEOUT limits the whole transfer, so a large file hits it even while data flows. Leave it unset for downloads and use CURLOPT_CONNECTTIMEOUT with CURLOPT_LOW_SPEED_LIMIT and CURLOPT_LOW_SPEED_TIME to stop a stalled connection.

How do I resume a download with libcurl?

Set CURLOPT_RESUME_FROM_LARGE to the number of bytes you already have. libcurl sends a Range header. Check the status in your write callback, because a server that ignores Range answers 200 with the whole file.

Can a C++ program replace its own executable?

On macOS and Linux you can rename a new file over it. On Windows a running executable cannot be overwritten, so download the installer, start it, and exit. The customer or the installer finishes the replacement.

Sources

  1. libcurl, CURLOPT_RESUME_FROM_LARGE (checked November 2026)
  2. libcurl, CURLOPT_TIMEOUT (checked November 2026)