From d4e4dda6e0754289d6db3e819106b70e24714fb7 Mon Sep 17 00:00:00 2001 From: Compot Developer Date: Wed, 18 Nov 2026 22:02:41 +0000 Subject: [PATCH] feat: web page port in Network, the next free one when taken; camex 4.1.2 (2.25.0) The debug page listens on the port set in Network -> Web page port (default 8085, as before). When it is taken, for example by another of our apps on the device, the server takes the next free one (up to nine on), logs which and why, and /stats.json, the debug text and the dialog show the real port. The camex tunnel is told the port the page really got: a start waits until the page has tried its port (no restart right after the app's start), and a running tunnel restarts when the port changes (Network, or taken later). camex 4.1.2 (OpenIPC/camex#187): from the tunnel the library lets in only the app's own web port held by the app itself; the server shows an error rather than another app's page. tests/e2e.sh: the port taken by adbd (adb reverse tcp:8085): the page is on 8086 through the tunnel, 8085 through the tunnel is refused; the camera check waits for the reader, which takes longer with the round trip. Closes #284 --- CHANGELOG.md | 14 +++ README.md | 4 +- README.ru.md | 4 +- README.zh-CN.md | 4 +- android/app/build.gradle | 4 +- .../java/com/openipc/decoder/DebugServer.java | 110 +++++++++++++++--- .../java/com/openipc/decoder/Decoder.java | 8 +- .../com/openipc/decoder/NetworkPanel.java | 71 ++++++++++- .../java/com/openipc/decoder/WebPassword.java | 2 +- .../java/com/openipc/decoder/WebPort.java | 69 +++++++++++ .../java/com/openipc/decoder/WebPortTest.java | 41 +++++++ bundles/camex | 2 +- docs/debug.md | 6 +- docs/security.md | 2 +- docs/testing.md | 2 +- tests/e2e.sh | 42 ++++++- 16 files changed, 344 insertions(+), 41 deletions(-) create mode 100644 android/app/src/main/java/com/openipc/decoder/WebPort.java create mode 100644 android/app/src/test/java/com/openipc/decoder/WebPortTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 35d206d..8d7c1e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,20 @@ 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.25.0 — 2026-11-18 + +- The web (debug) page's port is set in **Network** → **Web page port** (default 8085, as + before; empty: 8085). When the port is taken, for example by another of our apps on the same + device, the page takes the next free one (up to 8094 by default), logs which port and why, + and shows the real address in `/stats.json`, the debug text and the Network dialog (#284). +- The camex tunnel is told the port the page really got and restarts when it changes, so the + server's nginx reaches Decoder's own page. +- The camex tunnel is built from camex 4.1.2 (was 4.0.1): from the tunnel, the library lets in + only connections to the app's own web port, held by the app itself; anything else is refused + at once, so the server shows an error rather than another app's page (OpenIPC/camex#187). +- `tests/e2e.sh` checks a taken port: the page moves to 8086, through the tunnel too, and 8085 + through the tunnel is refused. + ## 2.24.3 — 2026-11-18 - The camex tunnel is built from camex 4.0.1 (was 4.0.0), which fixes the tunnel over TCP: diff --git a/README.md b/README.md index 35a6486..741ac64 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ A small Android app for watching RTSP streams from IP cameras, with hardware H.2 - **Audio:** AAC, Opus, G.711, L16 - **Views:** one camera, or multi-view with up to 8 cameras plus a camera that pushes RTP, decoding adapted to what the device can do - **Network:** RTSP over TCP, UDP (Auto falls back to TCP) or multicast, RTP pushed by the camera (Majestic `outgoing`), Basic and Digest authentication, automatic reconnection -- **More:** Android TV remote, zoom, camera web interface, URLs stored encrypted, a debug page on port 8085 +- **More:** Android TV remote, zoom, camera web interface, URLs stored encrypted, a debug page on port 8085 (settable)

Multi-view with eight cameras and the menu @@ -89,7 +89,7 @@ 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) 4.0.1: 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. +Decoder has a tunnel built in, [OpenIPC camex](https://github.com/OpenIPC/camex) 4.1.2: 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 port and 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. The debug page is on port 8085 unless Network sets another; when that port is taken (another app on the device serves its page there), Decoder takes the next free one (8086, 8087, …) and shows the real address. Decoder tells the server the port its page really is on (for nginx there; a camex server 3.19.0 or later), and the tunnel lets in only that port of Decoder's own page: another app's page is not reached through it. The password, when set, guards that page from the local network and through the tunnel alike; empty (the default), the page is open.

The Network dialog on a TV box: connected, the server and the client name diff --git a/README.ru.md b/README.ru.md index 70bcb03..d3e2df5 100644 --- a/README.ru.md +++ b/README.ru.md @@ -15,7 +15,7 @@ - **Звук:** AAC, Opus, G.711, L16 - **Режимы:** одна камера или мультивид — до 8 камер и камера, которая сама шлёт RTP; декодирование подстраивается под возможности устройства - **Сеть:** RTSP поверх TCP, UDP (Auto переходит на TCP) или multicast, RTP, который камера шлёт сама (Majestic `outgoing`), авторизация Basic и Digest, автоматическое переподключение -- **Прочее:** пульт Android TV, масштаб, веб-интерфейс камеры, адреса хранятся в зашифрованном виде, отладочная страница на порту 8085 +- **Прочее:** пульт Android TV, масштаб, веб-интерфейс камеры, адреса хранятся в зашифрованном виде, отладочная страница на порту 8085 (настраивается)

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

Окно Network на ТВ-приставке: подключено, сервер и имя клиента diff --git a/README.zh-CN.md b/README.zh-CN.md index 2ab77e5..f5b0014 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -15,7 +15,7 @@ - **音频:** AAC、Opus、G.711、L16 - **显示:** 单路画面,或多画面模式:最多 8 路摄像机外加一路主动推送 RTP 的摄像机,解码方式根据设备能力自动调整 - **网络:** RTSP over TCP、UDP(Auto 模式会回退到 TCP)或组播,接收摄像机主动推送的 RTP(Majestic `outgoing`),支持 Basic 和 Digest 认证,断线自动重连 -- **其他:** 支持 Android TV 遥控器、缩放、摄像机网页界面,地址加密保存,端口 8085 上的调试页面 +- **其他:** 支持 Android TV 遥控器、缩放、摄像机网页界面,地址加密保存,端口 8085(可更改)上的调试页面

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

电视盒子上的 Network 对话框:已连接、服务器和客户端名称 diff --git a/android/app/build.gradle b/android/app/build.gradle index ca4bdbf..d9c1e30 100755 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -26,8 +26,8 @@ android { applicationId "com.openipc.decoder" minSdk 21 targetSdk 36 - versionCode 60 - versionName "2.24.3" + versionCode 61 + versionName "2.25.0" // Keep only these locales of the libraries' resources, as in the other OpenIPC apps resourceConfigurations += ['en', 'ru', 'zh-rCN'] diff --git a/android/app/src/main/java/com/openipc/decoder/DebugServer.java b/android/app/src/main/java/com/openipc/decoder/DebugServer.java index 71680bf..5cf2bc3 100644 --- a/android/app/src/main/java/com/openipc/decoder/DebugServer.java +++ b/android/app/src/main/java/com/openipc/decoder/DebugServer.java @@ -30,7 +30,8 @@ import java.util.concurrent.TimeUnit; /** - * Serves what the decoder knows about itself on port 8085, for a browser or curl: + * Serves what the decoder knows about itself on the port of {@link WebPort} (8085 unless Network + * sets another; the next free one when it is taken, #284), 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. With a password set in * Network, every request needs it (HTTP Basic, any user name), from the local network and the @@ -40,7 +41,6 @@ */ final class DebugServer { private static final String TAG = "OpenIPCDecoder"; - static final int PORT = 8085; /** Lines of the app's log served by /log. */ static final int LOG_LINES = 500; private static final int SOCKET_TIMEOUT_MS = 3000; @@ -77,6 +77,12 @@ interface Source { private volatile Source source; /** "listening" or why the port could not be opened, for the debug text. */ private volatile String state = "starting"; + /** The port the server listens on, 0 while it has none. */ + private volatile int port; + /** True once the first port was tried: the tunnel waits for it, so it starts with that port. */ + private volatile boolean settled; + /** The open socket, closed by {@link #rebind()} to take the port set in Network now. */ + private volatile ServerSocket server; private final ThreadPoolExecutor workers = new ThreadPoolExecutor(2, 2, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), r -> { // Background priority: on a box busy decoding, a request waits, not the video @@ -133,24 +139,96 @@ void clearSource(Source s) { String state() { return state; } - private void acceptLoop() { - while (true) { - try (ServerSocket server = new ServerSocket()) { - server.setReuseAddress(true); - server.bind(new InetSocketAddress(PORT)); - state = "listening"; - Log.i(TAG, "Debug HTTP server on port " + PORT); - while (true) { - Socket s = server.accept(); + /** The port the page is on: the one listened on, else the one asked for. */ + int port() { + int p = port; + return p != 0 ? p : WebPort.get(App.context); + } + + /** Whether the server has tried its port since the start (it listens, or none was free). */ + boolean settled() { + return settled; + } + + /** Takes the port now set in Network: the open socket is closed and the next one opened. */ + void rebind() { + ServerSocket s = server; + if (s == null) return; + port = 0; // until the new one is open, port() is the one now set + try { + s.close(); + } catch (IOException ignored) { + // closed already + } + } + + /** + * The set port or, when it is taken, the next free one of {@link WebPort#TRIES}; null when + * none is free. The reason the set port is taken goes to {@code why[0]}. + */ + private static ServerSocket open(int wanted, String[] why) { + for (int p = wanted; p < wanted + WebPort.TRIES && p <= WebPort.MAX; p++) { + ServerSocket s = null; + try { + s = new ServerSocket(); + s.setReuseAddress(true); + s.bind(new InetSocketAddress(p)); + return s; + } catch (IOException e) { + if (p == wanted) why[0] = e.getMessage(); + if (s != null) { try { - workers.execute(() -> handle(s)); - } catch (RejectedExecutionException busy) { - closeQuietly(s); + s.close(); + } catch (IOException ignored) { + // not open } } - } catch (IOException e) { - state = "port " + PORT + " unavailable: " + e.getMessage(); + } + } + return null; + } + + private void acceptLoop() { + while (true) { + int wanted = WebPort.get(App.context); + String[] why = new String[1]; + ServerSocket opened = open(wanted, why); + if (opened == null) { + port = 0; + int last = Math.min(wanted + WebPort.TRIES - 1, WebPort.MAX); + state = "ports " + wanted + " to " + last + " unavailable: " + why[0]; Log.w(TAG, "Debug HTTP server: " + state + ", retrying"); + settled = true; + NetworkPanel.webPortSettled(wanted); + } else { + try (ServerSocket s = opened) { + server = s; + port = s.getLocalPort(); + state = "listening"; + if (port == wanted) { + Log.i(TAG, "Debug HTTP server on port " + port); + } else { + Log.w(TAG, "Debug HTTP server on port " + port + ": port " + wanted + + " is taken (" + why[0] + ")"); + } + settled = true; + NetworkPanel.webPortSettled(port); + while (true) { + Socket c = s.accept(); + try { + workers.execute(() -> handle(c)); + } catch (RejectedExecutionException busy) { + closeQuietly(c); + } + } + } catch (IOException e) { + server = null; + // closed by rebind(): the port set in Network now, at once + if (WebPort.get(App.context) != wanted) continue; + port = 0; + state = "port closed: " + e.getMessage(); + Log.w(TAG, "Debug HTTP server: " + state + ", retrying"); + } } try { Thread.sleep(REBIND_DELAY_MS); diff --git a/android/app/src/main/java/com/openipc/decoder/Decoder.java b/android/app/src/main/java/com/openipc/decoder/Decoder.java index ccafea6..c17b9d8 100755 --- a/android/app/src/main/java/com/openipc/decoder/Decoder.java +++ b/android/app/src/main/java/com/openipc/decoder/Decoder.java @@ -480,7 +480,7 @@ public void onToggleStats() { : "Debug text off", Toast.LENGTH_SHORT).show(); } - /** One line http://

:8085/ per device address while the debug text is on. */ + /** One line http://
:/ per device address while the debug text is on (#284: the real port). */ private void updateDebugUrls() { if (debugUrls == null) return; if (!showStats) { @@ -488,9 +488,10 @@ private void updateDebugUrls() { return; } StringBuilder sb = new StringBuilder(); + int port = DebugServer.get().port(); for (String ip : NetInfo.addresses()) { if (sb.length() > 0) sb.append('\n'); - sb.append("http://").append(ip).append(':').append(DebugServer.PORT).append('/'); + sb.append("http://").append(ip).append(':').append(port).append('/'); } if (sb.length() == 0) sb.append("Debug page: no network"); if (!sb.toString().contentEquals(debugUrls.getText())) debugUrls.setText(sb); @@ -1642,7 +1643,8 @@ private Map debugDevice() { m.put("screen", getResources().getDisplayMetrics().widthPixels + "x" + getResources().getDisplayMetrics().heightPixels); List urls = new ArrayList<>(); - for (String ip : NetInfo.addresses()) urls.add("http://" + ip + ":" + DebugServer.PORT + "/"); + int port = DebugServer.get().port(); + for (String ip : NetInfo.addresses()) urls.add("http://" + ip + ":" + port + "/"); m.put("addresses", urls); m.put("server", DebugServer.get().state()); // The video decoders and what they can do: instances, adaptive playback (#88) diff --git a/android/app/src/main/java/com/openipc/decoder/NetworkPanel.java b/android/app/src/main/java/com/openipc/decoder/NetworkPanel.java index b93d923..868ce76 100644 --- a/android/app/src/main/java/com/openipc/decoder/NetworkPanel.java +++ b/android/app/src/main/java/com/openipc/decoder/NetworkPanel.java @@ -15,6 +15,8 @@ import android.content.pm.PackageManager; import android.graphics.Color; import android.os.Build; +import android.os.Handler; +import android.os.Looper; import android.text.InputType; import android.util.Log; import android.util.TypedValue; @@ -37,8 +39,10 @@ * The camex tunnel (the library of bundles/camex): the Network screen is built from its fields, * the values are kept in Decoder's settings as {@code tunnel_camex_} (the psk sealed with * {@link CredentialStore}), and {@code tunnel_on} connects now and at every start of the app. - * The web port is not asked: it is always the debug page's {@link DebugServer#PORT}. The same - * dialog holds the password of that page ({@link WebPassword}). + * The library's web port is not asked: it is the port the debug page really listens on + * ({@link DebugServer#port()}: the one of {@link WebPort} or, when that is taken, the next free + * one), and the tunnel restarts when that changes (#284). The same dialog holds the page's port + * and password ({@link WebPassword}). * Android's VPN consent: a person confirms the system dialog once; a box without a person gets * it while it is prepared: adb shell appops set com.openipc.decoder ACTIVATE_VPN allow. */ @@ -84,8 +88,9 @@ private static Map load(Context c, Map unreadabl } v.put(f.key, s != null ? s : f.initial); } - // nginx on the server reaches the box's web page there (camex 3.19.0, needs that server) - v.put(CamexTunnel.WEB_PORT, String.valueOf(DebugServer.PORT)); + // nginx on the server reaches the box's web page there (camex 3.19.0, needs that server); + // camex 4.1.2 lets in from the tunnel only this port, held by this app (camex#187) + v.put(CamexTunnel.WEB_PORT, String.valueOf(DebugServer.get().port())); return v; } @@ -179,7 +184,46 @@ static void onVpnResult(Activity a, int resultCode) { start(a, askAfterConsent); } + /** The web port the running tunnel was given; 0 before the first start. */ + private static volatile int announcedPort; + + /** A start that waits for the debug page's port (see {@link #start}); main thread only. */ + private static Runnable pendingStart; + + /** + * The debug page tried its port: it got this one (at the start, or another one after a + * change in Network or when the set one is taken), or none was free and this is the one + * asked for. A start that waited for it goes on now; a running tunnel given another port + * restarts with this one, so the server's nginx and camex's gate point at the page (#284). + * Any thread. + */ + static void webPortSettled(int port) { + Handler main = new Handler(Looper.getMainLooper()); + main.post(() -> { + Runnable r = pendingStart; + pendingStart = null; + if (r != null) r.run(); + }); + Context c = App.context; + if (c == null || port == announcedPort || !CamexTunnel.running() || !isOn(c)) return; + main.post(() -> { + if (port == announcedPort || !CamexTunnel.running()) return; + Map v = load(c); + if (CamexTunnel.check(v) != null) return; + Log.i(TAG, "Network: the web page is on port " + port + " now, the tunnel restarts"); + announcedPort = port; + CamexTunnel.start(c.getApplicationContext(), v); + }); + } + private static void start(Activity a, boolean askNotifications) { + // the tunnel tells the server the page's port: right after the app's start the page may + // not have it yet (8085 taken: 8086); wait for it rather than restart the tunnel then + if (!DebugServer.get().settled()) { + pendingStart = () -> start(a, askNotifications); + return; + } + pendingStart = null; Map v = load(a); if (CamexTunnel.check(v) != null) { Log.w(TAG, "Network is on, but its settings are not complete"); @@ -192,6 +236,7 @@ private static void start(Activity a, boolean askNotifications) { a.requestPermissions(new String[]{"android.permission.POST_NOTIFICATIONS"}, REQ_NOTIFY); } CamexTunnel.setNotificationLook("Decoder", R.drawable.ic_launcher_foreground); + announcedPort = Integer.parseInt(v.get(CamexTunnel.WEB_PORT)); CamexTunnel.start(a.getApplicationContext(), v); } @@ -278,11 +323,17 @@ static void show(Activity a) { content.addView(view); views.put(f.key, view); } - // the web page on port 8085, from the local network and the tunnel alike + // the web page: its port (8085 unless set; the next free one when taken) and password, + // from the local network and the tunnel alike + int webPort = DebugServer.get().port(); + content.addView(label(a, "Web page port (empty: " + WebPort.DEFAULT + "; taken: the next free" + + (webPort != WebPort.get(a) ? "; now " + webPort : "") + ")")); + EditText port = field(a, WebPort.text(a), InputType.TYPE_CLASS_NUMBER); + content.addView(port); String webPassword = WebPassword.read(a); final String keepWebPassword = webPassword == null ? WebPassword.stored(a) : null; content.addView(label(a, webPassword != null - ? "Web page password (port " + DebugServer.PORT + "; empty: open)" + ? "Web page password (empty: open)" : "Web page password: the stored one cannot be read, the page is locked;" + " enter it again or a new one")); EditText web = field(a, webPassword != null ? webPassword : "", @@ -329,6 +380,12 @@ protected void onMeasure(int widthSpec, int heightSpec) { n.put(f.key, ((EditText) view).getText().toString()); } } + String badPort = WebPort.check(port.getText().toString()); + if (badPort != null) { + port.setError(badPort); + port.requestFocus(); + return; + } String[] problem = on.isChecked() ? CamexTunnel.check(n) : null; if (problem != null) { View view = views.get(problem[0]); @@ -337,6 +394,8 @@ protected void onMeasure(int widthSpec, int heightSpec) { return; } save(a, n, unreadable, on.isChecked()); + // a new port: the page moves there now (and a running tunnel is told it below) + if (WebPort.save(a, port.getText().toString())) DebugServer.get().rebind(); WebPassword.save(a, web.getText().toString(), removeWeb != null && removeWeb.isChecked() ? null : keepWebPassword); // on: (re)connect with the saved values (a running tunnel restarts); off: stop diff --git a/android/app/src/main/java/com/openipc/decoder/WebPassword.java b/android/app/src/main/java/com/openipc/decoder/WebPassword.java index 58b2fc7..e42492a 100644 --- a/android/app/src/main/java/com/openipc/decoder/WebPassword.java +++ b/android/app/src/main/java/com/openipc/decoder/WebPassword.java @@ -1,7 +1,7 @@ /* * Copyright (c) OpenIPC https://openipc.org Prosperity Public License 3.0.0 * - * WebPassword.java — the password of the web page on port 8085, set in Network + * WebPassword.java — the password of the web page, set in Network * */ diff --git a/android/app/src/main/java/com/openipc/decoder/WebPort.java b/android/app/src/main/java/com/openipc/decoder/WebPort.java new file mode 100644 index 0000000..d2d1c78 --- /dev/null +++ b/android/app/src/main/java/com/openipc/decoder/WebPort.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) OpenIPC https://openipc.org Prosperity Public License 3.0.0 + * + * WebPort.java — the port of the web page, set in Network (#284) + * + */ + +package com.openipc.decoder; + +import android.content.Context; + +/** + * The port {@link DebugServer} asks for: 8085 unless Network sets another. When it is taken + * (another of our apps on the device serves its page there), the server takes the next free + * one of {@link #TRIES}, and the camex tunnel is told the port it really got. + */ +final class WebPort { + static final int DEFAULT = 8085; + /** The set port and the ports after it that are tried: 8085 to 8094 by default. */ + static final int TRIES = 10; + /** No privileged ports: an app cannot open them. */ + static final int MIN = 1024; + static final int MAX = 65535; + private static final String PREFS = "settings"; + static final String KEY = "web_port"; + + private WebPort() { + } + + /** The set port: {@link #DEFAULT} when nothing (or nothing valid) is set, or no context yet. */ + static int get(Context c) { + if (c == null) return DEFAULT; + Integer p = parse(c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, "")); + return p != null ? p : DEFAULT; + } + + /** As the Network field shows it: empty for the default. */ + static String text(Context c) { + int p = get(c); + return p == DEFAULT ? "" : String.valueOf(p); + } + + /** null when the text is a port the field takes (empty: the default), else what is wrong. */ + static String check(String text) { + return parse(text) != null ? null : "A port from " + MIN + " to " + MAX + ", or empty for " + DEFAULT; + } + + /** Saves a checked text; returns true when the set port changed. */ + static boolean save(Context c, String text) { + int before = get(c); + Integer p = parse(text); + int after = p != null ? p : DEFAULT; + c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putString(KEY, after == DEFAULT ? "" : String.valueOf(after)).apply(); + return after != before; + } + + /** The port of a text, the default for an empty one, null for anything else. */ + static Integer parse(String text) { + String s = text == null ? "" : text.trim(); + if (s.isEmpty()) return DEFAULT; + if (s.length() > 5) return null; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) < '0' || s.charAt(i) > '9') return null; + } + int p = Integer.parseInt(s); + return p >= MIN && p <= MAX ? p : null; + } +} diff --git a/android/app/src/test/java/com/openipc/decoder/WebPortTest.java b/android/app/src/test/java/com/openipc/decoder/WebPortTest.java new file mode 100644 index 0000000..dd13b96 --- /dev/null +++ b/android/app/src/test/java/com/openipc/decoder/WebPortTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) OpenIPC https://openipc.org Prosperity Public License 3.0.0 + * + * WebPortTest.java — the Network field of the web page's port (#284) + * + */ + +package com.openipc.decoder; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +public class WebPortTest { + @Test + public void emptyIsTheDefault() { + assertEquals(Integer.valueOf(8085), WebPort.parse("")); + assertEquals(Integer.valueOf(8085), WebPort.parse(" ")); + assertEquals(Integer.valueOf(8085), WebPort.parse(null)); + assertNull(WebPort.check("")); + } + + @Test + public void portsAnAppCanOpen() { + assertEquals(Integer.valueOf(8585), WebPort.parse("8585")); + assertEquals(Integer.valueOf(1024), WebPort.parse("1024")); + assertEquals(Integer.valueOf(65535), WebPort.parse(" 65535 ")); + assertNull(WebPort.check("8086")); + } + + @Test + public void anythingElseIsRefused() { + for (String s : new String[]{"80", "1023", "65536", "99999", "123456", "-1", "+8085", + "80a5", "8085.0", "0x1f95"}) { + assertNull(s, WebPort.parse(s)); + assertNotNull(s, WebPort.check(s)); + } + } +} diff --git a/bundles/camex b/bundles/camex index 9e721e5..53c3dd8 160000 --- a/bundles/camex +++ b/bundles/camex @@ -1 +1 @@ -Subproject commit 9e721e58ffedcda7a72750a0056be5298f68231c +Subproject commit 53c3dd86fc67d24732a717335c3fff8c521efd69 diff --git a/docs/debug.md b/docs/debug.md index baea46f..3c023fc 100644 --- a/docs/debug.md +++ b/docs/debug.md @@ -12,7 +12,7 @@ ## Debug server -While the app runs it serves its debug information over HTTP on port **8085**, for a browser or `curl` on the same network. It is always on and read-only. +While the app runs it serves its debug information over HTTP on port **8085**, for a browser or `curl` on the same network. **Network** → **Web page port** sets another port (1024 to 65535; empty: 8085). It is always on and read-only. | Path | Content | |------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| @@ -26,7 +26,7 @@ While the app runs it serves its debug information over HTTP on port **8085**, f - Only clients on the local network are answered; others get `403`. With a password set in **Network** (**Web page password**) the browser asks for it (any user name; `curl -u :`). The rule and what is hidden: [security.md](security.md#debug-server). - `GET` only (`405` otherwise), one request per connection, `Cache-Control: no-store`. - Two worker threads at background priority, a short queue, a 20 s deadline per request: the server never gets in the way of decoding; a busy server drops the connection. -- If port 8085 is taken, the server retries every 10 s; `server` in `/stats.json` says why. +- If the port is taken (another app on the device serves its page there), the server takes the next free one, up to nine ports on (8086 … 8094), and logs which one and why; `addresses` in `/stats.json`, the Network dialog and the debug text show the real port. With none of them free it retries every 10 s, and `server` in `/stats.json` says why. The camex tunnel is told the port the page really got, and restarts when it changes. - On a phone that is only on a camera's or toy's Wi‑Fi, open the pages on the phone itself: `http://127.0.0.1:8085/`. The device's addresses are in `addresses` of `/stats.json`, and the [U cell](usage.md#the-u-cell) shows them while it waits for a stream. @@ -90,7 +90,7 @@ In the single view (and the U view) the page and the snapshot still show the who | `android` | string | release and SDK level, e.g. `10 (SDK 29)` | | `screen` | string | display size in pixels, `WxH` | | `addresses` | list | `http://:8085/` for every address of the device | -| `server` | string | `listening`, or why port 8085 could not be opened | +| `server` | string | `listening`, or why no port could be opened | | `decoders` | list or `"loading"` | the device's video decoders, see [decoders](#decoders) | | `ui_thread` | string | `ok`, or `not responding within 1000 ms` (then only the fields above are present) | | `mode` | string | `single`, `multi-view`, `slides` (multi-view with Slides on), `udp` (U cell full-screen), `paused` (app in background); `no activity` when no activity is attached | diff --git a/docs/security.md b/docs/security.md index af29b1b..4b60380 100644 --- a/docs/security.md +++ b/docs/security.md @@ -33,7 +33,7 @@ Use the app on trusted networks only, or inside a secure channel of your own (a ## Debug server -The [debug server](debug.md) on port 8085 has no encryption, and no password unless one is set in **Network** (**Web page password**). It is always on while the app runs, and: +The [debug server](debug.md) on port 8085 (or the one set in **Network**) has no encryption, and no password unless one is set in **Network** (**Web page password**). It is always on while the app runs, and: - answers only local-network clients: loopback, link-local (169.254/16, fe80::/10), the IPv4 private ranges 10/8, 172.16/12, 192.168/16, and IPv6 unique-local fc00::/7. Every other address gets `403 Forbidden: local network only`; - with a password set, asks every request for it (HTTP Basic, any user name), from the local network and through the camex tunnel alike; a wrong one is answered after a second (about two guesses a second at most), so a long password is worth it; it is kept sealed like the camera URLs (Android 6.0+; on 5.x, as those, it is stored as it is), and one that cannot be read keeps the pages locked until it can be read again, is entered again or is removed in Network. Over the local network the password travels as plain HTTP, through the tunnel encrypted by camex; diff --git a/docs/testing.md b/docs/testing.md index 6e7a5a3..02cd5aa 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -138,7 +138,7 @@ cd android The native code is built for arm64-v8a and armeabi-v7a by default; `-PdecoderAbis` takes a list of `arm64-v8a`, `armeabi-v7a`, `x86_64`, `x86` (an empty or unknown one fails the build). -`tests/e2e.sh [API]` plays a camera through a camex server and the tunnel on an x86_64 emulator in Docker (API 21 and 34 are checked): 15 checks (16 with `TRANSPORT=TCP`, the tunnel over TCP), from no camera with Network off to the password of the debug page through the tunnel and a restart of the tunnel with Network → Save. The links of the emulator, the hub and the Linux edge get a netem delay of `DELAY_MS` each way (default 30 ms, 60 ms between the box and the hub; `tc` comes from the `decoder-netem` image of `tests/netem`, built on the first run), so the video rate check catches a TCP tunnel that crawls, as camex 4.0.0 did (#281). Its output is in `tests/out/` (ignored by git). +`tests/e2e.sh [API]` plays a camera through a camex server and the tunnel on an x86_64 emulator in Docker (API 21 and 34 are checked): 17 checks (18 with `TRANSPORT=TCP`, the tunnel over TCP), from no camera with Network off to the password of the debug page through the tunnel and a restart of the tunnel with Network → Save and the web page's port taken by another program (adbd's `adb reverse tcp:8085`): the page moves to 8086, through the tunnel too, and 8085 through the tunnel is refused. The links of the emulator, the hub and the Linux edge get a netem delay of `DELAY_MS` each way (default 30 ms, 60 ms between the box and the hub; `tc` comes from the `decoder-netem` image of `tests/netem`, built on the first run), so the video rate check catches a TCP tunnel that crawls, as camex 4.0.0 did (#281). Its output is in `tests/out/` (ignored by git). A release build needs a keystore at `android/key.jks` and `KEYSTORE_PASS`, `KEY_ALIAS`, `KEY_PASS` in the environment (`./gradlew assembleRelease`). Debug and release builds are signed with different keys: to switch, uninstall first, which removes the saved camera URLs. diff --git a/tests/e2e.sh b/tests/e2e.sh index 53ae3bb..d92b0c9 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -282,7 +282,8 @@ else ok "the VPN leaves IPv6 alone (no ::/0 on tun0)"; fi # Decoder retries the camera on its own: wait for a viewer from the tunnel address i=0 -until [ -n "${TUN:-}" ] && docker logs "$CAM" 2>&1 | grep -q "created by $TUN:"; do +# (and for it to read: with the round trip the RTSP setup takes a few seconds after "created") +until [ -n "${TUN:-}" ] && docker logs "$CAM" 2>&1 | grep -q "created by $TUN:" && [ "$(readers)" -ge 1 ]; do i=$((i + 1)); [ $i -lt 60 ] || break sleep 1 done @@ -446,6 +447,45 @@ if [ -z "$SHOTS" ]; then fi fi +# the web page's port taken by another program (adbd's reverse forward listens on 8085): Decoder +# takes the next free one, tells the tunnel, and the hub's side reaches the page there; 8085 +# through the tunnel is refused, not served by the other program (#284, camex#187) +if [ -z "$SHOTS" ]; then + $ADB shell am force-stop $PKG + sleep 2 + $ADB reverse tcp:8085 tcp:9 >/dev/null + # listeners on 8085 (1F95), state 0A: who holds it before Decoder starts + held() { $ADB shell cat /proc/net/tcp /proc/net/tcp6 2>/dev/null | awk '$2 ~ /:1F95$/ && $4 == "0A" { print $2, "uid", $8 }'; } + { echo "before:"; held; } > "$OUT/port-8085.txt" + $ADB logcat -c 2>/dev/null || true + $ADB shell am start -n $ACTIVITY >/dev/null + # (curl exits non-zero on a refused connection; its code is then 000) + page() { docker exec "$PEER" curl -s -o /dev/null -m 5 -w '%{http_code}' "$@" || true; } + moved="" + for n in $(seq 1 45); do + # Android 5 at times does not start the app right after force-stop: start it again + if [ $((n % 10)) -eq 0 ] && ! $ADB shell ps | grep -q "$PKG"; then + $ADB shell am start -n $ACTIVITY >/dev/null + fi + TUN=$($ADB shell 'ip addr show tun0 2>/dev/null' | sed -n 's/.*inet \([0-9.]*\).*/\1/p') + if [ -n "$TUN" ] && [ "$(page "http://$TUN:8086/stats.json")" = 401 ]; then moved=1; break; fi + sleep 2 + done + $ADB logcat -d > "$OUT/logcat-port.txt" 2>&1 || true + { echo "after:"; held; } >> "$OUT/port-8085.txt" + if [ -n "$moved" ] && grep -q 'Debug HTTP server on port 8086: port 8085 is taken' "$OUT/logcat-port.txt" && + page -u "anyone:$WEB_PASSWORD" "http://$TUN:8086/stats.json" | grep -q 200 && + docker exec "$PEER" curl -s -m 5 -u "anyone:$WEB_PASSWORD" "http://$TUN:8086/stats.json" | grep -q ':8086/'; then + ok "8085 taken: the page is on 8086, through the tunnel too, and says so" + else + bad "8085 taken: no page on 8086 through the tunnel (tests/out/logcat-port.txt)" + fi + c=$(page "http://${TUN:-0}:8085/") + if [ "$c" = 000 ]; then ok "8085 through the tunnel is refused (the other program's port)"; else + bad "8085 through the tunnel answered $c: another program's page"; fi + $ADB reverse --remove tcp:8085 >/dev/null 2>&1 || true +fi + $ADB logcat -d -b crash > "$OUT/crash.log" 2>&1 || true if grep -q "$PKG" "$OUT/crash.log"; then bad "crash in logcat (tests/out/crash.log)"; else ok "no crash"; fi