feat(profiles): WAN-mode / conditional-override profiles [T2] — the real §7 feature
The Profiles page was a stub for the actual catalog §7 feature (WAN-mode / failover conditional overrides); this implements it. A `config profile` defines conditions (active default-route interface, a connectivity probe up/down, a time window — all AND'd) and overrides (force-enable/disable named rules, override the default catch-all target/egress). The highest-priority profile whose conditions all hold is active; its overrides are applied at gen/reconcile time and the cron re-applies when the active profile flips. - model.go/uci.go: Profile struct + `config profile` parse. - profile_wanmode.go: defaultIface() (ip route), profileProbeUp() (HTTP), condition eval, activeWanProfile() (priority + AND conditions; no-condition profile never auto-activates), ProfileStatusJSON. strSet helper. - generate.go: builder.activeProfile set in buildConfigInternal; buildRoutingRules applies enable/disable-by-name + injects a default-target catch-all when active. - schedule.go: scheduleSignature includes the active profile name, so shater-cron reconciles on a profile transition (iface/probe/time boundary). - main.go: `xrayctl wanmode`. shater.uc `wanmode` ubus + acl. - profiles.js: rewritten to host WAN-mode Profiles (config profile GridSection) + active-profile banner + Config snapshots + Backup/Restore + xray compatibility. - tests: profile_wanmode_test.go (iface/schedule/AND conditions, priority selection, no-condition never active, override enable/disable, default-target injection, inactive-no-override). Verified live on the 512M VM: `wanmode` reports active sim-mode (iface eth1); force-enabled a disabled rule (profileonly.example appears); flipping the iface condition deactivates it; schedule condition active at 22:30 / inactive at 12:00; xray -test OK. Playwright: Profiles page renders the WAN-mode form + active banner + snapshots + backup + compat with 0 console errors. r16. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
21ee972df1
commit
6c01d8db41
14 files changed
+595
-138
No files matched your search
+25
@@ -168,6 +168,31 @@ config preset 'block_ads'
|
|||||||
Без geodata гео-only паки (block-ads/ru-bypass) выкидываются (fail-open); private
|
Без geodata гео-only паки (block-ads/ru-bypass) выкидываются (fail-open); private
|
||||||
работает всегда (литеральные RFC1918/ULA).
|
работает всегда (литеральные RFC1918/ULA).
|
||||||
|
|
||||||
|
### profile (0..N — WAN-mode / условные оверрайды, T2)
|
||||||
|
```
|
||||||
|
config profile 'sim_mode'
|
||||||
|
option name 'sim-mode'
|
||||||
|
option enabled '1'
|
||||||
|
option priority '10' # выше = приоритетнее среди активных
|
||||||
|
# условия (все указанные И-объединяются; профиль без условий НЕ активируется):
|
||||||
|
list match_iface 'wwan0' # активен когда default-route dev ∈ списке
|
||||||
|
option probe_url '' # опц. connectivity-probe (HTTP)
|
||||||
|
option probe_mode 'up' # up|down (down = failover: активен когда probe лежит)
|
||||||
|
list sched_day 'mon' # окно по дням/времени (как в rule)
|
||||||
|
option sched_start '09:00'
|
||||||
|
option sched_end '18:00'
|
||||||
|
option sched_tz ''
|
||||||
|
# оверрайды при активности:
|
||||||
|
list enable_rule 'sim-vless-wrap' # форс-включить правила по имени
|
||||||
|
list disable_rule 'direct-ru' # выключить правила
|
||||||
|
option default_target 'group:ru-reality' # переопределить catch-all target
|
||||||
|
option default_egress ''
|
||||||
|
```
|
||||||
|
Активный профиль (наивысший priority с выполненными условиями) вычисляется при
|
||||||
|
gen/reconcile; `xrayctl wanmode` показывает активный. shater-cron переприменяет при
|
||||||
|
смене активного профиля (входит в scheduleSignature). Кейсы: SIM-аплинк→VLESS-egress,
|
||||||
|
whitelist-часы→RU-reality.
|
||||||
|
|
||||||
### resolver (0..N) + dns_rule (0..N) — DNS
|
### resolver (0..N) + dns_rule (0..N) — DNS
|
||||||
```
|
```
|
||||||
config resolver
|
config resolver
|
||||||
|
|||||||
@@ -180,6 +180,21 @@ egress-binding и DNS-рендер; далее T1 (цепочки в UI, per-cli
|
|||||||
|
|
||||||
Пруф: `ip netns exec shater_lan uclient-fetch https://1.1.1.1/cdn-cgi/trace` → exit ≠ WAN; nft-счётчик `c_rule_lan_proxy`=26 пакетов; оба `192.168.1.60/.61` в set `clients`; 184/254 ноды alive (observatory). Конфиг восстановлен (sub0-кеш→group g0 leastPing→tproxy inbound lan→rule src 192.168.1.0/24→group). Т.е. весь control-plane (mux/wg/inbounds/presets/schedule/ops/sub-форматы) не сломал data-plane.
|
Пруф: `ip netns exec shater_lan uclient-fetch https://1.1.1.1/cdn-cgi/trace` → exit ≠ WAN; nft-счётчик `c_rule_lan_proxy`=26 пакетов; оба `192.168.1.60/.61` в set `clients`; 184/254 ноды alive (observatory). Конфиг восстановлен (sub0-кеш→group g0 leastPing→tproxy inbound lan→rule src 192.168.1.0/24→group). Т.е. весь control-plane (mux/wg/inbounds/presets/schedule/ops/sub-форматы) не сломал data-plane.
|
||||||
|
|
||||||
|
## Дозакрытие (2026-07-09) — WAN-mode / условные профили (каталог §7, T2) — БЫЛА заглушка, теперь реализовано
|
||||||
|
|
||||||
|
Настоящая фича «Профили» (не путать с config-снапшотами): `config profile` — условные
|
||||||
|
оверрайды, авто-переключающие роутинг по активному аплинку / connectivity-probe / окну времени.
|
||||||
|
| Что | Пруф (живой, 512M VM) |
|
||||||
|
|---|---|
|
||||||
|
| `xrayctl wanmode` | `{active:"sim-mode", default_iface:"eth1", profiles:[{active:true}]}` |
|
||||||
|
| условие по iface | профиль с `match_iface=eth1` активен (eth1 — текущий default); force-enable правила → `profileonly.example` появился в gen |
|
||||||
|
| смена условия | `match_iface=wwan-nope` → active:"", правило исчезло (gen: 0 совпадений) |
|
||||||
|
| условие по расписанию | `SHATER_FAKE_NOW=22:30` → active sim-mode; `12:00` → active "" |
|
||||||
|
| оверрайды | enable_rule/disable_rule по имени + default_target (инжектит catch-all); `xray -test OK` |
|
||||||
|
| приоритет / AND-условия | unit: priority-выбор, iface∧schedule, «нет условий ⇒ никогда не активен» |
|
||||||
|
| cron re-apply | активный профиль входит в `scheduleSignature` → shater-cron переприменяет при смене |
|
||||||
|
| UI | страница Backup/Profiles: секция **WAN-mode profiles** (config profile) + баннер активного + Config snapshots + Backup + Compat; Playwright: рендерит, **0 console-ошибок** |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## (продолжение) geodata-опциональность — детали пруфа
|
## (продолжение) geodata-опциональность — детали пруфа
|
||||||
|
|||||||
@@ -1,20 +1,25 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
'require view';
|
'require view';
|
||||||
|
'require form';
|
||||||
'require dom';
|
'require dom';
|
||||||
'require rpc';
|
'require rpc';
|
||||||
'require ui';
|
'require ui';
|
||||||
'require uci';
|
'require uci';
|
||||||
|
|
||||||
// Backup / restore, named config profiles, and xray version compatibility.
|
// This page hosts three things:
|
||||||
// Backend: xrayctl backup|restore|profile|compat via the `xray` ubus object.
|
// 1. WAN-mode Profiles (config profile) — conditional overrides that auto-switch
|
||||||
|
// routing by active uplink / connectivity probe / time window (catalog §7).
|
||||||
|
// 2. Config snapshots — save/restore/switch named backups of the whole config.
|
||||||
|
// 3. Backup/Restore + xray compatibility.
|
||||||
|
|
||||||
var callBackup = rpc.declare({ object: 'xray', method: 'backup', expect: { '': {} } });
|
var callBackup = rpc.declare({ object: 'xray', method: 'backup', expect: { '': {} } });
|
||||||
var callRestore = rpc.declare({ object: 'xray', method: 'restore', params: ['b64', 'confirm'], expect: { '': {} } });
|
var callRestore = rpc.declare({ object: 'xray', method: 'restore', params: ['b64', 'confirm'], expect: { '': {} } });
|
||||||
var callProfiles = rpc.declare({ object: 'xray', method: 'profile_list', expect: { '': {} } });
|
var callSnapshots = rpc.declare({ object: 'xray', method: 'profile_list', expect: { '': {} } });
|
||||||
var callProfileSave = rpc.declare({ object: 'xray', method: 'profile_save', params: ['name'], expect: { '': {} } });
|
var callSnapSave = rpc.declare({ object: 'xray', method: 'profile_save', params: ['name'], expect: { '': {} } });
|
||||||
var callProfileSwitch = rpc.declare({ object: 'xray', method: 'profile_switch', params: ['name', 'confirm'], expect: { '': {} } });
|
var callSnapSwitch = rpc.declare({ object: 'xray', method: 'profile_switch', params: ['name', 'confirm'], expect: { '': {} } });
|
||||||
var callProfileDelete = rpc.declare({ object: 'xray', method: 'profile_delete', params: ['name'], expect: { '': {} } });
|
var callSnapDelete = rpc.declare({ object: 'xray', method: 'profile_delete', params: ['name'], expect: { '': {} } });
|
||||||
var callCompat = rpc.declare({ object: 'xray', method: 'compat', expect: { '': {} } });
|
var callCompat = rpc.declare({ object: 'xray', method: 'compat', expect: { '': {} } });
|
||||||
|
var callWanmode = rpc.declare({ object: 'xray', method: 'wanmode', expect: { '': {} } });
|
||||||
|
|
||||||
function fmtBytes(v) {
|
function fmtBytes(v) {
|
||||||
v = v || 0;
|
v = v || 0;
|
||||||
@@ -22,36 +27,153 @@ function fmtBytes(v) {
|
|||||||
if (v >= 1024) return (v / 1024).toFixed(1) + ' KB';
|
if (v >= 1024) return (v / 1024).toFixed(1) + ' KB';
|
||||||
return v + ' B';
|
return v + ' B';
|
||||||
}
|
}
|
||||||
|
function confirmTimeout() { return uci.get('shater', 'globals', 'confirm_timeout') || '0'; }
|
||||||
function confirmTimeout() {
|
function reloadSoon() { window.setTimeout(function () { window.location.reload(); }, 800); }
|
||||||
var v = uci.get('shater', 'globals', 'confirm_timeout');
|
var HHMM = /^([01]?\d|2[0-3]):[0-5]\d$/;
|
||||||
return v || '0';
|
|
||||||
}
|
|
||||||
|
|
||||||
function reloadSoon() {
|
|
||||||
window.setTimeout(function () { window.location.reload(); }, 800);
|
|
||||||
}
|
|
||||||
|
|
||||||
return view.extend({
|
return view.extend({
|
||||||
handleSaveApply: null,
|
|
||||||
handleSave: null,
|
|
||||||
handleReset: null,
|
|
||||||
|
|
||||||
load: function () {
|
load: function () {
|
||||||
return Promise.all([
|
return Promise.all([
|
||||||
uci.load('shater'),
|
uci.load('shater'),
|
||||||
L.resolveDefault(callProfiles(), { profiles: [] }),
|
L.resolveDefault(callSnapshots(), { profiles: [] }),
|
||||||
L.resolveDefault(callCompat(), {})
|
L.resolveDefault(callCompat(), {}),
|
||||||
|
L.resolveDefault(callWanmode(), {})
|
||||||
]);
|
]);
|
||||||
},
|
},
|
||||||
|
|
||||||
render: function (data) {
|
render: function (data) {
|
||||||
var profiles = (data[1] && data[1].profiles) || [];
|
var snapshots = (data[1] && data[1].profiles) || [];
|
||||||
var compat = data[2] || {};
|
var compat = data[2] || {};
|
||||||
|
var wan = data[3] || {};
|
||||||
|
|
||||||
// --- Backup / Restore card ---
|
// ---------- 1. WAN-mode Profiles (editable config) ----------
|
||||||
var downloadBtn = E('button', {
|
var m = new form.Map('shater', null,
|
||||||
'class': 'btn cbi-button cbi-button-action',
|
_('Conditional overrides that auto-switch routing by the active uplink, a ' +
|
||||||
|
'connectivity probe, or a time window. The highest-priority profile whose ' +
|
||||||
|
'conditions all hold becomes active and applies its overrides.'));
|
||||||
|
var s = m.section(form.GridSection, 'profile', _('WAN-mode profiles'));
|
||||||
|
s.addremove = true;
|
||||||
|
s.anonymous = true;
|
||||||
|
s.nodescriptions = true;
|
||||||
|
s.addbtntitle = _('Add profile');
|
||||||
|
|
||||||
|
var o = s.option(form.Value, 'name', _('Name'));
|
||||||
|
o.rmempty = false;
|
||||||
|
o.placeholder = 'sim-mode';
|
||||||
|
|
||||||
|
o = s.option(form.Flag, 'enabled', _('Enabled'));
|
||||||
|
o.default = '0';
|
||||||
|
o.editable = true;
|
||||||
|
|
||||||
|
o = s.option(form.Value, 'priority', _('Priority'));
|
||||||
|
o.datatype = 'uinteger';
|
||||||
|
o.default = '0';
|
||||||
|
|
||||||
|
// conditions
|
||||||
|
o = s.option(form.DynamicList, 'match_iface', _('Active uplink is'),
|
||||||
|
_('Profile active when the default route egresses via one of these interfaces (e.g. wwan0, usb0).'));
|
||||||
|
o.modalonly = true;
|
||||||
|
o.placeholder = 'wwan0';
|
||||||
|
|
||||||
|
o = s.option(form.Value, 'probe_url', _('Connectivity probe URL'),
|
||||||
|
_('Optional. Profile gated on whether this URL is reachable.'));
|
||||||
|
o.modalonly = true;
|
||||||
|
o.placeholder = 'http://www.gstatic.com/generate_204';
|
||||||
|
|
||||||
|
o = s.option(form.ListValue, 'probe_mode', _('Probe condition'));
|
||||||
|
o.value('up', _('active when probe is UP'));
|
||||||
|
o.value('down', _('active when probe is DOWN (failover)'));
|
||||||
|
o.default = 'up';
|
||||||
|
o.modalonly = true;
|
||||||
|
|
||||||
|
o = s.option(form.MultiValue, 'sched_day', _('Days'));
|
||||||
|
[['mon', 'Mon'], ['tue', 'Tue'], ['wed', 'Wed'], ['thu', 'Thu'],
|
||||||
|
['fri', 'Fri'], ['sat', 'Sat'], ['sun', 'Sun']].forEach(function (d) { o.value(d[0], _(d[1])); });
|
||||||
|
o.widget = 'checkbox';
|
||||||
|
o.modalonly = true;
|
||||||
|
|
||||||
|
o = s.option(form.Value, 'sched_start', _('Window start (HH:MM)'));
|
||||||
|
o.modalonly = true;
|
||||||
|
o.placeholder = '09:00';
|
||||||
|
o.validate = function (sid, v) { return (!v || HHMM.test(v)) ? true : _('Use HH:MM'); };
|
||||||
|
|
||||||
|
o = s.option(form.Value, 'sched_end', _('Window end (HH:MM)'));
|
||||||
|
o.modalonly = true;
|
||||||
|
o.placeholder = '18:00';
|
||||||
|
o.validate = function (sid, v) { return (!v || HHMM.test(v)) ? true : _('Use HH:MM'); };
|
||||||
|
|
||||||
|
o = s.option(form.Value, 'sched_tz', _('Timezone'));
|
||||||
|
o.modalonly = true;
|
||||||
|
o.optional = true;
|
||||||
|
|
||||||
|
// overrides
|
||||||
|
o = s.option(form.DynamicList, 'enable_rule', _('Force-enable rules'),
|
||||||
|
_('Rule names to enable while this profile is active.'));
|
||||||
|
o.modalonly = true;
|
||||||
|
o = s.option(form.DynamicList, 'disable_rule', _('Disable rules'));
|
||||||
|
o.modalonly = true;
|
||||||
|
o = s.option(form.Value, 'default_target', _('Override default target'),
|
||||||
|
_('group:/node:/chain:/direct/block — becomes the catch-all while active.'));
|
||||||
|
o.modalonly = true;
|
||||||
|
o.placeholder = 'group:ru-reality';
|
||||||
|
o = s.option(form.Value, 'default_egress', _('Override default egress'));
|
||||||
|
o.modalonly = true;
|
||||||
|
|
||||||
|
// active-profile banner
|
||||||
|
var activeTxt = wan.active
|
||||||
|
? E('span', {}, [_('Active WAN-mode profile: '), E('strong', { 'style': 'color:#5cb85c' }, wan.active)])
|
||||||
|
: E('span', { 'style': 'opacity:.7' }, _('No WAN-mode profile is currently active.'));
|
||||||
|
var banner = E('div', { 'class': 'cbi-section', 'style': 'padding:.4em .6em' }, [
|
||||||
|
activeTxt,
|
||||||
|
wan.default_iface ? E('span', { 'style': 'opacity:.7;margin-left:1em' }, [_('default uplink: '), E('code', {}, wan.default_iface)]) : ''
|
||||||
|
]);
|
||||||
|
|
||||||
|
// ---------- 2. Config snapshots ----------
|
||||||
|
var nameInput = E('input', { 'type': 'text', 'class': 'cbi-input-text', 'placeholder': _('snapshot name') });
|
||||||
|
var saveBtn = E('button', {
|
||||||
|
'class': 'btn cbi-button cbi-button-add',
|
||||||
|
'click': ui.createHandlerFn(this, function () {
|
||||||
|
var n = (nameInput.value || '').trim();
|
||||||
|
if (!n) { ui.addNotification(null, E('p', {}, _('Enter a name.')), 'warning'); return; }
|
||||||
|
return callSnapSave(n).then(function () { ui.addNotification(null, E('p', {}, _('Snapshot saved.')), 'info'); reloadSoon(); });
|
||||||
|
})
|
||||||
|
}, _('Save current as…'));
|
||||||
|
var rows = snapshots.map(function (p) {
|
||||||
|
return E('tr', { 'class': 'tr' }, [
|
||||||
|
E('td', { 'class': 'td' }, [p.name, p.active ? E('span', { 'class': 'label', 'style': 'margin-left:.5em;background:#5cb85c;color:#fff' }, _('active')) : '']),
|
||||||
|
E('td', { 'class': 'td' }, fmtBytes(p.size)),
|
||||||
|
E('td', { 'class': 'td' }, 'v' + (p.schema_version || 0)),
|
||||||
|
E('td', { 'class': 'td' }, [
|
||||||
|
E('button', { 'class': 'btn cbi-button cbi-button-action', 'style': 'margin-right:.4em',
|
||||||
|
'click': ui.createHandlerFn(this, function () {
|
||||||
|
if (!confirm(_('Switch to snapshot "%s"?').format(p.name))) return;
|
||||||
|
ui.showModal(_('Switching…'), [E('p', { 'class': 'spinning' }, _('Applying snapshot.'))]);
|
||||||
|
return callSnapSwitch(p.name, confirmTimeout()).then(function () { ui.hideModal(); reloadSoon(); })
|
||||||
|
.catch(function (e) { ui.hideModal(); ui.addNotification(null, E('p', {}, '' + e), 'danger'); });
|
||||||
|
}) }, _('Switch')),
|
||||||
|
E('button', { 'class': 'btn cbi-button cbi-button-remove',
|
||||||
|
'click': ui.createHandlerFn(this, function () {
|
||||||
|
if (!confirm(_('Delete snapshot "%s"?').format(p.name))) return;
|
||||||
|
return callSnapDelete(p.name).then(function () { reloadSoon(); });
|
||||||
|
}) }, _('Delete'))
|
||||||
|
])
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
var snapTable = E('table', { 'class': 'table cbi-section-table' }, [
|
||||||
|
E('tr', { 'class': 'tr table-titles' }, [
|
||||||
|
E('th', { 'class': 'th' }, _('Snapshot')), E('th', { 'class': 'th' }, _('Size')),
|
||||||
|
E('th', { 'class': 'th' }, _('Schema')), E('th', { 'class': 'th' }, _('Actions'))
|
||||||
|
])
|
||||||
|
].concat(rows.length ? rows : [E('tr', { 'class': 'tr' }, [E('td', { 'class': 'td', 'colspan': 4 }, E('em', {}, _('No snapshots.')))])]));
|
||||||
|
var snapCard = E('div', { 'class': 'cbi-section' }, [
|
||||||
|
E('h3', {}, _('Config snapshots')),
|
||||||
|
E('p', {}, _('Named snapshots of the whole config you can switch between atomically (commit-confirm protected).')),
|
||||||
|
snapTable,
|
||||||
|
E('div', { 'style': 'margin-top:.6em;display:flex;gap:.5em;align-items:center' }, [nameInput, saveBtn])
|
||||||
|
]);
|
||||||
|
|
||||||
|
// ---------- 3. Backup / Restore ----------
|
||||||
|
var downloadBtn = E('button', { 'class': 'btn cbi-button cbi-button-action',
|
||||||
'click': ui.createHandlerFn(this, function () {
|
'click': ui.createHandlerFn(this, function () {
|
||||||
return callBackup().then(function (r) {
|
return callBackup().then(function (r) {
|
||||||
if (!r || !r.data) throw _('Backup failed');
|
if (!r || !r.data) throw _('Backup failed');
|
||||||
@@ -59,18 +181,12 @@ return view.extend({
|
|||||||
for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
||||||
var url = URL.createObjectURL(new Blob([buf], { type: 'application/gzip' }));
|
var url = URL.createObjectURL(new Blob([buf], { type: 'application/gzip' }));
|
||||||
var a = E('a', { 'href': url, 'download': r.filename || 'shater-backup.tar.gz' });
|
var a = E('a', { 'href': url, 'download': r.filename || 'shater-backup.tar.gz' });
|
||||||
document.body.appendChild(a); a.click(); a.remove();
|
document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
|
||||||
URL.revokeObjectURL(url);
|
|
||||||
ui.addNotification(null, E('p', {}, _('Backup downloaded.')), 'info');
|
ui.addNotification(null, E('p', {}, _('Backup downloaded.')), 'info');
|
||||||
}).catch(function (e) {
|
}).catch(function (e) { ui.addNotification(null, E('p', {}, _('Backup error: ') + e), 'danger'); });
|
||||||
ui.addNotification(null, E('p', {}, _('Backup error: ') + e), 'danger');
|
}) }, _('Download backup'));
|
||||||
});
|
|
||||||
})
|
|
||||||
}, _('Download backup'));
|
|
||||||
|
|
||||||
var fileInput = E('input', { 'type': 'file', 'accept': '.tar.gz,application/gzip' });
|
var fileInput = E('input', { 'type': 'file', 'accept': '.tar.gz,application/gzip' });
|
||||||
var restoreBtn = E('button', {
|
var restoreBtn = E('button', { 'class': 'btn cbi-button cbi-button-negative',
|
||||||
'class': 'btn cbi-button cbi-button-negative',
|
|
||||||
'click': ui.createHandlerFn(this, function () {
|
'click': ui.createHandlerFn(this, function () {
|
||||||
var f = fileInput.files && fileInput.files[0];
|
var f = fileInput.files && fileInput.files[0];
|
||||||
if (!f) { ui.addNotification(null, E('p', {}, _('Choose a backup file first.')), 'warning'); return; }
|
if (!f) { ui.addNotification(null, E('p', {}, _('Choose a backup file first.')), 'warning'); return; }
|
||||||
@@ -79,123 +195,49 @@ return view.extend({
|
|||||||
var reader = new FileReader();
|
var reader = new FileReader();
|
||||||
reader.onload = function () {
|
reader.onload = function () {
|
||||||
var b64 = String(reader.result).replace(/^data:[^,]*,/, '');
|
var b64 = String(reader.result).replace(/^data:[^,]*,/, '');
|
||||||
ui.showModal(_('Restoring…'), [E('p', { 'class': 'spinning' }, _('Validating and applying the restored config.'))]);
|
ui.showModal(_('Restoring…'), [E('p', { 'class': 'spinning' }, _('Validating and applying.'))]);
|
||||||
callRestore(b64, confirmTimeout()).then(function (r) {
|
callRestore(b64, confirmTimeout()).then(function (r) {
|
||||||
ui.hideModal();
|
ui.hideModal();
|
||||||
if (r && r.ok === false)
|
if (r && r.ok === false) ui.addNotification(null, E('p', {}, _('Restore failed (config kept).')), 'danger');
|
||||||
ui.addNotification(null, E('p', {}, _('Restore failed (config kept).')), 'danger');
|
else { ui.addNotification(null, E('p', {}, _('Restored. Reloading…')), 'info'); reloadSoon(); }
|
||||||
else {
|
|
||||||
ui.addNotification(null, E('p', {}, _('Restored. Reloading…')), 'info');
|
|
||||||
reloadSoon();
|
|
||||||
}
|
|
||||||
resolve();
|
resolve();
|
||||||
}).catch(function (e) { ui.hideModal(); ui.addNotification(null, E('p', {}, _('Restore error: ') + e), 'danger'); resolve(); });
|
}).catch(function (e) { ui.hideModal(); ui.addNotification(null, E('p', {}, _('Restore error: ') + e), 'danger'); resolve(); });
|
||||||
};
|
};
|
||||||
reader.readAsDataURL(f);
|
reader.readAsDataURL(f);
|
||||||
});
|
});
|
||||||
})
|
}) }, _('Restore'));
|
||||||
}, _('Restore'));
|
|
||||||
|
|
||||||
var backupCard = E('div', { 'class': 'cbi-section' }, [
|
var backupCard = E('div', { 'class': 'cbi-section' }, [
|
||||||
E('h3', {}, _('Backup / Restore')),
|
E('h3', {}, _('Backup / Restore')),
|
||||||
E('p', {}, _('A backup bundles /etc/config/shater and the subscription caches. ' +
|
E('p', {}, _('A backup bundles /etc/config/shater and the subscription caches. It contains credentials — keep it private.')),
|
||||||
'It contains credentials — keep it private. Restore validates the config ' +
|
E('div', { 'style': 'display:flex;gap:.75em;align-items:center;flex-wrap:wrap' }, [downloadBtn, E('span', { 'style': 'width:1em' }), fileInput, restoreBtn])
|
||||||
'with xray -test and applies it with commit-confirm.')),
|
|
||||||
E('div', { 'style': 'display:flex;gap:.75em;align-items:center;flex-wrap:wrap' }, [
|
|
||||||
downloadBtn, E('span', { 'style': 'width:1em' }), fileInput, restoreBtn
|
|
||||||
])
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// --- Profiles card ---
|
// ---------- 4. Compatibility ----------
|
||||||
var nameInput = E('input', { 'type': 'text', 'class': 'cbi-input-text', 'placeholder': _('profile name') });
|
|
||||||
var saveBtn = E('button', {
|
|
||||||
'class': 'btn cbi-button cbi-button-add',
|
|
||||||
'click': ui.createHandlerFn(this, function () {
|
|
||||||
var n = (nameInput.value || '').trim();
|
|
||||||
if (!n) { ui.addNotification(null, E('p', {}, _('Enter a name.')), 'warning'); return; }
|
|
||||||
return callProfileSave(n).then(function () {
|
|
||||||
ui.addNotification(null, E('p', {}, _('Profile saved.')), 'info'); reloadSoon();
|
|
||||||
});
|
|
||||||
})
|
|
||||||
}, _('Save current as…'));
|
|
||||||
|
|
||||||
var rows = profiles.map(function (p) {
|
|
||||||
return E('tr', { 'class': 'tr' }, [
|
|
||||||
E('td', { 'class': 'td' }, [
|
|
||||||
p.name, p.active ? E('span', { 'class': 'label', 'style': 'margin-left:.5em;background:#5cb85c;color:#fff' }, _('active')) : ''
|
|
||||||
]),
|
|
||||||
E('td', { 'class': 'td' }, fmtBytes(p.size)),
|
|
||||||
E('td', { 'class': 'td' }, 'v' + (p.schema_version || 0)),
|
|
||||||
E('td', { 'class': 'td' }, [
|
|
||||||
E('button', {
|
|
||||||
'class': 'btn cbi-button cbi-button-action', 'style': 'margin-right:.4em',
|
|
||||||
'click': ui.createHandlerFn(this, function () {
|
|
||||||
if (!confirm(_('Switch to profile "%s"?').format(p.name))) return;
|
|
||||||
ui.showModal(_('Switching…'), [E('p', { 'class': 'spinning' }, _('Applying profile.'))]);
|
|
||||||
return callProfileSwitch(p.name, confirmTimeout()).then(function () { ui.hideModal(); reloadSoon(); })
|
|
||||||
.catch(function (e) { ui.hideModal(); ui.addNotification(null, E('p', {}, '' + e), 'danger'); });
|
|
||||||
})
|
|
||||||
}, _('Switch')),
|
|
||||||
E('button', {
|
|
||||||
'class': 'btn cbi-button cbi-button-remove',
|
|
||||||
'click': ui.createHandlerFn(this, function () {
|
|
||||||
if (!confirm(_('Delete profile "%s"?').format(p.name))) return;
|
|
||||||
return callProfileDelete(p.name).then(function () { reloadSoon(); });
|
|
||||||
})
|
|
||||||
}, _('Delete'))
|
|
||||||
])
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
var profileTable = E('table', { 'class': 'table cbi-section-table' }, [
|
|
||||||
E('tr', { 'class': 'tr table-titles' }, [
|
|
||||||
E('th', { 'class': 'th' }, _('Profile')),
|
|
||||||
E('th', { 'class': 'th' }, _('Size')),
|
|
||||||
E('th', { 'class': 'th' }, _('Schema')),
|
|
||||||
E('th', { 'class': 'th' }, _('Actions'))
|
|
||||||
])
|
|
||||||
].concat(rows.length ? rows : [E('tr', { 'class': 'tr' }, [E('td', { 'class': 'td', 'colspan': 4 }, E('em', {}, _('No saved profiles.')))])]));
|
|
||||||
|
|
||||||
var profilesCard = E('div', { 'class': 'cbi-section' }, [
|
|
||||||
E('h3', {}, _('Config profiles')),
|
|
||||||
E('p', {}, _('Named config snapshots you can switch between atomically (commit-confirm protected).')),
|
|
||||||
profileTable,
|
|
||||||
E('div', { 'style': 'margin-top:.6em;display:flex;gap:.5em;align-items:center' }, [nameInput, saveBtn])
|
|
||||||
]);
|
|
||||||
|
|
||||||
// --- Compat card ---
|
|
||||||
var feats = (compat.features || []).map(function (f) {
|
var feats = (compat.features || []).map(function (f) {
|
||||||
return E('tr', { 'class': 'tr' }, [
|
return E('tr', { 'class': 'tr' }, [
|
||||||
E('td', { 'class': 'td' }, f.name),
|
E('td', { 'class': 'td' }, f.name), E('td', { 'class': 'td' }, f.required || '—'),
|
||||||
E('td', { 'class': 'td' }, f.required || '—'),
|
|
||||||
E('td', { 'class': 'td' }, f.detected || '?'),
|
E('td', { 'class': 'td' }, f.detected || '?'),
|
||||||
E('td', { 'class': 'td' }, f.ok
|
E('td', { 'class': 'td' }, f.ok ? E('span', { 'style': 'color:#5cb85c' }, '✓') : E('span', { 'style': 'color:#c00' }, '✗'))
|
||||||
? E('span', { 'style': 'color:#5cb85c' }, '✓')
|
|
||||||
: E('span', { 'style': 'color:#c00' }, '✗'))
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
var compatCard = E('div', { 'class': 'cbi-section' }, [
|
var compatCard = E('div', { 'class': 'cbi-section' }, [
|
||||||
E('h3', {}, _('xray compatibility')),
|
E('h3', {}, _('xray compatibility')),
|
||||||
E('p', {}, [
|
E('p', {}, [_('Detected xray: '), E('strong', {}, compat.xray_version || _('unknown')), ' — ',
|
||||||
_('Detected xray: '), E('strong', {}, compat.xray_version || _('unknown')),
|
compat.ok ? E('span', { 'style': 'color:#5cb85c' }, _('all used features supported')) : E('span', { 'style': 'color:#c00' }, _('some features need a newer xray'))]),
|
||||||
' — ', compat.ok
|
|
||||||
? E('span', { 'style': 'color:#5cb85c' }, _('all used features supported'))
|
|
||||||
: E('span', { 'style': 'color:#c00' }, _('some features need a newer xray'))
|
|
||||||
]),
|
|
||||||
feats.length ? E('table', { 'class': 'table cbi-section-table' }, [
|
feats.length ? E('table', { 'class': 'table cbi-section-table' }, [
|
||||||
E('tr', { 'class': 'tr table-titles' }, [
|
E('tr', { 'class': 'tr table-titles' }, [E('th', { 'class': 'th' }, _('Feature')), E('th', { 'class': 'th' }, _('Requires')), E('th', { 'class': 'th' }, _('Detected')), E('th', { 'class': 'th' }, _('OK'))])
|
||||||
E('th', { 'class': 'th' }, _('Feature')),
|
|
||||||
E('th', { 'class': 'th' }, _('Requires')),
|
|
||||||
E('th', { 'class': 'th' }, _('Detected')),
|
|
||||||
E('th', { 'class': 'th' }, _('OK'))
|
|
||||||
])
|
|
||||||
].concat(feats)) : E('p', {}, E('em', {}, _('No version-sensitive features in use.')))
|
].concat(feats)) : E('p', {}, E('em', {}, _('No version-sensitive features in use.')))
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return E('div', {}, [
|
return m.render().then(function (wanForm) {
|
||||||
E('h2', {}, _('Shater — Backup / Profiles')),
|
return E('div', {}, [
|
||||||
backupCard,
|
E('h2', {}, _('Shater — Backup / Profiles')),
|
||||||
profilesCard,
|
banner,
|
||||||
compatCard
|
wanForm,
|
||||||
]);
|
snapCard,
|
||||||
|
backupCard,
|
||||||
|
compatCard
|
||||||
|
]);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
"read": {
|
"read": {
|
||||||
"uci": [ "shater" ],
|
"uci": [ "shater" ],
|
||||||
"ubus": {
|
"ubus": {
|
||||||
"xray": [ "status", "nodes", "stats", "explain", "geodata_status", "compat", "profile_list", "backup", "sub_info", "conns", "node_qr" ]
|
"xray": [ "status", "nodes", "stats", "explain", "geodata_status", "compat", "profile_list", "backup", "sub_info", "conns", "node_qr", "wanmode" ]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"write": {
|
"write": {
|
||||||
|
|||||||
@@ -232,6 +232,13 @@ return {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Active WAN-mode profile + evaluation { default_iface, active, profiles:[...] }.
|
||||||
|
wanmode: {
|
||||||
|
call: function() {
|
||||||
|
return run_json(XRAYCTL + ' wanmode');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
// List saved config profiles -> { profiles: [...] }.
|
// List saved config profiles -> { profiles: [...] }.
|
||||||
profile_list: {
|
profile_list: {
|
||||||
call: function() {
|
call: function() {
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ include $(TOPDIR)/rules.mk
|
|||||||
|
|
||||||
PKG_NAME:=shater-core
|
PKG_NAME:=shater-core
|
||||||
PKG_VERSION:=0.1.0
|
PKG_VERSION:=0.1.0
|
||||||
PKG_RELEASE:=15
|
PKG_RELEASE:=16
|
||||||
|
|
||||||
PKG_MAINTAINER:=Shater <maqrota@icloud.com>
|
PKG_MAINTAINER:=Shater <maqrota@icloud.com>
|
||||||
PKG_LICENSE:=GPL-2.0-or-later
|
PKG_LICENSE:=GPL-2.0-or-later
|
||||||
|
|||||||
+1
-1
@@ -10,7 +10,7 @@ include $(TOPDIR)/rules.mk
|
|||||||
|
|
||||||
PKG_NAME:=xrayctl
|
PKG_NAME:=xrayctl
|
||||||
PKG_VERSION:=0.1.0
|
PKG_VERSION:=0.1.0
|
||||||
PKG_RELEASE:=15
|
PKG_RELEASE:=16
|
||||||
|
|
||||||
PKG_MAINTAINER:=shater
|
PKG_MAINTAINER:=shater
|
||||||
PKG_LICENSE:=MIT
|
PKG_LICENSE:=MIT
|
||||||
|
|||||||
+30
-2
@@ -42,8 +42,9 @@ type builder struct {
|
|||||||
groupFallback map[string]string // group name -> balancer fallbackTag (block|direct), kill-switch driven
|
groupFallback map[string]string // group name -> balancer fallbackTag (block|direct), kill-switch driven
|
||||||
probeURL string
|
probeURL string
|
||||||
probeItv string
|
probeItv string
|
||||||
geoOK bool // geoip.dat/geosite.dat present -> geo matchers are usable
|
geoOK bool // geoip.dat/geosite.dat present -> geo matchers are usable
|
||||||
geoStripped int // count of geosite:/geoip: matchers dropped when absent
|
geoStripped int // count of geosite:/geoip: matchers dropped when absent
|
||||||
|
activeProfile *Profile // active WAN-mode override, or nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// apiInboundPort is the loopback dokodemo port exposing the xray gRPC API
|
// apiInboundPort is the loopback dokodemo port exposing the xray gRPC API
|
||||||
@@ -99,6 +100,10 @@ func newProbeBuilder(m *Model) *builder { return newBuilder(m) }
|
|||||||
func buildConfigInternal(m *Model, withAPI bool) (map[string]any, error) {
|
func buildConfigInternal(m *Model, withAPI bool) (map[string]any, error) {
|
||||||
b := newBuilder(m)
|
b := newBuilder(m)
|
||||||
|
|
||||||
|
// WAN-mode: pick the active conditional-override profile (nil if none). Its
|
||||||
|
// rule enable/disable + default-target override are applied in buildRoutingRules.
|
||||||
|
b.activeProfile = activeWanProfile(m, timeNow())
|
||||||
|
|
||||||
// Kill-switch: decide each group balancer's fallbackTag before emitting them.
|
// Kill-switch: decide each group balancer's fallbackTag before emitting them.
|
||||||
b.computeGroupFallback()
|
b.computeGroupFallback()
|
||||||
|
|
||||||
@@ -634,6 +639,29 @@ func (b *builder) buildRoutingRules() {
|
|||||||
// Preset packs sort ahead of user rules by their low Order (first-match).
|
// Preset packs sort ahead of user rules by their low Order (first-match).
|
||||||
rules := append([]Rule(nil), b.presetRules()...)
|
rules := append([]Rule(nil), b.presetRules()...)
|
||||||
rules = append(rules, b.m.Rules...)
|
rules = append(rules, b.m.Rules...)
|
||||||
|
// WAN-mode active profile: force-enable / disable rules by name, and append a
|
||||||
|
// default-target catch-all when the profile overrides the default egress/target.
|
||||||
|
if p := b.activeProfile; p != nil {
|
||||||
|
en := strSet(p.EnableRules)
|
||||||
|
dis := strSet(p.DisableRules)
|
||||||
|
for i := range rules {
|
||||||
|
if en[rules[i].Name] {
|
||||||
|
rules[i].Enabled = true
|
||||||
|
}
|
||||||
|
if dis[rules[i].Name] {
|
||||||
|
rules[i].Enabled = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.DefaultTarget != "" || p.DefaultEgress != "" {
|
||||||
|
rules = append(rules, Rule{
|
||||||
|
Name: "_profile-" + p.Name + "-default",
|
||||||
|
Enabled: true,
|
||||||
|
Order: 1 << 20, // sorts last: catches everything unmatched
|
||||||
|
Target: orDefault(p.DefaultTarget, "direct"),
|
||||||
|
Egress: p.DefaultEgress,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
sort.SliceStable(rules, func(i, j int) bool { return rules[i].Order < rules[j].Order })
|
sort.SliceStable(rules, func(i, j int) bool { return rules[i].Order < rules[j].Order })
|
||||||
now := timeNow()
|
now := timeNow()
|
||||||
for _, r := range rules {
|
for _, r := range rules {
|
||||||
|
|||||||
@@ -63,6 +63,8 @@ func run(args []string) int {
|
|||||||
return errWrap(Migrate())
|
return errWrap(Migrate())
|
||||||
case "compat":
|
case "compat":
|
||||||
return emit(CompatJSON())
|
return emit(CompatJSON())
|
||||||
|
case "wanmode":
|
||||||
|
return emit(ProfileStatusJSON())
|
||||||
case "ruleset":
|
case "ruleset":
|
||||||
return cmdRuleset(rest)
|
return cmdRuleset(rest)
|
||||||
case "status":
|
case "status":
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ type Model struct {
|
|||||||
Rulesets []Ruleset
|
Rulesets []Ruleset
|
||||||
Rules []Rule
|
Rules []Rule
|
||||||
Presets []Preset
|
Presets []Preset
|
||||||
|
Profiles []Profile
|
||||||
Resolvers []Resolver
|
Resolvers []Resolver
|
||||||
DNSRules []DNSRule
|
DNSRules []DNSRule
|
||||||
}
|
}
|
||||||
@@ -182,6 +183,33 @@ type Egress struct {
|
|||||||
Target string
|
Target string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Profile is a `config profile` — a WAN-mode / failover conditional override
|
||||||
|
// (catalog §7, T2). When its conditions hold (active default-route interface,
|
||||||
|
// connectivity probe up/down, and/or a time window — all AND'd), the highest-
|
||||||
|
// priority active profile applies its overrides: force-enable / disable named
|
||||||
|
// rules and optionally override the default catch-all target/egress. Evaluated
|
||||||
|
// at gen/reconcile time; the cron re-applies when the active profile changes.
|
||||||
|
type Profile struct {
|
||||||
|
Name string
|
||||||
|
Enabled bool
|
||||||
|
Priority int
|
||||||
|
|
||||||
|
// conditions (only the specified ones are checked; all must hold)
|
||||||
|
MatchIface []string // active default-route dev in this set (e.g. wwan0, usb0)
|
||||||
|
ProbeURL string // connectivity probe (HTTP); empty = no probe condition
|
||||||
|
ProbeMode string // up|down — active when the probe succeeds/fails (default up)
|
||||||
|
SchedDays []string
|
||||||
|
SchedStart string
|
||||||
|
SchedEnd string
|
||||||
|
SchedTZ string
|
||||||
|
|
||||||
|
// overrides applied while active
|
||||||
|
EnableRules []string // rule names to force-enable
|
||||||
|
DisableRules []string // rule names to disable
|
||||||
|
DefaultTarget string // override the default catch-all target (group:/node:/chain:/direct/block)
|
||||||
|
DefaultEgress string // override the default egress binding
|
||||||
|
}
|
||||||
|
|
||||||
// Ruleset is a `config ruleset` (reusable domain/ip list).
|
// Ruleset is a `config ruleset` (reusable domain/ip list).
|
||||||
type Ruleset struct {
|
type Ruleset struct {
|
||||||
Name string
|
Name string
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
// WAN-mode / failover profiles (catalog §7, T2). A `config profile` defines
|
||||||
|
// conditions (active default-route interface, a connectivity probe up/down, a
|
||||||
|
// time window — all AND'd) and overrides (force-enable/disable named rules,
|
||||||
|
// override the default catch-all target/egress). The highest-priority profile
|
||||||
|
// whose conditions all hold is "active"; its overrides are applied at gen time.
|
||||||
|
// Evaluated on every reconcile; the cron re-applies when the active profile
|
||||||
|
// changes (its name feeds scheduleSignature).
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"os/exec"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// strSet builds a lookup set from a string slice.
|
||||||
|
func strSet(ss []string) map[string]bool {
|
||||||
|
m := map[string]bool{}
|
||||||
|
for _, s := range ss {
|
||||||
|
m[s] = true
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// defaultIface returns the interface of the current default route (lowest metric
|
||||||
|
// first), or "" if none / unavailable.
|
||||||
|
func defaultIface() string {
|
||||||
|
out, err := exec.Command("ip", "route", "show", "default").Output()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
best, bestMetric := "", 1<<30
|
||||||
|
for _, line := range strings.Split(string(out), "\n") {
|
||||||
|
f := strings.Fields(line)
|
||||||
|
dev, metric := "", 0
|
||||||
|
for i := 0; i < len(f); i++ {
|
||||||
|
if f[i] == "dev" && i+1 < len(f) {
|
||||||
|
dev = f[i+1]
|
||||||
|
}
|
||||||
|
if f[i] == "metric" && i+1 < len(f) {
|
||||||
|
metric = atoiOr(f[i+1], 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dev != "" && metric < bestMetric {
|
||||||
|
best, bestMetric = dev, metric
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
// profileProbeUp reports whether an HTTP(S) probe to url succeeds (2xx/3xx).
|
||||||
|
func profileProbeUp(url string) bool {
|
||||||
|
if !strings.Contains(url, "://") {
|
||||||
|
url = "http://" + url
|
||||||
|
}
|
||||||
|
c := &http.Client{Timeout: 6 * time.Second}
|
||||||
|
resp, err := c.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
return resp.StatusCode < 400
|
||||||
|
}
|
||||||
|
|
||||||
|
// profileConditionsHold checks a profile's specified conditions (all must hold).
|
||||||
|
// iface and now are passed in so a full evaluation dials the probe at most once.
|
||||||
|
func profileConditionsHold(p Profile, iface string, now time.Time) bool {
|
||||||
|
if len(p.MatchIface) > 0 {
|
||||||
|
hit := false
|
||||||
|
for _, want := range p.MatchIface {
|
||||||
|
if strings.EqualFold(strings.TrimSpace(want), iface) {
|
||||||
|
hit = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !hit {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.ProbeURL != "" {
|
||||||
|
up := profileProbeUp(p.ProbeURL)
|
||||||
|
if strings.EqualFold(p.ProbeMode, "down") {
|
||||||
|
if up {
|
||||||
|
return false // want probe down, but it's up
|
||||||
|
}
|
||||||
|
} else if !up {
|
||||||
|
return false // want probe up, but it's down
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.SchedStart != "" || p.SchedEnd != "" || len(p.SchedDays) > 0 {
|
||||||
|
r := Rule{SchedEnabled: true, SchedDays: p.SchedDays, SchedStart: p.SchedStart, SchedEnd: p.SchedEnd, SchedTZ: p.SchedTZ}
|
||||||
|
if !ruleActiveNow(r, now) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// activeWanProfile returns the highest-priority enabled profile whose conditions
|
||||||
|
// all hold, or nil. A profile with NO conditions never activates (avoids a
|
||||||
|
// permanent override with an empty match set).
|
||||||
|
func activeWanProfile(m *Model, now time.Time) *Profile {
|
||||||
|
var candidates []Profile
|
||||||
|
for _, p := range m.Profiles {
|
||||||
|
if !p.Enabled {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(p.MatchIface) == 0 && p.ProbeURL == "" && p.SchedStart == "" && p.SchedEnd == "" && len(p.SchedDays) == 0 {
|
||||||
|
continue // no conditions -> never auto-activates
|
||||||
|
}
|
||||||
|
candidates = append(candidates, p)
|
||||||
|
}
|
||||||
|
sort.SliceStable(candidates, func(i, j int) bool { return candidates[i].Priority > candidates[j].Priority })
|
||||||
|
iface := ""
|
||||||
|
needIface := false
|
||||||
|
for _, p := range candidates {
|
||||||
|
if len(p.MatchIface) > 0 {
|
||||||
|
needIface = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if needIface {
|
||||||
|
iface = defaultIface()
|
||||||
|
}
|
||||||
|
for i := range candidates {
|
||||||
|
if profileConditionsHold(candidates[i], iface, now) {
|
||||||
|
p := candidates[i]
|
||||||
|
return &p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProfileStatusJSON reports the currently-active WAN-mode profile + evaluation.
|
||||||
|
func ProfileStatusJSON() ([]byte, error) {
|
||||||
|
m, err := ReadUCI()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
now := timeNow()
|
||||||
|
iface := defaultIface()
|
||||||
|
active := activeWanProfile(m, now)
|
||||||
|
type row struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
Active bool `json:"active"`
|
||||||
|
}
|
||||||
|
var rows []row
|
||||||
|
for _, p := range m.Profiles {
|
||||||
|
rows = append(rows, row{p.Name, p.Enabled, active != nil && active.Name == p.Name})
|
||||||
|
}
|
||||||
|
res := map[string]any{
|
||||||
|
"default_iface": iface,
|
||||||
|
"active": "",
|
||||||
|
"profiles": rows,
|
||||||
|
}
|
||||||
|
if active != nil {
|
||||||
|
res["active"] = active.Name
|
||||||
|
}
|
||||||
|
return jsonMarshalIndent(res)
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProfileConditionsIface(t *testing.T) {
|
||||||
|
p := Profile{Name: "sim", Enabled: true, MatchIface: []string{"wwan0", "usb0"}}
|
||||||
|
now := at(t, "2026-07-09T12:00:00Z")
|
||||||
|
if !profileConditionsHold(p, "wwan0", now) {
|
||||||
|
t.Fatal("should hold on wwan0")
|
||||||
|
}
|
||||||
|
if profileConditionsHold(p, "eth0", now) {
|
||||||
|
t.Fatal("should not hold on eth0")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProfileConditionsSchedule(t *testing.T) {
|
||||||
|
p := Profile{Name: "night", Enabled: true, SchedTZ: "UTC", SchedStart: "22:00", SchedEnd: "23:00"}
|
||||||
|
if !profileConditionsHold(p, "", at(t, "2026-07-09T22:30:00Z")) {
|
||||||
|
t.Fatal("should hold at 22:30")
|
||||||
|
}
|
||||||
|
if profileConditionsHold(p, "", at(t, "2026-07-09T12:00:00Z")) {
|
||||||
|
t.Fatal("should not hold at 12:00")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProfileConditionsAND(t *testing.T) {
|
||||||
|
// iface AND schedule: both must hold
|
||||||
|
p := Profile{Name: "x", Enabled: true, MatchIface: []string{"wwan0"}, SchedTZ: "UTC", SchedStart: "22:00", SchedEnd: "23:00"}
|
||||||
|
if profileConditionsHold(p, "wwan0", at(t, "2026-07-09T12:00:00Z")) {
|
||||||
|
t.Fatal("iface ok but out of window -> must not hold")
|
||||||
|
}
|
||||||
|
if profileConditionsHold(p, "eth0", at(t, "2026-07-09T22:30:00Z")) {
|
||||||
|
t.Fatal("in window but wrong iface -> must not hold")
|
||||||
|
}
|
||||||
|
if !profileConditionsHold(p, "wwan0", at(t, "2026-07-09T22:30:00Z")) {
|
||||||
|
t.Fatal("both hold -> must hold")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActiveWanProfilePriority(t *testing.T) {
|
||||||
|
m := &Model{Globals: defaultGlobals()}
|
||||||
|
m.Profiles = []Profile{
|
||||||
|
{Name: "lo", Enabled: true, Priority: 1, SchedTZ: "UTC", SchedStart: "00:00", SchedEnd: "23:59"},
|
||||||
|
{Name: "hi", Enabled: true, Priority: 9, SchedTZ: "UTC", SchedStart: "00:00", SchedEnd: "23:59"},
|
||||||
|
}
|
||||||
|
p := activeWanProfile(m, at(t, "2026-07-09T12:00:00Z"))
|
||||||
|
if p == nil || p.Name != "hi" {
|
||||||
|
t.Fatalf("expected 'hi' by priority, got %v", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActiveWanProfileNoConditionsNeverActive(t *testing.T) {
|
||||||
|
m := &Model{Globals: defaultGlobals()}
|
||||||
|
m.Profiles = []Profile{{Name: "empty", Enabled: true}}
|
||||||
|
if activeWanProfile(m, at(t, "2026-07-09T12:00:00Z")) != nil {
|
||||||
|
t.Fatal("a profile with no conditions must never auto-activate")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProfileOverrideEnableDisable(t *testing.T) {
|
||||||
|
saved := timeNow
|
||||||
|
defer func() { timeNow = saved }()
|
||||||
|
timeNow = func() time.Time { return at(t, "2026-07-09T22:30:00Z") }
|
||||||
|
|
||||||
|
m := &Model{Globals: defaultGlobals()}
|
||||||
|
m.Nodes = []Node{{Name: "n1", Enabled: true, URI: vlessReality}}
|
||||||
|
m.Rules = []Rule{
|
||||||
|
{Name: "off-by-default", Enabled: false, Order: 10, DstDomain: []string{"ru.example"}, Target: "node:n1"},
|
||||||
|
{Name: "on-by-default", Enabled: true, Order: 11, DstDomain: []string{"keep.example"}, Target: "node:n1"},
|
||||||
|
}
|
||||||
|
m.Profiles = []Profile{{
|
||||||
|
Name: "night", Enabled: true, SchedTZ: "UTC", SchedStart: "22:00", SchedEnd: "23:00",
|
||||||
|
EnableRules: []string{"off-by-default"}, DisableRules: []string{"on-by-default"},
|
||||||
|
}}
|
||||||
|
cfg, err := BuildConfig(m)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BuildConfig: %v", err)
|
||||||
|
}
|
||||||
|
if ruleWithDomain(cfg, "ru.example") == nil {
|
||||||
|
t.Fatal("profile should have enabled 'off-by-default'")
|
||||||
|
}
|
||||||
|
if ruleWithDomain(cfg, "keep.example") != nil {
|
||||||
|
t.Fatal("profile should have disabled 'on-by-default'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProfileDefaultTargetInjected(t *testing.T) {
|
||||||
|
saved := timeNow
|
||||||
|
defer func() { timeNow = saved }()
|
||||||
|
timeNow = func() time.Time { return at(t, "2026-07-09T22:30:00Z") }
|
||||||
|
|
||||||
|
m := &Model{Globals: defaultGlobals()}
|
||||||
|
m.Nodes = []Node{{Name: "ru", Enabled: true, URI: vlessReality}}
|
||||||
|
m.Profiles = []Profile{{
|
||||||
|
Name: "whitelist", Enabled: true, SchedTZ: "UTC", SchedStart: "22:00", SchedEnd: "23:00",
|
||||||
|
DefaultTarget: "node:ru",
|
||||||
|
}}
|
||||||
|
cfg, err := BuildConfig(m)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BuildConfig: %v", err)
|
||||||
|
}
|
||||||
|
if routingHasTarget(cfg, "node_ru") == nil {
|
||||||
|
t.Fatal("profile default target should inject a catch-all to node_ru")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProfileInactiveNoOverride(t *testing.T) {
|
||||||
|
saved := timeNow
|
||||||
|
defer func() { timeNow = saved }()
|
||||||
|
timeNow = func() time.Time { return at(t, "2026-07-09T12:00:00Z") } // outside window
|
||||||
|
|
||||||
|
m := &Model{Globals: defaultGlobals()}
|
||||||
|
m.Nodes = []Node{{Name: "n1", Enabled: true, URI: vlessReality}}
|
||||||
|
m.Rules = []Rule{{Name: "off-by-default", Enabled: false, Order: 10, DstDomain: []string{"ru.example"}, Target: "node:n1"}}
|
||||||
|
m.Profiles = []Profile{{
|
||||||
|
Name: "night", Enabled: true, SchedTZ: "UTC", SchedStart: "22:00", SchedEnd: "23:00",
|
||||||
|
EnableRules: []string{"off-by-default"},
|
||||||
|
}}
|
||||||
|
cfg, _ := BuildConfig(m)
|
||||||
|
if ruleWithDomain(cfg, "ru.example") != nil {
|
||||||
|
t.Fatal("inactive profile must not enable the rule")
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-2
@@ -113,8 +113,9 @@ func ruleActiveNow(r Rule, now time.Time) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// scheduleSignature hashes the set of currently-active scheduled rules; it changes
|
// scheduleSignature hashes the set of currently-active scheduled rules AND the
|
||||||
// exactly when a schedule boundary is crossed.
|
// active WAN-mode profile; it changes exactly when a schedule boundary is crossed
|
||||||
|
// or the active profile flips, so the cron reconciles at those transitions.
|
||||||
func scheduleSignature(m *Model, now time.Time) string {
|
func scheduleSignature(m *Model, now time.Time) string {
|
||||||
var active []string
|
var active []string
|
||||||
for _, r := range m.Rules {
|
for _, r := range m.Rules {
|
||||||
@@ -128,6 +129,9 @@ func scheduleSignature(m *Model, now time.Time) string {
|
|||||||
h.Write([]byte(n))
|
h.Write([]byte(n))
|
||||||
h.Write([]byte{0})
|
h.Write([]byte{0})
|
||||||
}
|
}
|
||||||
|
if p := activeWanProfile(m, now); p != nil {
|
||||||
|
h.Write([]byte("profile:" + p.Name))
|
||||||
|
}
|
||||||
return strconv.FormatUint(h.Sum64(), 16)
|
return strconv.FormatUint(h.Sum64(), 16)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -161,6 +161,23 @@ func ParseUCIExport(text string) (*Model, error) {
|
|||||||
Order: parseInt(s.opt("order"), 0),
|
Order: parseInt(s.opt("order"), 0),
|
||||||
Target: s.opt("target"),
|
Target: s.opt("target"),
|
||||||
})
|
})
|
||||||
|
case "profile":
|
||||||
|
m.Profiles = append(m.Profiles, Profile{
|
||||||
|
Name: s.optOr("name", s.Name),
|
||||||
|
Enabled: s.optBool("enabled", false),
|
||||||
|
Priority: parseInt(s.opt("priority"), 0),
|
||||||
|
MatchIface: nonEmpty(s.list("match_iface")),
|
||||||
|
ProbeURL: s.opt("probe_url"),
|
||||||
|
ProbeMode: s.optOr("probe_mode", "up"),
|
||||||
|
SchedDays: s.list("sched_day"),
|
||||||
|
SchedStart: s.opt("sched_start"),
|
||||||
|
SchedEnd: s.opt("sched_end"),
|
||||||
|
SchedTZ: s.opt("sched_tz"),
|
||||||
|
EnableRules: nonEmpty(s.list("enable_rule")),
|
||||||
|
DisableRules: nonEmpty(s.list("disable_rule")),
|
||||||
|
DefaultTarget: s.opt("default_target"),
|
||||||
|
DefaultEgress: s.opt("default_egress"),
|
||||||
|
})
|
||||||
case "resolver":
|
case "resolver":
|
||||||
m.Resolvers = append(m.Resolvers, Resolver{
|
m.Resolvers = append(m.Resolvers, Resolver{
|
||||||
Name: firstNonEmpty(s.opt("name"), s.Name),
|
Name: firstNonEmpty(s.opt("name"), s.Name),
|
||||||
|
|||||||
Reference in new issue
Block a user