Commit Graph
24 Commits
Author SHA1 Message Date
Dushnilin 488bbfefd5 fix: комплексный аудит и исправление ucode кодовой базы
Критические исправления:
- safe_proxy_restart: удаление lock-файла после фонового перезапуска
  с защитой от stale lock (>300 сек)
- write_json_file: атомарная запись через tmp+mv вместо прямой
- write_reload_state: атомарная запись через tmp+mv
- state_add_list: отклонение значений с пробелами

Исправления безопасности:
- killall logread заменён на pkill -f 'logread -f'
- SIGTERM→SIGKILL для Telegram и sing-box при остановке
- Recover OOM scale: инкремент +0.05 каждые 10 минут
- nfqueue и byedpi: trap для корректного завершения дочерних процессов
- nfqueue: валидация стратегий и откат при ошибке запуска
- nfqueue: flush mangle_output перед добавлением правил
- Исправлен парсинг exit code в 14 файлах (status & 127)

Улучшения стабильности:
- init.d: trap для start_service/stop_service
- watchdog: signal traps для legacy fallback loop
- lifecycle: логирование ошибок при остановке компонентов
- singbox/priority: SIGTERM→SIGKILL при остановке
- telegram: exponential backoff (1x→300s) при ошибках API
- telegram: process_updates возвращает boolean для отслеживания успеха
- watchdog: кэш proxy port для уменьшения чтения конфига sing-box
- singbox/generator: упрощён atomic_write_json_file
- packages.uc: переупорядочивание apk_version (лёгкие запросы первыми)
- dns/apply: проверка PID sing-box перед настройкой dnsmasq
- server/service: cleanup_orphaned_server_certs перед вызовом
2026-08-06 00:03:51 +03:00
Dushnilin ff627cfb52 fix: FD-cascade при reinstall + SHA версии в UI + тип outdated_same_release
- action.uc: killall logread перед restart_tachyon_after_successful_change,
  предотвращает FD-каскад при reinstall/update (orphan logread pipe FD)
- action.uc: current_sha/latest_sha в ответе check_update для Tachyon
- updates.uc: SHA пробрасывается через кэш проверки обновлений
- fe/types.ts: outdated_same_release добавлен в union статусов,
  поля current_sha/latest_sha в ComponentActionResult,
  AI Watchdog поля в ConfigSection (pre-existing TS2339 fix)
- fe/store.service.ts: outdated_same_release и SHA в состоянии updatesChecks
- fe/initController.ts: рендер SHA hash-badge для outdated_same_release,
  setCheckResult принимает SHA, applyCachedCheckResults/handleCheckResult обновлены
- fe/styles.ts: .sha-info — monospace badge для отображения коммит-хешей
2026-08-04 16:03:07 +03:00
Dushnilin b7d05034c8 исправление: утечки ФД и временных файлов, переполнение ОЗУ
Проблема с FD-каскадом (зависание sing-box):
watchdog.uc открывал logread -f через popen() без O_CLOEXEC. Каждый
фоновый system('... &') порождал дочерний процесс, наследующий read-end
logread pipe. После kill watchdog — дочерний процесс держал pipe, logread
не получал SIGPIPE и оставался живым. За N перезапусков накапливалось
N orphan-процессов logread → исчерпание лимита 1024 FD → генератор
конфига sing-box не мог открыть .uc файлы → sing-box не стартовал.

Исправления FD-утечки:
- watchdog.uc: добавлена переменная logread_pipe_fd + помощник bg_system(),
  который закрывает FD logread перед запуском фоновых процессов
- watchdog.uc: killall logread перед открытием нового logread -f в
  setup_syslog_listener() для очистки orphan-процессов от предыдущих экземпляров
- watchdog.uc: все 7 вызовов system('... &') переведены на bg_system():
  restart, reload_firewall (x3), WAN ifdown/ifup, subscription_update_async (x3)
- initd.uc: killall logread в stop_service() после остановки tachyon
- nft/apply.uc: добавлены </dev/null >/dev/null 2>&1 к голому reload_firewall &
- updates.uc: добавлены редиректы к tachyon reload &
- telegram.uc: добавлен </dev/null к reload_firewall &

Проблема с утечкой временных файлов (500MB в /tmp):
При каждом tachyon restart (SIGKILL) процессы-генераторы умирали на
полуслове, оставляя /tmp/tmp.* файлы (sing-box config JSON ~3.4MB,
reload state). За 8 дней накопилось 227 файлов = 506MB в tmpfs,
что занимало 25% всего ОЗУ (519MB из 2007MB shared).

Исправления утечки временных файлов:
- temp_path() в runtime.uc и updates.uc теперь создаёт /tmp/tachyon-XXXXXX
  вместо /tmp/tmp.XXXXXX (безопасный для очистки префикс)
- nft/apply.uc и lifecycle.uc: аналогичное изменение mktemp
- lifecycle.uc start_impl(): автоматическая очистка /tmp/tachyon-* файлов
  старше 30 минут при каждом старте сервиса

Результат на роутере 192.168.2.1:
  logread после stop  = 0 (было 1+)
  logread после start = 1 (было 2+ в каскаде)
  sing-box = запущен
  /tmp shared         = 27MB (было 519MB, освобождено ~490MB)
  ОЗУ available       = 1691MB (было 1195MB)
2026-08-04 15:36:37 +03:00
Dushnilin 22a236e5d1 feat: commit-level version tracking for same-release updates
Backend:
- constants.uc: add TACHYON_COMMIT_SHA constant (placeholder __COMPILED_COMMIT_SHA__)
- build.sh: capture git rev-parse HEAD and sed-replace commit SHA placeholder
- Makefile: same commit SHA sed replacement for OpenWrt builds
- action.uc: modify check_tachyon() to compare installed commit SHA with
  target_commitish from GitHub release, new status 'outdated_same_release'
- action.uc: reuse release_json for both version and commit SHA extraction
- updater.uc: add release_commit_sha helper to extract target_commitish
- updates.uc: extend cacheable status to include outdated_same_release

Frontend:
- main.js: handle outdated_same_release status in renderComponentCard
- main.js: include outdated_same_release in shouldShowInstallAfterCheck
- main.js: include outdated_same_release in applyCachedCheckResults

i18n:
- Add 'Update is available for current release' and 'Update is available
  for current release:' to .pot and .ru.po files

78 tests pass.
2026-08-03 21:35:06 +03:00
Dushnilin 4e12681179 fix: migration error handling + updates retry mechanism
migration.uc:
- try/catch around migration.run() with error logging
- try/catch around apply_operations() with error logging
- Error checking for UCI cursor operations in apply_operations
- Checked fs.writefile return values in ensure_runtime_cache_format

updates.uc:
- Write pending marker on lock acquisition failure for next retry
2026-08-03 20:01:09 +03:00
Dushnilin c7febcb0dc fix: atomic writes, crash safety, deadlock prevention across 10 files
watchdog.uc:
- H-4: ai_heal_uci_config atomic write (tmp → rename)
- H-5: backup validation via uci valid before restart
- H-6: proxy restart cooldown (max 3 per 10 min)
- H-7: restart lock file prevents parallel restarts
- H-13: ai_heal_wan_interface reads 'network' not 'tachyon' config
- M-3: nslookup -port=53 → plain nslookup (BusyBox compat)

generator.uc: atomic_write_json_file for main config output
hosts.uc: atomic cache write (tmp + mv), TOCTOU double stat fix
telegram.uc: atomic config restore, persistent /etc/.tachyon/ paths
migration.uc: UCI commit before cache removal
updates.uc: background reload inside locked section (deadlock prevention)
lifecycle.uc: uci commit return check, watchdog/telegram failure logging
package.uc: postinst_restore returns actual start result
build.sh/install.sh: Wave 1 backup/restore fixes
2026-08-03 19:43:10 +03:00
Dushnilin 5eef78b877 fix: DNS петля + watchdog автоисправление + централизация file_is_usable
Ключевые изменения:

1. core/helpers.uc: file_is_usable(path, min_bytes) + file_size_value(path)
   для единообразной проверки файлов (минимальный размер порог).

2. singbox/dns.uc: WAN fallback DNS серверы (fallback_wan_main) теперь
   используют прямой UDP без detour — исправлена петля когда
   DNS шёл через мёртвую прокси-секцию.
   Health probes для ВСЕХ DNS серверов (включая DoH) идут direct —
   failover может определить доступность DNS серверов.

3. watchdog.uc: ai_heal_empty_sections() — автообнаружение пустых
   proxy-секций с подписками → запуск subscription_update_async.
   ai_heal_dns_loop() — при обнаружении DNS-петли (dead proxy +
   dead DNS) → временно отключает DNS detour → загружает подписку →
   восстанавливает настройки.

4. Единая file_is_usable: nft/apply.uc, generator_routes.uc,
   components/{updates,action}.uc, config/validator.uc,
   subscription/cache.uc — все используют helpers.file_is_usable.

5. Тест tests/file_usable.sh для проверки helpers CLI.

6. Исправлен components_updater_job.sh mock lib — добавлен core/helpers.uc
2026-08-03 14:07:57 +03:00
Dushnilin c7ff142a48 Release 1.2.43 - Pre-download and cache all preset rulesets & databases 2026-07-29 08:58:00 +03:00
Dushnilin 5ff4c448bd fix: nft populate community subnets on reload + generator_routes return fix for Telegram 2026-07-27 09:02:44 +03:00
Dushnilin 197013f043 fix: persistent community subnet storage & reboot fallback for Telegram in section Main 2026-07-27 08:38:55 +03:00
Dushnilin c012a5710b refactor: remove hardcoded Telegram IP arrays in favor of fully dynamic community subnet loading
- updates.uc: cache downloaded built-in subnet lists (telegram, meta, twitter, etc.) to community-subnets-<service>.lst.
- generator_routes.uc: dynamically load community list IP CIDRs from cached subnet files for all community lists into sing-box route rules. Zero hardcoded IP arrays.
2026-07-26 21:45:15 +03:00
Dushnilin e98a2c325e fix: community subnets nftables population & Telegram IP ranges
- nft/apply.uc: nft_add_community_subnet_file_for_section now populates
  common_set (tachyon_subnets / tachyon_rule_<Section>_subnets) when section
  is not a priority rule section. Previously, community subnets for normal
  proxy/VPN sections were skipped completely.
- updates.uc: fix typo SUBNETS_TELERAM -> SUBNETS_TELEGRAM in BUILTIN_SUBNET_URLS
- bump version 1.2.31 -> 1.2.32
2026-07-26 21:18:26 +03:00
Dushnilin 595c4cef3b feat(download): add ghproxy mirror fallback chain and disk cache fallback
- Add download_candidates helper in core/url.uc to auto-generate ghproxy mirror URLs (ghproxy.net, mirror.ghproxy.com, gh-proxy.com) for GitHub and external downloads
- Enhance download_to_file and download_subscription to try mirror candidates if direct download fails due to DPI or blocking
- Fallback to disk cache if all download attempts fail, preventing sing-box and service crashes on network outages
- Add 'Load Current Records' button in UI hosts import modal to pre-fill editor from saved configuration
- Synchronize localization catalogs
2026-07-25 12:35:37 +03:00
Dushnilin ab92110bad fix: предотвратить состояние гонки (race conditions) nft в list_update при reload-firewall 2026-07-16 19:11:39 +03:00
Dushnilin becc129a49 fix: исправлен race condition nft + управление Telegram ботом в LuCI
- backend: исправлена гонка данных (race condition) при старте роутера,
  когда list_update пытался добавить элементы в nft-сеты, пока reload-firewall
  ещё пересоздавал таблицу TachyonTable. Фаза применения nft теперь защищена
  RELOAD_LOCK_DIR, что устраняет ошибку 'nft add element ... No such file or directory'

- backend: добавлены CLI-команды telegram_status, telegram_start, telegram_stop
  в /usr/bin/tachyon для управления ботом из LuCI

- luci: добавлен виджет статуса Telegram-бота на вкладке настроек —
  показывает состояние (запущен/остановлен с PID), кнопки Запустить/Остановить,
  автообновление каждые 10 секунд без перезагрузки страницы

- frontend: пересобран main.js (yarn ci — 507 тестов прошли успешно)
- версия npm-пакета: 1.2.0
2026-07-16 16:55:13 +03:00
Dushnilin 509cf128b8 Merge: объединить изменения из upstream forkop в tachyon, разрешить конфликты и исправить тесты E2E 2026-07-15 17:56:18 +03:00
Dushnilin 46ef97fe89 Release 1.0.6: синхронизировать изменения из upstream и исправить баг фильтра URLTest/Priority 2026-07-14 08:56:31 +03:00
Dushnilin bb1de1fd83 Merge branch 'temp-upstream-rebrand' into main
Resolves merge conflicts:
- install.sh, build.sh, .github/workflows/build.yml: Reverted to Dushnilin's versions to avoid installing SourceForge mirrors.
- fe-app-tachyon: Resolved type, formatting and copyOutbound conflicts, keeping both Dushnilin's custom features and ushan0v's frontend performance optimizations.
- backend: Kept Dushnilin's ucode refactorings, Telegram bot integration, and release repository URL (Dushnilin/tachyon) while merging updates.uc cache format v8 & persistent cache format v7.
- tests: Merged tests from both branches, preserving ucode -L wrappers for local test execution.
2026-07-14 08:01:45 +03:00
Dushnilin 14df12a18d Rebrand upstream: переименовать forkop в tachyon 2026-07-14 07:48:33 +03:00
Dushnilin baea672ee3 Исправление оставшихся синтаксических ошибок от скрипта дедупликации (updates.uc, rulesets.uc, constants.uc) 2026-07-13 22:55:32 +03:00
Dushnilin f017d01a52 Рефакторинг кода: дедупликация ucode, исправления shellcheck и глобальное улучшение install.sh 2026-07-13 22:38:24 +03:00
Dushnilin 8c9bb8734b Рефакторинг и стабилизация: обновление установщика, бэкенд-утилит и оптимизация фронтенда
- Установщик (install.sh): внедрена верификация хешей sha256sums.txt, нормализована очерёдность бутстрапа ucode до языковых проверок.
- Сборщик (build.sh): добавлена автоматическая генерация sha256sums.txt для пакетов релиза.
- Бэкенд: права на honeypot FIFO ограничены до 0660 в watchdog.uc, исправлена опечатка в SUBNETS_TELEGRAM, удалён helpers.old.uc.
- Тесты бэкенда: написаны тесты для core_ip, core_url и config_connections.
- Фронтенд: реализовано автопереподключение WebSocket с экспоненциальным бэкоффом, проведена дедупликация виджетов и модальных окон в initController.ts, мигрирован CSS-префикс с fkp_ на tachyon_.
- Тесты фронтенда: добавлен initController.test.ts для тестирования загрузки дашборда.
2026-07-13 20:23:33 +03:00
Dushnilin f57dac6b52 refactor(rebrand): полный ребрендинг в Tachyon и перенос служб watchdog/doctor на Ucode 2026-07-13 14:09:38 +03:00
Dushnilin e89a795566 refactor(rebrand): полный ребрендинг в Tachyon и перенос служб watchdog/doctor на Ucode 2026-07-13 14:03:31 +03:00