@mikrojs/native 0.22.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CMakeLists.txt +19 -0
- package/dist/runtime/result/native-result.node-shim.d.ts +2 -0
- package/dist/runtime/result/native-result.node-shim.d.ts.map +1 -1
- package/dist/runtime/result/native-result.node-shim.js +57 -0
- package/dist/runtime/result/native-result.node-shim.js.map +1 -1
- package/dist/runtime/result/types.d.ts +33 -0
- package/dist/runtime/result/types.d.ts.map +1 -1
- package/include/mikrojs/app_store.h +16 -0
- package/include/mikrojs/ble_port.h +50 -0
- package/include/mikrojs/build_install.h +36 -0
- package/include/mikrojs/device_store.h +84 -0
- package/include/mikrojs/http_native.h +52 -0
- package/include/mikrojs/mikrojs.h +19 -9
- package/include/mikrojs/ota.h +75 -0
- package/include/mikrojs/ota_env.h +1 -1
- package/include/mikrojs/platform.h +29 -0
- package/include/mikrojs/private.h +4 -1
- package/include/mikrojs/utils.h +5 -0
- package/package.json +4 -4
- package/prebuilds/darwin-arm64/mikrojs.napi.node +0 -0
- package/prebuilds/linux-arm64/mikrojs.napi.node +0 -0
- package/prebuilds/linux-x64/mikrojs.napi.node +0 -0
- package/runtime/http/server-impl.ts +5 -60
- package/runtime/http/server.ts +0 -1
- package/runtime/internal.d.ts +2 -0
- package/runtime/result/native-result.node-shim.ts +60 -0
- package/runtime/result/result.ts +1 -1
- package/runtime/result/types.ts +61 -0
- package/runtime/sys/sys.ts +1 -2
- package/src/mik_app_store.cpp +32 -0
- package/src/mik_ble.cpp +1573 -0
- package/src/mik_build_install.cpp +785 -0
- package/src/mik_config.cpp +330 -0
- package/src/mik_console.cpp +15 -24
- package/src/mik_deploy.cpp +759 -0
- package/src/mik_ota.cpp +1403 -0
- package/src/mik_ota_client_module.cpp +1142 -0
- package/src/mik_ota_env.cpp +318 -0
- package/src/mik_repl.cpp +12 -4
- package/src/mik_result.cpp +159 -0
- package/src/mik_sys.cpp +25 -51
- package/src/mik_test_supervisor.cpp +151 -0
- package/src/mik_watchdog.cpp +4 -5
- package/src/mik_wifi_client.cpp +1 -2
- package/src/mikrojs.cpp +15 -6
- package/src/modules.cpp +1 -1
package/src/mik_ota.cpp
ADDED
|
@@ -0,0 +1,1403 @@
|
|
|
1
|
+
// Native OTA install module for Mikro.js firmware, shared by every port.
|
|
2
|
+
//
|
|
3
|
+
// Registers `native:mikro/ota`, the privileged half of over-the-air updates the
|
|
4
|
+
// JS layer can't do: /app is read-only from JS and there is no gunzip/untar in
|
|
5
|
+
// the runtime, but C in firmware has a writable FS, miniz, and plain file I/O.
|
|
6
|
+
//
|
|
7
|
+
// The surface (consumed by the JS helper that owns the OTA protocol):
|
|
8
|
+
// stageBegin(checksum, size) stage a download, resume if partial
|
|
9
|
+
// stageWrite(bytes) append to the staged .tgz
|
|
10
|
+
// stageFinish(trialBoots, requireConfirm, installNow) verify + schedule install
|
|
11
|
+
// stageAbort() drop the in-progress staging file
|
|
12
|
+
// markValid() confirm the running trial (promote)
|
|
13
|
+
// revert() roll back to the last-good build
|
|
14
|
+
// running() { checksum?, trial }
|
|
15
|
+
// reconcile() outcome of the boot-time reconcile
|
|
16
|
+
//
|
|
17
|
+
// The actual install (gunzip -> untar -> atomic swap) runs at boot on a clean
|
|
18
|
+
// heap from MIK_OtaBootReconcile(), which also drives the trial/rollback
|
|
19
|
+
// state machine. The unpack itself (gunzip + untar + SHA-256 + swap) is
|
|
20
|
+
// mik__install_build (mikrojs/build_install.h), host-tested in
|
|
21
|
+
// @mikrojs/firmware's test/ota_host/. The install state and the app filesystem
|
|
22
|
+
// come from the device store (mikrojs/device_store.h): NVS and LittleFS on the
|
|
23
|
+
// ESP32.
|
|
24
|
+
|
|
25
|
+
#include "mikrojs/app_store.h"
|
|
26
|
+
#include "mikrojs/build_install.h"
|
|
27
|
+
#include "mikrojs/device_store.h"
|
|
28
|
+
#include "mikrojs/mikrojs.h"
|
|
29
|
+
#include "mikrojs/ota.h"
|
|
30
|
+
#include "mikrojs/ota_env.h"
|
|
31
|
+
#include "mikrojs/platform.h"
|
|
32
|
+
#include "mikrojs/private.h"
|
|
33
|
+
#include "quickjs.h"
|
|
34
|
+
|
|
35
|
+
#include <cstdint>
|
|
36
|
+
#include <cstdio>
|
|
37
|
+
#include <cstdlib>
|
|
38
|
+
#include <cstring>
|
|
39
|
+
#include <sys/stat.h>
|
|
40
|
+
#include <unistd.h>
|
|
41
|
+
|
|
42
|
+
namespace {
|
|
43
|
+
|
|
44
|
+
const char* err_kind(MIKBuildErr k) {
|
|
45
|
+
switch (k) {
|
|
46
|
+
case MIK_BUILD_ERR_CORRUPT:
|
|
47
|
+
return "corrupt";
|
|
48
|
+
case MIK_BUILD_ERR_OOM:
|
|
49
|
+
return "oom";
|
|
50
|
+
case MIK_BUILD_ERR_TRANSIENT:
|
|
51
|
+
default:
|
|
52
|
+
return "transient";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ── On-disk layout (under the device store's fs_base) ────────────────────────
|
|
57
|
+
struct Paths {
|
|
58
|
+
const char* base;
|
|
59
|
+
const char* staging; // in-progress download sink
|
|
60
|
+
const char* pending; // verified, awaiting install
|
|
61
|
+
const char* last_good; // revert target
|
|
62
|
+
const char* last_good_tmp; // adopt: install source (legacy)
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// The paths share one heap block, rebuilt when the base changes. All empty
|
|
66
|
+
// without a store that names an app filesystem, or when out of memory.
|
|
67
|
+
const Paths& paths(void) {
|
|
68
|
+
static Paths p = {"", "", "", "", ""};
|
|
69
|
+
static char* block = nullptr;
|
|
70
|
+
const MIKDeviceStore* store = mik__device_store();
|
|
71
|
+
const char* base = store ? store->fs_base : nullptr;
|
|
72
|
+
if (block && base && strcmp(p.base, base) == 0) return p;
|
|
73
|
+
|
|
74
|
+
free(block);
|
|
75
|
+
block = nullptr;
|
|
76
|
+
p = {"", "", "", "", ""};
|
|
77
|
+
if (!base) return p;
|
|
78
|
+
|
|
79
|
+
static const char* const suffixes[] = {"", "/.ota-staging.tgz", "/.ota-pending.tgz",
|
|
80
|
+
"/.ota-last-good.tgz", "/.ota-last-good.tmp"};
|
|
81
|
+
const char** const slots[] = {&p.base, &p.staging, &p.pending, &p.last_good,
|
|
82
|
+
&p.last_good_tmp};
|
|
83
|
+
block = mik__join_paths(base, suffixes, sizeof(suffixes) / sizeof(suffixes[0]), slots);
|
|
84
|
+
return p;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// State keys, in the store's "mik.ota" namespace. Kept <= 15 chars (the ESP32's
|
|
88
|
+
// NVS limit).
|
|
89
|
+
constexpr const char* kKeyState = "state"; // u8: 0 GOOD, 1 TRIAL
|
|
90
|
+
constexpr const char* kKeyTrialLeft = "trialLeft"; // u8
|
|
91
|
+
constexpr const char* kKeyTrialN = "trialN"; // u8: trial budget for a pending install
|
|
92
|
+
constexpr const char* kKeyConfirm = "confirm"; // u8: trial requires markValid() to promote
|
|
93
|
+
constexpr const char* kKeyPending = "pending"; // u8: 1 = .ota-pending.tgz awaits clean-heap install
|
|
94
|
+
constexpr const char* kKeyPendMode = "pendMode"; // u8: how to install the pending build (see below)
|
|
95
|
+
constexpr const char* kKeyInstLeft = "instLeft"; // u8: install-attempt budget
|
|
96
|
+
constexpr const char* kKeyPromLeft = "promLeft"; // u8: promote-attempt budget
|
|
97
|
+
constexpr const char* kKeyRbLeft = "rbLeft"; // u8: rollback-attempt budget
|
|
98
|
+
constexpr const char* kKeyNeutLeft = "neutLeft"; // u8: brownout boots a trial may absorb
|
|
99
|
+
constexpr const char* kKeyInstChk = "instChk"; // str: running good (last-good) checksum
|
|
100
|
+
constexpr const char* kKeyPendChk = "pendChk"; // str: pending/trial checksum
|
|
101
|
+
constexpr const char* kKeyStgChk = "stgChk"; // str: in-progress staging expected checksum
|
|
102
|
+
constexpr const char* kKeyStgSize = "stgSize"; // u32: expected staged size
|
|
103
|
+
constexpr const char* kKeyFwHash = "fwHash"; // str: firmware elf sha256 (reflash guard)
|
|
104
|
+
constexpr const char* kKeyTrialBad = "trialBad"; // u8: trial app hit a fatal JS error this boot
|
|
105
|
+
constexpr const char* kKeyBadDetail = "badDetail"; // str: that error, for the revert diagnostic
|
|
106
|
+
// Boot-reconcile outcome, read once by reconcile() and then cleared.
|
|
107
|
+
constexpr const char* kKeyOInst = "oInst"; // str: checksum just installed
|
|
108
|
+
constexpr const char* kKeyORevert = "oRevert"; // u8
|
|
109
|
+
constexpr const char* kKeyORsn = "oRsn"; // str: diagnostic reason
|
|
110
|
+
constexpr const char* kKeyODetail = "oDetail"; // str: diagnostic detail
|
|
111
|
+
// Adopt-install outcome, read once by MIK_CMD_DEPLOY_RESULT and then cleared.
|
|
112
|
+
// Separate from the reconcile record above: that one reaches the registry as
|
|
113
|
+
// `lastInstall` and would blacklist a checksum the developer is re-pushing.
|
|
114
|
+
constexpr const char* kKeyDRes = "dRes"; // u8: 1 ok, 2 fail
|
|
115
|
+
constexpr const char* kKeyDChk = "dChk"; // str: staged checksum
|
|
116
|
+
constexpr const char* kKeyDRsn = "dRsn"; // str: failure reason
|
|
117
|
+
constexpr const char* kKeyDDetail = "dDetail"; // str: failure detail
|
|
118
|
+
|
|
119
|
+
constexpr uint8_t kStateGood = 0;
|
|
120
|
+
constexpr uint8_t kStateTrial = 1;
|
|
121
|
+
// kKeyPendMode values. Trial is the OTA path (trialBoots, rollback, abandon
|
|
122
|
+
// policy); adopt is the cable-deploy path (straight to GOOD, no trial, no
|
|
123
|
+
// rollback baseline, one install attempt). Absent defaults to trial so a
|
|
124
|
+
// pending build staged by older firmware keeps its semantics.
|
|
125
|
+
constexpr uint8_t kPendModeTrial = 0;
|
|
126
|
+
constexpr uint8_t kPendModeAdopt = 1;
|
|
127
|
+
constexpr uint8_t kInstallBudget = 3; // boot install attempts before abandoning a pending build
|
|
128
|
+
// Boot attempts to make a survived trial the revert target before giving up on
|
|
129
|
+
// the revert target rather than on the device: a trial that cannot promote and
|
|
130
|
+
// never resolves leaves applyOffer skipping every future offer, so the device
|
|
131
|
+
// stops being updatable at all and only a reflash recovers it.
|
|
132
|
+
constexpr uint8_t kPromoteBudget = 3;
|
|
133
|
+
// Boot attempts to install the revert target before keeping the trial build
|
|
134
|
+
// instead. install_build can panic rather than return, so an unbudgeted rollback
|
|
135
|
+
// that crashes mid-install re-enters itself every boot forever.
|
|
136
|
+
constexpr uint8_t kRollbackBudget = 3;
|
|
137
|
+
// Brownout boots a trial absorbs before they start counting as ordinary boots.
|
|
138
|
+
// A brownout is ambiguous (bad supply, or the new build drawing more than the
|
|
139
|
+
// board can deliver), so don't convict on the first one -- but don't absorb them
|
|
140
|
+
// forever either: applyOffer skips every offer while a trial is unresolved, so a
|
|
141
|
+
// trial held open indefinitely shuts the one channel that could ship a fix.
|
|
142
|
+
constexpr uint8_t kNeutralBudget = 3;
|
|
143
|
+
|
|
144
|
+
// ── small fs helpers ─────────────────────────────────────────────────────────
|
|
145
|
+
bool path_exists(const char* path) {
|
|
146
|
+
struct stat st;
|
|
147
|
+
return stat(path, &st) == 0;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Make the pending build the new revert target. The old last-good is only
|
|
151
|
+
// dropped once the replacement is in hand: unlinking first and then failing the
|
|
152
|
+
// rename (ENOSPC on littlefs metadata, or paths().pending lost to a power cut) would
|
|
153
|
+
// leave a GOOD state whose instChk names a build with no .tgz on disk, so a
|
|
154
|
+
// later revert() would have nothing to reinstall.
|
|
155
|
+
bool promote_pending(void) {
|
|
156
|
+
if (!path_exists(paths().pending)) return false;
|
|
157
|
+
// rename replaces an existing destination atomically (lfs_rename removes it
|
|
158
|
+
// as part of the same commit), so paths().last_good must NOT be unlinked first: a
|
|
159
|
+
// failed rename after the unlink would leave a GOOD state whose instChk
|
|
160
|
+
// names a build with no .tgz on disk, and a later revert() would have
|
|
161
|
+
// nothing to reinstall.
|
|
162
|
+
return rename(paths().pending, paths().last_good) == 0;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ── State store helpers ──────────────────────────────────────────────────────
|
|
166
|
+
// The device store's state hooks, open for one operation.
|
|
167
|
+
struct State {
|
|
168
|
+
const MIKDeviceStore* store = nullptr;
|
|
169
|
+
void* h = nullptr;
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
bool state_open(State* st, bool writable) {
|
|
173
|
+
const MIKDeviceStore* store = mik__device_store();
|
|
174
|
+
if (!store || !store->state_open || !paths().base[0]) return false;
|
|
175
|
+
st->store = store;
|
|
176
|
+
st->h = store->state_open(writable);
|
|
177
|
+
return st->h != nullptr;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
void state_close(State& st) { st.store->state_close(st.h); }
|
|
181
|
+
void state_commit(State& st) { st.store->state_commit(st.h); }
|
|
182
|
+
void state_erase(State& st, const char* key) { st.store->state_erase(st.h, key); }
|
|
183
|
+
void state_set_u8(State& st, const char* key, uint8_t v) { st.store->state_set_u8(st.h, key, v); }
|
|
184
|
+
void state_set_u32(State& st, const char* key, uint32_t v) {
|
|
185
|
+
st.store->state_set_u32(st.h, key, v);
|
|
186
|
+
}
|
|
187
|
+
void state_set_str(State& st, const char* key, const char* v) {
|
|
188
|
+
st.store->state_set_str(st.h, key, v);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
uint8_t state_u8(State& st, const char* key, uint8_t def) {
|
|
192
|
+
uint8_t v = def;
|
|
193
|
+
if (!st.store->state_get_u8(st.h, key, &v)) v = def;
|
|
194
|
+
return v;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
uint32_t state_u32(State& st, const char* key, uint32_t def) {
|
|
198
|
+
uint32_t v = def;
|
|
199
|
+
if (!st.store->state_get_u32(st.h, key, &v)) v = def;
|
|
200
|
+
return v;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Read a string key into `buf`. Returns true and a non-empty string on success.
|
|
204
|
+
bool state_str(State& st, const char* key, char* buf, size_t cap) {
|
|
205
|
+
if (!st.store->state_get_str(st.h, key, buf, cap)) {
|
|
206
|
+
buf[0] = 0;
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
return buf[0] != 0;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Drop the trial crash flag and its diagnostic. Must run wherever the state
|
|
213
|
+
// machine leaves a trial or starts a new one: the flag outliving the build that
|
|
214
|
+
// set it makes the *next* trial roll back on its first reboot, blamed with the
|
|
215
|
+
// previous build's error string.
|
|
216
|
+
void clear_trial_failure(State& h) {
|
|
217
|
+
state_erase(h, kKeyTrialBad);
|
|
218
|
+
state_erase(h, kKeyBadDetail);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Record a boot/promote diagnostic for the next reconcile() call to report.
|
|
222
|
+
void record_diag(State& h, const char* reason, const char* detail) {
|
|
223
|
+
state_set_str(h, kKeyORsn, reason);
|
|
224
|
+
if (detail && detail[0]) state_set_str(h, kKeyODetail, detail);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ── staging write cache ──────────────────────────────────────────────────────
|
|
228
|
+
// stageBegin fills these, stageWrite appends without reopening, and
|
|
229
|
+
// stageFinish/stageAbort flush them. Without the cache every 4 KB chunk cost a
|
|
230
|
+
// state-store open + stat + fopen/fclose (~50 flash metadata commits for a 200 KB
|
|
231
|
+
// build). Safe as plain statics because staging writes and the boot reconcile
|
|
232
|
+
// never overlap: both run on the single main task.
|
|
233
|
+
FILE* g_stage_file = nullptr;
|
|
234
|
+
uint32_t g_stage_cap = 0; // declared size from stageBegin; 0 = uncapped
|
|
235
|
+
long g_stage_have = 0; // bytes in the staging file
|
|
236
|
+
|
|
237
|
+
// Flush and close the staging file. False if the close failed, which on
|
|
238
|
+
// littlefs is where a full disk surfaces.
|
|
239
|
+
bool stage_close(void) {
|
|
240
|
+
if (!g_stage_file) return true;
|
|
241
|
+
bool ok = fclose(g_stage_file) == 0;
|
|
242
|
+
g_stage_file = nullptr;
|
|
243
|
+
return ok;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// ── JS result-object builders ────────────────────────────────────────────────
|
|
247
|
+
JSValue ok_obj(JSContext* ctx) {
|
|
248
|
+
JSValue o = JS_NewObject(ctx);
|
|
249
|
+
JS_SetPropertyStr(ctx, o, "ok", JS_TRUE);
|
|
250
|
+
return o;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
JSValue err_obj(JSContext* ctx, const char* msg) {
|
|
254
|
+
JSValue o = JS_NewObject(ctx);
|
|
255
|
+
JS_SetPropertyStr(ctx, o, "ok", JS_FALSE);
|
|
256
|
+
JS_SetPropertyStr(ctx, o, "error", JS_NewString(ctx, msg));
|
|
257
|
+
return o;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
JSValue err_obj_kind(JSContext* ctx, const char* msg, MIKBuildErr kind) {
|
|
261
|
+
JSValue o = err_obj(ctx, msg);
|
|
262
|
+
JS_SetPropertyStr(ctx, o, "kind", JS_NewString(ctx, err_kind(kind)));
|
|
263
|
+
return o;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// ── JS bindings ──────────────────────────────────────────────────────────────
|
|
267
|
+
|
|
268
|
+
// sha256_file emits lowercase hex and the comparison in stageFinish is strcmp,
|
|
269
|
+
// so anything else can never match. Rejecting it here matters because the
|
|
270
|
+
// mismatch would otherwise surface as corrupt, which the policy layer treats
|
|
271
|
+
// as "these bytes can never succeed" and abandons the checksum permanently: an
|
|
272
|
+
// uppercase digest from a registry would blacklist a perfectly good build.
|
|
273
|
+
bool valid_checksum(const char* s) {
|
|
274
|
+
size_t i = 0;
|
|
275
|
+
for (; s[i]; i++) {
|
|
276
|
+
if (i >= 64) return false;
|
|
277
|
+
const char c = s[i];
|
|
278
|
+
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false;
|
|
279
|
+
}
|
|
280
|
+
return i == 64;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// ── Staging cores ────────────────────────────────────────────────────────────
|
|
284
|
+
// The install machinery, with no JSContext in sight. Two callers sit on top: the
|
|
285
|
+
// native:mikro/ota JS bindings below, and the MIKOtaEnv install ops the native
|
|
286
|
+
// OTA client drives (mik__ota_fill_install_ops). One implementation, so the two
|
|
287
|
+
// can never drift on something as unforgiving as install safety.
|
|
288
|
+
|
|
289
|
+
struct CoreErr {
|
|
290
|
+
const char* msg = nullptr;
|
|
291
|
+
MIKBuildErr kind = MIK_BUILD_ERR_TRANSIENT;
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
bool core_fail(CoreErr* e, const char* msg, MIKBuildErr kind = MIK_BUILD_ERR_TRANSIENT) {
|
|
295
|
+
if (e) {
|
|
296
|
+
e->msg = msg;
|
|
297
|
+
e->kind = kind;
|
|
298
|
+
}
|
|
299
|
+
return false;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
bool core_stage_begin(const char* checksum, int64_t size, int64_t* out_resume, CoreErr* e) {
|
|
303
|
+
if (!checksum) return core_fail(e, "checksum not a string");
|
|
304
|
+
if (!valid_checksum(checksum)) {
|
|
305
|
+
// transient, not the default: the build is fine, the offer is
|
|
306
|
+
// malformed, so this must not count against the build's retry budget.
|
|
307
|
+
return core_fail(e, "checksum must be 64 lowercase hex characters",
|
|
308
|
+
MIK_BUILD_ERR_TRANSIENT);
|
|
309
|
+
}
|
|
310
|
+
if (size <= 0) return core_fail(e, "invalid size");
|
|
311
|
+
// Reject an impossible size while it is still int64: stgSize is u32, so a
|
|
312
|
+
// bogus offer above 4 GB would otherwise truncate into a small cap.
|
|
313
|
+
long fs_total = 0;
|
|
314
|
+
long fs_free = 0;
|
|
315
|
+
if (mik__fs_space(&fs_total, &fs_free) && size > fs_total) {
|
|
316
|
+
return core_fail(e, "offered build is larger than the filesystem");
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
stage_close(); // flush any prior staging file before stat/unlink below
|
|
320
|
+
|
|
321
|
+
State h;
|
|
322
|
+
if (!state_open(&h, true)) return core_fail(e, "OTA state unavailable");
|
|
323
|
+
|
|
324
|
+
// Resume only if the in-progress staging file is for the same checksum+size
|
|
325
|
+
// and hasn't already grown past the declared size.
|
|
326
|
+
char prev[96];
|
|
327
|
+
uint32_t prev_size = state_u32(h, kKeyStgSize, 0);
|
|
328
|
+
long have = mik__file_size(paths().staging);
|
|
329
|
+
int64_t resume = 0;
|
|
330
|
+
if (state_str(h, kKeyStgChk, prev, sizeof(prev)) && strcmp(prev, checksum) == 0 &&
|
|
331
|
+
prev_size == (uint32_t)size && have >= 0 && have <= size) {
|
|
332
|
+
resume = have;
|
|
333
|
+
} else {
|
|
334
|
+
unlink(paths().staging); // different target — start fresh
|
|
335
|
+
state_set_str(h, kKeyStgChk, checksum);
|
|
336
|
+
state_set_u32(h, kKeyStgSize, (uint32_t)size);
|
|
337
|
+
state_commit(h);
|
|
338
|
+
}
|
|
339
|
+
state_close(h);
|
|
340
|
+
|
|
341
|
+
g_stage_cap = (uint32_t)size;
|
|
342
|
+
g_stage_have = resume;
|
|
343
|
+
if (out_resume) *out_resume = resume;
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
bool core_stage_write(const uint8_t* data, size_t len, CoreErr* e) {
|
|
348
|
+
if (!data) return core_fail(e, "bytes not a Uint8Array");
|
|
349
|
+
if (len == 0) return true;
|
|
350
|
+
|
|
351
|
+
// Enforce the size cap from stageBegin so a runaway download can't fill flash.
|
|
352
|
+
if (g_stage_cap > 0 && (uint64_t)g_stage_have + len > g_stage_cap) {
|
|
353
|
+
return core_fail(e, "staged write exceeds declared size", MIK_BUILD_ERR_TRANSIENT);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
if (!g_stage_file) {
|
|
357
|
+
g_stage_file = fopen(paths().staging, "ab");
|
|
358
|
+
if (!g_stage_file) return core_fail(e, "open staging file", MIK_BUILD_ERR_TRANSIENT);
|
|
359
|
+
}
|
|
360
|
+
size_t wrote = fwrite(data, 1, len, g_stage_file);
|
|
361
|
+
if (wrote != len) {
|
|
362
|
+
// A short write still leaves `wrote` bytes on disk. Close first so the
|
|
363
|
+
// stream flushes, then resync from the file itself: an understated
|
|
364
|
+
// g_stage_have desyncs the resume offset from the real file, and the
|
|
365
|
+
// duplicated/skipped bytes surface later as a checksum mismatch, which
|
|
366
|
+
// is classified corrupt and blacklists the checksum forever. A full
|
|
367
|
+
// filesystem must stay transient.
|
|
368
|
+
stage_close();
|
|
369
|
+
long actual = mik__file_size(paths().staging);
|
|
370
|
+
g_stage_have = actual < 0 ? g_stage_have + (long)wrote : actual;
|
|
371
|
+
return core_fail(e, "write staging file (disk full?)", MIK_BUILD_ERR_TRANSIENT);
|
|
372
|
+
}
|
|
373
|
+
g_stage_have += (long)len;
|
|
374
|
+
return true;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
bool core_stage_finish(int64_t trial_boots, bool require_confirm, bool install_now, CoreErr* e) {
|
|
378
|
+
if (trial_boots < 0) trial_boots = 0;
|
|
379
|
+
// A confirm-gated trial needs at least one boot to run in. Boot reconcile
|
|
380
|
+
// evaluates the trial before the app loads, so trialBoots:0 with confirm set
|
|
381
|
+
// reverts at the next boot without the new build ever having had the chance
|
|
382
|
+
// to call markValid() -- every such update would revert, deterministically.
|
|
383
|
+
if (require_confirm && trial_boots < 1) trial_boots = 1;
|
|
384
|
+
if (trial_boots > 255) trial_boots = 255;
|
|
385
|
+
|
|
386
|
+
if (!stage_close()) {
|
|
387
|
+
return core_fail(e, "write staging file (disk full?)", MIK_BUILD_ERR_TRANSIENT);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
State h;
|
|
391
|
+
if (!state_open(&h, true)) {
|
|
392
|
+
return core_fail(e, "OTA state unavailable", MIK_BUILD_ERR_TRANSIENT);
|
|
393
|
+
}
|
|
394
|
+
char want_chk[96];
|
|
395
|
+
bool has_chk = state_str(h, kKeyStgChk, want_chk, sizeof(want_chk));
|
|
396
|
+
uint32_t want_size = state_u32(h, kKeyStgSize, 0);
|
|
397
|
+
|
|
398
|
+
if (!has_chk) {
|
|
399
|
+
state_close(h);
|
|
400
|
+
return core_fail(e, "no staged build", MIK_BUILD_ERR_TRANSIENT);
|
|
401
|
+
}
|
|
402
|
+
long have = mik__file_size(paths().staging);
|
|
403
|
+
if (have < 0) {
|
|
404
|
+
state_close(h);
|
|
405
|
+
return core_fail(e, "staging file missing", MIK_BUILD_ERR_TRANSIENT);
|
|
406
|
+
}
|
|
407
|
+
if ((uint32_t)have != want_size) {
|
|
408
|
+
state_close(h);
|
|
409
|
+
return core_fail(e, "staged size mismatch", MIK_BUILD_ERR_CORRUPT);
|
|
410
|
+
}
|
|
411
|
+
char got_chk[65];
|
|
412
|
+
if (!mik__sha256_file(paths().staging, got_chk)) {
|
|
413
|
+
state_close(h);
|
|
414
|
+
return core_fail(e, "read staging file", MIK_BUILD_ERR_TRANSIENT);
|
|
415
|
+
}
|
|
416
|
+
if (strcmp(got_chk, want_chk) != 0) {
|
|
417
|
+
state_close(h);
|
|
418
|
+
return core_fail(e, "checksum mismatch (corrupt download)", MIK_BUILD_ERR_CORRUPT);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Verified. Promote the staging file to the pending build.
|
|
422
|
+
unlink(paths().pending);
|
|
423
|
+
if (rename(paths().staging, paths().pending) != 0) {
|
|
424
|
+
state_close(h);
|
|
425
|
+
return core_fail(e, "stage pending build", MIK_BUILD_ERR_TRANSIENT);
|
|
426
|
+
}
|
|
427
|
+
g_stage_cap = 0;
|
|
428
|
+
g_stage_have = 0;
|
|
429
|
+
state_erase(h, kKeyStgChk);
|
|
430
|
+
state_erase(h, kKeyStgSize);
|
|
431
|
+
state_set_str(h, kKeyPendChk, want_chk);
|
|
432
|
+
// Explicit even though trial is the default: a leftover adopt marker from
|
|
433
|
+
// an earlier cable deploy must not turn this OTA build into an adopt.
|
|
434
|
+
state_set_u8(h, kKeyPendMode, kPendModeTrial);
|
|
435
|
+
state_set_u8(h, kKeyTrialN, (uint8_t)trial_boots);
|
|
436
|
+
state_set_u8(h, kKeyConfirm, require_confirm ? 1 : 0);
|
|
437
|
+
|
|
438
|
+
if (install_now) {
|
|
439
|
+
const char* err = nullptr;
|
|
440
|
+
MIKBuildErr kind = MIK_BUILD_ERR_TRANSIENT;
|
|
441
|
+
if (!mik__install_build(paths().base, paths().pending, &err, &kind)) {
|
|
442
|
+
// The verified .tgz is already on flash. Leaving it with pending=0
|
|
443
|
+
// would strand it there forever and let the next stageBegin build a
|
|
444
|
+
// second staging file beside it.
|
|
445
|
+
if (kind == MIK_BUILD_ERR_CORRUPT) {
|
|
446
|
+
state_set_u8(h, kKeyPending, 0); // identical bytes can't succeed
|
|
447
|
+
unlink(paths().pending);
|
|
448
|
+
} else {
|
|
449
|
+
state_set_u8(h, kKeyPending, 1); // boot reconcile retries it
|
|
450
|
+
state_set_u8(h, kKeyInstLeft, kInstallBudget);
|
|
451
|
+
}
|
|
452
|
+
state_commit(h);
|
|
453
|
+
state_close(h);
|
|
454
|
+
return core_fail(e, err, kind);
|
|
455
|
+
}
|
|
456
|
+
// New app is live but unproven: enter the trial. The caller restarts.
|
|
457
|
+
state_set_u8(h, kKeyState, kStateTrial);
|
|
458
|
+
state_set_u8(h, kKeyTrialLeft, (uint8_t)trial_boots);
|
|
459
|
+
state_set_u8(h, kKeyPending, 0);
|
|
460
|
+
state_erase(h, kKeyPromLeft); // per-trial budgets
|
|
461
|
+
state_erase(h, kKeyRbLeft);
|
|
462
|
+
state_erase(h, kKeyNeutLeft);
|
|
463
|
+
clear_trial_failure(h); // fresh trial: this build has not failed yet
|
|
464
|
+
state_commit(h);
|
|
465
|
+
state_close(h);
|
|
466
|
+
return true;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// Defer: install at the next boot on a clean heap.
|
|
470
|
+
state_set_u8(h, kKeyPending, 1);
|
|
471
|
+
state_set_u8(h, kKeyInstLeft, kInstallBudget);
|
|
472
|
+
state_commit(h);
|
|
473
|
+
state_close(h);
|
|
474
|
+
return true;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
void core_stage_abort(void) {
|
|
478
|
+
stage_close();
|
|
479
|
+
g_stage_cap = 0;
|
|
480
|
+
g_stage_have = 0;
|
|
481
|
+
unlink(paths().staging);
|
|
482
|
+
State h;
|
|
483
|
+
if (state_open(&h, true)) {
|
|
484
|
+
state_erase(h, kKeyStgChk);
|
|
485
|
+
state_erase(h, kKeyStgSize);
|
|
486
|
+
state_commit(h);
|
|
487
|
+
state_close(h);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// Confirm the running trial: promote it to GOOD and make the pending build the
|
|
492
|
+
// new revert target.
|
|
493
|
+
void core_mark_valid(void) {
|
|
494
|
+
State h;
|
|
495
|
+
if (!state_open(&h, true)) return;
|
|
496
|
+
if (state_u8(h, kKeyState, kStateGood) == kStateTrial) {
|
|
497
|
+
// Stay in the trial if the promotion failed: going GOOD anyway would
|
|
498
|
+
// point instChk at a build that has no .tgz left to revert to.
|
|
499
|
+
if (promote_pending()) {
|
|
500
|
+
char chk[96];
|
|
501
|
+
if (state_str(h, kKeyPendChk, chk, sizeof(chk))) state_set_str(h, kKeyInstChk, chk);
|
|
502
|
+
state_set_u8(h, kKeyState, kStateGood);
|
|
503
|
+
state_set_u8(h, kKeyTrialLeft, 0);
|
|
504
|
+
state_set_u8(h, kKeyPending, 0);
|
|
505
|
+
state_erase(h, kKeyPromLeft);
|
|
506
|
+
clear_trial_failure(h);
|
|
507
|
+
} else {
|
|
508
|
+
record_diag(h, "promote-failed", "could not make the trial build the revert target");
|
|
509
|
+
}
|
|
510
|
+
state_commit(h);
|
|
511
|
+
}
|
|
512
|
+
state_close(h);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
bool core_revert(CoreErr* e) {
|
|
516
|
+
if (!path_exists(paths().last_good)) return core_fail(e, "no last-good build to revert to");
|
|
517
|
+
const char* err = nullptr;
|
|
518
|
+
MIKBuildErr kind = MIK_BUILD_ERR_TRANSIENT;
|
|
519
|
+
if (!mik__install_build(paths().base, paths().last_good, &err, &kind)) {
|
|
520
|
+
return core_fail(e, err, kind);
|
|
521
|
+
}
|
|
522
|
+
State h;
|
|
523
|
+
if (state_open(&h, true)) {
|
|
524
|
+
state_set_u8(h, kKeyState, kStateGood);
|
|
525
|
+
state_set_u8(h, kKeyTrialLeft, 0);
|
|
526
|
+
state_set_u8(h, kKeyPending, 0);
|
|
527
|
+
clear_trial_failure(h);
|
|
528
|
+
unlink(paths().pending);
|
|
529
|
+
state_commit(h);
|
|
530
|
+
state_close(h);
|
|
531
|
+
}
|
|
532
|
+
return true;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
void core_running(char* chk, size_t chk_len, bool* out_trial) {
|
|
536
|
+
bool trial = false;
|
|
537
|
+
if (chk && chk_len) chk[0] = '\0';
|
|
538
|
+
State h;
|
|
539
|
+
if (state_open(&h, false)) {
|
|
540
|
+
trial = state_u8(h, kKeyState, kStateGood) == kStateTrial;
|
|
541
|
+
if (chk && chk_len) state_str(h, trial ? kKeyPendChk : kKeyInstChk, chk, chk_len);
|
|
542
|
+
state_close(h);
|
|
543
|
+
}
|
|
544
|
+
if (out_trial) *out_trial = trial;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// Read the outcome the boot-time reconcile recorded, then clear it so a second
|
|
548
|
+
// call reads empty.
|
|
549
|
+
void core_reconcile(char* installed, size_t installed_len, bool* out_reverted, char* reason,
|
|
550
|
+
size_t reason_len, char* detail, size_t detail_len) {
|
|
551
|
+
if (installed && installed_len) installed[0] = '\0';
|
|
552
|
+
if (reason && reason_len) reason[0] = '\0';
|
|
553
|
+
if (detail && detail_len) detail[0] = '\0';
|
|
554
|
+
bool reverted = false;
|
|
555
|
+
|
|
556
|
+
State h;
|
|
557
|
+
if (state_open(&h, true)) {
|
|
558
|
+
reverted = state_u8(h, kKeyORevert, 0) != 0;
|
|
559
|
+
if (installed && installed_len) state_str(h, kKeyOInst, installed, installed_len);
|
|
560
|
+
if (reason && reason_len) state_str(h, kKeyORsn, reason, reason_len);
|
|
561
|
+
if (detail && detail_len) state_str(h, kKeyODetail, detail, detail_len);
|
|
562
|
+
state_erase(h, kKeyOInst);
|
|
563
|
+
state_erase(h, kKeyORevert);
|
|
564
|
+
state_erase(h, kKeyORsn);
|
|
565
|
+
state_erase(h, kKeyODetail);
|
|
566
|
+
state_commit(h);
|
|
567
|
+
state_close(h);
|
|
568
|
+
}
|
|
569
|
+
if (out_reverted) *out_reverted = reverted;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// ── JS bindings ──────────────────────────────────────────────────────────────
|
|
573
|
+
// Argument coercion and result shaping only; the work is in the cores above.
|
|
574
|
+
|
|
575
|
+
JSValue core_err_obj(JSContext* ctx, const CoreErr& e) {
|
|
576
|
+
return err_obj_kind(ctx, e.msg ? e.msg : "ota error", e.kind);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// stageBegin(checksum, size) -> { ok, resumeOffset } | { ok:false, error }
|
|
580
|
+
JSValue js_stage_begin(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
|
|
581
|
+
if (argc < 2) return err_obj(ctx, "missing checksum/size");
|
|
582
|
+
const char* checksum = JS_ToCString(ctx, argv[0]);
|
|
583
|
+
if (!checksum) {
|
|
584
|
+
// JS_ToCString throws on a value with a throwing toString. Clear it
|
|
585
|
+
// rather than strand it on the context for some unrelated later
|
|
586
|
+
// operation to surface, the same way the size path below does.
|
|
587
|
+
JS_FreeValue(ctx, JS_GetException(ctx));
|
|
588
|
+
return err_obj(ctx, "checksum not a string");
|
|
589
|
+
}
|
|
590
|
+
int64_t size = 0;
|
|
591
|
+
if (JS_ToInt64(ctx, &size, argv[1])) {
|
|
592
|
+
JS_FreeCString(ctx, checksum);
|
|
593
|
+
// JS_ToInt64 throws on a value with a throwing valueOf. We report through
|
|
594
|
+
// the result object, so clear it rather than strand it on the context.
|
|
595
|
+
JS_FreeValue(ctx, JS_GetException(ctx));
|
|
596
|
+
return err_obj(ctx, "invalid size");
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
CoreErr e;
|
|
600
|
+
int64_t resume = 0;
|
|
601
|
+
bool ok = core_stage_begin(checksum, size, &resume, &e);
|
|
602
|
+
JS_FreeCString(ctx, checksum);
|
|
603
|
+
if (!ok) return core_err_obj(ctx, e);
|
|
604
|
+
|
|
605
|
+
JSValue o = ok_obj(ctx);
|
|
606
|
+
JS_SetPropertyStr(ctx, o, "resumeOffset", JS_NewInt64(ctx, resume));
|
|
607
|
+
return o;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// stageWrite(bytes) -> { ok } | { ok:false, error, kind? }
|
|
611
|
+
JSValue js_stage_write(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
|
|
612
|
+
if (argc < 1) return err_obj(ctx, "missing bytes");
|
|
613
|
+
size_t len = 0;
|
|
614
|
+
const uint8_t* data = JS_GetUint8Array(ctx, &len, argv[0]);
|
|
615
|
+
if (!data) {
|
|
616
|
+
JS_FreeValue(ctx, JS_GetException(ctx)); // JS_GetUint8Array throws; we report via err_obj
|
|
617
|
+
return err_obj(ctx, "bytes not a Uint8Array");
|
|
618
|
+
}
|
|
619
|
+
CoreErr e;
|
|
620
|
+
if (!core_stage_write(data, len, &e)) return core_err_obj(ctx, e);
|
|
621
|
+
return ok_obj(ctx);
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
// stageFinish(trialBoots, requireConfirm, installNow)
|
|
625
|
+
// -> { ok } | { ok:false, error, kind }
|
|
626
|
+
// Verifies SHA-256 + size over the whole staged file, then either installs in
|
|
627
|
+
// place now (installNow) or marks a verified build staged-for-install so the
|
|
628
|
+
// next boot's reconcile installs it on a clean heap.
|
|
629
|
+
JSValue js_stage_finish(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
|
|
630
|
+
int64_t trial_boots = 1;
|
|
631
|
+
if (argc >= 1 && JS_ToInt64(ctx, &trial_boots, argv[0])) {
|
|
632
|
+
// A throwing valueOf leaves trial_boots indeterminate and an exception
|
|
633
|
+
// pending; we report through the result object, so clear it and default.
|
|
634
|
+
JS_FreeValue(ctx, JS_GetException(ctx));
|
|
635
|
+
trial_boots = 1;
|
|
636
|
+
}
|
|
637
|
+
bool require_confirm = argc >= 2 && JS_ToBool(ctx, argv[1]);
|
|
638
|
+
bool install_now = argc >= 3 && JS_ToBool(ctx, argv[2]);
|
|
639
|
+
|
|
640
|
+
CoreErr e;
|
|
641
|
+
if (!core_stage_finish(trial_boots, require_confirm, install_now, &e)) {
|
|
642
|
+
return core_err_obj(ctx, e);
|
|
643
|
+
}
|
|
644
|
+
return ok_obj(ctx);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// stageAbort() -> void
|
|
648
|
+
JSValue js_stage_abort(JSContext*, JSValueConst, int, JSValueConst*) {
|
|
649
|
+
core_stage_abort();
|
|
650
|
+
return JS_UNDEFINED;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// markValid() -> void
|
|
654
|
+
JSValue js_mark_valid(JSContext*, JSValueConst, int, JSValueConst*) {
|
|
655
|
+
core_mark_valid();
|
|
656
|
+
return JS_UNDEFINED;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// revert() -> { ok } | { ok:false, error }. Re-install the last-good build.
|
|
660
|
+
JSValue js_revert(JSContext* ctx, JSValueConst, int, JSValueConst*) {
|
|
661
|
+
CoreErr e;
|
|
662
|
+
// Historically reported without a kind, and the policy maps every revert
|
|
663
|
+
// failure to transient anyway.
|
|
664
|
+
if (!core_revert(&e)) return err_obj(ctx, e.msg ? e.msg : "revert failed");
|
|
665
|
+
return ok_obj(ctx);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// running() -> { checksum?, trial }
|
|
669
|
+
JSValue js_running(JSContext* ctx, JSValueConst, int, JSValueConst*) {
|
|
670
|
+
JSValue o = JS_NewObject(ctx);
|
|
671
|
+
char chk[96] = {0};
|
|
672
|
+
bool trial = false;
|
|
673
|
+
core_running(chk, sizeof(chk), &trial);
|
|
674
|
+
if (chk[0]) JS_SetPropertyStr(ctx, o, "checksum", JS_NewString(ctx, chk));
|
|
675
|
+
JS_SetPropertyStr(ctx, o, "trial", JS_NewBool(ctx, trial));
|
|
676
|
+
return o;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// reconcile() -> { installed?, reverted, diagnostic? }
|
|
680
|
+
JSValue js_reconcile(JSContext* ctx, JSValueConst, int, JSValueConst*) {
|
|
681
|
+
JSValue o = JS_NewObject(ctx);
|
|
682
|
+
char installed[96] = {0};
|
|
683
|
+
char reason[96] = {0};
|
|
684
|
+
char detail[160] = {0};
|
|
685
|
+
bool reverted = false;
|
|
686
|
+
core_reconcile(installed, sizeof(installed), &reverted, reason, sizeof(reason), detail,
|
|
687
|
+
sizeof(detail));
|
|
688
|
+
|
|
689
|
+
if (installed[0]) JS_SetPropertyStr(ctx, o, "installed", JS_NewString(ctx, installed));
|
|
690
|
+
JS_SetPropertyStr(ctx, o, "reverted", JS_NewBool(ctx, reverted));
|
|
691
|
+
if (reason[0]) {
|
|
692
|
+
JSValue diag = JS_NewObject(ctx);
|
|
693
|
+
JS_SetPropertyStr(ctx, diag, "reason", JS_NewString(ctx, reason));
|
|
694
|
+
if (detail[0]) JS_SetPropertyStr(ctx, diag, "detail", JS_NewString(ctx, detail));
|
|
695
|
+
JS_SetPropertyStr(ctx, o, "diagnostic", diag);
|
|
696
|
+
}
|
|
697
|
+
return o;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// ── MIKOtaEnv install ops ────────────────────────────────────────────────────
|
|
701
|
+
// The native OTA client reaches the staging machinery through these. They are
|
|
702
|
+
// the same cores the JS bindings above call, so nothing can drift between the
|
|
703
|
+
// two implementations while both are in the tree.
|
|
704
|
+
|
|
705
|
+
namespace {
|
|
706
|
+
|
|
707
|
+
int env_err_kind(MIKBuildErr kind) {
|
|
708
|
+
switch (kind) {
|
|
709
|
+
case MIK_BUILD_ERR_CORRUPT:
|
|
710
|
+
return MIK_OTA_ERR_CORRUPT;
|
|
711
|
+
case MIK_BUILD_ERR_OOM:
|
|
712
|
+
return MIK_OTA_ERR_OOM;
|
|
713
|
+
case MIK_BUILD_ERR_TRANSIENT:
|
|
714
|
+
break;
|
|
715
|
+
}
|
|
716
|
+
return MIK_OTA_ERR_TRANSIENT;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
void env_copy_err(const CoreErr& e, char* err_buf, size_t err_len) {
|
|
720
|
+
if (err_buf && err_len) snprintf(err_buf, err_len, "%s", e.msg ? e.msg : "ota error");
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
bool env_stage_begin(void*, const char* checksum, size_t size, size_t* out_resume, char* err_buf,
|
|
724
|
+
size_t err_len) {
|
|
725
|
+
CoreErr e;
|
|
726
|
+
int64_t resume = 0;
|
|
727
|
+
if (!core_stage_begin(checksum, (int64_t)size, &resume, &e)) {
|
|
728
|
+
env_copy_err(e, err_buf, err_len);
|
|
729
|
+
return false;
|
|
730
|
+
}
|
|
731
|
+
if (out_resume) *out_resume = (size_t)resume;
|
|
732
|
+
return true;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
bool env_stage_write(void*, const uint8_t* data, size_t len, char* err_buf, size_t err_len) {
|
|
736
|
+
CoreErr e;
|
|
737
|
+
if (!core_stage_write(data, len, &e)) {
|
|
738
|
+
env_copy_err(e, err_buf, err_len);
|
|
739
|
+
return false;
|
|
740
|
+
}
|
|
741
|
+
return true;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
bool env_stage_finish(void*, int trial_boots, bool require_confirm, bool install_now, char* err_buf,
|
|
745
|
+
size_t err_len, int* out_err_kind) {
|
|
746
|
+
CoreErr e;
|
|
747
|
+
if (!core_stage_finish(trial_boots, require_confirm, install_now, &e)) {
|
|
748
|
+
env_copy_err(e, err_buf, err_len);
|
|
749
|
+
if (out_err_kind) *out_err_kind = env_err_kind(e.kind);
|
|
750
|
+
return false;
|
|
751
|
+
}
|
|
752
|
+
return true;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
void env_stage_abort(void*) { core_stage_abort(); }
|
|
756
|
+
void env_mark_valid(void*) { core_mark_valid(); }
|
|
757
|
+
|
|
758
|
+
bool env_revert(void*, char* err_buf, size_t err_len) {
|
|
759
|
+
CoreErr e;
|
|
760
|
+
if (!core_revert(&e)) {
|
|
761
|
+
env_copy_err(e, err_buf, err_len);
|
|
762
|
+
return false;
|
|
763
|
+
}
|
|
764
|
+
return true;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
bool env_running(void*, MIKOtaRunningBuild* out) {
|
|
768
|
+
if (!out) return false;
|
|
769
|
+
*out = {};
|
|
770
|
+
char chk[96] = {0};
|
|
771
|
+
bool trial = false;
|
|
772
|
+
core_running(chk, sizeof(chk), &trial);
|
|
773
|
+
// The checksum field is a 64-hex digest plus its terminator; a longer value
|
|
774
|
+
// could only come from a corrupted store, and truncating it is what the JS path
|
|
775
|
+
// effectively did too.
|
|
776
|
+
snprintf(out->checksum, sizeof(out->checksum), "%s", chk);
|
|
777
|
+
out->trial = trial;
|
|
778
|
+
// version is left empty on purpose: the policy fills it from the app's
|
|
779
|
+
// package.json through read_app_version.
|
|
780
|
+
return true;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
void env_reconcile(void*, MIKOtaReconcileOutcome* out) {
|
|
784
|
+
if (!out) return;
|
|
785
|
+
*out = {};
|
|
786
|
+
char installed[96] = {0};
|
|
787
|
+
char reason[96] = {0};
|
|
788
|
+
char detail[160] = {0};
|
|
789
|
+
bool reverted = false;
|
|
790
|
+
core_reconcile(installed, sizeof(installed), &reverted, reason, sizeof(reason), detail,
|
|
791
|
+
sizeof(detail));
|
|
792
|
+
snprintf(out->installed, sizeof(out->installed), "%s", installed);
|
|
793
|
+
out->reverted = reverted;
|
|
794
|
+
if (reason[0]) {
|
|
795
|
+
out->has_diagnostic = true;
|
|
796
|
+
snprintf(out->diagnostic.reason, sizeof(out->diagnostic.reason), "%s", reason);
|
|
797
|
+
snprintf(out->diagnostic.detail, sizeof(out->diagnostic.detail), "%s", detail);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
} // namespace
|
|
802
|
+
|
|
803
|
+
// ── module registration ──────────────────────────────────────────────────────
|
|
804
|
+
int mik__ota_module_init(JSContext* ctx, JSModuleDef* m) {
|
|
805
|
+
JS_SetModuleExport(ctx, m, "stageBegin",
|
|
806
|
+
JS_NewCFunction(ctx, js_stage_begin, "stageBegin", 2));
|
|
807
|
+
JS_SetModuleExport(ctx, m, "stageWrite",
|
|
808
|
+
JS_NewCFunction(ctx, js_stage_write, "stageWrite", 1));
|
|
809
|
+
JS_SetModuleExport(ctx, m, "stageFinish",
|
|
810
|
+
JS_NewCFunction(ctx, js_stage_finish, "stageFinish", 3));
|
|
811
|
+
JS_SetModuleExport(ctx, m, "stageAbort",
|
|
812
|
+
JS_NewCFunction(ctx, js_stage_abort, "stageAbort", 0));
|
|
813
|
+
JS_SetModuleExport(ctx, m, "markValid", JS_NewCFunction(ctx, js_mark_valid, "markValid", 0));
|
|
814
|
+
JS_SetModuleExport(ctx, m, "revert", JS_NewCFunction(ctx, js_revert, "revert", 0));
|
|
815
|
+
JS_SetModuleExport(ctx, m, "running", JS_NewCFunction(ctx, js_running, "running", 0));
|
|
816
|
+
JS_SetModuleExport(ctx, m, "reconcile", JS_NewCFunction(ctx, js_reconcile, "reconcile", 0));
|
|
817
|
+
return 0;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
JSModuleDef* mik__ota_init(JSContext* ctx) {
|
|
821
|
+
JSModuleDef* m = JS_NewCModule(ctx, "native:mikro/ota", mik__ota_module_init);
|
|
822
|
+
if (!m) return nullptr;
|
|
823
|
+
JS_AddModuleExport(ctx, m, "stageBegin");
|
|
824
|
+
JS_AddModuleExport(ctx, m, "stageWrite");
|
|
825
|
+
JS_AddModuleExport(ctx, m, "stageFinish");
|
|
826
|
+
JS_AddModuleExport(ctx, m, "stageAbort");
|
|
827
|
+
JS_AddModuleExport(ctx, m, "markValid");
|
|
828
|
+
JS_AddModuleExport(ctx, m, "revert");
|
|
829
|
+
JS_AddModuleExport(ctx, m, "running");
|
|
830
|
+
JS_AddModuleExport(ctx, m, "reconcile");
|
|
831
|
+
return m;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// ── boot-time reconcile (trial state machine) ────────────────────────────────
|
|
835
|
+
|
|
836
|
+
// Map a reset reason to a trial verdict.
|
|
837
|
+
enum class TrialVerdict { kCrash, kNeutral, kClean };
|
|
838
|
+
|
|
839
|
+
// The platform's reset reason (MIKPlatform.get_reset_reason), as a stable string.
|
|
840
|
+
const char* reset_reason(void) {
|
|
841
|
+
const MIKPlatform* p = MIK_GetPlatform();
|
|
842
|
+
const char* r = p && p->get_reset_reason ? p->get_reset_reason() : nullptr;
|
|
843
|
+
return r ? r : "unknown";
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
bool is_crash_reset(const char* r) {
|
|
847
|
+
return strcmp(r, MIK_RESET_PANIC) == 0 || strcmp(r, MIK_RESET_INT_WATCHDOG) == 0 ||
|
|
848
|
+
strcmp(r, MIK_RESET_TASK_WATCHDOG) == 0 || strcmp(r, MIK_RESET_WATCHDOG) == 0;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
TrialVerdict classify_reset(const char* r) {
|
|
852
|
+
if (is_crash_reset(r)) return TrialVerdict::kCrash;
|
|
853
|
+
if (strcmp(r, MIK_RESET_BROWNOUT) == 0) {
|
|
854
|
+
// Ambiguous: a bad supply, or the new build drawing more than the
|
|
855
|
+
// board can deliver. Absorbed a bounded number of times (kNeutralBudget).
|
|
856
|
+
return TrialVerdict::kNeutral;
|
|
857
|
+
}
|
|
858
|
+
// "power-on", "software", "deep-sleep", "external", ...: a cold start is an
|
|
859
|
+
// ordinary boot: nothing went wrong, and the app is about to get its chance
|
|
860
|
+
// to run and confirm. Counting it as neutral would let a mains device that
|
|
861
|
+
// only ever power-cycles sit in an unresolved trial forever.
|
|
862
|
+
return TrialVerdict::kClean;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// The crash's name for the revert diagnostic.
|
|
866
|
+
const char* reset_reason_name(const char* r) { return is_crash_reset(r) ? r : "crash"; }
|
|
867
|
+
|
|
868
|
+
// Record the just-installed checksum so reconcile() can report it after the
|
|
869
|
+
// post-install restart.
|
|
870
|
+
void record_installed(State& h, const char* chk) {
|
|
871
|
+
state_set_str(h, kKeyOInst, chk);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
void record_revert(State& h, const char* reason, const char* detail) {
|
|
875
|
+
state_set_u8(h, kKeyORevert, 1);
|
|
876
|
+
record_diag(h, reason, detail);
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
// The trial build is still what /app holds, so make instChk name it. Leaving
|
|
880
|
+
// instChk on the previous build would make running() report a checksum the
|
|
881
|
+
// device is not running: the registry would never re-offer the build that is
|
|
882
|
+
// actually live, and revert() would install the older build over the newer one.
|
|
883
|
+
void keep_trial_as_installed(State& h) {
|
|
884
|
+
char chk[96];
|
|
885
|
+
if (state_str(h, kKeyPendChk, chk, sizeof(chk))) state_set_str(h, kKeyInstChk, chk);
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
// Install the revert target, ending the trial. Both trial-failure paths funnel
|
|
889
|
+
// here so the attempt budget is charged identically.
|
|
890
|
+
//
|
|
891
|
+
// The budget is charged and committed BEFORE the install, for the reason the
|
|
892
|
+
// deferred-install path documents: install_build does not only return false, it
|
|
893
|
+
// can panic (a littlefs assert, the task watchdog, an allocation the OOM handler
|
|
894
|
+
// turns into a restart). Charging on the return paths alone means a rollback
|
|
895
|
+
// that crashes mid-install leaves the state untouched, so the next boot re-enters the
|
|
896
|
+
// identical rollback and the budget is never reached -- a loop only a reflash
|
|
897
|
+
// escapes, and one every device that took the bad build enters together.
|
|
898
|
+
//
|
|
899
|
+
// Returns false if the last-good build is not live, in which case the caller
|
|
900
|
+
// keeps the trial build and must carry pendChk across.
|
|
901
|
+
bool attempt_rollback(State& h, const char* reason, const char* detail) {
|
|
902
|
+
if (!path_exists(paths().last_good)) {
|
|
903
|
+
record_revert(h, reason, "no rollback build available");
|
|
904
|
+
return false;
|
|
905
|
+
}
|
|
906
|
+
uint8_t left = state_u8(h, kKeyRbLeft, kRollbackBudget);
|
|
907
|
+
if (left == 0) {
|
|
908
|
+
record_revert(h, reason, "rollback install failed repeatedly; keeping this build");
|
|
909
|
+
return false;
|
|
910
|
+
}
|
|
911
|
+
state_set_u8(h, kKeyRbLeft, (uint8_t)(left - 1));
|
|
912
|
+
state_commit(h);
|
|
913
|
+
|
|
914
|
+
const char* err = nullptr;
|
|
915
|
+
MIKBuildErr kind = MIK_BUILD_ERR_TRANSIENT;
|
|
916
|
+
if (!mik__install_build(paths().base, paths().last_good, &err, &kind)) {
|
|
917
|
+
record_revert(h, reason, "rollback install failed");
|
|
918
|
+
return false;
|
|
919
|
+
}
|
|
920
|
+
state_erase(h, kKeyRbLeft);
|
|
921
|
+
record_revert(h, reason, detail);
|
|
922
|
+
return true;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
// Resolve a failed adopt install: drop the pending build, record the outcome
|
|
926
|
+
// for MIK_CMD_DEPLOY_RESULT, and leave the previous /app running. No rollback
|
|
927
|
+
// and no retry -- the developer is on the serial cable and re-pushes. Never
|
|
928
|
+
// touches the reconcile record (oRsn/oDetail), which reaches the registry.
|
|
929
|
+
void adopt_fail(State& h, const char* chk, const char* reason, const char* detail) {
|
|
930
|
+
state_set_u8(h, kKeyPending, 0);
|
|
931
|
+
state_erase(h, kKeyPendChk);
|
|
932
|
+
state_erase(h, kKeyPendMode);
|
|
933
|
+
state_erase(h, kKeyInstLeft);
|
|
934
|
+
unlink(paths().pending);
|
|
935
|
+
state_set_u8(h, kKeyDRes, 2);
|
|
936
|
+
state_set_str(h, kKeyDChk, chk);
|
|
937
|
+
state_set_str(h, kKeyDRsn, reason);
|
|
938
|
+
state_set_str(h, kKeyDDetail, detail);
|
|
939
|
+
state_commit(h);
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
} // namespace
|
|
943
|
+
|
|
944
|
+
void mik__ota_fill_install_ops(MIKOtaEnv* env) {
|
|
945
|
+
if (!env) return;
|
|
946
|
+
env->stage_begin = env_stage_begin;
|
|
947
|
+
env->stage_write = env_stage_write;
|
|
948
|
+
env->stage_finish = env_stage_finish;
|
|
949
|
+
env->stage_abort = env_stage_abort;
|
|
950
|
+
env->mark_valid = env_mark_valid;
|
|
951
|
+
env->revert = env_revert;
|
|
952
|
+
env->running = env_running;
|
|
953
|
+
env->reconcile = env_reconcile;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
// Stage a streamed .tgz for adopt install at the next boot (the cable-deploy
|
|
957
|
+
// path, distinct from an OTA download which runs a trial). The install itself
|
|
958
|
+
// runs from MIK_OtaBootReconcile() on a clean heap: doing it here, with the
|
|
959
|
+
// app live, needs a 32 KB contiguous inflate window a fragmented heap cannot
|
|
960
|
+
// provide. Verification stays synchronous so a corrupt upload still fails over
|
|
961
|
+
// serial; empty checksum skips the check. NOT JS-exposed — called from the
|
|
962
|
+
// serial DEPLOY_BUILD handler.
|
|
963
|
+
bool MIK_OtaStageAdopt(const char* tgz_path, const char* checksum, const char** err) {
|
|
964
|
+
if (!path_exists(tgz_path)) {
|
|
965
|
+
*err = "build not staged";
|
|
966
|
+
return false;
|
|
967
|
+
}
|
|
968
|
+
if (checksum && checksum[0]) {
|
|
969
|
+
char got[65];
|
|
970
|
+
if (!mik__sha256_file(tgz_path, got)) {
|
|
971
|
+
*err = "read staged build";
|
|
972
|
+
return false;
|
|
973
|
+
}
|
|
974
|
+
if (strcmp(got, checksum) != 0) {
|
|
975
|
+
*err = "checksum mismatch (corrupt build)";
|
|
976
|
+
return false;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
State h;
|
|
980
|
+
if (!state_open(&h, true)) {
|
|
981
|
+
*err = "OTA state unavailable";
|
|
982
|
+
return false;
|
|
983
|
+
}
|
|
984
|
+
// Move the .tgz out of the deploy tmp tree before acking: MIK_DeployRecover
|
|
985
|
+
// cleans that tree at boot, before the reconcile would read it. Rename
|
|
986
|
+
// before anything else mutates: a failed rename (e.g. littlefs metadata
|
|
987
|
+
// ENOSPC) must error back over serial having left trial state untouched.
|
|
988
|
+
unlink(paths().pending);
|
|
989
|
+
if (rename(tgz_path, paths().pending) != 0) {
|
|
990
|
+
state_close(h);
|
|
991
|
+
*err = "stage pending build";
|
|
992
|
+
return false;
|
|
993
|
+
}
|
|
994
|
+
// A cable deploy supersedes an in-flight trial. Resolve it to GOOD now,
|
|
995
|
+
// while the trial's checksum is still in pendChk (overwritten below): the
|
|
996
|
+
// trial build is what /app holds, so it becomes the installed build, the
|
|
997
|
+
// same accounting the reflash guard does. Without this, the next boot's
|
|
998
|
+
// trial verdict would roll back or promote against the pending slot this
|
|
999
|
+
// deploy just replaced.
|
|
1000
|
+
if (state_u8(h, kKeyState, kStateGood) == kStateTrial) {
|
|
1001
|
+
char trial_chk[96];
|
|
1002
|
+
if (state_str(h, kKeyPendChk, trial_chk, sizeof(trial_chk))) {
|
|
1003
|
+
state_set_str(h, kKeyInstChk, trial_chk);
|
|
1004
|
+
}
|
|
1005
|
+
state_set_u8(h, kKeyState, kStateGood);
|
|
1006
|
+
state_set_u8(h, kKeyTrialLeft, 0);
|
|
1007
|
+
state_erase(h, kKeyPromLeft);
|
|
1008
|
+
state_erase(h, kKeyRbLeft);
|
|
1009
|
+
state_erase(h, kKeyNeutLeft);
|
|
1010
|
+
clear_trial_failure(h);
|
|
1011
|
+
}
|
|
1012
|
+
state_set_str(h, kKeyPendChk, checksum ? checksum : "");
|
|
1013
|
+
state_set_u8(h, kKeyPendMode, kPendModeAdopt);
|
|
1014
|
+
state_set_u8(h, kKeyPending, 1);
|
|
1015
|
+
state_set_u8(h, kKeyInstLeft, 1); // one attempt: the developer is on the cable
|
|
1016
|
+
// Drop any unread outcome from an earlier adopt (e.g. a --no-restart deploy
|
|
1017
|
+
// that installed at a natural boot), so the post-restart result read can
|
|
1018
|
+
// only ever see this deploy's outcome.
|
|
1019
|
+
state_erase(h, kKeyDRes);
|
|
1020
|
+
state_erase(h, kKeyDChk);
|
|
1021
|
+
state_erase(h, kKeyDRsn);
|
|
1022
|
+
state_erase(h, kKeyDDetail);
|
|
1023
|
+
state_commit(h);
|
|
1024
|
+
state_close(h);
|
|
1025
|
+
return true;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
// Read and clear the adopt-install outcome for MIK_CMD_DEPLOY_RESULT.
|
|
1029
|
+
void mik__ota_take_deploy_result(MIKDeployResult* out) {
|
|
1030
|
+
memset(out, 0, sizeof(*out));
|
|
1031
|
+
State h;
|
|
1032
|
+
if (!state_open(&h, true)) return;
|
|
1033
|
+
out->status = state_u8(h, kKeyDRes, 0);
|
|
1034
|
+
state_str(h, kKeyDChk, out->checksum, sizeof(out->checksum));
|
|
1035
|
+
state_str(h, kKeyDRsn, out->reason, sizeof(out->reason));
|
|
1036
|
+
state_str(h, kKeyDDetail, out->detail, sizeof(out->detail));
|
|
1037
|
+
if (out->status != 0) {
|
|
1038
|
+
state_erase(h, kKeyDRes);
|
|
1039
|
+
state_erase(h, kKeyDChk);
|
|
1040
|
+
state_erase(h, kKeyDRsn);
|
|
1041
|
+
state_erase(h, kKeyDDetail);
|
|
1042
|
+
state_commit(h);
|
|
1043
|
+
}
|
|
1044
|
+
state_close(h);
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// MIK_CMD_DEPLOY_RESULT. Reply: u8 status | 3 x (u16le len | bytes) for the
|
|
1048
|
+
// checksum, the reason and the detail.
|
|
1049
|
+
bool MIK_OtaHandleDeployResult(MIKReplTransport* transport, uint32_t payload_len) {
|
|
1050
|
+
mik__proto_drain(transport, payload_len);
|
|
1051
|
+
MIKDeployResult res;
|
|
1052
|
+
mik__ota_take_deploy_result(&res);
|
|
1053
|
+
uint8_t buf[1 + 3 * 2 + sizeof(res.checksum) + sizeof(res.reason) + sizeof(res.detail)];
|
|
1054
|
+
size_t n = 0;
|
|
1055
|
+
buf[n++] = res.status;
|
|
1056
|
+
const char* fields[] = {res.checksum, res.reason, res.detail};
|
|
1057
|
+
for (const char* s : fields) {
|
|
1058
|
+
size_t len = strlen(s);
|
|
1059
|
+
buf[n++] = (uint8_t)(len & 0xFF);
|
|
1060
|
+
buf[n++] = (uint8_t)((len >> 8) & 0xFF);
|
|
1061
|
+
memcpy(buf + n, s, len);
|
|
1062
|
+
n += len;
|
|
1063
|
+
}
|
|
1064
|
+
mik__proto_send(transport, MIK_MSG_OK, buf, n);
|
|
1065
|
+
return true;
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
// True while an unconfirmed OTA trial is the running build.
|
|
1069
|
+
bool mik__ota_in_trial(void) {
|
|
1070
|
+
State h;
|
|
1071
|
+
if (!state_open(&h, false)) return false;
|
|
1072
|
+
bool trial = state_u8(h, kKeyState, kStateGood) == kStateTrial;
|
|
1073
|
+
state_close(h);
|
|
1074
|
+
return trial;
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
// Flag the running trial as failed after a fatal JS error, so the next reconcile
|
|
1078
|
+
// reverts it even though the reboot will look like a clean software reset. No-op
|
|
1079
|
+
// outside a trial; the first detail recorded wins.
|
|
1080
|
+
static void note_trial_failure(const char* detail) {
|
|
1081
|
+
State h;
|
|
1082
|
+
if (!state_open(&h, true)) return;
|
|
1083
|
+
if (state_u8(h, kKeyState, kStateGood) == kStateTrial && state_u8(h, kKeyTrialBad, 0) == 0) {
|
|
1084
|
+
state_set_u8(h, kKeyTrialBad, 1);
|
|
1085
|
+
if (detail && detail[0]) state_set_str(h, kKeyBadDetail, detail);
|
|
1086
|
+
state_commit(h);
|
|
1087
|
+
}
|
|
1088
|
+
state_close(h);
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
void MIK_OtaTrialErrorHandler(JSContext* ctx, JSValue error, void* /*opaque*/) {
|
|
1092
|
+
if (!mik__ota_in_trial()) {
|
|
1093
|
+
return;
|
|
1094
|
+
}
|
|
1095
|
+
char detail[160] = "uncaught error";
|
|
1096
|
+
if (JS_IsObject(error)) {
|
|
1097
|
+
JSValue name_v = JS_GetPropertyStr(ctx, error, "name");
|
|
1098
|
+
JSValue msg_v = JS_GetPropertyStr(ctx, error, "message");
|
|
1099
|
+
const char* name = JS_ToCString(ctx, name_v);
|
|
1100
|
+
const char* msg = JS_ToCString(ctx, msg_v);
|
|
1101
|
+
if (name && name[0] && msg && msg[0]) {
|
|
1102
|
+
snprintf(detail, sizeof(detail), "%s: %s", name, msg);
|
|
1103
|
+
} else if (msg && msg[0]) {
|
|
1104
|
+
snprintf(detail, sizeof(detail), "%s", msg);
|
|
1105
|
+
} else if (name && name[0]) {
|
|
1106
|
+
snprintf(detail, sizeof(detail), "%s", name);
|
|
1107
|
+
}
|
|
1108
|
+
/* A throwing getter (or a toString that throws) leaves an exception
|
|
1109
|
+
* pending on ctx that nothing downstream would ever clear. */
|
|
1110
|
+
if (!name || !msg) {
|
|
1111
|
+
JS_FreeValue(ctx, JS_GetException(ctx));
|
|
1112
|
+
}
|
|
1113
|
+
if (name) JS_FreeCString(ctx, name);
|
|
1114
|
+
if (msg) JS_FreeCString(ctx, msg);
|
|
1115
|
+
JS_FreeValue(ctx, name_v);
|
|
1116
|
+
JS_FreeValue(ctx, msg_v);
|
|
1117
|
+
}
|
|
1118
|
+
note_trial_failure(detail);
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
// Boot reconcile: NOT JS-exposed. Called by the port before the JS app loads,
|
|
1122
|
+
// after MIK_DeployRecover(). Runs the reflash guard, an adopt install (cable
|
|
1123
|
+
// deploy), the trial verdict, and a deferred trial install in that order. True
|
|
1124
|
+
// when it installed a build the port should start fresh (see mikrojs/ota.h).
|
|
1125
|
+
bool MIK_OtaBootReconcile(void) {
|
|
1126
|
+
State h;
|
|
1127
|
+
if (!state_open(&h, true)) return false;
|
|
1128
|
+
|
|
1129
|
+
// Legacy leftover: firmware that installed cable deploys synchronously
|
|
1130
|
+
// staged its install source here and could die before promoting it. Never
|
|
1131
|
+
// valid across a boot, and a whole build's worth of flash.
|
|
1132
|
+
unlink(paths().last_good_tmp);
|
|
1133
|
+
|
|
1134
|
+
// 1. Reflash guard. An out-of-band flash (`idf.py flash`) swaps
|
|
1135
|
+
// the firmware without touching OTA state; a stale pending/staged build
|
|
1136
|
+
// must not then revert or overwrite the freshly-flashed /app. Detect via
|
|
1137
|
+
// the device store's firmware hash and scrub OTA install state when it
|
|
1138
|
+
// changed.
|
|
1139
|
+
const char* fw_now = h.store->firmware_hash ? h.store->firmware_hash() : nullptr;
|
|
1140
|
+
char fw_stored[65];
|
|
1141
|
+
bool have_fw = state_str(h, kKeyFwHash, fw_stored, sizeof(fw_stored));
|
|
1142
|
+
if (fw_now && (!have_fw || strcmp(fw_stored, fw_now) != 0)) {
|
|
1143
|
+
// A firmware flash leaves /appfs alone, so if a trial was in flight the
|
|
1144
|
+
// trial build is what /app still holds. Forcing GOOD without moving
|
|
1145
|
+
// pendChk across would leave instChk naming the previous build: the
|
|
1146
|
+
// device would report the wrong checksum to the registry forever, and
|
|
1147
|
+
// revert() would install that older build over the newer live one.
|
|
1148
|
+
if (state_u8(h, kKeyState, kStateGood) == kStateTrial) {
|
|
1149
|
+
char pend_chk[96];
|
|
1150
|
+
if (state_str(h, kKeyPendChk, pend_chk, sizeof(pend_chk))) {
|
|
1151
|
+
state_set_str(h, kKeyInstChk, pend_chk);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
state_erase(h, kKeyPendChk);
|
|
1155
|
+
state_erase(h, kKeyPendMode);
|
|
1156
|
+
state_set_u8(h, kKeyState, kStateGood);
|
|
1157
|
+
state_set_u8(h, kKeyTrialLeft, 0);
|
|
1158
|
+
state_set_u8(h, kKeyPending, 0);
|
|
1159
|
+
unlink(paths().pending);
|
|
1160
|
+
unlink(paths().staging);
|
|
1161
|
+
state_erase(h, kKeyStgChk);
|
|
1162
|
+
state_erase(h, kKeyStgSize);
|
|
1163
|
+
state_set_str(h, kKeyFwHash, fw_now);
|
|
1164
|
+
state_commit(h);
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
// 2. Adopt install: a cable deploy staged by MIK_CMD_DEPLOY_BUILD. No
|
|
1168
|
+
// trial, no rollback baseline, one attempt (charged before the attempt,
|
|
1169
|
+
// same crash reasoning as the deferred install below). Runs before the
|
|
1170
|
+
// trial verdict as a backstop: stage_adopt resolves an in-flight trial
|
|
1171
|
+
// at stage time, but stale trial state must never roll back or promote
|
|
1172
|
+
// against the pending slot the deploy overwrote.
|
|
1173
|
+
if (state_u8(h, kKeyPending, 0) == 1 &&
|
|
1174
|
+
state_u8(h, kKeyPendMode, kPendModeTrial) == kPendModeAdopt) {
|
|
1175
|
+
char chk[96] = {0};
|
|
1176
|
+
state_str(h, kKeyPendChk, chk, sizeof(chk));
|
|
1177
|
+
if (!path_exists(paths().pending)) {
|
|
1178
|
+
adopt_fail(h, chk, "install-failed", "staged build missing");
|
|
1179
|
+
state_close(h);
|
|
1180
|
+
return false;
|
|
1181
|
+
}
|
|
1182
|
+
uint8_t left = state_u8(h, kKeyInstLeft, 1);
|
|
1183
|
+
if (left == 0) {
|
|
1184
|
+
// The charged attempt never came back: the install panicked.
|
|
1185
|
+
adopt_fail(h, chk, "install-failed", "install did not complete (device restarted)");
|
|
1186
|
+
state_close(h);
|
|
1187
|
+
return false;
|
|
1188
|
+
}
|
|
1189
|
+
state_set_u8(h, kKeyInstLeft, (uint8_t)(left - 1));
|
|
1190
|
+
state_commit(h);
|
|
1191
|
+
|
|
1192
|
+
const char* err = nullptr;
|
|
1193
|
+
MIKBuildErr kind = MIK_BUILD_ERR_TRANSIENT;
|
|
1194
|
+
if (!mik__install_build(paths().base, paths().pending, &err, &kind)) {
|
|
1195
|
+
adopt_fail(h, chk, kind == MIK_BUILD_ERR_CORRUPT ? "install-corrupt" : "install-failed",
|
|
1196
|
+
err != nullptr ? err : "install failed");
|
|
1197
|
+
state_close(h);
|
|
1198
|
+
return false;
|
|
1199
|
+
}
|
|
1200
|
+
// Installed. A cable deploy resets the OTA safety story like a reflash
|
|
1201
|
+
// does: nothing to roll back to until the next OTA trial promotes.
|
|
1202
|
+
unlink(paths().pending);
|
|
1203
|
+
unlink(paths().last_good);
|
|
1204
|
+
state_set_str(h, kKeyInstChk, chk);
|
|
1205
|
+
state_set_u8(h, kKeyState, kStateGood);
|
|
1206
|
+
state_set_u8(h, kKeyTrialLeft, 0);
|
|
1207
|
+
state_set_u8(h, kKeyPending, 0);
|
|
1208
|
+
state_erase(h, kKeyPendChk);
|
|
1209
|
+
state_erase(h, kKeyPendMode);
|
|
1210
|
+
state_erase(h, kKeyInstLeft);
|
|
1211
|
+
state_erase(h, kKeyPromLeft);
|
|
1212
|
+
state_erase(h, kKeyRbLeft);
|
|
1213
|
+
state_erase(h, kKeyNeutLeft);
|
|
1214
|
+
clear_trial_failure(h);
|
|
1215
|
+
state_set_u8(h, kKeyDRes, 1);
|
|
1216
|
+
state_set_str(h, kKeyDChk, chk);
|
|
1217
|
+
state_erase(h, kKeyDRsn);
|
|
1218
|
+
state_erase(h, kKeyDDetail);
|
|
1219
|
+
state_commit(h);
|
|
1220
|
+
state_close(h);
|
|
1221
|
+
return true; // start the deployed app on a clean heap
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// 3. Trial verdict. Evaluate why we just reset while a trial was in flight.
|
|
1225
|
+
if (state_u8(h, kKeyState, kStateGood) == kStateTrial) {
|
|
1226
|
+
const char* reason = reset_reason();
|
|
1227
|
+
TrialVerdict verdict = classify_reset(reason);
|
|
1228
|
+
// A fatal JS error the trial app flagged in-process (a top-level throw or
|
|
1229
|
+
// an unhandled rejection) reboots as a clean software reset, which would
|
|
1230
|
+
// otherwise be read as "survived". Treat it like a crash.
|
|
1231
|
+
bool js_failed = state_u8(h, kKeyTrialBad, 0) != 0;
|
|
1232
|
+
if (js_failed || verdict == TrialVerdict::kCrash) {
|
|
1233
|
+
// The new app failed: roll back to last-good immediately, bypassing
|
|
1234
|
+
// the counter. If no rollback build exists (first-ever OTA), we
|
|
1235
|
+
// can't reinstall — stop the trial loop and record the diagnostic so
|
|
1236
|
+
// the app can surface it (the deploy app remains serial-recoverable).
|
|
1237
|
+
char detail[160];
|
|
1238
|
+
const char* rsn;
|
|
1239
|
+
const char* why;
|
|
1240
|
+
if (js_failed) {
|
|
1241
|
+
rsn = "startup-crash";
|
|
1242
|
+
if (!state_str(h, kKeyBadDetail, detail, sizeof(detail))) {
|
|
1243
|
+
snprintf(detail, sizeof(detail), "trial app threw at startup");
|
|
1244
|
+
}
|
|
1245
|
+
why = detail;
|
|
1246
|
+
} else {
|
|
1247
|
+
rsn = reset_reason_name(reason);
|
|
1248
|
+
why = "reverted to last-good build";
|
|
1249
|
+
}
|
|
1250
|
+
if (!attempt_rollback(h, rsn, why)) keep_trial_as_installed(h);
|
|
1251
|
+
state_set_u8(h, kKeyState, kStateGood);
|
|
1252
|
+
state_set_u8(h, kKeyTrialLeft, 0);
|
|
1253
|
+
state_set_u8(h, kKeyPending, 0);
|
|
1254
|
+
state_erase(h, kKeyPendChk);
|
|
1255
|
+
state_erase(h, kKeyTrialBad);
|
|
1256
|
+
state_erase(h, kKeyBadDetail);
|
|
1257
|
+
unlink(paths().pending);
|
|
1258
|
+
state_commit(h);
|
|
1259
|
+
state_close(h);
|
|
1260
|
+
return false;
|
|
1261
|
+
}
|
|
1262
|
+
if (verdict == TrialVerdict::kNeutral) {
|
|
1263
|
+
uint8_t left = state_u8(h, kKeyNeutLeft, kNeutralBudget);
|
|
1264
|
+
if (left > 0) {
|
|
1265
|
+
state_set_u8(h, kKeyNeutLeft, (uint8_t)(left - 1));
|
|
1266
|
+
state_commit(h);
|
|
1267
|
+
} else {
|
|
1268
|
+
// Budget spent: stop absorbing and let the trial progress on the
|
|
1269
|
+
// clean path, so it reaches a verdict instead of staying open.
|
|
1270
|
+
verdict = TrialVerdict::kClean;
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
if (verdict == TrialVerdict::kClean) {
|
|
1274
|
+
uint8_t left = state_u8(h, kKeyTrialLeft, 0);
|
|
1275
|
+
bool confirm = state_u8(h, kKeyConfirm, 0) != 0;
|
|
1276
|
+
if (left == 0) {
|
|
1277
|
+
if (confirm) {
|
|
1278
|
+
// Trial elapsed without an explicit markValid(): roll back.
|
|
1279
|
+
if (!attempt_rollback(h, "unconfirmed",
|
|
1280
|
+
"trial elapsed without markValid()")) {
|
|
1281
|
+
keep_trial_as_installed(h);
|
|
1282
|
+
}
|
|
1283
|
+
state_set_u8(h, kKeyState, kStateGood);
|
|
1284
|
+
state_set_u8(h, kKeyPending, 0);
|
|
1285
|
+
state_erase(h, kKeyPendChk);
|
|
1286
|
+
unlink(paths().pending);
|
|
1287
|
+
} else if (promote_pending()) {
|
|
1288
|
+
// Promote: the trial proved stable.
|
|
1289
|
+
char chk[96];
|
|
1290
|
+
if (state_str(h, kKeyPendChk, chk, sizeof(chk))) {
|
|
1291
|
+
state_set_str(h, kKeyInstChk, chk);
|
|
1292
|
+
}
|
|
1293
|
+
state_set_u8(h, kKeyState, kStateGood);
|
|
1294
|
+
state_erase(h, kKeyPromLeft);
|
|
1295
|
+
} else if (uint8_t prom = state_u8(h, kKeyPromLeft, kPromoteBudget); prom > 1) {
|
|
1296
|
+
// Stay in the trial rather than go GOOD with no revert
|
|
1297
|
+
// target; the next clean boot retries the promotion.
|
|
1298
|
+
state_set_u8(h, kKeyPromLeft, (uint8_t)(prom - 1));
|
|
1299
|
+
record_diag(h, "promote-failed",
|
|
1300
|
+
"could not make the trial build the revert target");
|
|
1301
|
+
} else {
|
|
1302
|
+
// Budget spent, so the failure is not transient (paths().pending
|
|
1303
|
+
// lost, or a filesystem that will not take the rename).
|
|
1304
|
+
// Resolve to GOOD with no revert target. That is the lesser
|
|
1305
|
+
// loss: the build has survived its whole trial and is
|
|
1306
|
+
// running, whereas staying in TRIAL makes applyOffer skip
|
|
1307
|
+
// every future offer, so the one channel that could ship a
|
|
1308
|
+
// fix is shut. The next update re-establishes a baseline.
|
|
1309
|
+
char chk[96];
|
|
1310
|
+
if (state_str(h, kKeyPendChk, chk, sizeof(chk))) {
|
|
1311
|
+
state_set_str(h, kKeyInstChk, chk);
|
|
1312
|
+
}
|
|
1313
|
+
state_set_u8(h, kKeyState, kStateGood);
|
|
1314
|
+
state_set_u8(h, kKeyPending, 0);
|
|
1315
|
+
state_erase(h, kKeyPromLeft);
|
|
1316
|
+
unlink(paths().pending);
|
|
1317
|
+
record_diag(h, "promote-failed",
|
|
1318
|
+
"gave up making the trial build the revert target; "
|
|
1319
|
+
"this build is kept but cannot be rolled back");
|
|
1320
|
+
}
|
|
1321
|
+
state_commit(h);
|
|
1322
|
+
} else {
|
|
1323
|
+
state_set_u8(h, kKeyTrialLeft, (uint8_t)(left - 1));
|
|
1324
|
+
state_commit(h);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
// kNeutral: don't penalize — leave the trial untouched and proceed.
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
// 4. Deferred trial install. A build verified by stageFinish(installNow=
|
|
1331
|
+
// false) is installed here, on a clean heap, then we restart into its
|
|
1332
|
+
// trial. (An adopt-mode pending build never reaches this: step 2
|
|
1333
|
+
// returns.)
|
|
1334
|
+
if (state_u8(h, kKeyPending, 0) == 1 && state_u8(h, kKeyState, kStateGood) == kStateGood) {
|
|
1335
|
+
if (!path_exists(paths().pending)) {
|
|
1336
|
+
state_set_u8(h, kKeyPending, 0);
|
|
1337
|
+
state_commit(h);
|
|
1338
|
+
state_close(h);
|
|
1339
|
+
return false;
|
|
1340
|
+
}
|
|
1341
|
+
// Charge the attempt BEFORE making it, and commit, so the budget
|
|
1342
|
+
// survives a boot that never comes back. install_build does not only
|
|
1343
|
+
// return false: it can panic (a littlefs assert, the task watchdog, an
|
|
1344
|
+
// allocation the OOM handler turns into a restart). Decrementing on the
|
|
1345
|
+
// return paths alone means a build that crashes mid-install leaves the state
|
|
1346
|
+
// untouched, so the next boot re-enters the identical install and the
|
|
1347
|
+
// budget is never reached — a fleet-wide loop only a reflash escapes.
|
|
1348
|
+
// Same reasoning the install's rmtree depth cap is documented with.
|
|
1349
|
+
uint8_t inst_left = state_u8(h, kKeyInstLeft, kInstallBudget);
|
|
1350
|
+
if (inst_left == 0) {
|
|
1351
|
+
state_set_u8(h, kKeyPending, 0);
|
|
1352
|
+
unlink(paths().pending);
|
|
1353
|
+
state_commit(h);
|
|
1354
|
+
state_close(h);
|
|
1355
|
+
return false;
|
|
1356
|
+
}
|
|
1357
|
+
state_set_u8(h, kKeyInstLeft, (uint8_t)(inst_left - 1));
|
|
1358
|
+
state_commit(h);
|
|
1359
|
+
|
|
1360
|
+
const char* err = nullptr;
|
|
1361
|
+
MIKBuildErr kind = MIK_BUILD_ERR_TRANSIENT;
|
|
1362
|
+
if (mik__install_build(paths().base, paths().pending, &err, &kind)) {
|
|
1363
|
+
char chk[96] = {0};
|
|
1364
|
+
state_str(h, kKeyPendChk, chk, sizeof(chk));
|
|
1365
|
+
record_installed(h, chk);
|
|
1366
|
+
uint8_t trial_n = state_u8(h, kKeyTrialN, 1);
|
|
1367
|
+
state_set_u8(h, kKeyState, kStateTrial);
|
|
1368
|
+
state_set_u8(h, kKeyTrialLeft, trial_n);
|
|
1369
|
+
state_set_u8(h, kKeyPending, 0);
|
|
1370
|
+
state_erase(h, kKeyPromLeft); // per-trial budgets
|
|
1371
|
+
state_erase(h, kKeyRbLeft);
|
|
1372
|
+
state_erase(h, kKeyNeutLeft);
|
|
1373
|
+
state_set_u8(h, kKeyTrialBad, 0); // fresh trial: clear any prior crash flag
|
|
1374
|
+
state_erase(h, kKeyBadDetail);
|
|
1375
|
+
state_commit(h);
|
|
1376
|
+
state_close(h);
|
|
1377
|
+
return true; // start the freshly-installed app on a clean heap
|
|
1378
|
+
}
|
|
1379
|
+
// Recorded like every other failure, and for a reason this path needs
|
|
1380
|
+
// more than most: the diagnostic is what reaches the registry as
|
|
1381
|
+
// `lastInstall`, and that is what stops the same build being offered
|
|
1382
|
+
// again. Without it a build that verifies but will not unpack is
|
|
1383
|
+
// re-downloaded and rewritten to flash on every boot, forever, since
|
|
1384
|
+
// nothing on either side learns it failed. `install: 'next-boot'` is
|
|
1385
|
+
// the default, so this is the ordinary path, not a corner.
|
|
1386
|
+
record_diag(h, kind == MIK_BUILD_ERR_CORRUPT ? "install-corrupt" : "install-failed",
|
|
1387
|
+
err != nullptr ? err : "deferred install failed");
|
|
1388
|
+
// The attempt is already charged above; this only decides whether to
|
|
1389
|
+
// keep the build for another boot.
|
|
1390
|
+
if (kind == MIK_BUILD_ERR_CORRUPT) {
|
|
1391
|
+
state_set_u8(h, kKeyPending, 0); // identical bytes can't succeed — abandon
|
|
1392
|
+
unlink(paths().pending);
|
|
1393
|
+
} else if (inst_left <= 1) {
|
|
1394
|
+
state_set_u8(h, kKeyPending, 0); // budget exhausted — abandon
|
|
1395
|
+
unlink(paths().pending);
|
|
1396
|
+
}
|
|
1397
|
+
state_commit(h);
|
|
1398
|
+
}
|
|
1399
|
+
state_close(h);
|
|
1400
|
+
return false;
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
MIK_REGISTER_MODULE(ota, "native:mikro/ota", mik__ota_init, nullptr, nullptr)
|