From a90e3e07b96c629501335ef6b44ecce9844766ea Mon Sep 17 00:00:00 2001 From: Daniil Shteud <71660667+shteudguy@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:33:05 +0300 Subject: [PATCH 1/2] Add Nokia G-010S-A Web Serial console setup --- .github/workflows/build.yml | 2 + .vitepress/theme/components/NokiaSerial.vue | 202 ++++++++++ .vitepress/theme/index.ts | 2 + .vitepress/theme/lib/nokiaSerial.js | 313 ++++++++++++++++ ont/ont-huawei-ma5671a-root-web.md | 4 + ont/ont-nokia-g-010s-a.md | 22 ++ package.json | 1 + tests/nokiaSerial.test.js | 396 ++++++++++++++++++++ 8 files changed, 942 insertions(+) create mode 100644 .vitepress/theme/components/NokiaSerial.vue create mode 100644 .vitepress/theme/lib/nokiaSerial.js create mode 100644 tests/nokiaSerial.test.js diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4e6d7e6e..bf835bb9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -32,6 +32,8 @@ jobs: cache: npm - name: Install Node deps run: npm ci + - name: Run serial protocol tests + run: npm test - name: Build with VitePress run: npm run build - name: Upload artifact diff --git a/.vitepress/theme/components/NokiaSerial.vue b/.vitepress/theme/components/NokiaSerial.vue new file mode 100644 index 00000000..e1cf212b --- /dev/null +++ b/.vitepress/theme/components/NokiaSerial.vue @@ -0,0 +1,202 @@ + + + + + diff --git a/.vitepress/theme/index.ts b/.vitepress/theme/index.ts index 6b8ee811..88d7b39b 100644 --- a/.vitepress/theme/index.ts +++ b/.vitepress/theme/index.ts @@ -9,6 +9,7 @@ import HisensePloam from './components/HisensePloam.vue' import ImageFigure from './components/ImageFigure.vue' import LantiqEeprom from './components/LantiqEeprom.vue' import Mermaid from './components/Mermaid.vue' +import NokiaSerial from './components/NokiaSerial.vue' import OmciVlanParser from './components/OmciVlanParser.vue' import RootLantiq from './components/RootLantiq.vue' import SpeedCalculator from './components/SpeedCalculator.vue' @@ -27,6 +28,7 @@ export default { app.component('ImageFigure', ImageFigure) app.component('LantiqEeprom', LantiqEeprom) app.component('Mermaid', Mermaid) + app.component('NokiaSerial', NokiaSerial) app.component('OmciVlanParser', OmciVlanParser) app.component('RootLantiq', RootLantiq) app.component('SpeedCalculator', SpeedCalculator) diff --git a/.vitepress/theme/lib/nokiaSerial.js b/.vitepress/theme/lib/nokiaSerial.js new file mode 100644 index 00000000..65c8a63a --- /dev/null +++ b/.vitepress/theme/lib/nokiaSerial.js @@ -0,0 +1,313 @@ +// Nokia G-010S-A console settings only. This procedure never flashes firmware, +// applies Huawei GPIO settings, or treats BootROM output as a command prompt. +const PROMPT = /(?:^|\n)[ \t]*FALCON[ \t]*=>[ \t]*$/; +const ROM = /(?:^|\n)[ \t]*ROM:/; +const STARTUP = /(?:^|\n)[ \t]*(?:U-Boot\b|Chip:|Bootmode:|Reset cause:|CPU Clock:|Press SPACE|Hit any key|Autoboot)/; +const STARTUP_EVENTS = /(?:^|\n)[ \t]*(?:ROM:[ \t]*V|U-Boot\b|Chip:|Bootmode:|Reset cause:|CPU Clock:|Press SPACE|Hit any key|Autoboot)/g; +const LINUX = /(?:^|\n)[ \t]*(?:Starting kernel|Linux version |BusyBox |[^\n]*[Ll]ogin:[ \t]*$|root@[^\n]*[#$][ \t]*$)/m; +const RECOVERABLE = new Set(['BreakError', 'FramingError', 'ParityError']); +const VARIABLES = ['asc0', 'bootdelay', 'preboot']; +const MAX_OUTPUT = 256 * 1024; + +function failure(code, message) { + return Object.assign(new Error(message), { name: 'NokiaSerialError', code }); +} + +function cancelled() { + return new DOMException('The Nokia UART procedure was cancelled.', 'AbortError'); +} + +function checkAbort(signal) { + if (signal?.aborted) throw cancelled(); +} + +// A timed-out read remains owned by the session until it is consumed or closed. +// This avoids concurrent readers and losing bytes between polling intervals. +async function bounded(promise, ms, signal, error) { + if (signal?.aborted) { + // The caller may already have started an I/O request when abort fires. + // Observe a late rejection even though this operation cannot continue. + Promise.resolve(promise).catch(() => {}); + throw cancelled(); + } + let timer; + let abort; + const interrupted = new Promise((_, reject) => { + if (ms !== undefined) timer = setTimeout(() => reject(error), Math.max(0, ms)); + abort = () => reject(cancelled()); + signal?.addEventListener('abort', abort, { once: true }); + }); + try { + return await Promise.race([promise, interrupted]); + } finally { + clearTimeout(timer); + signal?.removeEventListener('abort', abort); + } +} + +function normalize(text) { + return text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/\r\n?/g, '\n'); +} + +function checkConsole(text, command = false) { + if (/ROM:\s*Boot\?|Boot\?\s*\(0-9A-F/i.test(text)) { + throw failure('BOOTROM_MENU', 'The module is at the BootROM recovery menu, not the FALCON U-Boot console. Use the documented Nokia recovery procedure.'); + } + if (LINUX.test(text)) { + throw failure('LINUX_CONSOLE', 'The module has booted into Linux. Use SSH to enable UART, or power-cycle the module and retry to stop U-Boot.'); + } + if (command && (ROM.test(text) || STARTUP.test(text))) { + throw failure('DISCONNECTED', 'The module restarted during the command. No further commands will be sent.'); + } +} + +class NokiaConsole { + constructor(port, { signal, baudRate, startupTimeoutMs, commandTimeoutMs, ioTimeoutMs }) { + Object.assign(this, { port, signal, baudRate, startupTimeoutMs, commandTimeoutMs, ioTimeoutMs }); + this.buffer = ''; + this.decoder = new TextDecoder(); + this.encoder = new TextEncoder(); + this.verified = false; + this.readErrors = 0; + } + + async open() { + checkAbort(this.signal); + this.opening = this.port.open({ baudRate: this.baudRate, dataBits: 8, stopBits: 1, parity: 'none', flowControl: 'none' }); + await bounded(this.opening, this.ioTimeoutMs, this.signal, failure('TIMEOUT', 'Opening the serial port timed out.')); + this.opened = true; + this.reader = this.port.readable?.getReader(); + this.writer = this.port.writable?.getWriter(); + if (!this.reader || !this.writer) throw failure('DISCONNECTED', 'The serial port has no readable/writable connection.'); + } + + async write(text, deadline) { + checkAbort(this.signal); + if (!this.writer) throw failure('DISCONNECTED', 'The serial connection is closed.'); + const remaining = Math.min(this.ioTimeoutMs, deadline - Date.now()); + if (remaining <= 0) throw failure('TIMEOUT', 'The serial operation timed out.'); + try { + await bounded(this.writer.write(this.encoder.encode(text)), remaining, this.signal, + failure('TIMEOUT', 'Writing to the serial port timed out.')); + } catch (error) { + if (error.name === 'AbortError' || error.code) throw error; + throw failure('DISCONNECTED', `Could not write to the serial port: ${error.message}`); + } + } + + async read(deadline, pollMs = Infinity) { + checkAbort(this.signal); + if (!this.pendingRead) this.pendingRead = this.reader.read(); + let result; + try { + result = await bounded(this.pendingRead, Math.min(pollMs, deadline - Date.now()), this.signal, + failure('POLL', 'Waiting for serial data.')); + } catch (error) { + if (error.code === 'POLL') return false; + this.pendingRead = undefined; + // Web Serial replaces its readable stream after these nonfatal + // errors (FTDI adapters can report BREAK during module insertion). + if (RECOVERABLE.has(error.name) && ++this.readErrors <= 5) { + this.reader.releaseLock(); + this.reader = this.port.readable?.getReader(); + this.decoder = new TextDecoder(); + if (this.reader) return true; + } + if (error.name === 'AbortError') throw error; + throw failure('DISCONNECTED', `Serial reading failed (${error.name}): ${error.message}. Check the adapter, wiring and 115200 8-N-1 settings.`); + } + this.pendingRead = undefined; + if (result.done) throw failure('DISCONNECTED', 'The serial connection closed before the procedure completed.'); + this.buffer += this.decoder.decode(result.value, { stream: true }); + if (this.buffer.length > MAX_OUTPUT) throw failure('TIMEOUT', 'Too much serial output was received without a FALCON prompt.'); + return true; + } + + async acquire() { + this.verified = false; + const deadline = Date.now() + this.startupTimeoutMs; + await this.write('\r', deadline); // Also elicit a prompt from an idle U-Boot. + let lastEvent = -1; + let interruptUntil = 0; + let nextInterrupt = 0; + while (Date.now() < deadline) { + checkAbort(this.signal); + const text = normalize(this.buffer); + checkConsole(text); + if (PROMPT.test(text)) { + this.buffer = ''; + const bytes = crypto.getRandomValues(new Uint8Array(12)); + const nonce = '__NOKIA_UART_' + Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('') + '__'; + const response = await this.exchange(`echo ${nonce}`, Math.min(deadline, Date.now() + this.commandTimeoutMs)); + if (!normalize(response).split('\n').some(line => line.trim() === nonce)) { + throw failure('UNVERIFIED', 'The FALCON prompt did not return the console verification response. No settings were changed.'); + } + this.verified = true; + return; + } + const events = Array.from(text.matchAll(STARTUP_EVENTS)); + const latest = events.at(-1)?.index ?? -1; + if (latest > lastEvent) { + lastEvent = latest; + interruptUntil = Math.min(deadline, Date.now() + 5000); + nextInterrupt = Date.now(); + } + if (Date.now() < interruptUntil && Date.now() >= nextInterrupt) { + await this.write('\x03', deadline); + nextInterrupt = Date.now() + 50; + } + await this.read(deadline, Date.now() < interruptUntil ? Math.max(1, nextInterrupt - Date.now()) : Infinity); + } + const text = normalize(this.buffer); + if (ROM.test(text) && !STARTUP.test(text)) { + throw failure('ROM_ONLY', 'Only BootROM output was received; an interactive U-Boot prompt was not obtained. The UART console may be disabled by asc0=3. Enable it through SSH or the supported web interface, or use the documented Nokia recovery procedure if network access is unavailable. No settings were changed.'); + } + throw failure('TIMEOUT', 'Timed out waiting for a verified FALCON prompt. Check the Nokia pinout and power-cycle the module after starting this procedure. No settings were changed.'); + } + + async exchange(command, deadline) { + await this.write(command + '\r', deadline); + while (Date.now() < deadline) { + await this.read(deadline); + const text = normalize(this.buffer); + checkConsole(text, true); + const prompt = PROMPT.exec(text); + if (prompt) { + this.buffer = ''; + return text.slice(0, prompt.index); + } + } + throw failure('TIMEOUT', `U-Boot did not finish the ${command.split(' ')[0]} command in time. No further commands will be sent.`); + } + + async command(command) { + if (!this.verified) throw failure('UNVERIFIED', 'A verified FALCON console is required before sending commands.'); + try { + return await this.exchange(command, Date.now() + this.commandTimeoutMs); + } catch (error) { + this.verified = false; + throw error; + } + } + + async close() { + this.verified = false; + if (!this.opened) { + // An open request may finish after its timeout or user cancellation. + this.opening?.then(() => this.port.close()).catch(() => {}); + return; + } + const limit = Math.min(1000, this.ioTimeoutMs); + const cleanup = promise => bounded(Promise.resolve(promise).catch(() => {}), limit, undefined, + failure('TIMEOUT', 'Serial cleanup timed out.')).catch(() => {}); + await Promise.all([cleanup(this.reader?.cancel()), cleanup(this.writer?.abort())]); + try { this.reader?.releaseLock(); } catch { /* A disconnected stream can already be released. */ } + try { this.writer?.releaseLock(); } catch { /* A disconnected stream can already be released. */ } + await cleanup(this.port.close()); + } +} + +function commandFailed(response) { + return /\b(?:error|failed|failure|bad crc|unknown command|timeout|timed out)\b|^\s*Usage:/im.test(response); +} + +async function readSettings(serial) { + const settings = {}; + for (const variable of VARIABLES) { + const command = `printenv ${variable}`; + const response = await serial.command(command); + const lines = normalize(response).split('\n').map(line => line.trim()).filter(line => + line && line !== command && line !== `FALCON => ${command}`); + const missing = new RegExp(`^## Error: ["']?${variable}["']? not defined$`, 'i'); + if (lines.length === 1 && missing.test(lines[0])) { + settings[variable] = null; + } else if (lines.length === 1 && lines[0].startsWith(variable + '=') && !commandFailed(response)) { + settings[variable] = lines[0].slice(variable.length + 1); + } else { + throw failure('COMMAND_FAILED', `Could not reliably read ${variable}. No further changes will be made; check the serial console and U-Boot environment.`); + } + } + return settings; +} + +function sameSettings(a, b) { + return VARIABLES.every(variable => a[variable] === b[variable]); +} + +/** + * Enable the Nokia G-010S-A UART from an already accessible U-Boot console. + * Missing environment variables are represented by null. onBackup receives the + * three original settings; confirmChanges must explicitly return true before + * any mutation. Success leaves U-Boot paused, ready for a manual power cycle. + * Timeout overrides are useful for slower adapters and deterministic tests. + */ +export async function enableNokiaSerial(port, { + signal, onStatus = () => {}, onBackup = () => {}, confirmChanges, + baudRate = 115200, startupTimeoutMs = 45000, commandTimeoutMs = 5000, ioTimeoutMs = 5000 +} = {}) { + for (const timeout of [startupTimeoutMs, commandTimeoutMs, ioTimeoutMs]) { + if (!Number.isFinite(timeout) || timeout <= 0) throw new TypeError('Serial timeouts must be positive finite numbers.'); + } + const serial = new NokiaConsole(port, { signal, baudRate, startupTimeoutMs, commandTimeoutMs, ioTimeoutMs }); + try { + onStatus('Opening the serial port.'); + await serial.open(); + onStatus('Serial port open. Power-cycle the Nokia G-010S-A now if it is already running.'); + await serial.acquire(); + onStatus('FALCON console verified. Reading the current UART settings.'); + const before = await readSettings(serial); + await bounded(Promise.resolve(onBackup({ ...before })), undefined, signal); + if (before.asc0 !== null && !/^[0-3]$/.test(before.asc0)) { + throw failure('UNEXPECTED_ASC0', 'The module has an unexpected asc0 value. Its original settings were captured, but no settings were changed. Review the bootloader configuration manually.'); + } + const preboot = (before.preboot ?? '').trim().replace(/\s+/g, ' '); + if (!['', 'gpio clear 100', 'run start_netconsole'].includes(preboot)) { + throw failure('UNSAFE_PREBOOT', 'The module has a custom preboot command. Its original settings were captured, but no settings were changed. Review preboot manually before enabling UART.'); + } + const delay = Number(before.bootdelay); + const positiveDelay = /^\d+$/.test(before.bootdelay ?? '') && Number.isSafeInteger(delay) && delay > 0 && delay <= 0x7fffffff; + const after = { asc0: '0', bootdelay: positiveDelay ? before.bootdelay : '5', preboot: null }; + if (sameSettings(before, after)) { + onStatus('UART is already enabled with a positive boot delay. No settings were changed. U-Boot remains paused.'); + return { before, after, changed: false, saved: false }; + } + onStatus('Review the original settings and proposed changes before saving.'); + checkAbort(signal); + if (typeof confirmChanges !== 'function' || + await bounded(Promise.resolve(confirmChanges({ before: { ...before }, after: { ...after } })), undefined, signal) !== true) { + throw cancelled(); + } + // The module could have rebooted, disconnected, or been changed while + // the user reviewed the proposal. Obtain a fresh prompt and readback. + await serial.acquire(); + if (!sameSettings(await readSettings(serial), before)) { + throw failure('SETTINGS_CHANGED', 'The U-Boot settings changed while confirmation was pending. Nothing was written; start again to review the current values.'); + } + onStatus('Applying the confirmed Nokia UART settings.'); + for (const variable of VARIABLES) { + if (before[variable] === after[variable]) continue; + const command = `setenv ${variable}` + (after[variable] === null ? '' : ` ${after[variable]}`); + if (commandFailed(await serial.command(command))) { + throw failure('COMMAND_FAILED', `U-Boot rejected ${variable}. Changes have not been saved to flash; power-cycle to discard the temporary settings.`); + } + } + if (!sameSettings(await readSettings(serial), after)) { + throw failure('COMMAND_FAILED', 'UART settings did not match the requested values. Changes have not been saved to flash; power-cycle to discard the temporary settings.'); + } + onStatus('Settings verified. Saving the U-Boot environment.'); + checkAbort(signal); + let saved; + try { + saved = await serial.command('saveenv'); + } catch (error) { + throw failure('SAVE_FAILED', `The saveenv operation was interrupted (${error.message}). The saved state is uncertain; keep power connected and inspect the console before rebooting.`); + } + if (commandFailed(saved) || !/\b(?:done|ok)[.!]?\s*$/i.test(saved)) { + throw failure('SAVE_FAILED', 'U-Boot did not confirm a successful saveenv. The saved state is uncertain; keep power connected and inspect the console before rebooting.'); + } + onStatus('UART settings saved. U-Boot remains paused; power-cycle the module to boot normally.'); + return { before, after, changed: true, saved: true }; + } finally { + await serial.close(); + } +} diff --git a/ont/ont-huawei-ma5671a-root-web.md b/ont/ont-huawei-ma5671a-root-web.md index aad8e4e0..f3361b2f 100644 --- a/ont/ont-huawei-ma5671a-root-web.md +++ b/ont/ont-huawei-ma5671a-root-web.md @@ -6,6 +6,10 @@ parent: Huawei MA5671A # Root the stick +::: warning Nokia G-010S-A +This procedure is for Huawei MA5671A. For Nokia G-010S-A, use the [Nokia serial-console instructions and helper](/ont-nokia-g-010s-a#enabling-serial). Its boot log may omit the `U-Boot` banner expected here, and the GPIO and Linux-shell steps are different. Receiving only `ROM:` lines does not mean that U-Boot commands can be executed. +::: + Connect the SFP adapter to the TTL adapter according to the following diagram: | USB TTL (UART) Adapter | wire colour in picture | SFP 20pins Molex connector | diff --git a/ont/ont-nokia-g-010s-a.md b/ont/ont-nokia-g-010s-a.md index cb5782f5..77896417 100644 --- a/ont/ont-nokia-g-010s-a.md +++ b/ont/ont-nokia-g-010s-a.md @@ -92,12 +92,34 @@ See more info on: [Firmwares G-010S-A](https://github.com/hwti/G-010S-A#firmware ## Enabling serial +Run these commands from an administrative SSH shell on the stick, then reboot it: + ```sh fw_setenv bootdelay 5 fw_setenv asc0 0 fw_setenv preboot ``` +After rebooting, connect at 115200 8-N-1 and press Ctrl-C during the boot delay. Check that you can obtain the `FALCON =>` prompt and execute a command before relying on UART for recovery. + +If the output stops after the three `ROM:` lines, the UART console may be disabled (for example, by `asc0=3`). Those lines are emitted by BootROM and do not prove that an interactive U-Boot console is available. Use the SSH commands above, or the serial-console setting provided by your firmware, while network access still works. Firmware that also stores an ASC setting in its own configuration may need that setting enabled as well. + +### Configure serial through the browser + +The helper below is specific to **G-010S-A**. Connect the USB-UART adapter using this page's [serial pinout](#serial), close other programs using the port, and select **Configure Nokia UART**. When prompted, power-cycle the module. If it is already stopped at `FALCON =>`, it can be used directly. + +The helper waits for the actual `FALCON =>` prompt rather than a `U-Boot` version banner, which is absent from some Nokia boot logs. It verifies command input with an `echo` challenge, reads `asc0`, `bootdelay` and `preboot`, and lets you download the original settings and review changes before saving. It sets `asc0=0`, keeps a positive boot delay (otherwise sets `5`), and clears only recognized Nokia `preboot` values. A custom `preboot` requires manual review. + + + +After a successful save, the module remains at the bootloader. Power-cycle it to boot normally, then verify both UART and network access. This helper changes console settings; it does not flash firmware or change Linux login credentials. + +::: warning ROM-only output is not a command prompt +This helper cannot enable a console that never accepts U-Boot commands. It stops with an explanation if only BootROM output is received, instead of sending configuration commands blindly. If neither SSH nor an interactive bootloader is available, see the [G-010S-A recovery procedure](https://github.com/wteiken/G-010S-A/blob/main/unbricking.md#unbrick-unprepared-sfp-modules). +::: + +The [documented Nokia boot transcript](https://github.com/wteiken/G-010S-A/blob/main/unbricking.md#connecting-to-the-console) illustrates why a `U-Boot` banner alone is not a suitable trigger. The Huawei MA5671A web-root procedure uses different GPIO and Linux-shell steps and should not be used for G-010S-A. + # GPON ONU status ## Getting the operational status of the ONU diff --git a/package.json b/package.json index 9b67f329..229b246e 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "scripts": { "dev": "vitepress dev", "build": "vitepress build && node scripts/optimize-images.mjs", + "test": "node --test tests/*.test.js", "preview": "vitepress preview", "convert": "node scripts/jekyll-to-vitepress.mjs" }, diff --git a/tests/nokiaSerial.test.js b/tests/nokiaSerial.test.js new file mode 100644 index 00000000..39449681 --- /dev/null +++ b/tests/nokiaSerial.test.js @@ -0,0 +1,396 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { enableNokiaSerial } from '../.vitepress/theme/lib/nokiaSerial.js'; + +const FAST = { startupTimeoutMs: 150, commandTimeoutMs: 150, ioTimeoutMs: 150 }; +const decoder = new TextDecoder(); +const encoder = new TextEncoder(); +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + +// The fixture implements the Web Serial surface with real Web Streams. It +// interprets a small console transcript; it never executes received commands. +class FakePort { + constructor({ initial = [], promptOnCR = true, onWrite, environment, breakOnce = false, noise = false } = {}) { + Object.assign(this, { initial, promptOnCR, onWrite, breakOnce, noise }); + this.environment = { asc0: '3', bootdelay: '5', preboot: 'gpio clear 100', ...environment }; + this.writes = []; + this.openCount = 0; + this.closeCount = 0; + this.breakReleases = 0; + } + + async open(options) { + this.openCount++; + this.options = options; + this.readable = new ReadableStream({ + start: controller => { this.controller = controller; } + }); + if (this.breakOnce) { + const recovered = this.readable; + this.readable = { + getReader: () => ({ + read: () => Promise.reject(new DOMException('FTDI module insertion BREAK', 'BreakError')), + releaseLock: () => { this.breakReleases++; this.readable = recovered; }, + cancel: async () => {} + }) + }; + } + this.writable = new WritableStream({ + write: async bytes => { + const text = decoder.decode(bytes); + this.writes.push(text); + if (await this.onWrite?.(text, this)) return; + if (text === '\r') { + if (this.promptOnCR) this.emit('FALCON => '); + return; + } + if (text === '\x03') return; + assert.ok(text.endsWith('\r'), 'console commands end with CR'); + const command = text.slice(0, -1); + let response = ''; + if (command.startsWith('echo ')) { + response = command.slice(5) + '\r\n'; + } else if (command.startsWith('printenv ')) { + const variable = command.slice(9); + const value = this.environment[variable]; + response = value === null || value === undefined + ? `## Error: "${variable}" not defined\r\n` + : `${variable}=${value}\r\n`; + } else if (command.startsWith('setenv ')) { + const [, variable, ...value] = command.split(' '); + this.environment[variable] = value.length ? value.join(' ') : null; + } else if (command === 'saveenv') { + response = 'Saving Environment to SPI Flash...\r\nErasing SPI flash...Writing to SPI flash...done\r\n'; + } else { + assert.fail(`Unexpected command: ${command}`); + } + this.emit(command + '\r\n' + response + 'FALCON => '); + } + }); + for (const chunk of this.initial) this.emit(chunk); + if (this.noise) this.noiseTimer = setInterval(() => this.emit('unrelated output\r\n'), 5); + } + + emit(text) { + this.controller.enqueue(encoder.encode(text)); + } + + async close() { + clearInterval(this.noiseTimer); + assert.equal(this.readable.locked, false, 'read lock released before port.close'); + assert.equal(this.writable.locked, false, 'write lock released before port.close'); + this.closeCount++; + } + + commands() { + return this.writes.filter(value => value !== '\r' && value !== '\x03').map(value => value.trim()); + } + + mutations() { + return this.commands().filter(command => /^(?:setenv|saveenv|reset)\b/.test(command)); + } +} + +function run(port, options = {}) { + return enableNokiaSerial(port, { ...FAST, confirmChanges: async () => true, ...options }); +} + +test('bannerless Nokia boot, split prompt, backup, confirmation and verified save', { timeout: 2000 }, async () => { + let sentPrompt = false; + const port = new FakePort({ + initial: ['ROM: V1.1.4\r\nChip: FALCON-S (A22)\r\nBootmode: 0x06\r\n'], + promptOnCR: false, + environment: { bootdelay: '-1' }, + onWrite(text, device) { + if (text === '\x03' && !sentPrompt) { + sentPrompt = true; + device.emit('FAL'); + device.emit('CON ='); + device.emit('> '); + device.promptOnCR = true; + } + } + }); + const events = []; + const result = await run(port, { + onStatus(message) { + if (message.includes('Power-cycle')) assert.equal(port.openCount, 1, 'listen before asking for a reboot'); + }, + onBackup(before) { + assert.deepEqual(before, { asc0: '3', bootdelay: '-1', preboot: 'gpio clear 100' }); + assert.deepEqual(port.mutations(), []); + events.push('backup'); + }, + confirmChanges(proposal) { + assert.deepEqual(proposal.after, { asc0: '0', bootdelay: '5', preboot: null }); + assert.deepEqual(port.mutations(), []); + events.push('confirm'); + return true; + } + }); + assert.deepEqual(events, ['backup', 'confirm']); + assert.equal(result.saved, true); + assert.deepEqual(port.mutations(), ['setenv asc0 0', 'setenv bootdelay 5', 'setenv preboot', 'saveenv']); + assert.deepEqual(port.environment, result.after); + assert.equal(port.commands().filter(command => command.startsWith('echo ')).length, 2, 'reverify after human confirmation'); + assert.equal(port.commands().filter(command => command.startsWith('printenv ')).length, 9, 'read before, after confirmation, and before save'); + assert.deepEqual(port.options, { baudRate: 115200, dataBits: 8, stopBits: 1, parity: 'none', flowControl: 'none' }); + assert.equal(port.openCount, 1); + assert.equal(port.closeCount, 1); + assert.ok(!port.commands().some(command => command === 'reset' || command.includes('gpio set'))); +}); + +test('preserves an existing positive boot delay and removes only the known preboot', async () => { + const port = new FakePort({ environment: { bootdelay: '3', preboot: 'run start_netconsole' } }); + await run(port); + assert.deepEqual(port.mutations(), ['setenv asc0 0', 'setenv preboot', 'saveenv']); + assert.equal(port.environment.bootdelay, '3'); +}); + +test('an overflowing bootdelay is not mistaken for a valid positive delay', async () => { + const port = new FakePort({ environment: { bootdelay: '999999999999999999999' } }); + const result = await run(port); + assert.equal(result.after.bootdelay, '5'); + assert.ok(port.mutations().includes('setenv bootdelay 5')); +}); + +test('already enabled settings are read-only and require no confirmation', async () => { + const port = new FakePort({ environment: { asc0: '0', preboot: null } }); + const result = await run(port, { confirmChanges: () => assert.fail('nothing to confirm') }); + assert.equal(result.changed, false); + assert.equal(result.saved, false); + assert.deepEqual(port.mutations(), []); + assert.equal(port.closeCount, 1); +}); + +test('ROM-only output times out without environment commands or lingering writes', { timeout: 1500 }, async () => { + const port = new FakePort({ + initial: ['ROM: V1.1.4\r\nROM: CFG 0x00000006\r\nROM: SFLASH-4\r\n'], promptOnCR: false + }); + await assert.rejects(run(port, { startupTimeoutMs: 80 }), { code: 'ROM_ONLY' }); + assert.deepEqual(port.commands(), []); + const writes = port.writes.length; + await sleep(80); + assert.equal(port.writes.length, writes); + assert.equal(port.closeCount, 1); +}); + +test('a U-Boot banner alone does not authorize commands', { timeout: 1000 }, async () => { + const port = new FakePort({ initial: ['U-Boot 2011.12\r\n'], promptOnCR: false }); + await assert.rejects(run(port, { startupTimeoutMs: 60 }), { code: 'TIMEOUT' }); + assert.deepEqual(port.commands(), []); +}); + +test('continuous irrelevant output does not extend the overall timeout', { timeout: 1000 }, async () => { + const port = new FakePort({ promptOnCR: false, noise: true }); + await assert.rejects(run(port, { startupTimeoutMs: 70 }), { code: 'TIMEOUT' }); + assert.deepEqual(port.writes, ['\r'], 'no blind Ctrl+C on an unknown console'); + assert.equal(port.closeCount, 1); +}); + +test('BootROM recovery menu and Linux console have distinct errors', async t => { + for (const [text, code] of [ + ['ROM: Boot? (0-9A-F)\r\n', 'BOOTROM_MENU'], + ['Linux version 3.10.108\r\nroot@NOKIA:~# ', 'LINUX_CONSOLE'] + ]) { + await t.test(code, async () => { + const port = new FakePort({ initial: [text], promptOnCR: false }); + await assert.rejects(run(port), { code }); + assert.deepEqual(port.commands(), []); + assert.equal(port.closeCount, 1); + }); + } +}); + +test('echoed command and stale prompt cannot satisfy the nonce challenge', async t => { + for (const response of ['echo-only', 'prompt-only']) { + await t.test(response, async () => { + const port = new FakePort({ + onWrite(text, device) { + if (!text.startsWith('echo ')) return false; + device.emit((response === 'echo-only' ? text + '\n' : '') + 'FALCON => '); + return true; + } + }); + await assert.rejects(run(port), { code: 'UNVERIFIED' }); + assert.equal(port.commands().length, 1); + assert.deepEqual(port.mutations(), []); + }); + } +}); + +test('unexpected preboot is backed up and rejected before confirmation or mutation', async () => { + const port = new FakePort({ environment: { preboot: 'run custom_startup' } }); + let backedUp = false; + await assert.rejects(run(port, { + onBackup: before => { backedUp = before.preboot === 'run custom_startup'; }, + confirmChanges: () => assert.fail('unsafe settings must not be proposed') + }), { code: 'UNSAFE_PREBOOT' }); + assert.equal(backedUp, true); + assert.deepEqual(port.mutations(), []); +}); + +test('unexpected asc0 values stop before proposing or writing changes', async () => { + const port = new FakePort({ environment: { asc0: '7' } }); + await assert.rejects(run(port, { + confirmChanges: () => assert.fail('unexpected bootloader value must be reviewed manually') + }), { code: 'UNEXPECTED_ASC0' }); + assert.deepEqual(port.mutations(), []); +}); + +test('declining confirmation never changes the environment', async () => { + const port = new FakePort(); + await assert.rejects(run(port, { confirmChanges: () => false }), { name: 'AbortError' }); + assert.deepEqual(port.mutations(), []); + assert.equal(port.closeCount, 1); +}); + +test('aborting an unanswered confirmation closes the port and cannot resume later', { timeout: 1000 }, async () => { + const controller = new AbortController(); + let resolveConfirmation; + let notifyReview; + const reviewing = new Promise(resolve => { notifyReview = resolve; }); + const port = new FakePort(); + const operation = run(port, { + signal: controller.signal, + confirmChanges: () => { + notifyReview(); + return new Promise(resolve => { resolveConfirmation = resolve; }); + } + }); + await reviewing; + controller.abort(); + await assert.rejects(operation, { name: 'AbortError' }); + const count = port.writes.length; + resolveConfirmation(true); + await sleep(10); + assert.equal(port.writes.length, count); + assert.deepEqual(port.mutations(), []); + assert.equal(port.closeCount, 1); +}); + +test('aborting a pending read releases the reader and closes the port', { timeout: 1000 }, async () => { + const controller = new AbortController(); + const port = new FakePort({ promptOnCR: false }); + const operation = run(port, { signal: controller.signal }); + setTimeout(() => controller.abort(), 15); + await assert.rejects(operation, { name: 'AbortError' }); + assert.deepEqual(port.commands(), []); + assert.equal(port.closeCount, 1); +}); + +test('settings changed during confirmation are detected by a fresh read', async () => { + const port = new FakePort(); + await assert.rejects(run(port, { + confirmChanges: () => { port.environment.asc0 = '2'; return true; } + }), { code: 'SETTINGS_CHANGED' }); + assert.deepEqual(port.mutations(), []); +}); + +test('CRC/environment errors are not treated as undefined variables', async () => { + const port = new FakePort({ + onWrite(text, device) { + if (text !== 'printenv asc0\r') return false; + device.emit('Warning: bad CRC, using default environment\r\nasc0=3\r\nFALCON => '); + return true; + } + }); + await assert.rejects(run(port), { code: 'COMMAND_FAILED' }); + assert.deepEqual(port.mutations(), []); +}); + +test('failed setenv readback prevents saveenv', async () => { + const port = new FakePort({ + onWrite(text, device) { + if (text !== 'setenv asc0 0\r') return false; + device.emit('setenv asc0 0\r\nFALCON => '); // Prompt, but unchanged value. + return true; + } + }); + await assert.rejects(run(port), { code: 'COMMAND_FAILED' }); + assert.ok(!port.commands().includes('saveenv')); +}); + +test('saveenv failure is not hidden by an earlier OK string', async () => { + const port = new FakePort({ + onWrite(text, device) { + if (text !== 'saveenv\r') return false; + device.emit('Erasing... OK\r\nError: writing environment failed\r\nFALCON => '); + return true; + } + }); + await assert.rejects(run(port), { code: 'SAVE_FAILED' }); + assert.equal(port.closeCount, 1); +}); + +test('saveenv requires a final acknowledgement, not an earlier erase OK', async () => { + const port = new FakePort({ + onWrite(text, device) { + if (text !== 'saveenv\r') return false; + device.emit('Erasing... OK\r\nWriting environment... timeout\r\nFALCON => '); + return true; + } + }); + await assert.rejects(run(port), { code: 'SAVE_FAILED' }); +}); + +test('cancellation during saveenv reports uncertain persistence', { timeout: 1000 }, async () => { + const controller = new AbortController(); + const port = new FakePort({ + onWrite(text) { + if (text !== 'saveenv\r') return false; + controller.abort(); + return true; + } + }); + await assert.rejects(run(port, { signal: controller.signal }), error => { + assert.equal(error.code, 'SAVE_FAILED'); + assert.match(error.message, /saved state is uncertain/); + return true; + }); + assert.equal(port.closeCount, 1); +}); + +test('a bannerless Nokia restart invalidates an in-flight command', async () => { + const port = new FakePort({ + onWrite(text, device) { + if (text !== 'setenv asc0 0\r') return false; + device.emit('Chip: FALCON-S (A22)\r\nBootmode: 0x06\r\nFALCON => '); + return true; + } + }); + await assert.rejects(run(port), { code: 'DISCONNECTED' }); + assert.deepEqual(port.mutations(), ['setenv asc0 0'], 'no further environment or save commands after restart'); +}); + +test('a disconnect during verification cannot be accepted as a usable prompt', async () => { + const port = new FakePort({ + onWrite(text, device) { + if (!text.startsWith('echo ')) return false; + device.controller.close(); + return true; + } + }); + await assert.rejects(run(port), { code: 'DISCONNECTED' }); + assert.deepEqual(port.mutations(), []); +}); + +test('recoverable FTDI BREAK reacquires the stream without reopening the port', async () => { + const port = new FakePort({ breakOnce: true }); + const result = await run(port); + assert.equal(result.saved, true); + assert.equal(port.breakReleases, 1); + assert.equal(port.openCount, 1); + assert.equal(port.closeCount, 1); +}); + +test('a stalled serial write has a bounded deadline and releases the writer', { timeout: 1500 }, async () => { + const port = new FakePort({ + onWrite(text) { + if (text.startsWith('echo ')) return new Promise(() => {}); + } + }); + await assert.rejects(run(port, { ioTimeoutMs: 60 }), { code: 'TIMEOUT' }); + assert.deepEqual(port.mutations(), []); + assert.equal(port.closeCount, 1); +}); From 65f687b80ee1a8f5f5b251133a5d8a61963e1fe4 Mon Sep 17 00:00:00 2001 From: Daniil Shteud <71660667+shteudguy@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:38:10 +0300 Subject: [PATCH 2/2] Clarify G-010S-P rooting report and G-010S-A guidance --- ont/ont-huawei-ma5671a-root-web.md | 4 +++- ont/ont-nokia-g-010s-p.md | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/ont/ont-huawei-ma5671a-root-web.md b/ont/ont-huawei-ma5671a-root-web.md index f3361b2f..f870a3f5 100644 --- a/ont/ont-huawei-ma5671a-root-web.md +++ b/ont/ont-huawei-ma5671a-root-web.md @@ -6,8 +6,10 @@ parent: Huawei MA5671A # Root the stick +The browser procedure below has also been [reported to work](https://github.com/hack-gpon/hack-gpon.github.io/pull/518#discussion_r4485260237) on an Alcatel-Lucent [G-010S-P](/ont-nokia-g-010s-p#web-rooting). The firmware version was not provided in that report, so it does not establish compatibility with every G-010S-P firmware version. + ::: warning Nokia G-010S-A -This procedure is for Huawei MA5671A. For Nokia G-010S-A, use the [Nokia serial-console instructions and helper](/ont-nokia-g-010s-a#enabling-serial). Its boot log may omit the `U-Boot` banner expected here, and the GPIO and Linux-shell steps are different. Receiving only `ROM:` lines does not mean that U-Boot commands can be executed. +For Nokia G-010S-A, use the [Nokia serial-console instructions and helper](/ont-nokia-g-010s-a#enabling-serial) and its [serial pinout](/ont-nokia-g-010s-a#serial). Its boot log may omit the `U-Boot` banner expected here, and the GPIO and Linux-shell steps are different. Receiving only `ROM:` lines does not mean that U-Boot commands can be executed. ::: Connect the SFP adapter to the TTL adapter according to the following diagram: diff --git a/ont/ont-nokia-g-010s-p.md b/ont/ont-nokia-g-010s-p.md index 41a3e453..cd59aaf1 100644 --- a/ont/ont-nokia-g-010s-p.md +++ b/ont/ont-nokia-g-010s-p.md @@ -116,6 +116,12 @@ For more info [XPONos partition layout](https://web.archive.org/web/202409250352 # General Settings and Useful Commands +## Web rooting + +The [Huawei MA5671A browser rooting procedure](/ont-huawei-ma5671a-root-web) has been [reported to work](https://github.com/hack-gpon/hack-gpon.github.io/pull/518#discussion_r4485260237) on an Alcatel-Lucent G-010S-P. The firmware version was not provided in that report; this does not establish compatibility with every G-010S-P firmware version. + +Use this page's [serial pinout](#serial) for G-010S-P. The [Nokia G-010S-A serial-console helper](/ont-nokia-g-010s-a#enabling-serial) is a separate procedure for a different model and pinout. + ## Bootloader unlock from shell ::: warning Warning It is strongly recommended that you unlock the bootloader before making any major changes to the firmware.