travelmate: update to 3.0.0, rewrite in ucode

Description:
travelmate 3.0.0, backend rewritten in ucode as procd daemon.
Major release for master only, no backport to 25.x.

- captive portal login scripts are ucode scripts (/etc/travelmate/*.uc),
  shell scripts are no longer supported; shipped scripts are ported
- vpn: every netifd vpn protocol is supported, the service follows the
  interface protocol
- the scan file is now JSON
- mail template is a ucode template
- new timeout defaults: trm_timeout 30s
- external commands (curl, msmtp, wifi, login scripts, ...) run directly
  via argv, no shell is involved; lookup() uses the ucode resolver
  (new dependency ucode-mod-resolv)

Compile tested: private build based on OpenWrt SNAPSHOT (r37596-df70de353d)
Run tested: Cudy TR3000 v1, mediatek/filogic, OpenWrt SNAPSHOT (r37596-df70de353d)

Co-authored-by: Claude <noreply@anthropic.com>
Signed-off-by: Dirk Brenken <dev@brenken.org>
This commit is contained in:
Dirk BrenkenandClaude committed 2026-10-30 08:46:53 +01:00
1 parent a07832959f
commit 8398abfce7
31 files changed
+3023 -2170

No files matched your search

+17 -14
View File
@@ -6,19 +6,20 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=travelmate
PKG_VERSION:=2.4.9
PKG_RELEASE:=6
PKG_VERSION:=3.0.0
PKG_RELEASE:=1
PKG_LICENSE:=GPL-3.0-or-later
PKG_MAINTAINER:=Dirk Brenken <dev@brenken.org>
include $(INCLUDE_DIR)/package.mk
define Package/travelmate
SECTION:=net
CATEGORY:=Network
TITLE:=A wlan connection manager for travel router
DEPENDS:=+iwinfo +jshn +jsonfilter +curl +ca-bundle +rpcd +rpcd-mod-rpcsys
PKGARCH:=all
SECTION:=net
CATEGORY:=Network
TITLE:=A wlan connection manager for travel router
DEPENDS:=+ucode +ucode-mod-fs +ucode-mod-ubus +ucode-mod-uci +ucode-mod-log +ucode-mod-resolv \
+curl +ca-bundle +rpcd +rpcd-mod-rpcsys +rpcd-mod-iwinfo
PKGARCH:=all
endef
define Package/travelmate/description
@@ -41,25 +42,27 @@ define Build/Compile
endef
define Package/travelmate/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) ./files/travelmate-service.sh $(1)/usr/bin
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_BIN) ./files/travelmate.uc $(1)/usr/sbin/travelmate
$(INSTALL_DIR) $(1)/usr/share/ucode/travelmate
$(INSTALL_DATA) ./src/*.uc $(1)/usr/share/ucode/travelmate/
$(INSTALL_DIR) $(1)/etc/init.d
$(INSTALL_BIN) ./files/travelmate.init $(1)/etc/init.d/travelmate
$(INSTALL_DIR) $(1)/usr/lib
$(INSTALL_CONF) ./files/travelmate-functions.sh $(1)/usr/lib
$(INSTALL_DIR) $(1)/etc/hotplug.d/ntp
$(INSTALL_BIN) ./files/25-travelmate.hotplug $(1)/etc/hotplug.d/ntp/25-travelmate
$(INSTALL_DIR) $(1)/etc/uci-defaults
$(INSTALL_BIN) ./files/travelmate.uci-defaults $(1)/etc/uci-defaults/95_travelmate
$(INSTALL_DIR) $(1)/etc/config
$(INSTALL_CONF) ./files/travelmate.conf $(1)/etc/config/travelmate
$(INSTALL_DIR) $(1)/etc/travelmate
$(INSTALL_BIN) ./files/login/*.uc $(1)/etc/travelmate
$(INSTALL_CONF) ./files/mail.template $(1)/etc/travelmate
$(INSTALL_BIN) ./files/travelmate.vpn $(1)/etc/travelmate
$(INSTALL_BIN) ./files/*.login $(1)/etc/travelmate
endef
$(eval $(call BuildPackage,travelmate))
+41 -42
View File
@@ -50,8 +50,8 @@ For a typical setup these few steps are enough to get travelmate up and running
* Continuously checks the existing uplink quality, e.g. for conditional uplink (dis)connections
* Automatically add open uplinks to your wireless config, e.g. hotel captive portals
* Captive portal detection with a 'heartbeat' function to keep the uplink connection up and running
* Captive portal hook for auto-login configured via uci/LuCI, using an external script (see the examples below)
* VPN hook supports 'wireguard' or 'openvpn' client setups to handle VPN (re)connections automatically
* Captive portal hook for auto-login configured via uci/LuCI, using an external ucode script (see the examples below)
* VPN hook handles VPN (re)connections automatically, for 'wireguard', 'openvpn' and every other vpn protocol netifd brings up, e.g. 'openconnect' or 'vpnc'
* E-mail hook via 'msmtp' sends notification e-mails after every successful uplink connect
* Proactively scan and switch to a higher priority uplink, replacing an existing connection
* Check router subnet vs. uplink subnet, to show conflicts with the router LAN network
@@ -71,8 +71,9 @@ For a typical setup these few steps are enough to get travelmate up and running
* 'dnsmasq' as dns backend
* 'ubus iwinfo' for wlan scanning
* 'curl' for connection checking and all kinds of captive portal magic, e.g. cp detection and auto-logins
* The `travelmate` package brings the 'ucode' interpreter and its fs, ubus, uci and log modules, the backend is written in ucode
* a 'wpad' variant to support various WPA encrypted networks (WEP-based uplinks are no longer supported!)
* optional: 'wireguard' or 'openvpn' for vpn client connections
* optional: a vpn client like 'wireguard', 'openvpn' or another netifd vpn protocol for vpn client connections
* optional: 'msmtp' to send out travelmate related status messages via e-mail
<a id="installation-and-usage"></a>
@@ -125,7 +126,7 @@ Available commands:
info Dump procd service info
```
The `setup` sub-command is the CLI equivalent of the LuCI **Interface Wizard** and only needs to be run once. The `scan` sub-command writes its result to `/var/run/travelmate/travelmate.scan`, sorted by signal quality, and is used by the **Wireless Stations** tab in LuCI as well.
The `setup` sub-command is the CLI equivalent of the LuCI **Interface Wizard** and only needs to be run once. The `scan` sub-command writes its result as JSON array to `/var/run/travelmate/travelmate.scan`, sorted by signal quality, and is used by the **Wireless Stations** tab in LuCI as well.
The `status` sub-command prints the current runtime information:
@@ -133,15 +134,15 @@ The `status` sub-command prints the current runtime information:
~# /etc/init.d/travelmate status
::: travelmate runtime information
+ travelmate_status : connected, net ok/100
+ frontend_ver : 2.4.7-1
+ backend_ver : 2.4.7-1
+ station_id : radio0/GlutenfreiVerbunden/-
+ station_mac : 42:40:45:EC:B3:D1
+ station_interfaces : wwan, -
+ station_subnet : 10.168.20.0 (lan: 10.200.1.0)
+ run_flags : autoadd: ✘, captive: ✔, eviltwin: ✘, mail: ✔, netcheck: ✘, ntp: ✔, proactive: ✔, randomize: ✔, vpn: ✘
+ last_run : mode: start, date / time: 2026-08-06 09:08:24, memory: 412.35 MB available
+ system_info : cores: 2, fetch: curl, Cudy TR3000 v1, mediatek/filogic, OpenWrt SNAPSHOT (r32287-1c7ec8ab19)
+ frontend_ver : 3.0.0-r1
+ backend_ver : 3.0.0-r1
+ station_id : radio0/blackhole.nl/-
+ station_mac : 26:b7:ad:14:08:f7
+ station_interfaces : wwan, wireguard
+ station_subnet : 192.168.1.0 (lan: 10.200.1.0)
+ run_flags : autoadd: ✔, captive: ✔, eviltwin: ✘, mail: ✔, netcheck: ✔, ntp: ✔, proactive: ✔, randomize: ✔, vpn: ✔
+ last_run : mode: start, date / time: 2026-10-21 17:34:13, memory: 306.00 MB available
+ system_info : cores: 2, fetch: curl, Cudy TR3000 v1, mediatek/filogic, OpenWrt SNAPSHOT (r37596-df70de353d)
```
The `travelmate_status` field reports one of the following states:
@@ -174,11 +175,11 @@ A stopped service does not report a state at all, it truncates the runtime file
| trm_ssidfilter | -, not set | list of SSID patterns for filtering/skipping specific open uplinks, e.g. 'Chromecast*' |
| trm_randomize | 0, disabled | generate a random unicast MAC address for each uplink connection |
| trm_eviltwin | 0, disabled | detect and skip access points with locally administered (LAA) BSSIDs to mitigate evil twin attacks |
| trm_triggerdelay | 2 | additional trigger delay in seconds before travelmate processing begins |
| trm_triggerdelay | 5 | additional trigger delay in seconds before travelmate processing begins |
| trm_maxretry | 3 | retry limit to connect to an uplink, set to '0' for unlimited retries |
| trm_minquality | 35 | minimum signal quality threshold as percent for conditional uplink (dis-) connections |
| trm_maxwait | 30 | how long should travelmate wait for a successful wlan uplink connection |
| trm_timeout | 60 | overall retry timeout in seconds |
| trm_timeout | 30 | overall retry timeout in seconds |
| trm_maxautoadd | 5 | limit the max. number of automatically added open uplinks. To disable this limitation set it to '0' |
| trm_captiveurl | http://detectportal.firefox.com | custom/pre-configured provider URLs that will be used for connectivity- and captive portal checks |
| trm_useragent | Mozilla/5.0 ... | pre-configured user agents that will be used for connectivity- and captive portal checks |
@@ -189,7 +190,7 @@ A stopped service does not report a state at all, it truncates the runtime file
| trm_mailtopic | travelmate connection to '<sta>' | topic for travelmate notification E-Mails |
| trm_mailprofile | trm_notify | profile used by 'msmtp' for travelmate notification E-Mails |
| trm_vpn | 0, disabled | VPN connections will be managed by travelmate |
| trm_stdvpnservice | -, not set | standard vpn service which will be automatically added to new STA profiles |
| trm_vpnifacelist | -, not set | limit vpn processing to these interfaces, default: all wireguard/openvpn and all referenced vpn ones |
| trm_stdvpniface | -, not set | standard vpn interface which will be automatically added to new STA profiles |
**Please note:** 'trm_netcheck' is evaluated independently of 'trm_captive'. A detected captive portal does not count as an error as long as 'trm_captive' is enabled - such an uplink stays connected so that a manual or script based portal login is still possible. With 'trm_captive' disabled travelmate can neither allowlist the portal domain nor run a login script, so a detected portal is treated like a failed connectivity check. Only a failed connectivity check counts, and it is confirmed by a second probe before it is acted on. Such a failure is then handled like a failed connection attempt: after 'trm_maxretry' tries the affected uplink gets disabled in the travelmate config. A longer lasting outage of your upstream provider may therefore disable all configured uplinks, which have to be re-enabled manually.
@@ -207,8 +208,7 @@ A stopped service does not report a state at all, it truncates the runtime file
| script_args | -, not set | optional runtime args for the auto login script |
| macaddr | -, not set | use a specified MAC address for the uplink |
| vpn | 0, disabled | automatically handle VPN (re-) connections |
| vpnservice | -, not set | reference the already configured 'wireguard' or 'openvpn' client instance as vpn provider |
| vpniface | -, not set | the logical vpn interface, e.g. 'wg0' or 'tun0' |
| vpniface | -, not set | the logical vpn interface, e.g. 'wg0' |
<a id="examples"></a>
## Examples
@@ -218,14 +218,11 @@ Please read one of the following guides to get a working vpn client setup on you
* [Wireguard client setup guide](https://openwrt.org/docs/guide-user/services/vpn/wireguard/client)
* [OpenVPN client setup guide](https://openwrt.org/docs/guide-user/services/vpn/openvpn/client-luci)
Make sure to uncheck the "Bring up on boot" option during vpn interface setup, so that netifd doesn't interfere with travelmate. Also prevent potential vpn protocol autostarts, e.g. add an additional 'globals' section in newer openvpn uci configs:
Make sure to uncheck the "Bring up on boot" option during vpn interface setup, so that netifd doesn't interfere with travelmate.
```
config globals 'globals'
option autostart '0'
```
Once your vpn client connection setup is correct, you can reference the vpn interface in travelmate ('vpniface' per uplink or 'trm_stdvpniface' for new uplinks) to handle VPN (re-) connections automatically. Travelmate takes the vpn interface up and down via netifd, the vpn service follows its protocol: 'wireguard' and 'openvpn' interfaces are always known, interfaces with any other protocol (e.g. 'openconnect', 'vpnc', 'l2tp') are handled as soon as they are referenced or listed in 'trm_vpnifacelist'. The former 'vpnservice' and 'trm_stdvpnservice' options are gone.
Once your vpn client connection setup is correct, you can reference that config in travelmate to handle VPN (re-) connections automatically.
**Please note:** OpenVPN is a netifd protocol ('proto openvpn') now, the former setup with an openvpn init instance on a 'proto none' interface is no longer supported. Uplinks that referenced such an interface are pointed to the migrated openvpn interface on update.
**E-Mail setup**
To use e-mail notifications you have to set up the package 'msmtp'. Modify the file `/etc/msmtprc`, e.g. for gmail:
@@ -249,21 +246,23 @@ password zzz
Finally enable e-mail support in travelmate and add a valid e-mail receiver address.
**Captive portal auto-logins**
For automated captive portal logins you can reference an external shell script per uplink. All login scripts have to be executable and located in `/etc/travelmate` with the extension `.login`. A login script signals its result via the exit code: `0` means the login succeeded, any other value means it failed. Only `0` makes travelmate re-check the connectivity right away, every other value is just logged. The package ships multiple ready to run auto-login scripts:
The mail body is rendered from the ucode template `/etc/travelmate/mail.template` (option 'trm_mailtemplate'), which gets `banner`, `board` (ubus 'system board'), `status` (as printed by `/etc/init.d/travelmate status`) and `station_id` as variables.
* 'wifibahn.login' for german DB railway hotspots
* 'telekom.login' for telekom hotspots (DE)
* 'vodafone.login' for vodafone hotspots (DE)
* 'generic-user-pass.login' a template to demonstrate the optional parameter handling in login scripts
**Captive portal auto-logins**
For automated captive portal logins you can reference an external ucode script per uplink. All login scripts have to be executable and located in `/etc/travelmate` with the extension `.uc`, shell scripts (formerly `.login`) are no longer supported. On upgrade, an uplink that still references one of the shipped `.login` scripts is switched to the `.uc` script of the same name. A login script signals its result via the exit code: `0` means the login succeeded, any other value means it failed. Only `0` makes travelmate re-check the connectivity right away, every other value is just logged. The package ships multiple ready to run auto-login scripts:
* 'wifibahn.uc' for german DB railway hotspots
* 'telekom.uc' for telekom hotspots (DE)
* 'vodafone.uc' for vodafone hotspots (DE)
* 'generic-user-pass.uc' a template to demonstrate the optional parameter handling in login scripts
A typical and successful captive portal login looks like this:
```
[...]
user.info trm-2.4.7-1[26222]: captive portal domain 'www.wifibahn.de' added to dhcp rebind allowlist
user.info trm-2.4.7-1[26222]: captive portal login script for 'www.wifibahn.de' has been finished with rc '0'
user.info trm-2.4.7-1[26222]: connected to uplink 'radio1/WIFI@DB/-' with mac 'B2:9D:F5:96:86:A4' (1/3)
user.info trm-3.0.0-r1[26222]: captive portal domain 'www.wifibahn.de' added to dhcp rebind allowlist
user.info trm-3.0.0-r1[26222]: captive portal login script for 'www.wifibahn.de' has been finished with rc '0'
user.info trm-3.0.0-r1[26222]: connected to uplink 'radio1/WIFI@DB/-' with mac 'B2:9D:F5:96:86:A4' (1/3)
[...]
```
**Building your own login script**
@@ -273,10 +272,10 @@ The fastest way to a working script is to record the login once by hand and then
2. Open the developer tools (usually `F12`) and switch to the `Network` tab. Enable `Preserve log` (Chromium, Edge, Safari) resp. `Persist Logs` (Firefox, behind the gear icon) and `Disable cache`. A portal login almost always ends in a redirect, and without these options the recorded entries are dropped at that point.
3. Perform the login manually and watch which requests are sent.
4. Right-click the request that carries your credentials and choose `Copy` -> `Copy as cURL`. You now have the exact URL, method, headers, cookies and form fields as the browser sent them. `Save All As HAR` resp. `Export HAR` records the whole session if you want to study it later - note that recent Chromium versions strip cookies and authorization headers from the export unless you allow sensitive data in the devtools settings.
5. Strip the copied command down: the browser adds a lot of `Accept*`, `Sec-*` and `Priority` headers that no portal cares about. Keep the request body, the `Content-Type` and whatever the portal actually validates, then replace curl's flags with travelmate's `${trm_fetchcmd} ${trm_fetchparm}` and `--user-agent "${trm_useragent}"`.
6. Look for values that are only valid for one session - CSRF tokens, session ids, `sid` parameters. Those must not be copied into the script but fetched at runtime, see `wifibahn.login` (cookie jar plus awk) or `vodafone.login` (json response plus jsonfilter) for the two usual patterns.
7. Never hardcode credentials. Pass them via the uplink's `script_args` option and read them as `${1}` and `${2}`, like `generic-user-pass.login` does.
8. Test the script on the router while the portal is actually in the way: `sh -x /etc/travelmate/my.login user pass; echo "rc: ${?}"`. Make sure it only exits `0` when the login really succeeded - a script that reports success too eagerly is worse than one that fails, because travelmate will happily keep the uplink.
5. Strip the copied command down: the browser adds a lot of `Accept*`, `Sec-*` and `Priority` headers that no portal cares about. Keep the request body, the `Content-Type` and whatever the portal actually validates, and pass them as `args` to `fetch()` from the `travelmate.login` module. `fetch(url, { args: [ '--data', 'a=b' ] })` runs curl with travelmate's own settings (timeouts, uplink device, user agent) and returns `{ rc, body }`, `follow: false` keeps curl from following redirects and `write_out` adds a curl `--write-out` format. The module also provides `lookup()`, `urlencode()`, `between()` (text between two tags, the usual way to cut an url out of a portal page), `https_on(url, host)` (check an url taken from a portal page before credentials are sent to it) and the configured `captiveurl` and `useragent`.
6. Look for values that are only valid for one session - CSRF tokens, session ids, `sid` parameters. Those must not be copied into the script but fetched at runtime, see `wifibahn.uc` (cookie jar) or `vodafone.uc` (json response) for the two usual patterns.
7. Never hardcode credentials. Pass them via the uplink's `script_args` option and read them as `ARGV[0]` and `ARGV[1]`, like `generic-user-pass.uc` does.
8. Test the script on the router while the portal is actually in the way: `ucode /etc/travelmate/my.uc user pass; echo "rc: ${?}"`. Make sure it only exits `0` when the login really succeeded - a script that reports success too eagerly is worse than one that fails, because travelmate will happily keep the uplink.
The portal domain travelmate detected is in the system log: `logread -e "trm-"` shows it as `captive portal domain '<domain>' added to dhcp rebind allowlist`.
@@ -291,9 +290,9 @@ If your router has more than one radio, keep the AP and the uplink on separate r
`trm_minquality` (default 35%) decides twice: a scan result below the threshold is not considered as a connection candidate at all, and an existing connection that drops below it is torn down so that travelmate can look for something better. Raising the value makes travelmate switch away earlier, lowering it keeps weak uplinks alive longer. Values well above 50% tend to make travelmate restless in hotels.
**Retry behaviour**
`trm_maxretry` (default 3) limits the connection attempts per uplink. When the limit is reached, the affected uplink is disabled in the travelmate config and has to be re-enabled manually - which is intentional for permanently broken credentials, but worth keeping in mind in combination with `trm_netcheck`. Set `trm_maxretry` to '0' for unlimited retries if you never want an uplink to be disabled automatically.
`trm_maxretry` (default 3) limits the connection attempts per uplink. When the limit is reached, the affected uplink is disabled in the travelmate config and has to be re-enabled manually - which is intentional for permanently broken credentials, but worth keeping in mind in combination with `trm_netcheck`. Set `trm_maxretry` to '0' for unlimited retries if you never want an uplink to be disabled automatically. The disable shows up in the log as `uplink has been disabled '<radio>/<ssid>/<bssid>' (3/3)`, re-enable the uplink with the **On/Off** button in the LuCI station list or via `uci set travelmate.<section>.enabled='1'` and `uci commit travelmate`. With only one configured uplink, consider `revive` (see below), otherwise a longer outage or a slow radio after a wifi reload leaves you without uplink until you step in.
Per uplink, `revive` softens that. With a value of n, an uplink disabled by the retry limit is set back to 'enabled' after n run cycles, so a network that was only temporarily unavailable comes back on its own. Values below 10 are raised to 10, since a run cycle is roughly `trm_timeout` seconds long and shorter intervals only produce needless reconnect attempts. The number of revivals is capped by the global `trm_maxretry`, which also means that `revive` has no effect with `trm_maxretry` set to '0'. The cycle and round counters are kept in the runtime file '/var/run/travelmate/travelmate.revive', they are never written to the config and are cleared when the service is stopped. The enable and disable itself is still recorded in the travelmate config, so the LuCI station list always shows the real state.
Per uplink, `revive` softens that. With a value of n, an uplink disabled by the retry limit is set back to 'enabled' after n run cycles, so a network that was only temporarily unavailable comes back on its own. Values below 10 are raised to 10, since a run cycle is roughly `trm_timeout` seconds long and shorter intervals only produce needless reconnect attempts. The number of revivals is capped by the global `trm_maxretry`, which also means that `revive` has no effect with `trm_maxretry` set to '0'. The cycle and round counters are kept in the runtime file '/var/run/travelmate/travelmate.revive', they are never written to the config and are cleared when the service is stopped or restarted, e.g. by a config change, so an uplink switched off by hand stays off. A successful connection clears the counters of that uplink. The enable and disable itself is still recorded in the travelmate config, so the LuCI station list always shows the real state.
**Open uplinks**
`trm_autoadd` adds open networks to your wireless config on the fly, which is handy in hotels and on trains. Keep `trm_maxautoadd` at a sane value so that a busy location doesn't flood your config, and use `trm_ssidfilter` to skip the usual noise, e.g. `Chromecast*` or printer and camera SSIDs.
@@ -302,7 +301,7 @@ Per uplink, `revive` softens that. With a value of n, an uplink disabled by the
`trm_randomize` generates a new random unicast MAC address for each uplink connection, so a hotspot operator can't trivially recognize your router across visits. `trm_eviltwin` skips access points with a locally administered (LAA) BSSID, which is a cheap indicator for a spoofed access point - note that some legit setups (mesh, repeaters) use LAA BSSIDs as well.
**Timing**
`trm_maxwait` (default 30s) is the budget for a single connection attempt and also scales the internal curl timeouts. On slow uplinks or with captive portals that take their time, raising it to 45-60s helps, lowering it makes travelmate give up on weak candidates faster. `trm_triggerdelay` adds a delay before processing starts after an ifup event, which is useful if your uplink needs a moment to settle.
`trm_maxwait` (default 30s) is the budget for a single connection attempt (association and DHCP) and scales the internal wait times, the curl requests use a fixed timeout of 5s per attempt. Some drivers need 30s and more to associate after a wifi reload, if attempts regularly time out ('uplink connection could not be established after ... seconds'), raise it to 45-60s. Lowering it makes travelmate give up on weak candidates faster. `trm_triggerdelay` adds a delay before processing starts after an ifup event, which is useful if your uplink needs a moment to settle.
**Subnet conflicts**
Travelmate compares the uplink subnet against your router LAN network and logs a warning if both overlap. If you run into this frequently, change your LAN network to something uncommon, e.g. `10.200.1.0/24`, because most hotel networks use `192.168.0.0/24` or `192.168.1.0/24`.
@@ -314,9 +313,9 @@ Travelmate provides an optional debug mode that writes detailed diagnostic infor
Whenever you encounter travelmate related processing problems, please enable `trm_debug`, restart travelmate and check the `Log View` tab in LuCI (or the syslog via `logread -e "trm-"`).
Typical symptoms:
* No uplink is found although it is in range: compare the reported signal quality in the debug log against `trm_minquality`, and make sure the uplink is still enabled in the travelmate config - the retry limit may have disabled it
* No uplink is found although it is in range: compare the reported signal quality in the debug log against `trm_minquality`, and make sure the uplink is still enabled in the travelmate config - the retry limit may have disabled it (log line `uplink has been disabled`, see 'Retry behaviour' above)
* An uplink connects but has no internet: the debug output of `f_net` shows the probe host, the effective url and the resulting state (`net ok`, `net cp '<domain>'` or `net nok`). A `net cp` state means a captive portal was detected and is waiting for a login
* A captive portal login script doesn't run: it has to be executable and located in `/etc/travelmate` with the extension `.login`, everything else is rejected for security reasons
* A captive portal login script doesn't run: it has to be an executable ucode script located in `/etc/travelmate` with the extension `.uc`, everything else is rejected for security reasons
* The connection drops right after connecting: check for a subnet conflict warning between the uplink network and your router LAN network
<a id="support"></a>
+1 -3
View File
@@ -7,7 +7,6 @@
# shellcheck disable=all
trm_init="/etc/init.d/travelmate"
trm_funlib="/usr/lib/travelmate-functions.sh"
trm_ntplock="/var/run/travelmate/travelmate.ntp.lock"
# ensure runtime directory exists
@@ -23,7 +22,6 @@ case "${stratum}" in
esac
if [ "${ACTION}" = "stratum" ] && "${trm_init}" enabled; then
if mkdir "${trm_ntplock}" 2>/dev/null; then
. "${trm_funlib}"
f_log "info" "get ntp time sync (stratum: ${stratum:-"-"})"
logger -p user.info -t "trm-ntp" "get ntp time sync (stratum: ${stratum:-"-"})"
fi
fi
@@ -1,28 +0,0 @@
#!/bin/sh
# captive portal auto-login script template with credentials as parameters
# Copyright (c) 2020-2026 Dirk Brenken (dev@brenken.org)
# This is free software, licensed under the GNU General Public License v3.
# set (s)hellcheck exceptions
# shellcheck disable=all
export LC_ALL=C
export PATH="/usr/sbin:/usr/bin:/sbin:/bin"
trm_funlib="/usr/lib/travelmate-functions.sh"
if [ -z "${trm_bver}" ]; then
. "${trm_funlib}"
f_conf
fi
user="${1}"
password="${2}"
trm_domain="example.com"
if ! "${trm_lookupcmd}" "${trm_domain}" >/dev/null 2>&1; then
exit 1
fi
# login with credentials
#
"${trm_fetchcmd}" ${trm_fetchparm} --user-agent "${trm_useragent}" --header "Content-Type:application/x-www-form-urlencoded" --data "username=${user}&password=${password}" --output /dev/null "http://${trm_domain}"
[ "${?}" = "0" ] && exit 0 || exit 255
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/ucode
// captive portal auto-login script template with credentials as parameters
// Copyright (c) 2020-2026 Dirk Brenken (dev@brenken.org)
// This is free software, licensed under the GNU General Public License v3.
import { fetch, lookup } from 'travelmate.login';
let user = ARGV[0] ?? '', password = ARGV[1] ?? '';
let domain = 'example.com';
if (!lookup(domain))
exit(1);
// login with credentials
let r = fetch('http://' + domain, { args: [ '--header', 'Content-Type:application/x-www-form-urlencoded',
'--data', 'username=' + user + '&password=' + password, '--output', '/dev/null' ] });
exit(r.rc == 0 ? 0 : 255);
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/ucode
// captive portal auto-login script for telekom hotspots (DE)
// Copyright (c) 2021-2026 Dirk Brenken (dev@brenken.org)
// This is free software, licensed under the GNU General Public License v3.
import { fetch, lookup, urlencode, between, https_on, captiveurl } from 'travelmate.login';
let username = urlencode(ARGV[0] ?? ''), password = urlencode(ARGV[1] ?? '');
let domain = 'hotspot.t-mobile.net';
if (!lookup(domain))
exit(1);
// get redirect url
let redirect_url = replace(between(fetch(captiveurl).body, '<loginurl>', '</loginurl>'), /&amp;/g, '&');
// the credentials go to the hotspot host via https only
if (!https_on(redirect_url, domain))
exit(1);
// final login request
let r = fetch(redirect_url, { args: [ '--referer', 'https://' + domain + '/wlan/rest/freeLogin',
'--header', 'content-type: application/x-www-form-urlencoded',
'--data', 'UserName=' + username + '&Password=' + password + '&FNAME=0&button=Login&OriginatingServer=' + urlencode(captiveurl) ] });
exit(length(between(r.body, '<logoffurl>', '</logoffurl>')) ? 0 : 255);
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/ucode
// captive portal auto-login script for vodafone hotspots (DE)
// Copyright (c) 2021-2026 Dirk Brenken (dev@brenken.org)
// This is free software, licensed under the GNU General Public License v3.
import { fetch, lookup, captiveurl } from 'travelmate.login';
let username = ARGV[0] ?? '', password = ARGV[1] ?? '';
let domain = 'hotspot.vodafone.de';
if (!lookup(domain))
exit(1);
// get sid, from the redirect the portal answers with
let redirect_url = fetch(captiveurl, { follow: false, write_out: '%{redirect_url}', args: [ '--output', '/dev/null' ] }).body;
let sid = split(redirect_url, /[=&]/)[1] ?? '';
if (!length(sid))
exit(1);
// get session
let raw = fetch('https://' + domain + '/api/v4/session?sid=' + sid,
{ args: [ '--referer', 'http://' + domain + '/portal/?sid=' + sid ] }).body;
let res = null;
try { res = json(raw); } catch (e) { }
let session = res?.session;
if (session == null || !length('' + session))
exit(2);
// login profile 4: csc community account
let ids = map(res?.loginProfiles ?? [], (p) => '' + p?.id);
if (index(ids, '4') < 0)
exit(3);
// final login request
if (length(username) && length(password))
raw = fetch('https://' + domain + '/api/v4/login?sid=' + sid, { args: [ '--referer', 'http://' + domain + '/portal/?sid=' + sid,
'--data', 'loginProfile=4&accessType=csc-community&accountType=csc&password=' + password +
'&session=' + session + '&username=' + username ] }).body;
res = null;
try { res = json(raw); } catch (e) { }
exit(('' + res?.success) == 'true' ? 0 : 255);
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/ucode
// captive portal auto-login script for bahn/ICE hotspots (DE)
// Copyright (c) 2020-2026 Dirk Brenken (dev@brenken.org)
// This is free software, licensed under the GNU General Public License v3.
import { readfile, unlink } from 'fs';
import { fetch, lookup } from 'travelmate.login';
let domain = 'wifi.bahn.de';
if (!lookup(domain)) {
domain = 'login.wifionice.de';
if (!lookup(domain))
exit(1);
}
// current cna portal api
let r = fetch('https://' + domain + '/cna/logon', { args: [ '--header', 'Content-Type: application/json',
'--header', 'X-Requested-With: XMLHttpRequest', '--header', 'X-Csrf-Token: csrf',
'--header', 'Referer: https://' + domain + '/cna/', '--data', '{}' ] });
if (index(r.body, 'success') >= 0)
exit(0);
// legacy portal api, get security token from the cookie jar
let jar = '/var/run/travelmate/' + domain + '.cookie', token = '';
if (fetch('https://' + domain + '/en/', { args: [ '--cookie-jar', jar, '--output', '/dev/null' ] }).rc == 0) {
for (let l in split(readfile(jar) ?? '', '\n'))
if (index(l, 'csrf') >= 0)
token += (split(trim(l, ' \t'), /[ \t]+/)[6] ?? '') + '\n';
token = rtrim(token, '\n');
}
unlink(jar);
if (!length(token))
exit(2);
// legacy portal api, final post request
r = fetch('https://' + domain + '/en/', { args: [ '--header', 'Cookie: csrf=' + token,
'--data', 'login=true&CSRFToken=' + token, '--output', '/dev/null' ] });
exit(r.rc == 0 ? 0 : 255);
+35 -22
View File
@@ -1,27 +1,40 @@
# travelmate mail template/include - a wlan connection manager for travel router
# Copyright (c) 2016-2026 Dirk Brenken (dev@brenken.org)
# This is free software, licensed under the GNU General Public License v3.
{%-
// travelmate mail template (ucode), variables: banner, board (ubus system
// board), status (as 'travelmate status'), station_id; html() escapes them
# info preparation
#
local travelmate_status station_info system_info mail_text
function html(s) {
return replace('' + (s ?? ''), /[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
travelmate_status="$(/etc/init.d/travelmate status 2>/dev/null)"
system_info="$(strings /etc/banner 2>/dev/null
"${trm_ubuscmd}" call system board |
"${trm_awkcmd}" 'BEGIN{FS="[{}\"]"}{if($2=="kernel"||$2=="hostname"||$2=="system"||$2=="model"||$2=="description")printf " + %-12s: %s\n",$2,$4}')"
station_info="$("${trm_jsoncmd}" -i "${trm_rtfile}" -q -l1 -e '@.data.station_id')"
let info = [];
# content header
#
mail_text="$(printf "%s\n" "<html><body><pre style='font-family:monospace;padding:20;background-color:#f3eee5;white-space:pre-wrap;overflow-x:auto;' >")"
for (let l in split(banner ?? '', '\n'))
if (length(trim(l)) >= 4)
push(info, rtrim(l));
# content body
#
mail_text="$(printf "%s\n" "${mail_text}\n<strong>++\n++ System Information ++\n++</strong>\n${system_info:-"-"}")"
mail_text="$(printf "%s\n" "${mail_text}\n\n<strong>++\n++ Travelmate Status ++\n++</strong>\n${travelmate_status:-"-"}")"
[ -n "${station_info}" ] && mail_text="$(printf "%s\n" "${mail_text}\n\n<strong>++\n++ Connection Status ++\n++</strong>\ntravelmate connection to ${station_info}")"
for (let k in [ 'kernel', 'hostname', 'system', 'model' ])
if (board?.[k] != null)
push(info, sprintf(' + %-12s: %s', k, board[k]));
# content footer
#
mail_text="$(printf "%s\n" "${mail_text}</pre></body></html>")"
if (board?.release?.description != null)
push(info, sprintf(' + %-12s: %s', 'description', board.release.description));
-%}
<html><body><pre style='font-family:monospace;padding:20;background-color:#f3eee5;white-space:pre-wrap;overflow-x:auto;' >
<strong>++
++ System Information ++
++</strong>
{{ html(length(info) ? join('\n', info) : '-') }}
<strong>++
++ Travelmate Status ++
++</strong>
{{ html(rtrim(status ?? '') || '-') }}
{%- if (length(station_id ?? '')): %}
<strong>++
++ Connection Status ++
++</strong>
travelmate connection to {{ html(station_id) }}
{%- endif %}
</pre></body></html>
-57
View File
@@ -1,57 +0,0 @@
#!/bin/sh
# captive portal auto-login script for telekom hotspots (DE)
# Copyright (c) 2021-2026 Dirk Brenken (dev@brenken.org)
# This is free software, licensed under the GNU General Public License v3.
# set (s)hellcheck exceptions
# shellcheck disable=all
# url encoding function
#
urlencode() {
local chr str="${1}" len="${#1}" pos=0
while [ "${pos}" -lt "${len}" ]; do
chr="${str:pos:1}"
case "${chr}" in
[a-zA-Z0-9.~_-])
printf "%s" "${chr}"
;;
" ")
printf "%%20"
;;
*)
printf "%%%02X" "'${chr}"
;;
esac
pos=$((pos + 1))
done
}
export LC_ALL=C
export PATH="/usr/sbin:/usr/bin:/sbin:/bin"
trm_funlib="/usr/lib/travelmate-functions.sh"
if [ -z "${trm_bver}" ]; then
. "${trm_funlib}"
f_conf
fi
username="$(urlencode "${1}")"
password="$(urlencode "${2}")"
trm_domain="hotspot.t-mobile.net"
if ! "${trm_lookupcmd}" "${trm_domain}" >/dev/null 2>&1; then
exit 1
fi
# get redirect url
#
raw_html="$("${trm_fetchcmd}" ${trm_fetchparm} --user-agent "${trm_useragent}" "${trm_captiveurl}")"
redirect_url="$(printf "%s" "${raw_html}" | "${trm_awkcmd}" 'match(tolower($0),/<loginurl>.*<\/loginurl>/){printf "%s",substr($0,RSTART+10,RLENGTH-21)}' 2>/dev/null | "${trm_awkcmd}" '{gsub("&amp;","\\&");printf "%s",$0}' 2>/dev/null)"
[ -z "${redirect_url}" ] && exit 1
# final login request
#
raw_html="$("${trm_fetchcmd}" ${trm_fetchparm} --user-agent "${trm_useragent}" --referer "https://${trm_domain}/wlan/rest/freeLogin" --header "content-type: application/x-www-form-urlencoded" --data "UserName=${username}&Password=${password}&FNAME=0&button=Login&OriginatingServer=http%3A%2F%2F${trm_captiveurl}" "${redirect_url}")"
login_url="$(printf "%s" "${raw_html}" | "${trm_awkcmd}" 'match(tolower($0),/<logoffurl>.*<\/logoffurl>/){printf "%s",substr($0,RSTART+11,RLENGTH-23)}' 2>/dev/null)"
[ -n "${login_url}" ] && exit 0 || exit 255
File diff suppressed because it is too large. Load diff
@@ -1,56 +0,0 @@
#!/bin/sh
# travelmate service script, a wlan connection manager for travel router
# Copyright (c) 2016-2026 Dirk Brenken (dev@brenken.org)
# This is free software, licensed under the GNU General Public License v3.
# set (s)hellcheck exceptions
# shellcheck disable=all
# initial defaults
#
export LC_ALL=C
export PATH="/usr/sbin:/usr/bin:/sbin:/bin"
trm_funlib="/usr/lib/travelmate-functions.sh"
trm_action="${1}"
# source required system libraries and perform initial checks
#
if [ -z "${trm_bver}" ]; then
. "${trm_funlib}"
f_conf
fi
# control travelmate actions
#
while :; do
# handle service stop and start actions, then execute main loop
#
if [ "${trm_action}" = "stop" ]; then
if [ -s "${trm_pidfile}" ]; then
f_log "info" "travelmate instance stopped ::: action: ${trm_action}, pid: $("${trm_catcmd}" "${trm_pidfile}")"
: >"${trm_rtfile}"
: >"${trm_revivefile}"
: >"${trm_pidfile}"
fi
break
elif [ -n "${trm_action}" ]; then
f_log "info" "travelmate instance started ::: action: ${trm_action}, pid: ${$}"
f_main
trm_action=""
fi
# wait for next action
#
while :; do
sleep "${trm_timeout}" 0 >/dev/null 2>&1
rc="${?}"
if [ "${rc}" != "0" ]; then
[ "$(f_getgw)" = "false" ] && rc="0"
fi
[ "${rc}" = "0" ] && break
done
json_cleanup
f_conf
f_main
done
+12 -39
View File
@@ -12,14 +12,14 @@ extra_command "scan" "[<radio>|<ifname>] Scan for available nearby uplinks"
extra_command "setup" "[<iface>] [<zone>] [<metric>] Setup the travelmate uplink interface, by default 'trm_wwan' with firewall zone 'wan' and metric '100'"
trm_init="/etc/init.d/travelmate"
trm_service="/usr/bin/travelmate-service.sh"
trm_funlib="/usr/lib/travelmate-functions.sh"
trm_daemon="/usr/sbin/travelmate"
trm_pidfile="/var/run/travelmate/travelmate.pid"
trm_actionfile="/var/run/travelmate/travelmate.action"
if [ -z "${IPKG_INSTROOT}" ]; then
if [ "${action}" = "boot" ] && "${trm_init}" running; then
exit 0
fi
. "${trm_funlib}"
fi
boot() {
@@ -34,62 +34,35 @@ start_service() {
if [ "${action}" = "boot" ]; then
return 0
fi
mkdir -p "${trm_pidfile%/*}"
printf "%s" "${1:-"${action}"}" >"${trm_actionfile}"
procd_open_instance "travelmate"
procd_set_param command "${trm_service}" "${@:-"${action}"}"
procd_set_param command "${trm_daemon}" run
procd_set_param pidfile "${trm_pidfile}"
procd_set_param nice "$(uci_get travelmate global trm_nice "0")"
procd_set_param stdout 0
procd_set_param stderr 1
procd_close_instance
else
f_log "err" "travelmate service autostart is disabled"
logger -p user.err -t "trm-init" "travelmate service autostart is disabled"
return 1
fi
}
reload_service() {
f_rmpid
procd_send_signal travelmate travelmate HUP
}
stop_service() {
rc_procd "${trm_service}" stop
"${trm_daemon}" stop
}
status_service() {
f_getstatus
"${trm_daemon}" status
}
scan() {
local result radio="${1:-radio0}"
case "${radio}" in
*[!a-z0-9]*) return 1 ;;
esac
result="$(f_scan "${radio}" full)"
if [ -z "${result}" ]; then
: >"${trm_tmpfile}"
mv -f "${trm_tmpfile}" "${trm_scanfile}"
return 0
fi
printf "%s\n" "${result}" | "${trm_awkcmd}" '
{
quality = $1
channel = $2
bssid = $3
rsn = $4
cipher = $5
auth = $6
ssid = ""
for (i=7; i<=NF; i++) {
ssid = ssid $i " "
}
sub(/[ \t]+$/, "", ssid)
printf "%3s %3s %17s %-12s %-10s %-10s %s\n",
quality, channel, bssid, rsn, cipher, auth, ssid
}' | "${trm_sortcmd}" -rn >"${trm_tmpfile}"
mv -f "${trm_tmpfile}" "${trm_scanfile}"
"${trm_daemon}" scan "${1:-radio0}"
}
setup() {
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/ucode
// travelmate - wlan connection manager for travel routers: 'run' is the
// procd daemon, the other commands serve the init script and LuCI
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
import { readfile, writefile, rename, unlink, open, readlink } from 'fs';
import { create, system_io, FILES } from 'travelmate.daemon';
function usage() {
warn('usage: travelmate run [<action>]\n' +
' travelmate stop\n' +
' travelmate scan <radio|ifname>\n' +
' travelmate status\n');
exit(1);
}
// syslog with the 'trm-<version>[pid]' tag LuCI filters on; TRM_TRACE
// redirects logs and sleeps into a file for the test suite
let trace = getenv('TRM_TRACE');
let syslog_tag = null;
function log_line(class, tag, msg) {
if (trace) {
let fh = open(trace, 'a');
fh?.write(sprintf('LOG %s %s: %s\n', class, tag, msg));
fh?.close();
return;
}
let l = require('log');
if (syslog_tag != tag) {
l.openlog(tag, l.LOG_PID, l.LOG_USER);
syslog_tag = tag;
}
l.syslog({ debug: l.LOG_DEBUG, info: l.LOG_INFO, err: l.LOG_ERR, emerg: l.LOG_EMERG }[class] ?? l.LOG_NOTICE, '%s', msg);
}
function make_io() {
let io = system_io(log_line);
if (trace) {
io.sleep = (s) => {
let fh = open(trace, 'a');
fh?.write(sprintf('SLEEP %d\n', s));
fh?.close();
};
io.time = () => '2026-01-01 00:00:00';
}
return io;
}
function stop_service() {
system([ '/etc/init.d/travelmate', 'stop' ]);
exit(0);
}
// wait for the cycle timeout; a reload (SIGHUP) cuts it short, then only a
// missing gateway starts a cycle, otherwise the full timeout starts over
let hup = false;
function idle(d) {
while (true) {
hup = false;
for (let left = +d.T.cfg.trm_timeout; left > 0 && !hup; left--)
sleep(1000);
if (!hup || !d.getgw())
return;
}
}
// the action comes from a file, not the command line, so a 'start' from a
// trigger leaves the running procd instance alone
function run(action) {
let d = create(make_io());
action ??= trim(readfile(FILES.actionfile) ?? '');
signal('SIGHUP', () => { hup = true; });
d.startup(length(action) ? action : 'start');
if (!d.conf())
stop_service();
if (length(d.T.action)) {
d.log('info', sprintf('travelmate instance started ::: action: %s, pid: %d', d.T.action, +readlink('/proc/self')));
d.main();
d.T.action = '';
}
while (true) {
idle(d);
if (!d.conf())
stop_service();
d.main();
}
}
function stop() {
let d = create(make_io());
let pid = trim(readfile(FILES.pidfile) ?? '');
d.startup('stop');
if (length(pid)) {
d.log('info', sprintf('travelmate instance stopped ::: action: stop, pid: %s', pid));
writefile(FILES.rtfile, '');
writefile(FILES.revivefile, '');
writefile(FILES.pidfile, '');
}
return 0;
}
function scan(radio) {
if (!match(radio ?? '', /^[a-z0-9]+$/))
return 1;
let d = create(make_io());
let tmp = FILES.scanfile + '.tmp';
writefile(tmp, sprintf('%J\n', d.scan(radio)));
rename(tmp, FILES.scanfile);
return 0;
}
function status() {
print(create(make_io()).status_text());
return 0;
}
switch (ARGV[0]) {
case 'run':
run(ARGV[1]);
break;
case 'stop':
exit(stop());
case 'scan':
exit(scan(ARGV[1]));
case 'status':
exit(status());
default:
usage();
}
@@ -0,0 +1,51 @@
#!/bin/sh
# Copyright (c) 2026 Dirk Brenken (dev@brenken.org)
# This is free software, licensed under the GNU General Public License v3.
[ -s "/etc/config/travelmate" ] || exit 0
# return the openvpn interface name for a given network interface name
#
trm_ovpniface() {
local dev odev iface="${1}"
[ "$(uci -q get network."${iface}".proto)" = "none" ] || return 1
dev="$(uci -q get network."${iface}".device || uci -q get network."${iface}".ifname)"
[ -n "${dev}" ] || return 1
for iface in $(uci -q -X show network | sed -n "s/^network\.\([^.]*\)\.proto='openvpn'$/\1/p"); do
odev="$(uci -q get network."${iface}".dev)"
case "${odev}" in
"tun" | "tap") odev="${odev}0" ;;
esac
if [ "${odev}" = "${dev}" ]; then
printf "%s" "${iface}"
return 0
fi
done
return 1
}
# migrate travelmate config options to new format
#
for section in $(uci -q -X show travelmate | sed -n "s/^travelmate\.\([^.]*\)=uplink$/\1/p"); do
script="$(uci -q get travelmate."${section}".script)"
case "${script}" in
"/etc/travelmate/"*".login")
[ -x "${script%.login}.uc" ] && uci -q set travelmate."${section}".script="${script%.login}.uc"
;;
esac
vpniface="$(uci -q get travelmate."${section}".vpniface)"
if [ -n "${vpniface}" ] && iface="$(trm_ovpniface "${vpniface}")"; then
uci -q set travelmate."${section}".vpniface="${iface}"
fi
uci -q delete travelmate."${section}".vpnservice
done
vpniface="$(uci -q get travelmate.global.trm_stdvpniface)"
if [ -n "${vpniface}" ] && iface="$(trm_ovpniface "${vpniface}")"; then
uci -q set travelmate.global.trm_stdvpniface="${iface}"
fi
uci -q delete travelmate.global.trm_stdvpnservice
uci -q commit travelmate
exit 0
-86
View File
@@ -1,86 +0,0 @@
#!/bin/sh
# vpn handler called by travelmate
# Copyright (c) 2020-2026 Dirk Brenken (dev@brenken.org)
# This is free software, licensed under the GNU General Public License v3.
# set (s)hellcheck exceptions
# shellcheck disable=all
export LC_ALL=C
export PATH="/usr/sbin:/usr/bin:/sbin:/bin"
vpn="${1}"
vpn_action="${2}"
vpn_service="${3}"
vpn_iface="${4}"
vpn_instance="${5}"
vpn_status=""
trm_funlib="/usr/lib/travelmate-functions.sh"
if [ -z "${trm_bver}" ]; then
. "${trm_funlib}"
f_conf
fi
f_net() {
local json_rc
json_rc="$("${trm_fetchcmd}" ${trm_fetchparm} --user-agent "${trm_useragent}" --header "Cache-Control: no-cache, no-store, must-revalidate, max-age=0" --write-out "%{response_code}" --output /dev/null "${trm_captiveurl}")"
if [ "${json_rc}" = "200" ] || [ "${json_rc}" = "204" ]; then
json_rc="net ok"
fi
printf "%s" "${json_rc}"
}
if [ "${vpn}" = "1" ] && [ "${vpn_action%_*}" = "enable" ]; then
if [ "${vpn_action}" = "enable_keep" ]; then
vpn_status="$("${trm_ubuscmd}" -S call network.interface."${vpn_iface}" status 2>/dev/null | "${trm_jsoncmd}" -ql1 -e '@.up')"
fi
f_log "info" "start vpn processing (vpn: ${vpn:-"-"}, action: ${vpn_action:-"-"}, interface: ${vpn_iface:-"-"}, instance: ${vpn_instance:-"-"}, status: ${vpn_status:-"-"})"
if [ "${vpn_action}" = "enable" ] || [ "${vpn_status}" != "true" ]; then
if [ "${vpn_status}" != "true" ]; then
/sbin/ifdown "${vpn_iface}"
"${trm_ubuscmd}" -S call network.interface."${vpn_iface}" remove >/dev/null 2>&1
if [ "${vpn_service}" = "openvpn" ] && [ -n "${vpn_instance}" ] && [ -x "/etc/init.d/openvpn" ]; then
if /etc/init.d/openvpn running "${vpn_instance}"; then
/etc/init.d/openvpn stop "${vpn_instance}"
fi
/etc/init.d/openvpn start "${vpn_instance}"
fi
fi
sleep 1
/sbin/ifup "${vpn_iface}"
if ! "${trm_ubuscmd}" -t "$((trm_maxwait / 6))" wait_for network.interface."${vpn_iface}" >/dev/null 2>&1; then
f_log "info" "travelmate vpn interface '${vpn_iface}' does not appear on ubus on ifup event"
fi
cnt="0"
while :; do
vpn_status="$("${trm_ubuscmd}" -S call network.interface."${vpn_iface}" status 2>/dev/null | "${trm_jsoncmd}" -ql1 -e '@.up')"
if [ "${vpn_status}" = "true" ]; then
net_status="$(f_net)"
if [ "${net_status}" = "net ok" ]; then
: >"${trm_vpnfile}"
f_log "info" "${vpn_service} client connection enabled '${vpn_iface}/${vpn_instance:-"-"}'"
break
fi
fi
if [ "${cnt}" -ge "$((trm_maxwait / 3))" ]; then
/sbin/ifdown "${vpn_iface}"
"${trm_ubuscmd}" -S call network.interface."${vpn_iface}" remove >/dev/null 2>&1
if [ "${vpn_service}" = "openvpn" ] && [ -n "${vpn_instance}" ] && [ -x "/etc/init.d/openvpn" ] && /etc/init.d/openvpn running "${vpn_instance}"; then
/etc/init.d/openvpn stop "${vpn_instance}"
fi
rm -f "${trm_vpnfile}"
f_log "info" "${vpn_service} client connection can't be established '${vpn_iface}/${vpn_instance:-"-"}, rc: ${net_status:-"-"}'"
exit 1
fi
cnt="$((cnt + 1))"
sleep 1
done
fi
elif { [ "${vpn}" != "1" ] && [ "${vpn_action%_*}" = "enable" ]; } || [ "${vpn_action}" = "disable" ]; then
/sbin/ifdown "${vpn_iface}"
"${trm_ubuscmd}" -S call network.interface."${vpn_iface}" remove >/dev/null 2>&1
if [ "${vpn_service}" = "openvpn" ] && [ -n "${vpn_instance}" ] && [ -x "/etc/init.d/openvpn" ] && /etc/init.d/openvpn running "${vpn_instance}"; then
/etc/init.d/openvpn stop "${vpn_instance}"
fi
rm -f "${trm_vpnfile}"
f_log "info" "${vpn_service} client connection disabled '${vpn_iface}/${vpn_instance:-"-"}'"
fi
-54
View File
@@ -1,54 +0,0 @@
#!/bin/sh
# captive portal auto-login script for vodafone hotspots (DE)
# Copyright (c) 2021-2026 Dirk Brenken (dev@brenken.org)
# This is free software, licensed under the GNU General Public License v3.
# set (s)hellcheck exceptions
# shellcheck disable=all
export LC_ALL=C
export PATH="/usr/sbin:/usr/bin:/sbin:/bin"
trm_funlib="/usr/lib/travelmate-functions.sh"
if [ -z "${trm_bver}" ]; then
. "${trm_funlib}"
f_conf
fi
username="${1}"
password="${2}"
trm_domain="hotspot.vodafone.de"
if ! "${trm_lookupcmd}" "${trm_domain}" >/dev/null 2>&1; then
exit 1
fi
# get sid
#
redirect_url="$("${trm_fetchcmd}" ${trm_fetchparm} --user-agent "${trm_useragent}" --write-out "%{redirect_url}" --output /dev/null "${trm_captiveurl}")"
sid="$(printf "%s" "${redirect_url}" 2>/dev/null | "${trm_awkcmd}" 'BEGIN{FS="[=&]"}{printf "%s",$2}')"
[ -z "${sid}" ] && exit 1
# get session
#
raw_html="$("${trm_fetchcmd}" ${trm_fetchparm} --user-agent "${trm_useragent}" --referer "http://${trm_domain}/portal/?sid=${sid}" "https://${trm_domain}/api/v4/session?sid=${sid}")"
session="$(printf "%s" "${raw_html}" 2>/dev/null | "${trm_jsoncmd}" -q -l1 -e '@.session')"
[ -z "${session}" ] && exit 2
ids="$(printf "%s" "${raw_html}" 2>/dev/null | "${trm_jsoncmd}" -q -e '@.loginProfiles[*].id' | "${trm_sortcmd}" -n | "${trm_awkcmd}" '{ORS=" ";print $0}')"
for id in ${ids}; do
if [ "${id}" = "4" ]; then
login_id="4"
access_type="csc-community"
account_type="csc"
break
fi
done
[ -z "${login_id}" ] && exit 3
# final login request
#
if [ "${login_id}" = "4" ] && [ -n "${username}" ] && [ -n "${password}" ]; then
raw_html="$("${trm_fetchcmd}" ${trm_fetchparm} --user-agent "${trm_useragent}" --referer "http://${trm_domain}/portal/?sid=${sid}" --data "loginProfile=${login_id}&accessType=${access_type}&accountType=${account_type}&password=${password}&session=${session}&username=${username}" "https://${trm_domain}/api/v4/login?sid=${sid}")"
fi
success="$(printf "%s" "${raw_html}" 2>/dev/null | "${trm_jsoncmd}" -q -l1 -e '@.success')"
[ "${success}" = "true" ] && exit 0 || exit 255
-41
View File
@@ -1,41 +0,0 @@
#!/bin/sh
# captive portal auto-login script for bahn/ICE hotspots (DE)
# Copyright (c) 2020-2026 Dirk Brenken (dev@brenken.org)
# This is free software, licensed under the GNU General Public License v3.
# set (s)hellcheck exceptions
# shellcheck disable=all
export LC_ALL=C
export PATH="/usr/sbin:/usr/bin:/sbin:/bin"
trm_funlib="/usr/lib/travelmate-functions.sh"
if [ -z "${trm_bver}" ]; then
. "${trm_funlib}"
f_conf
fi
trm_domain="wifi.bahn.de"
if ! "${trm_lookupcmd}" "${trm_domain}" >/dev/null 2>&1; then
trm_domain="login.wifionice.de"
if ! "${trm_lookupcmd}" "${trm_domain}" >/dev/null 2>&1; then
exit 1
fi
fi
# current cna portal api
#
raw_html="$("${trm_fetchcmd}" ${trm_fetchparm} --user-agent "${trm_useragent}" --header "Content-Type: application/json" --header "X-Requested-With: XMLHttpRequest" --header "X-Csrf-Token: csrf" --header "Referer: https://${trm_domain}/cna/" --data "{}" "https://${trm_domain}/cna/logon")"
printf "%s" "${raw_html}" | "${trm_grepcmd}" -qF "success" && exit 0
# legacy portal api, get security token
#
"${trm_fetchcmd}" ${trm_fetchparm} --user-agent "${trm_useragent}" --cookie-jar "/tmp/${trm_domain}.cookie" --output /dev/null "https://${trm_domain}/en/"
[ "${?}" = "0" ] && sec_token="$("${trm_awkcmd}" '/csrf/{print $7}' "/tmp/${trm_domain}.cookie" 2>/dev/null)"
rm -f "/tmp/${trm_domain}.cookie"
[ -z "${sec_token}" ] && exit 2
# legacy portal api, final post request
#
"${trm_fetchcmd}" ${trm_fetchparm} --user-agent "${trm_useragent}" --header "Cookie: csrf=${sec_token}" --data "login=true&CSRFToken=${sec_token}" --output /dev/null "https://${trm_domain}/en/"
[ "${?}" = "0" ] && exit 0 || exit 255
+136
View File
@@ -0,0 +1,136 @@
// travelmate - uplink check decisions: init() resolves the uplink before the
// poll, round() returns the steps (op) of one polling round
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
import { ref as uplink_ref, option as uplink_option } from 'travelmate.uplink';
// st: { mode, status (bool), radio, essid, bssid, ifstatus, wifireload (bool) }
export function init(st, uplinks) {
let uref = uplink_ref(uplinks, st.radio, st.essid, st.bssid);
let enabled = true;
if (st.mode != 'rev' && length(st.radio) && st.radio != '-' && length(st.essid) && st.essid != '-')
enabled = uplink_option(uplinks, uref, 'enabled', '0') == '1';
// wifi reload on disconnects (not initial/dev), on disabled-uplink dev
// events or on idle dev events if requested by the main cycle
let wifi = (st.mode != 'initial' && st.mode != 'dev' && !st.status) ||
(st.mode == 'dev' && ((!st.status && st.wifireload) ||
(st.ifstatus !== st.status && !enabled)));
return { uplinkcfg: uref, enabled, wifi };
};
// drop the connection and settle the status
function drop(out, st, msg) {
if (msg)
push(out, { op: 'log', class: 'info', msg }, { op: 'vpn' });
push(out, { op: 'conn' }, { op: 'ifstatus', value: st.status }, { op: 'genstatus' }, { op: 'break' });
return out;
}
// st: { mode, status, enabled, ifstatus, connection, wait, maxwait,
// minquality, quality (of an earlier round), sta_id }, q: probe queries
export function round(st, q) {
let out = [], mode = st.mode, sta_id = st.sta_id;
if (q.wireless()) {
// dev mode: persist a status change and end
if (mode == 'dev') {
if (st.ifstatus !== st.status)
push(out, { op: 'ifstatus', value: st.status }, { op: 'genstatus' });
if (!st.status)
push(out, { op: 'sleep', s: int(st.maxwait / 6) });
push(out, { op: 'break' });
return out;
}
// rev mode: drop the connection state and end
if (mode == 'rev') {
push(out, { op: 'conn' }, { op: 'ifstatus', value: st.status }, { op: 'break' });
return out;
}
// initial/sta mode: look at the sta interface
let ifname = q.ifname();
if (length(ifname) && st.enabled) {
let quality = q.quality(ifname) ?? st.quality;
push(out, { op: 'probe', ifname, quality });
// no signal: connection dropped or overall wait timeout
if (quality == null) {
let up = q.up();
push(out, { op: 'ifstatus', value: up });
if (st.connection && up === false)
return drop(out, st, sprintf("no signal from uplink '%s'", sta_id));
if (st.wait == st.maxwait)
return drop(out, st, sprintf("uplink connection could not be established after %d seconds '%s'", st.maxwait, sta_id));
push(out, { op: 'continue' });
return out;
}
// acceptable signal: net/captive check once the interface is up
if (quality >= st.minquality) {
let up = q.up();
push(out, { op: 'ifstatus', value: up });
if (up === true) {
push(out, { op: 'net' });
return out;
}
}
// signal below minquality on an existing link
else if (st.connection && mode == 'initial') {
return drop(out, st, sprintf("uplink is out of range '%s' (%d/%d)", sta_id, quality, st.minquality));
}
// signal below minquality on an initial/sta probe
else if (mode == 'initial' || mode == 'sta') {
return drop(out, st);
}
}
else {
push(out, { op: 'probe', ifname, quality: st.quality });
// sta interface gone while connected
if (st.connection)
return drop(out, st, sprintf("uplink connection lost '%s' (interface gone)", sta_id));
// initial probe, no sta interface yet
if (mode == 'initial') {
push(out, { op: 'ifstatus', value: st.status }, { op: 'genstatus' }, { op: 'break' });
return out;
}
}
}
// initial mode safety net, also on an empty wireless status
if (mode == 'initial') {
if (st.connection)
push(out, { op: 'log', class: 'info', msg: sprintf("uplink connection lost '%s' (interface down)", sta_id) },
{ op: 'vpn' }, { op: 'conn' });
push(out, { op: 'ifstatus', value: st.status }, { op: 'genstatus' }, { op: 'break' });
}
return out;
};
+118
View File
@@ -0,0 +1,118 @@
// travelmate - shared settings: typed 'global' options, curl arguments and
// the command runner for the daemon and the login scripts, no shell involved
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
import { popen, access } from 'fs';
export const RUNDIR = '/var/run/travelmate';
// seconds per curl attempt and between its retries
export const FETCH_TIMEOUT = 5;
// option: [ type, default, min ]; bool: '1' is on, int: default if not a
// number or below min, list: a uci list or the words of an option
export const OPTIONS = {
trm_enabled: [ 'bool', false ],
trm_debug: [ 'bool', false ],
trm_iface: [ 'string', '' ],
trm_laniface: [ 'string', '' ],
trm_captive: [ 'bool', true ],
trm_proactive: [ 'bool', false ],
trm_vpn: [ 'bool', false ],
trm_netcheck: [ 'bool', false ],
trm_autoadd: [ 'bool', false ],
trm_randomize: [ 'bool', false ],
trm_eviltwin: [ 'bool', false ],
trm_mail: [ 'bool', false ],
trm_mailreceiver: [ 'string', '' ],
trm_mailsender: [ 'string', 'no-reply@travelmate' ],
trm_mailtopic: [ 'string', '' ],
trm_mailprofile: [ 'string', 'trm_notify' ],
trm_mailtemplate: [ 'string', '/etc/travelmate/mail.template' ],
trm_minquality: [ 'int', 35 ],
trm_maxretry: [ 'int', 3 ],
trm_maxwait: [ 'int', 30, 1 ],
trm_maxautoadd: [ 'int', 5 ],
trm_autoaddcnt: [ 'int', 0 ],
trm_timeout: [ 'int', 30, 1 ],
trm_radio: [ 'list', [] ],
trm_revradio: [ 'bool', false ],
trm_ssidfilter: [ 'list', [] ],
trm_vpnifacelist: [ 'list', [] ],
trm_stdvpniface: [ 'string', '' ],
trm_captiveurl: [ 'string', 'http://detectportal.firefox.com' ],
trm_useragent: [ 'string', 'Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0' ]
};
export function words(s) {
return filter(split(trim('' + (s ?? '')), /[ \t\n]+/), length);
};
// one option value as its type
export function typed(kind, v, dflt, min) {
if (v == null)
return dflt;
switch (kind) {
case 'bool':
return v == '1';
case 'int':
let n = int(v);
return (n == n && (min == null || n >= min)) ? n : dflt;
case 'list':
return (type(v) == 'array') ? v : words(v);
default:
return (type(v) == 'array') ? join(' ', v) : '' + v;
}
};
// the 'global' section, typed, unknown options are left out
export function global(c) {
let g = c.get_all('travelmate', 'global') ?? {};
let cfg = {};
for (let k, o in OPTIONS)
cfg[k] = typed(o[0], g[k], o[1], o[2]);
return cfg;
};
// curl arguments of every fetch, bound to the uplink device if known
export function fetch_args(cfg, device) {
let t = '' + FETCH_TIMEOUT;
let args = [ '--silent', '--location', '--fail', '--referer', 'http://www.example.com',
'--retry', '2', '--retry-delay', t, '--max-time', t ];
if (length(device ?? ''))
push(args, '--interface', device);
return args;
};
// run a command directly (no shell), return { out: stdout, rc: exit code }
export function capture(argv) {
let p = popen(argv, 'r');
if (!p)
return { out: '', rc: -1 };
let out = p.read('all') ?? '';
let rc = p.close();
return { out, rc: rc ?? -1 };
};
// command lookup in PATH, like 'command -v'
export function have(cmd) {
for (let dir in split(getenv('PATH') ?? '/usr/sbin:/usr/bin:/sbin:/bin', ':'))
if (length(dir) && access(dir + '/' + cmd, 'x') == true)
return true;
return false;
};
File diff suppressed because it is too large. Load diff
+101
View File
@@ -0,0 +1,101 @@
// travelmate - helpers for the login scripts /etc/travelmate/*.uc (args:
// credentials, exit code 0 on success), test: ucode /etc/travelmate/x.uc u p
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
import { cursor } from 'uci';
import { connect } from 'ubus';
import { query } from 'resolv';
import { global as cfg_global, fetch_args, capture, FETCH_TIMEOUT } from 'travelmate.common';
import { hostname } from 'travelmate.net';
const cfg = cfg_global(cursor());
export const captiveurl = cfg.trm_captiveurl;
export const useragent = cfg.trm_useragent;
let base = null;
// curl arguments like the daemon's, bound to the uplink device
function args() {
if (base == null) {
let dev = connect()?.call('network.interface.' + cfg.trm_iface, 'status')?.device;
base = fetch_args(cfg, (dev != null) ? '' + dev : '');
}
return base;
}
// fetch an url with the travelmate curl settings, returns { rc, body }; opts:
// args (extra curl arguments), follow (false: no redirects), write_out
export function fetch(url, opts) {
let a = [ ...args() ];
if (opts?.follow === false)
a = filter(a, (x) => x != '--location');
let argv = [ 'curl', ...a, '--user-agent', useragent ];
if (opts?.write_out != null)
push(argv, '--write-out', opts.write_out);
// '--url': an url from a portal page must never be taken as option
push(argv, ...(opts?.args ?? []), '--url', '' + url);
let r = capture(argv);
return { rc: r.rc, body: r.out };
};
// true if the dns name resolves to an address, via ucode's resolver
export function lookup(domain) {
if (!hostname(domain))
return false;
let r = query([ domain ], { type: [ 'A', 'AAAA' ], timeout: FETCH_TIMEOUT * 1000, retries: 1 });
for (let name, rr in (r ?? {}))
if (length(rr?.A) || length(rr?.AAAA))
return true;
return false;
};
// true if url is an https url on host (the login post of a script must not
// go to a host taken from a page of a spoofed hotspot)
export function https_on(url, host) {
return index(lc('' + url), 'https://' + lc(host) + '/') == 0;
};
// percent-encode everything but unreserved characters, a blank as %20
export function urlencode(s) {
let out = '';
for (let i = 0; i < length(s); i++) {
let c = substr(s, i, 1);
out += match(c, /^[a-zA-Z0-9.~_-]$/) ? c : sprintf('%%%02X', ord(s, i));
}
return out;
};
// per line the text between the first opening and the last closing tag,
// tags matched case-insensitively, all hits joined
export function between(text, open, close) {
let out = '';
open = lc(open);
close = lc(close);
for (let l in split(text ?? '', '\n')) {
let ll = lc(l), a = index(ll, open), b = rindex(ll, close);
if (a >= 0 && b >= a + length(open))
out += substr(l, a + length(open), b - a - length(open));
}
return out;
};
+189
View File
@@ -0,0 +1,189 @@
// travelmate - internet and captive portal check: classifies the curl
// probe reply as net ok, nok or cp (captive portal) with its host
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
export const MARKER = '#trm-meta#';
// lowercased host, port stripped (the host ends up in the dnsmasq rebind
// allowlist), an IPv6 literal keeps its brackets
function host(h) {
h = lc(h ?? '');
if (substr(h, 0, 1) == '[') {
let i = index(h, ']');
return (i >= 0) ? substr(h, 0, i + 1) : h;
}
return replace(h, /:[0-9]*$/, '');
}
export function probe_host(url) {
let i = index(url, '://');
if (i >= 0)
url = substr(url, i + 3);
return host(split(url, '/')[0]);
};
// bytes above 0x7f as '?', libc regex may refuse invalid UTF-8 from portal
// pages; lengths stay the same, so match offsets still apply
function ascii(s) {
let out = '';
for (let i = 0; i < length(s); i++)
out += (ord(s, i) > 127) ? '?' : substr(s, i, 1);
return out;
}
// host of an absolute ('scheme://') or scheme-relative ('//') redirect
// target, '' for a relative one; an IPv6 literal keeps its brackets
function target_host(t) {
t = replace(t, /^[ \t"']+/, '');
let m = match(t, /^([a-z][a-z0-9+.-]*:)?\/\//);
if (!m)
return '';
t = substr(t, length(m[0]));
if (substr(t, 0, 1) == '[') {
let i = index(t, ']');
return (i >= 0) ? substr(t, 0, i + 1) : t;
}
return replace(t, /[:\/?#;>"' \t].*$/, '');
}
// first body line with a redirect, the host of its target
function redirect(lines, needle, re) {
for (let l in lines) {
l = lc(l);
if (index(l, needle) < 0)
continue;
l = ascii(l);
let m = match(l, re);
if (m)
return target_host(substr(l, length(m[0])));
}
return '';
}
// last word of a curl error message that ends in a domain name
function err_domain(msg) {
msg = ascii(msg);
if (!match(msg, /([[:alnum:]_-]{1,63}\.)+[[:alpha:]]+$/))
return '';
let w = split(trim(msg), /[ \t]+/);
return lc(w[length(w) - 1]);
}
// a dns name: letters, digits and hyphens in dot separated labels, at
// least two labels, the last one not numeric; no ip address literal
export function hostname(h) {
if (type(h) != 'string' || length(h) > 253)
return false;
let labels = split(h, '.');
if (length(labels) < 2 || match(labels[-1], /^[0-9]+$/))
return false;
for (let l in labels)
if (!match(l, /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i))
return false;
return true;
};
export function classify(raw, probe_url, captive) {
let i = rindex(raw, MARKER);
let json_raw = (i >= 0) ? substr(raw, i + length(MARKER)) : raw;
let html_raw = (i >= 0) ? substr(raw, 0, i) : raw;
let r = {
result: 'net nok', probe_host: probe_host(probe_url),
ec: '', rc: '', eff_url: '', cp: '', html: '', js: '', err: ''
};
if (length(json_raw)) {
let meta = null;
try { meta = json(json_raw); } catch (e) { }
if (type(meta) == 'object') {
r.ec = '' + (meta.exitcode ?? '');
r.rc = '' + (meta.response_code ?? '');
r.eff_url = '' + (meta.url_effective ?? '');
}
r.cp = host(split(r.eff_url, '/')[2]);
if (r.ec == '0') {
if (length(r.cp) && r.cp != r.probe_host) {
r.result = sprintf("net cp '%s'", r.cp);
}
else if (r.rc == '200' || r.rc == '204') {
let lines = split(html_raw, '\n');
r.html = redirect(lines, 'http-equiv=', /^.*<meta[ \t]+http-equiv=['"]*refresh.*[ \t;]url=/);
r.js = redirect(lines, 'location.href=', /^.*location\.href=['"]*/);
if (length(r.html))
r.result = sprintf("net cp '%s'", r.html);
else if (length(r.js))
r.result = sprintf("net cp '%s'", r.js);
else
r.result = 'net ok';
}
}
else {
r.err = (type(meta) == 'object' && type(meta.errormsg) == 'string') ? meta.errormsg : '';
let ed = err_domain(r.err);
if (r.ec == '6') {
if (length(ed) && ed != r.probe_host)
r.result = sprintf("net cp '%s'", ed);
}
else if (length(r.cp) && r.cp != r.probe_host) {
r.result = sprintf("net cp '%s'", r.cp);
}
}
}
// without captive portal handling a detected portal is a dead end
if (substr(r.result, 0, 6) == 'net cp' && !captive)
r.result = 'net nok';
let m = match(r.result, /^net cp '(.*)'$/);
r.net = m ? 'cp' : substr(r.result, 4);
// the portal host, as far as it consists of host name or address
// characters; it is logged and, if a dns name, allowlisted
r.domain = m ? match(m[1], /^[]a-z0-9._:[-]*/)[0] : '';
return r;
};
// the debug fields of the net check
export function debug(r) {
let d = (v) => length(v) ? v : '-';
return sprintf('cp (url/html/js): %s/%s/%s, result: %s, error (rc/msg): %s/%s, probe_host: %s, eff_url: %s',
d(r.cp), d(r.html), d(r.js), r.result, r.ec, d(r.err), d(r.probe_host), d(r.eff_url));
};
+54
View File
@@ -0,0 +1,54 @@
// travelmate - uplink state probe: wireless status, sta interface, signal
// quality and interface state for one polling round, queries only
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
import { quality } from 'travelmate.scan';
// first interface in sta mode, in the order netifd reports the radios
function sta_ifname(status) {
for (let radio, r in status)
for (let i in (r?.interfaces ?? []))
if (i?.config?.mode == 'sta' && i?.ifname != null)
return '' + i.ifname;
return '';
}
// lazy, cached queries for one polling round, asked only as far as the
// decision gets; quality: int or null, up: bool or null
export function queries(conn, iface) {
let status, name, up, asked = false;
return {
wireless: () => (status ??= conn?.call('network.wireless', 'status') ?? false) !== false,
ifname: () => name ??= sta_ifname(status || {}),
quality: (ifname) => {
let signal = conn?.call('iwinfo', 'info', { device: ifname })?.signal;
return (type(signal) == 'int' && signal >= -120) ? quality(signal) : null;
},
up: () => {
if (!asked) {
let v = conn?.call('network.interface.' + iface, 'status')?.up;
up = (type(v) == 'bool') ? v : null;
asked = true;
}
return up;
}
};
};
// all radios up and not pending, the idle cycle skips the wifi reload then
export function ready(conn, radios) {
let status = conn?.call('network.wireless', 'status');
for (let radio in radios)
if ('' + status?.[radio]?.up != 'true' || '' + status?.[radio]?.pending != 'false')
return false;
return true;
};
+125
View File
@@ -0,0 +1,125 @@
// travelmate - uplink scan: ranks an iwinfo scan reply, one entry per
// BSS, for the connection loop and the LuCI scan file
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
const WPA = { '1': 'WPA1', '2': 'WPA2', '3': 'WPA3' };
// Drop control octets (awk [[:cntrl:]] under LC_ALL=C) bytewise: an ssid is
// arbitrary octets, and libc regex may refuse input that is not valid UTF-8.
function clean_ssid(s) {
let out = '';
for (let i = 0; i < length(s); i++) {
let c = ord(s, i);
if (c >= 32 && c != 127)
out += substr(s, i, 1);
}
return trim(out, ' ');
}
// -100 dBm = 0 %, -50 dBm = 100 %
export function quality(signal) {
if (type(signal) != 'int')
return 0;
let q = 2 * (signal + 100);
return q > 100 ? 100 : (q < 0 ? 0 : q);
}
// rpcd sends no 'wpa' array for WEP, only enabled plus 'wep'. Report it as
// such, otherwise the connection loop sees an open network.
function versions(enc) {
let out = [];
for (let n in (enc.wpa ?? []))
if (WPA[n])
push(out, WPA[n]);
if (!length(out) && enc.enabled)
return 'WEP';
return length(out) ? join('+', out) : '-';
}
function words(list) {
let out = [];
for (let w in (list ?? []))
if (length('' + w))
push(out, uc('' + w));
return length(out) ? join('+', out) : '-';
}
// quoted form used in scan lines and debug output
export function quote(s) {
return '"' + join('\\"', split(s, '"')) + '"';
};
export function entry(r) {
let enc = r?.encryption ?? {};
let ssid = clean_ssid('' + (r?.ssid ?? ''));
return {
raw: ssid,
quality: quality(r?.signal),
channel: r?.channel ?? 0,
bssid: length(r?.bssid ?? '') ? uc(r.bssid) : '-',
wpa: versions(enc),
cipher: words(enc.ciphers),
auth: words(enc.authentication),
ssid: length(ssid) ? quote(ssid) : 'hidden',
hidden: !length(ssid),
open: !enc.enabled,
enc
};
};
// the fields the connection loop compares, 'quality rsn wpa bssid essid',
// where rsn and wpa both '-' means open; also the sort key for ties
export function format(e) {
return sprintf('%d %s - %s %s', e.quality, e.wpa, e.bssid, e.ssid);
};
// Same order as 'sort -rn' on the formatted lines: quality descending, ties
// by the whole line in reverse byte order (busybox and GNU fallback).
export function rank(results) {
let rows = [];
for (let r in (results ?? [])) {
let e = entry(r);
e.line = format(e);
push(rows, e);
}
sort(rows, (a, b) => (b.quality - a.quality) ||
(a.line < b.line ? 1 : (a.line > b.line ? -1 : 0)));
return rows;
};
function upper(list) {
return map(filter(list ?? [], (w) => length('' + w)), (w) => uc('' + w));
}
// the scan file for LuCI, a JSON array in ranking order (a hidden ssid is ''
// with hidden: true, encrypted: false for an open network)
export function report(results) {
return map(rank(results), (e) => ({
quality: e.quality,
channel: e.channel,
bssid: (e.bssid == '-') ? '' : e.bssid,
ssid: e.raw,
hidden: !length(e.raw),
encrypted: !!e.enc.enabled,
wpa: map(filter(e.enc.wpa ?? [], (n) => n in [ 1, 2, 3 ]), (n) => +n),
ciphers: upper(e.enc.ciphers),
auth: upper(e.enc.authentication)
}));
};
+240
View File
@@ -0,0 +1,240 @@
// travelmate - uplink selection: walks the configured stations against the
// ranked scan of one radio, steps (op): log sta keep mismatch add try noscan
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
// bssid with upper-case hex digits
export function normbssid(b) {
return replace(b ?? '', /[a-f]/g, (m) => uc(m));
};
// locally administered address, the usual evil-twin pattern
function laa(bssid) {
return (hex(split(bssid, ':')[0]) & 2) != 0;
}
// bracket expression at p[i] == '[', returns the index after ']' and whether
// c matched, or null if there is no closing ']' (then '[' is literal)
function bracket(p, i, c) {
let j = i + 1, neg = false, ok = false;
if (substr(p, j, 1) == '!' || substr(p, j, 1) == '^') {
neg = true;
j++;
}
for (let first = true; j < length(p); first = false) {
let a = substr(p, j, 1);
if (a == ']' && !first)
return { next: j + 1, ok: ok != neg };
if (substr(p, j + 1, 1) == '-' && j + 2 < length(p) && substr(p, j + 2, 1) != ']') {
let b = substr(p, j + 2, 1);
if (ord(c) >= ord(a) && ord(c) <= ord(b))
ok = true;
j += 3;
}
else {
if (c == a)
ok = true;
j++;
}
}
return null;
}
// glob pattern match on bytes for trm_ssidfilter: *, ?, [...], backslash
export function glob(p, s, pi, si) {
pi ??= 0;
si ??= 0;
while (pi < length(p)) {
let c = substr(p, pi, 1);
if (c == '*') {
while (substr(p, pi, 1) == '*')
pi++;
if (pi == length(p))
return true;
for (let k = si; k <= length(s); k++)
if (glob(p, s, pi, k))
return true;
return false;
}
if (si >= length(s))
return false;
if (c == '?') {
pi++;
si++;
continue;
}
if (c == '[') {
let r = bracket(p, pi, substr(s, si, 1));
if (r) {
if (!r.ok)
return false;
pi = r.next;
si++;
continue;
}
}
if (c == '\\' && pi + 1 < length(p))
c = substr(p, ++pi, 1);
if (substr(s, si, 1) != c)
return false;
pi++;
si++;
}
return si == length(s);
};
function log(out, class, msg) {
push(out, { op: 'log', class, msg });
}
// an info that repeats every cycle as long as the scan stays the same, the
// daemon logs it once per run and as debug line afterwards
function note(out, msg) {
push(out, { op: 'log', class: 'info', msg, once: true });
}
// open uplinks to autoadd, in scan order: open, named, above minquality,
// not filtered, not configured yet and within the autoadd quota
function autoadd(out, opts, entries, known) {
let cfg = opts.cfg, radio = opts.radio, cnt = cfg.autoaddcnt;
for (let e in entries) {
if (e.quality < cfg.minquality)
break;
if (!e.open || e.hidden || known[radio + '\n' + e.raw])
continue;
// per bss: an LAA bss is skipped, another bss of the ssid may count
if (cfg.eviltwin && laa(e.bssid)) {
note(out, sprintf("skipped autoadd of LAA candidate (evil-twin) '%s/%s/%s'",
radio, e.ssid, e.bssid));
continue;
}
// per ssid: one decision, also for further bss of a filtered one
known[radio + '\n' + e.raw] = true;
let pattern = null;
for (let p in cfg.ssidfilter) {
if (glob(p, e.raw)) {
pattern = p;
break;
}
}
if (pattern != null) {
note(out, sprintf("open uplink filtered out '%s/%s/%s'", radio, e.raw, pattern));
continue;
}
if (cfg.maxautoadd != 0 && cnt >= cfg.maxautoadd)
break;
push(out, { op: 'add', radio, essid: e.raw }, { op: 'try' });
cnt++;
}
}
// configured stations first, in their order; open uplinks are added and tried
// only as last resort, never while the current uplink is kept
export function plan(opts) {
let out = [], cfg = opts.cfg, radio = opts.radio, cur = opts.current;
let ifaces = opts.ifaces ?? {}, entries = null, known = {};
for (let n, s in ifaces)
known[s.device + '\n' + s.ssid] = true;
for (let sta in opts.stalist ?? []) {
let w = ifaces[sta.section] ?? {};
let sradio = w.device ?? '', sessid = w.ssid ?? '', sbssid = normbssid(w.bssid);
if (!length(sradio) || !length(sessid)) {
note(out, sprintf("invalid wireless section '%s'", sta.section));
continue;
}
push(out, { op: 'sta', section: sta.section, radio: sradio, bssid: sbssid, essid: sessid });
if (cur && radio == cur.radio && sradio == cur.radio &&
sessid == cur.essid && sbssid == cur.bssid) {
push(out, { op: 'keep' });
return out;
}
log(out, 'debug', sprintf('f_main-5 ::: sta_radio: %s, sta_essid: "%s", sta_bssid: %s',
sradio, sessid, length(sbssid) ? sbssid : '-'));
entries ??= opts.scan() ?? [];
if (!length(entries)) {
push(out, { op: 'noscan', radio });
return out;
}
for (let e in entries) {
let named = !e.hidden && e.raw == sessid;
log(out, 'debug', sprintf('f_main-6 ::: radio(sta/scan): %s/%s, essid(sta/scan): "%s"/%s, bssid(sta/scan): %s/%s, quality(min/scan): %d/%d, open: %s',
sradio, radio, sessid, e.ssid, sbssid, e.bssid, cfg.minquality, e.quality, e.open ? '+' : '-'));
if (e.quality < cfg.minquality)
break;
if (length(sbssid) && radio == sradio && e.bssid != sbssid && named) {
push(out, { op: 'mismatch', bssid: e.bssid });
continue;
}
if (((named && (!length(sbssid) || e.bssid == sbssid)) ||
(e.bssid == sbssid && e.hidden)) && radio == sradio) {
if (cfg.eviltwin && !length(sbssid) && !e.hidden && laa(e.bssid)) {
note(out, sprintf("skipped LAA candidate (evil-twin) '%s/%s/%s => %s'",
sradio, sessid, length(sbssid) ? sbssid : '-', e.bssid));
continue;
}
push(out, { op: 'try' });
cur = null;
break;
}
}
}
if (cfg.autoadd) {
entries ??= opts.scan() ?? [];
if (!length(entries)) {
push(out, { op: 'noscan', radio });
return out;
}
autoadd(out, opts, entries, known);
}
return out;
};
+110
View File
@@ -0,0 +1,110 @@
// travelmate - runtime status: composes the status object for LuCI, the
// mail and the connection loop, decides whether the connect mail is due
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
import { normbssid } from 'travelmate.select';
import { ref as uplink_ref, option as uplink_option } from 'travelmate.uplink';
function dash(v) {
return length(v ?? '') ? '' + v : '-';
}
function flag(v) {
return v ? '✔' : '✘';
}
// first sta interface of 'network.wireless status', any radio
export function sta_info(wstatus) {
for (let radio, r in wstatus)
for (let i in (r?.interfaces ?? []))
if (i?.config?.mode == 'sta')
return {
section: '' + (i.section ?? ''),
essid: '' + (i.config.ssid ?? ''),
mac: '' + (i.config.macaddr ?? ''),
bssid: '' + (i.config.bssid ?? ''),
iface: '' + (i.config.network?.[0] ?? '')
};
return null;
};
// st: daemon state, sta: sta_info() or null, radio_of(section): wifi-iface
// device, ntp/mailed/vpnup: bools, mem: MiB, ts: 'YYYY-MM-DD HH:MM:SS'
export function compose(st, sta, uplinks, radio_of, ntp, mailed, vpnup, mem, ts) {
let r = { uplinkcfg: null, mail: false };
let section = '', sradio = '', sessid = '', sbssid = '', smac = '', siface = '';
let vpn = '', vpn_iface = '', vpn_done = false, status, runtime = null;
let uplinkcfg = st.uplinkcfg ?? '';
if (st.ifstatus === true) {
status = 'connected, ' + dash(st.connection);
if (sta) {
section = sta.section;
sessid = sta.essid;
smac = sta.mac;
sbssid = sta.bssid;
siface = sta.iface;
}
if (length(section)) {
sbssid = normbssid(sbssid);
sradio = radio_of(section) ?? '';
uplinkcfg = uplink_ref(uplinks, sradio, sessid, sbssid);
r.uplinkcfg = uplinkcfg;
}
vpn = uplink_option(uplinks, uplinkcfg, 'vpn');
if (st.vpn && length(st.vpnlist) && vpn == '1' && vpnup) {
vpn_iface = uplink_option(uplinks, uplinkcfg, 'vpniface');
vpn_done = true;
}
}
else if (st.ifstatus == 'error') {
status = 'program error';
}
else {
status = st.active ? 'processing' : 'not connected';
runtime = '-';
}
let mail_done = (st.mail && mailed);
if (st.ifstatus === true || st.ifstatus == 'error')
runtime = sprintf('mode: %s, date / time: %s, memory: %s MB available',
length(st.runmode) ? st.runmode : 'n/a', ts, length(mem) ? mem : '0');
r.data = {
travelmate_status: status,
frontend_ver: st.fver ?? '',
backend_ver: st.bver ?? '',
station_id: dash(sradio) + '/' + dash(sessid) + '/' + dash(sbssid),
station_mac: dash(smac),
station_interfaces: dash(siface) + ', ' + dash(vpn_iface),
station_subnet: dash(st.subnet),
run_flags: sprintf('autoadd: %s, captive: %s, eviltwin: %s, mail: %s, netcheck: %s, ntp: %s, proactive: %s, randomize: %s, vpn: %s',
flag(st.autoadd), flag(st.captive), flag(st.eviltwin), mail_done ? '✔' : '✘', flag(st.netcheck),
ntp ? '✔' : '✘', flag(st.proactive), flag(st.randomize), vpn_done ? '✔' : '✘'),
last_run: dash(runtime),
system_info: sprintf('cores: %s, fetch: %s, %s', st.cores ?? '', st.fetch ?? '', st.sysver ?? '')
};
// connect mail: once per connection, after ntp sync and, with a vpn
// uplink, only once the vpn is up
if (index(status, 'connected, net ok/') == 0 && st.mail && st.mailcmd &&
length(st.mailreceiver) && ntp && !mail_done &&
(!st.vpn || vpn != '1' || !length(st.vpnlist) || vpn_done)) {
r.mail = true;
mail_done = true;
}
r.debug = sprintf('section: %s, status: %s, sta_iface: %s, sta_radio: %s, sta_essid: %s, sta_bssid: %s, ntp: %d, vpn: %s/%d, mail: %s/%d',
dash(section), dash((st.ifstatus == null) ? '' : '' + st.ifstatus), dash(siface), dash(sradio), dash(sessid), dash(sbssid),
ntp ? 1 : 0, length(vpn) ? vpn : '0', vpn_done ? 1 : 0, st.mail ? 1 : 0, mail_done ? 1 : 0);
return r;
};
+43
View File
@@ -0,0 +1,43 @@
// travelmate - uplink lookup: maps a station (radio, essid, bssid) to its
// travelmate 'uplink' section by name and reads its options
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
import { normbssid } from 'travelmate.select';
// travelmate 'uplink' sections in config order
export function load(c) {
let out = [];
c.foreach('travelmate', 'uplink', (s) => push(out, s));
return out;
};
// section name of the first uplink matching radio, essid and bssid, '' if
// none; radio and essid must be set, bssid compares case-normalized
export function ref(uplinks, radio, essid, bssid) {
if (!length(radio) || !length(essid))
return '';
for (let u in uplinks)
if (u.device == radio && u.ssid == essid && normbssid(u.bssid) == normbssid(bssid))
return u['.name'];
return '';
};
// option of the referenced uplink as string, dflt if there is no such
// uplink or the option is unset or empty
export function option(uplinks, name, opt, dflt) {
if (length(name ?? ''))
for (let u in uplinks)
if (u['.name'] == name) {
let v = u[opt];
return (v == null || v == '') ? (dflt ?? '') : '' + v;
}
return dflt ?? '';
};
+79
View File
@@ -0,0 +1,79 @@
// travelmate - vpn handling decisions: plan() returns the steps for an action
// (op: down, clear, rc, pgm), infolist() the usable vpn interfaces
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2016-2026 Dirk Brenken <dev@brenken.org>
// netifd protocols that are vpn interfaces without further notice
const VPN_PROTOS = [ 'wireguard', 'openvpn' ];
// the vpn service of a network interface section, its netifd protocol
export function service(s) {
return '' + (s?.proto ?? '');
};
// st: { vpn, list, action, connection, connected, ntp }, up: { vpn, iface,
// service } of the current uplink; returns { steps, pgm }
export function plan(st, up, is_up) {
let out = [], connected = st.connected, action = st.action, pgm = false;
if (!st.vpn || !length(st.list))
return { steps: out, pgm };
// initial cleanup: tear down all known vpn interfaces
if (!connected || action == 'enable') {
for (let iface in st.list)
if (is_up(iface))
push(out, { op: 'down', iface, why: 'initial' });
push(out, { op: 'clear' });
connected = false;
}
// switch: tear down a foreign vpn interface, keep the configured one
else if (up.vpn && length(up.iface) && action == 'enable_keep') {
for (let iface in st.list) {
if (is_up(iface) && iface != up.iface) {
push(out, { op: 'down', iface, why: 'switch' }, { op: 'rc' }, { op: 'clear' });
connected = false;
break;
}
}
}
// start or stop the vpn connection on valid enable/disable transitions
if (length(up.service) && length(up.iface)) {
let enable = (action == 'enable' || action == 'enable_keep');
pgm = true;
if ((action == 'disable' && connected) ||
(!up.vpn && enable && connected) ||
(st.ntp && up.vpn && enable && !connected)) {
if (st.connection || action == 'disable')
push(out, { op: 'pgm', action: up.vpn ? action : 'disable', iface: up.iface, service: up.service });
}
}
return { steps: out, pgm };
};
// usable: all wireguard/openvpn interfaces and any other netifd protocol
// that is referenced (refs) or listed in trm_vpnifacelist
export function infolist(ifaces, filter_list, refs) {
let list = [], logs = [];
let dash = (v) => length(v ?? '') ? v : '-';
for (let s in ifaces) {
let iface = s['.name'], proto = service(s);
if ((!length(filter_list) || iface in filter_list) && !(iface in list) &&
(proto in VPN_PROTOS || (length(proto) && proto != 'none' && (length(filter_list) || iface in (refs ?? [])))))
push(list, iface);
push(logs, sprintf('f_getvpn ::: iface: %s, proto: %s, vpn_ifacelist: %s, vpn_infolist: %s',
dash(iface), dash(proto), dash(join(' ', filter_list)), dash(join(' ', list))));
}
return { list, logs };
};
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# travelmate has no version output by design: the runtime version comes from
# rpc-sys packagelist via ubus, which is not available in the CI container.
[ "$1" = "travelmate" ] || exit 1
exit 0
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# compile and load with the shipped ucode.
#
travelmate 2>&1 | grep 'usage: travelmate' || exit 1
ucode -e 'import * as a from "travelmate.daemon"; import * as b from "travelmate.login";
print("modules-ok\n");' |
grep 'modules-ok'