Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ Versions after 2.17 are `MAJOR.MINOR.PATCH` (2.17 is followed by 2.17.1 or 2.18.
`docs/testing.md`, "Versions and releases"); the headings below keep the numbers as they
were released.

## 2.24.0 — 2026-11-17

- **Network** has a **Web page password** (the last field, empty by default): when set, the page
on port 8085 and everything under it (`/stats.json`, `/snapshot.jpg`, `/log`, `/report.txt`)
asks for it (HTTP Basic, any user name), from the local network and through the tunnel alike.
A wrong one is answered after a second. Kept sealed, like the camera URLs (Android 6.0+); a
stored password that cannot be read keeps the pages locked until it can be read again, is
entered again or is removed in Network.
- The **Web port** field is gone: Decoder always tells the camex server its page is on 8085 (it
needs a camex server 3.19.0 or later).
- The debug page's snapshot says "black in the copy: a dark picture, or video this device does
not let be copied" in a live cell whose copy comes out black, instead of a black cell: on the SberBox (Amlogic) the screen
shows two of four cells on hardware video planes, which neither the snapshot nor `screencap`
can read; which two is up to the device.

## 2.23.0 — 2026-11-17

- **Network** takes camex 3.19.0 (`bundles/camex` moves to the 3.19.0 release): two optional
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,11 @@ Every item, the remote, sharing a URL from another app and **Reset**: [Usage](do

## Network (a tunnel to the cameras)

Decoder has a tunnel built in, [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0: cameras that are clients of the same camex server are watched from anywhere, without a separate VPN app. **Network** in the menu (a row under the grid) holds the server (`host:port`), the client name (the box's ID on the server), UDP or TCP, the server's public key, the pre-shared key, the server timeout, the web port for nginx on the server (a camex server 3.19.0 or later) and **On**: connect now and at every start. Off by default. The server gives the address, MTU and routes; only the tunnel network and the server's routes (none wider than a /8) go through it, the local network is reached as before. The state is shown in the dialog (Connecting, Connected with the address, VPN consent needed, Failed) and in a notification. A camera reached through the tunnel plays over TCP with Auto.
Decoder has a tunnel built in, [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0: cameras that are clients of the same camex server are watched from anywhere, without a separate VPN app. **Network** in the menu (a row under the grid) holds the server (`host:port`), the client name (the box's ID on the server), UDP or TCP, the server's public key, the pre-shared key, the server timeout, the password of the debug page and **On**: connect now and at every start. Off by default. The server gives the address, MTU and routes; only the tunnel network and the server's routes (none wider than a /8) go through it, the local network is reached as before. The state is shown in the dialog (Connecting, Connected with the address, VPN consent needed, Failed) and in a notification. A camera reached through the tunnel plays over TCP with Auto. Decoder tells the server its web page is on port 8085 (for nginx there; a camex server 3.19.0 or later). The password, when set, guards that page from the local network and through the tunnel alike; empty (the default), the page is open.

<p align="center">
<img src="screenshots/network.jpg" alt="The Network dialog on a TV box: connected, the server and the client name" width="400">
<img src="screenshots/network_more.jpg" alt="The end of the dialog: keepalive, server timeout, web port and On" width="400">
<img src="screenshots/network_more.jpg" alt="The end of the dialog: keepalive, server timeout, web port and On (2.23.0)" width="400">
</p>

The first connection asks Android for the VPN consent once (a system dialog). A device without a person at it gets the consent over adb while it is set up, with no dialog ever, and it survives reboots (no root needed):
Expand Down
4 changes: 2 additions & 2 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,11 @@

## Network (туннель к камерам)

В Decoder встроен туннель [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0: камеры, подключённые клиентами к тому же серверу camex, видны откуда угодно, без отдельного VPN-приложения. Пункт **Network** в меню (ряд под сеткой): сервер (`host:port`), имя клиента (идентификатор приставки на сервере), UDP или TCP, открытый ключ сервера, общий ключ (psk), таймаут сервера, веб-порт для nginx на сервере (сервер camex 3.19.0 или новее) и **On** — подключиться сейчас и при каждом запуске. По умолчанию выключено. Адрес, MTU и маршруты выдаёт сервер; через туннель идут только его сеть и маршруты сервера (не шире /8), локальная сеть доступна как прежде. Состояние видно в окне (Connecting, Connected с адресом, VPN consent needed, Failed) и в уведомлении. Камера за туннелем в режиме Auto идёт по TCP.
В Decoder встроен туннель [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0: камеры, подключённые клиентами к тому же серверу camex, видны откуда угодно, без отдельного VPN-приложения. Пункт **Network** в меню (ряд под сеткой): сервер (`host:port`), имя клиента (идентификатор приставки на сервере), UDP или TCP, открытый ключ сервера, общий ключ (psk), таймаут сервера, пароль отладочной страницы и **On** — подключиться сейчас и при каждом запуске. По умолчанию выключено. Адрес, MTU и маршруты выдаёт сервер; через туннель идут только его сеть и маршруты сервера (не шире /8), локальная сеть доступна как прежде. Состояние видно в окне (Connecting, Connected с адресом, VPN consent needed, Failed) и в уведомлении. Камера за туннелем в режиме Auto идёт по TCP. Decoder сообщает серверу, что его веб-страница на порту 8085 (для nginx на сервере; нужен сервер camex 3.19.0 или новее). Пароль, если задан, закрывает эту страницу одинаково из локальной сети и через туннель; пустой (по умолчанию) — страница открыта.

<p align="center">
<img src="screenshots/network.jpg" alt="Окно Network на ТВ-приставке: подключено, сервер и имя клиента" width="400">
<img src="screenshots/network_more.jpg" alt="Конец окна: keepalive, таймаут сервера, веб-порт и On" width="400">
<img src="screenshots/network_more.jpg" alt="Конец окна: keepalive, таймаут сервера, веб-порт и On (2.23.0)" width="400">
</p>

При первом подключении Android один раз спрашивает согласие на VPN (системное окно). Устройству без человека рядом согласие дают через adb при настройке, без окна; оно сохраняется после перезагрузки (root не нужен):
Expand Down
4 changes: 2 additions & 2 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,11 @@

## Network(通往摄像头的隧道)

Decoder 内置 [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0 隧道:作为客户端接入同一台 camex 服务器的摄像头,可以在任何地方观看,无需另装 VPN 应用。菜单中的 **Network**(网格下方一行)包含:服务器(`host:port`)、客户端名称(设备在服务器上的 ID)、UDP 或 TCP、服务器公钥、预共享密钥、服务器超时、供服务器上 nginx 使用的 Web 端口(需 camex 服务器 3.19.0 或更新版本),以及 **On**:立即连接并在每次启动时连接。默认关闭。地址、MTU 和路由由服务器下发;只有隧道网络和服务器的路由(不宽于 /8)经过隧道,本地网络照常访问。状态显示在对话框(Connecting、Connected 及地址、VPN consent needed、Failed)和通知中。经隧道访问的摄像头在 Auto 模式下走 TCP。
Decoder 内置 [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0 隧道:作为客户端接入同一台 camex 服务器的摄像头,可以在任何地方观看,无需另装 VPN 应用。菜单中的 **Network**(网格下方一行)包含:服务器(`host:port`)、客户端名称(设备在服务器上的 ID)、UDP 或 TCP、服务器公钥、预共享密钥、服务器超时、调试页面密码,以及 **On**:立即连接并在每次启动时连接。默认关闭。地址、MTU 和路由由服务器下发;只有隧道网络和服务器的路由(不宽于 /8)经过隧道,本地网络照常访问。状态显示在对话框(Connecting、Connected 及地址、VPN consent needed、Failed)和通知中。经隧道访问的摄像头在 Auto 模式下走 TCP。Decoder 告知服务器其网页位于 8085 端口(供服务器上的 nginx 使用;需 camex 服务器 3.19.0 或更新版本)。设置密码后,无论从本地网络还是经隧道访问,该页面都需要密码;为空(默认)时页面开放。

<p align="center">
<img src="screenshots/network.jpg" alt="电视盒子上的 Network 对话框:已连接、服务器和客户端名称" width="400">
<img src="screenshots/network_more.jpg" alt="对话框末尾:keepalive、服务器超时、Web 端口和 On" width="400">
<img src="screenshots/network_more.jpg" alt="对话框末尾:keepalive、服务器超时、Web 端口和 On(2.23.0)" width="400">
</p>

首次连接时 Android 会请求一次 VPN 授权(系统对话框)。无人值守的设备可在部署时通过 adb 授权,不弹对话框,重启后仍然有效(无需 root):
Expand Down
4 changes: 2 additions & 2 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ android {
applicationId "com.openipc.decoder"
minSdk 21
targetSdk 36
versionCode 56
versionName "2.23.0"
versionCode 57
versionName "2.24.0"
// Keep only these locales of the libraries' resources, as in the other OpenIPC apps
resourceConfigurations += ['en', 'ru', 'zh-rCN']

Expand Down
105 changes: 103 additions & 2 deletions android/app/src/main/java/com/openipc/decoder/DebugServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
/**
* Serves what the decoder knows about itself on port 8085, for a browser or curl:
* {@code /} a page refreshing itself, {@code /stats.json} the same as JSON, {@code /log} the
* app's recent log, {@code /report.txt} both in one file to download (#207). Always on; a client outside the local network gets 403. GET only, one
* app's recent log, {@code /report.txt} both in one file to download (#207). Always on; a client outside the local network gets 403. With a password set in
* Network, every request needs it (HTTP Basic, any user name), from the local network and the
* tunnel alike; without one the pages are open, as before. GET only, one
* request per connection, short timeouts and a few workers: it must never get in the way of
* decoding. Logins and passwords never leave the device (redacted like the log, #55).
*/
Expand All @@ -52,6 +54,8 @@ final class DebugServer {
private static final long REBIND_DELAY_MS = 10_000;
/** A snapshot this young is served again: several viewers cost one capture (#98). */
private static final long SNAPSHOT_REUSE_MS = 1000;
/** The answer to a wrong password waits this long: about two guesses a second at most. */
private static final long WRONG_PASSWORD_DELAY_MS = 1000;

/** What the server reports; called on a server thread. */
interface Source {
Expand Down Expand Up @@ -167,8 +171,24 @@ private void handle(Socket s) {
reply(out, 403, "text/plain", "Forbidden: local network only\n");
return;
}
String requestLine = readRequestHead(socket.getInputStream());
StringBuilder headers = new StringBuilder();
String requestLine = readRequestHead(socket.getInputStream(), headers);
if (requestLine == null) return;
if (!authorized(headers.toString(), WebPassword.get())) {
// a wrong password (not the browser's first try without one) costs a second:
// guessing goes slowly
if (hasAuthorization(headers.toString())) {
try {
Thread.sleep(WRONG_PASSWORD_DELAY_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
reply(out, 401, "text/plain", "Password needed\n".getBytes(StandardCharsets.UTF_8),
"WWW-Authenticate: Basic realm=\"OpenIPC Decoder\", charset=\"UTF-8\"\r\n");
return;
}
String[] parts = requestLine.split(" ");
if (parts.length < 2) {
reply(out, 400, "text/plain", "Bad request\n");
Expand Down Expand Up @@ -332,6 +352,11 @@ private byte[] snapshotJpeg(boolean labels) {

/** The request line; the headers are read and dropped. Null on a closed connection. */
static String readRequestHead(InputStream in) throws IOException {
return readRequestHead(in, null);
}

/** The request line; the header lines after it go to {@code headers}, when given. */
static String readRequestHead(InputStream in, StringBuilder headers) throws IOException {
ByteArrayOutputStream head = new ByteArrayOutputStream();
int matched = 0;
while (head.size() < MAX_HEADER_BYTES) {
Expand All @@ -348,9 +373,84 @@ static String readRequestHead(InputStream in) throws IOException {
String text = head.toString("ISO-8859-1");
int eol = text.indexOf('\n');
String line = (eol >= 0 ? text.substring(0, eol) : text).trim();
if (headers != null && eol >= 0) headers.append(text.substring(eol + 1));
return line.isEmpty() ? null : line;
}

/**
* Whether a request with these header lines may be served: always without a password
* (empty), never when the stored one cannot be read (null: locked until it is entered again
* in Network), otherwise when its Basic credentials carry the password, whatever the user
* name (the browser asks for both).
*/
static boolean authorized(String headers, String password) {
if (password == null) return false;
if (password.isEmpty()) return true;
for (String line : headers.split("\n")) {
int colon = line.indexOf(':');
if (colon < 0 || !line.substring(0, colon).trim().equalsIgnoreCase("Authorization")) {
continue;
}
String value = line.substring(colon + 1).trim();
int space = value.indexOf(' ');
if (space < 0 || !value.substring(0, space).equalsIgnoreCase("Basic")) return false;
byte[] pair = base64(value.substring(space + 1).trim());
if (pair == null) return false;
String userPass = new String(pair, StandardCharsets.UTF_8);
int sep = userPass.indexOf(':');
if (sep < 0) return false;
// the same time for a wrong password of any length
return java.security.MessageDigest.isEqual(
sha256(userPass.substring(sep + 1)), sha256(password));
}
return false;
}

/** Whether the request carries an Authorization header. */
static boolean hasAuthorization(String headers) {
for (String line : headers.split("\n")) {
int colon = line.indexOf(':');
if (colon > 0 && line.substring(0, colon).trim().equalsIgnoreCase("Authorization")) {
return true;
}
}
return false;
}

private static byte[] sha256(String s) {
try {
return java.security.MessageDigest.getInstance("SHA-256")
.digest(s.getBytes(StandardCharsets.UTF_8));
} catch (java.security.NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}

/**
* Standard base64 with or without padding, null when it is not base64 (java.util.Base64
* needs API 26, android.util.Base64 is a stub in the unit tests).
*/
static byte[] base64(String s) {
final String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int end = s.length();
while (end > 0 && s.charAt(end - 1) == '=') end--;
if (s.length() - end > 2) return null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int bits = 0, n = 0;
for (int i = 0; i < end; i++) {
int d = abc.indexOf(s.charAt(i));
if (d < 0) return null;
bits = (bits << 6) | d;
n += 6;
if (n >= 8) {
n -= 8;
out.write((bits >> n) & 0xFF);
}
}
if (n >= 6) return null; // a lone last character carries no byte
return out.toByteArray();
}

private static void reply(OutputStream out, int code, String type, String body)
throws IOException {
reply(out, code, type, body.getBytes(StandardCharsets.UTF_8));
Expand Down Expand Up @@ -380,6 +480,7 @@ private static String reason(int code) {
switch (code) {
case 200: return "OK";
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
Expand Down
Loading
Loading