diff --git a/README.md b/README.md index 2d444bd..82e4897 100644 --- a/README.md +++ b/README.md @@ -171,10 +171,36 @@ wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/m В панели самого роутера рядом с NetHaven VPN есть кнопка **Глобал логи**: при открытии блока сразу загружаются сохранённые записи. Журнал можно скачать, включить просмотр с обновлением каждые 3 секунды или очистить. -Записываются действия панели, Heartbeat, WAN и сообщения Xray. +Записываются действия панели, изменения связи Heartbeat/WAN, предупреждения +и ошибки Xray. Успешные Heartbeat без изменения состояния и повторяющиеся +события не заполняют журнал; подробности каждого соединения Xray отключены. +В просмотре успех отмечается зелёным, предупреждение — жёлтым, ошибка — красным. Журнал хранится в `/tmp/owrt-remote-logs/`, занимает около 2 МБ максимум, очищается каждые 24 часа и исчезает после перезагрузки. Сбор работает отдельно от туннеля; остановка Xray не останавливает журнал. Ключи и пароли скрываются. +Перед записью проверяется tmpfs: журнал и его служебное состояние не размещаются +на Flash. После очистки одинаковые факты могут быть записаны заново. + +В карточке роутера на VPS есть **Глобал логи**, открывающиеся в новой вкладке. +Там доступны те же скачивание, просмотр с обновлением каждые 3 секунды и очистка, +а также зелёные, жёлтые и красные записи. Роутер доставляет новые записи на VPS +отдельно от Heartbeat: повторная отправка после обрыва не создаёт дубликатов. +Остановка Remote кнопкой «Остановить» не прекращает доставку журнала: пока +работает интернет, записи об остановке и дальнейшие действия поступают на VPS. +Над журналом Hub показывает полученное состояние: Remote выключен, Xray +остановлен или Heartbeat поступает. Если точная причина обрыва не доставлена, +Hub сообщает об этом прямо; последнее предупреждение не выдаётся за доказанную +причину отключения. +Обновить для этого нужно и VPS, и каждый роутер, журнал которого нужен в Hub. + +Кнопка доступна и при оффлайн: Hub хранит последние доставленные записи в своей +базе, до 2 МБ на роутер. Архив сохраняется после перезагрузки роутера и Hub; +очистка ОЗУ роутера раз в сутки не удаляет копию на VPS. Hub записывает факт +истечения ожидания Heartbeat. Записи, созданные после полной потери связи, +появятся только при её восстановлении, если ещё сохранены в ОЗУ роутера. +Очистка из Hub сразу удаляет архив VPS, а очистка журнала оффлайн-роутера +применится при следующей доставке. Доступ к журналу требует полного доступа +к этому роутеру; удаление роутера удаляет его архив. Проверка на роутере: diff --git a/files/etc/init.d/owrt-remote b/files/etc/init.d/owrt-remote index f30dc06..c584430 100644 --- a/files/etc/init.d/owrt-remote +++ b/files/etc/init.d/owrt-remote @@ -66,6 +66,7 @@ start_service() { procd_open_instance xray procd_set_param command /usr/sbin/owrt-remote run + procd_set_param env OWRT_REMOTE_SERVICE_LOG=1 procd_set_param respawn 3600 5 5 procd_set_param stdout 1 procd_set_param stderr 1 @@ -73,6 +74,7 @@ start_service() { procd_open_instance heartbeat procd_set_param command /usr/sbin/owrt-remote heartbeat-loop + procd_set_param env OWRT_REMOTE_SERVICE_LOG=1 procd_set_param respawn 3600 5 5 procd_set_param stdout 1 procd_set_param stderr 1 diff --git a/files/etc/init.d/owrt-remote-logs b/files/etc/init.d/owrt-remote-logs index cdad7e2..68344a8 100644 --- a/files/etc/init.d/owrt-remote-logs +++ b/files/etc/init.d/owrt-remote-logs @@ -11,4 +11,10 @@ start_service() { procd_set_param stdout 1 procd_set_param stderr 1 procd_close_instance + + procd_open_instance archive + procd_set_param command /bin/sh /usr/lib/owrt-remote/logs.sh sync + procd_set_param env OWRT_REMOTE_SERVICE_LOG=1 + procd_set_param respawn 3600 5 5 + procd_close_instance } diff --git a/files/usr/lib/owrt-remote/logs.sh b/files/usr/lib/owrt-remote/logs.sh index 4c1b553..abd6548 100644 --- a/files/usr/lib/owrt-remote/logs.sh +++ b/files/usr/lib/owrt-remote/logs.sh @@ -5,8 +5,26 @@ LOG_LIMIT=1048576 LOG_KEEP_SECONDS=86400 log_clock() { cut -d. -f1 /proc/uptime; } +log_ram_storage() { + local resolved parent + if [ -e "$LOG_DIR" ] || [ -L "$LOG_DIR" ]; then + resolved="$(readlink -f "$LOG_DIR")" || return 1 + else + # BusyBox realpath may require the last component to exist. + # Resolve the existing parent before creating the journal directory. + parent="$(readlink -f "$(dirname "$LOG_DIR")")" || return 1 + resolved="$parent/$(basename "$LOG_DIR")" + fi + awk -v path="$resolved" ' + (path == $2 || index(path, $2 "/") == 1 || $2 == "/") && length($2) > best { + best = length($2); filesystem = $3 + } + END { exit(filesystem == "tmpfs" ? 0 : 1) } + ' /proc/mounts +} log_init() { umask 077 + log_ram_storage || { printf 'Remote journal requires RAM (tmpfs); refusing persistent storage.\n' >&2; return 1; } mkdir -p "$LOG_DIR" || return 1 chmod 700 "$LOG_DIR" } @@ -41,8 +59,22 @@ log_unlock() { log_reset_locked() { : >"$LOG_DIR/current.log" rm -f "$LOG_DIR/previous.log" + rm -f "$LOG_DIR/facts" "$LOG_DIR/facts.new" "$LOG_DIR/heartbeat-ok" + rm -f "$LOG_DIR/journal-id" "$LOG_DIR/total" "$LOG_DIR/sync-ack" log_clock >"$LOG_DIR/age" } +log_cursor_locked() { + local total + if [ ! -s "$LOG_DIR/journal-id" ]; then + cat /proc/sys/kernel/random/uuid >"$LOG_DIR/journal-id" 2>/dev/null || + printf '%s-%s-%s\n' "$(date +%s)" "$(log_clock)" "$$" >"$LOG_DIR/journal-id" + fi + if [ ! -s "$LOG_DIR/total" ]; then + total="$(wc -c <"$LOG_DIR/current.log")" + [ ! -f "$LOG_DIR/previous.log" ] || total=$((total + $(wc -c <"$LOG_DIR/previous.log"))) + printf '%s\n' "$total" >"$LOG_DIR/total" + fi +} log_maintain_locked() { local now age now="$(log_clock)" @@ -54,29 +86,83 @@ log_maintain_locked() { } log_redact() { # Never retain command blocks containing credentials or authenticated URLs. - LC_ALL=C awk ' + LC_ALL=C awk -v fallback="${1:-OK}" ' { line = substr($0, 1, 4096); lower = tolower(line) + # Old info/access output may still arrive until Xray restarts. + if (lower ~ /\[(info|debug)\]/ || lower ~ / from .* accepted / || lower ~ /a unified platform for anti-censorship/) next + level = fallback + if (line ~ /^\[(OK|WARN|ERROR)\]/) { level = substr(line, 2, index(line, "]") - 2); sub(/^\[[^]]+\][ ]*/, "", line) } + else if (lower ~ /core: xray .* started/) level = "OK" + else if (lower ~ /\[error\]|ошибка|Ошибка|ОШИБКА|не удалось|Не удалось|результат=bad|failed|cannot |could not |error:|syntax error|permission denied|network is unreachable|connection refused|connection reset|timed out|not permitted|no selected wan|wan has no|wan direct requires|already used by another rule|does not belong to remote|не применилось|dns failed|crash loop/) level = "ERROR" + else if (lower ~ /\[warn(ing)?\]|предупреждение|Предупреждение|результат=warn|retry|not ready|missing|не найден|restart postponed|dns unavailable|fallback|reconnecting|restarting|failover/) level = "WARN" if (lower ~ /(authorization|hub_token|vless_uuid|ssh_vless_uuid|password|passwd|web[._ -]?key|[?&]key=|[?&]token=|"uuid"|"privatekey"|"password")/ || lower ~ /[0-9a-f][0-9a-f][0-9a-f][0-9a-f]-[0-9a-f-]+-[0-9a-f-]+-[0-9a-f-]+/) - print "[строка с ключом или паролем скрыта]" - else print line + line = "[строка с ключом или паролем скрыта]" + print "[" level "] " line }' } +log_new_fact_locked() { + local key now heartbeat new_fact + # Compare event text without syslog timestamp, facility, PID or Xray time. + key="$(printf '%s\n' "$1" | tr '\t' ' ' | sed -e 's/^\[[^]]*\] *//' -e 's/.*owrt-remote\(\[[0-9][0-9]*\]\)\{0,1\}: *//' -e 's/^[0-9][0-9]*\/[0-9/:. ]* *//' -e 's/ *(\([0-9][0-9]*\)\/[0-9][0-9]*)//')" + heartbeat=0 + case "$key" in + 'Heartbeat: OK;'*) + heartbeat=1 + if [ "$(cat "$LOG_DIR/heartbeat-ok" 2>/dev/null)" = "$key" ]; then return 1; fi + printf '%s\n' "$key" >"$LOG_DIR/heartbeat-ok" + # A recovery lets a later failure with the same cause appear again. + if [ -f "$LOG_DIR/facts" ]; then + awk -F '\t' '$2 !~ /Heartbeat:|heartbeat failed/ { print }' "$LOG_DIR/facts" >"$LOG_DIR/facts.new" + mv -f "$LOG_DIR/facts.new" "$LOG_DIR/facts" + fi ;; + esac + if [ "$heartbeat" = 1 ]; then return 0; fi + key="${1%%]*}] $key" + now="$(log_clock)" + # A bounded cache suppresses repeated identical facts while they continue. + # After a quiet period a new occurrence is recorded, rather than lost forever. + awk -F '\t' -v now="$now" -v key="$key" ' + $2 == key { if (now - $1 < 120 && now >= $1) repeated = 1; next } + { saved[++n] = $0 } + END { + for (i = (n > 63 ? n - 62 : 1); i <= n; i++) print saved[i] + print now "\t" key + exit(repeated ? 1 : 0) + }' "$LOG_DIR/facts" >"$LOG_DIR/facts.new" 2>/dev/null + new_fact=$? + mv -f "$LOG_DIR/facts.new" "$LOG_DIR/facts" + [ "$new_fact" = 0 ] || return 1 + case "$key" in + *Heartbeat:*|*'heartbeat failed'*) + case "$1" in '[ERROR]'*|'[WARN]'*) rm -f "$LOG_DIR/heartbeat-ok" ;; esac ;; + *'Сервис: запуск') rm -f "$LOG_DIR/heartbeat-ok" ;; + esac + return 0 +} log_append() { local line size # Process one bounded line at a time and release the lock between writes. - log_redact | while IFS= read -r line; do + log_redact "${1:-OK}" | while IFS= read -r line; do log_lock || exit 1 trap 'log_unlock' EXIT trap 'exit 0' INT TERM log_maintain_locked + log_cursor_locked + [ -f "$LOG_DIR/facts" ] || : >"$LOG_DIR/facts" + if ! log_new_fact_locked "$line"; then + log_unlock + trap - EXIT INT TERM + continue + fi size="$(wc -c <"$LOG_DIR/current.log")" if [ "$size" -ge "$LOG_LIMIT" ]; then mv -f "$LOG_DIR/current.log" "$LOG_DIR/previous.log" : >"$LOG_DIR/current.log" fi printf '%s\n' "$line" >>"$LOG_DIR/current.log" + printf '%s\n' "$(( $(cat "$LOG_DIR/total") + $(printf '%s\n' "$line" | wc -c) ))" >"$LOG_DIR/total" log_unlock trap - EXIT INT TERM done @@ -110,6 +196,57 @@ log_clear() { log_reset_locked log_unlock } +log_export() { + local journal total previous current ack_id ack start available count clear_ack chunk + log_lock || return 1 + log_maintain_locked + log_cursor_locked + journal="$(cat "$LOG_DIR/journal-id")"; total="$(cat "$LOG_DIR/total")" + ack_id=''; ack=0 + if [ -s "$LOG_DIR/sync-ack" ]; then read -r ack_id ack <"$LOG_DIR/sync-ack"; fi + [ "$ack_id" = "$journal" ] || ack=0 + case "$ack" in ''|*[!0-9]*) ack=0 ;; esac + [ "$ack" -le "$total" ] || ack=0 + previous=0 + if [ -f "$LOG_DIR/previous.log" ]; then previous="$(wc -c <"$LOG_DIR/previous.log")"; exec 3<"$LOG_DIR/previous.log"; else exec 3/dev/null)" + log_unlock + chunk="$LOG_DIR/export.$$" + trap 'rm -f "$chunk"; exec 3<&- 4<&-' EXIT + : >"$chunk" + if [ "$count" -gt 0 ]; then + { head -c "$previous" <&3; head -c "$current" <&4; } | tail -c "$available" | head -c "$count" >"$chunk" + fi + count="$(wc -c <"$chunk")" + printf '{"journal_id":"%s","from":%s,"to":%s,"clear_ack":"%s","data":"' "$journal" "$start" "$((start + count))" "$clear_ack" + base64 <"$chunk" | tr -d '\r\n' + printf '"}\n' + rm -f "$chunk"; exec 3<&- 4<&-; trap - EXIT +} +log_ack() { + local journal offset clear_token + journal="$1"; offset="$2"; clear_token="${3:-}" + case "$journal$clear_token" in *[!a-zA-Z0-9._:-]*) return 1 ;; esac + case "$offset" in ''|*[!0-9]*) return 1 ;; esac + log_lock || return 1 + log_maintain_locked + if [ -n "$clear_token" ] && [ "$(cat "$LOG_DIR/sync-clear-ack" 2>/dev/null)" != "$clear_token" ]; then + log_reset_locked + printf '%s\n' "$clear_token" >"$LOG_DIR/sync-clear-ack" + elif [ "$(cat "$LOG_DIR/journal-id" 2>/dev/null)" = "$journal" ]; then + printf '%s %s\n' "$journal" "$offset" >"$LOG_DIR/sync-ack" + fi + log_unlock +} +log_sync_loop() { + while :; do + /usr/sbin/owrt-remote logs-sync >/dev/null 2>&1 + sleep 3 + done +} log_collect() { # These variables must remain visible to EXIT even after this function returns. log_init || return 1 @@ -134,10 +271,16 @@ log_collect() { } case "${1:-}" in + check) log_init ;; collect) log_collect ;; read) log_read "${2:-}" ;; clear) log_clear ;; + export) log_export ;; + ack) log_ack "$2" "$3" "${4:-}" ;; + sync) log_sync_loop ;; append) log_append ;; - event) { printf '%s owrt-remote: %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$2"; cat; } | log_append ;; + event) + case "${3:-ok}" in bad|error) level=ERROR ;; warn) level=WARN ;; *) level=OK ;; esac + { printf '%s owrt-remote: %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$2"; cat; } | log_append "$level" ;; *) printf 'Usage: logs.sh collect|read [live]|clear|append|event MESSAGE\n' >&2; exit 2 ;; esac diff --git a/files/usr/sbin/owrt-remote b/files/usr/sbin/owrt-remote index f29f851..97971ce 100644 --- a/files/usr/sbin/owrt-remote +++ b/files/usr/sbin/owrt-remote @@ -7,7 +7,8 @@ SECTION="main" XRAY_RELEASE_BASE_URL="${XRAY_RELEASE_BASE_URL:-https://github.com/XTLS/Xray-core/releases/latest/download}" log() { - printf '%s\n' "$*" >&2 + # procd already captures stderr. Use only logger for managed processes. + [ "${OWRT_REMOTE_SERVICE_LOG:-0}" = 1 ] || printf '%s\n' "$*" >&2 logger -t owrt-remote "$*" 2>/dev/null || true } @@ -27,6 +28,7 @@ usage() { owrt-remote run owrt-remote heartbeat owrt-remote heartbeat-loop + owrt-remote logs-sync owrt-remote network-diagnostics Настройки лежат в /etc/config/owrtremote. @@ -559,7 +561,9 @@ render_client_config() { cat >"$out" </dev/null; then + # Give a sender time to write its PID, then recover an abandoned lock. + for attempt in 1 2 3 4 5 6 7 8 9 10; do + owner="$(cat "$sync_lock/pid" 2>/dev/null)" + case "$owner" in ''|*[!0-9]*) sleep 0.1 ;; *) break ;; esac + done + owner="$(cat "$sync_lock/pid" 2>/dev/null)" + case "$owner" in ''|*[!0-9]*) ;; *) kill -0 "$owner" 2>/dev/null && return 0 ;; esac + rm -f "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || return 0 + mkdir "$sync_lock" 2>/dev/null || return 0 + fi + printf '%s\n' "$$" >"$sync_lock/pid" + file=''; response='' + trap 'rm -f "$file" "$response" "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || true' EXIT + trap 'exit 1' INT TERM + if truthy "$(uci_get wan_direct 0)" && [ ! -s "$WAN_STATE/active-interface" ]; then wan_prepare || return 1; fi + batch="$(sh "$helper" export)" || return 1 + router_id="$(safe_id "$(uci_get router_id main)")" + # export verifies that this directory is on tmpfs; payloads also stay in RAM. + umask 077 + file="${OWRT_REMOTE_LOG_DIR:-/tmp/owrt-remote-logs}/sync.$$"; response="$file.response" + printf '{"id":%s,"batch":%s,"state":%s}\n' "$(json_string "$router_id")" "$batch" "$(global_logs_state)" >"$file" + for endpoint in $(heartbeat_candidate_endpoints); do + base="$(heartbeat_base_from_endpoint "$endpoint")" + if post_json "$base/api/router-logs" "$token" "$file" >"$response" 2>/dev/null && + grep -Eq '"ok"[[:space:]]*:[[:space:]]*true' "$response"; then + journal="$(jsonfilter -i "$response" -e '@.journal_id' 2>/dev/null)" + offset="$(jsonfilter -i "$response" -e '@.offset' 2>/dev/null)" + clear_token="$(jsonfilter -i "$response" -e '@.clear_request' 2>/dev/null)" + sh "$helper" ack "$journal" "$offset" "$clear_token" + rc=$? + rm -f "$file" "$response" + rm -f "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || true + trap - EXIT INT TERM + return "$rc" + fi + done + rm -f "$file" "$response" + rm -f "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || true + trap - EXIT INT TERM + return 1 +) + heartbeat_base_from_endpoint() { printf '%s' "${1%/api/heartbeat}" } @@ -1284,6 +1347,9 @@ case "$cmd" in heartbeat-loop) heartbeat_loop ;; + logs-sync) + sync_global_logs + ;; *) usage >&2 exit 2 diff --git a/files/www/cgi-bin/owrt-remote b/files/www/cgi-bin/owrt-remote index d42eee2..bb60599 100644 --- a/files/www/cgi-bin/owrt-remote +++ b/files/www/cgi-bin/owrt-remote @@ -133,7 +133,7 @@ set_result() { RESULT_BODY="$2" RESULT_KIND="${3:-info}" if [ -r "$LOG_HELPER" ]; then - printf '%s\n' "$RESULT_BODY" | sh "$LOG_HELPER" event "Панель: $RESULT_TITLE; результат=$RESULT_KIND" >/dev/null 2>&1 || true + printf '%s\n' "$RESULT_BODY" | sh "$LOG_HELPER" event "Панель: $RESULT_TITLE; результат=$RESULT_KIND" "$RESULT_KIND" >/dev/null 2>&1 || true fi } @@ -145,6 +145,11 @@ logs_response() { printf 'Сборщик логов не установлен. Установи локальный фикс целиком.\n' return fi + if ! sh "$LOG_HELPER" check >/dev/null 2>&1; then + printf 'Status: 503 Service Unavailable\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n\r\n' + printf 'Журнал недоступен: для логов требуется ОЗУ (tmpfs). Запись на Flash запрещена.\n' + return + fi if [ "$mode" = clear ]; then if [ "${REQUEST_METHOD:-GET}" != POST ]; then printf 'Status: 405 Method Not Allowed\r\nAllow: POST\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n' @@ -359,6 +364,10 @@ run_action() { if [ "$rc" != "0" ]; then set_result "$RESULT_TITLE" "$(cat "$output")" "bad" fi + # Deliver the completed stop result without keeping a mobile HTTP request open. + if [ "$action" = stop ]; then + ( "$AGENT" logs-sync ) /dev/null 2>&1 & + fi rm -f "$output" } @@ -474,7 +483,7 @@ render_page() { -OpenWrt Remote Hub v115 +OpenWrt Remote Hub v116
+

Глобал логи

Вернуться в Hub

__TITLE__

+
Действия панели, Heartbeat, WAN, предупреждения и ошибки Xray этого роутера. Копия доставляется на VPS каждые 3 секунды, пока доступна связь. Если роутер оффлайн, доступны последние доставленные записи. На роутере журнал хранится только в ОЗУ и очищается после перезагрузки и каждые 24 часа. Архив VPS сохраняется отдельно: до 2 МБ на роутер. Ключи и пароли скрываются.
+
● Успешно● Предупреждение● Ошибка
+
Скачать логи
+
Получаю состояние роутера…
Загружаю сохранённые записи с VPS…
Загрузка записей журнала…
+
'''.replace('__TITLE__', title).replace('__DOWNLOAD__', download).replace('__ENDPOINT__', endpoint) + + def router_notes_html(router, username="", saved="", error="", draft=None, edit_note_id=""): router = dict(router or {}) router_id = str(router.get("id") or "").strip() @@ -12578,7 +12815,7 @@ button:hover{{filter:brightness(1.06)}}
{error_html} -

OpenWrt Remote Hub v115

+

OpenWrt Remote Hub v116

@@ -13050,7 +13287,7 @@ body::after{{content:"";position:fixed;inset:0;pointer-events:none;background:li -

OpenWrt Remote Hub v115

+

OpenWrt Remote Hub v116

@@ -14109,6 +14346,8 @@ class App: if not new: continue if bool(old.get("online")) and not bool(new.get("online")): + with self.conn() as conn: + record_router_connection_log(conn, router_id, False) notify_router_offline(new.get("router") or {}) def router_state_monitor_loop(self): @@ -15582,6 +15821,58 @@ a{{display:inline-flex;margin-top:18px;color:#93c5fd}} [("Set-Cookie", current_router_cookie(router_id))], ) + def router_logs_page(self, router_id): + if not self.require_router_access(router_id, 'G'): + return + with self.app.conn() as conn: + row = get_active_router(conn, router_id) + if not row: + self.send_text(404, 'router not found') + return + self.send_bytes(200, router_logs_html(row_to_router(row)).encode('utf-8'), 'text/html; charset=utf-8', + [('Cache-Control', 'no-store')]) + + def router_logs_api(self, router_id, mode='live'): + if not self.require_router_access(router_id, 'G', json_mode=True): + return + with self.app.conn() as conn: + row = get_active_router(conn, router_id) + if not row: + self.send_json(404, {'ok': False, 'error': 'router not found'}) + return + if mode == 'clear': + clear_router_log_archive(conn, router_id) + snapshot, raw = router_log_snapshot(conn, router_id) + else: + snapshot, raw = router_log_snapshot(conn, router_id) + router = row_to_router(row) + if mode == 'download': + name = clean_router_id(router_id) + filename = f'owrt-remote-global-{name}-{dt.datetime.now().strftime("%Y%m%d-%H%M%S")}.log' + self.send_bytes(200, raw, 'text/plain; charset=utf-8', + [('Cache-Control', 'no-store'), ('Content-Disposition', f'attachment; filename="{filename}"')]) + else: + payload = {'ok': True, 'router_id': router_id, 'online': router['online'], **snapshot} + if mode == 'clear': + payload['message'] = 'Архив VPS очищен. Журнал роутера будет очищен при следующем соединении.' + self.send_json(200, payload) + + def receive_router_logs_api(self): + if not self.agent_ok(): + self.send_json(401, {'ok': False, 'error': 'bad agent token'}) + return + try: + if self.headers.get('Transfer-Encoding') or not 0 < int(self.headers.get('Content-Length', '0')) <= 100000: + self.close_connection = True + self.send_json(413, {'ok': False, 'error': 'log request is too large or has no length'}) + return + payload = self.read_payload() + with self.app.conn() as conn: + reply = receive_router_logs(conn, payload.get('id'), payload.get('batch'), payload.get('state')) + self.send_json(200, {'ok': True, **reply}) + except Exception as exc: + self.send_json(400, {'ok': False, 'error': str(exc)}) + def router_notes_page(self, router_id, error="", draft=None, status=200, edit_note_id=""): if not self.require_router_access(router_id, "A"): return @@ -17246,6 +17537,10 @@ exit 127 return self.send_json(200, push_status_snapshot()) return + log_match = re.fullmatch(r'/api/router/([^/]+)/logs(?:/(download))?', path) + if log_match: + self.router_logs_api(urllib.parse.unquote(log_match[1]), log_match[2] or 'live') + return if path.startswith("/api/router/") and path.endswith("/wol/devices"): parts = path.strip("/").split("/") if len(parts) != 5 or parts[0] != "api" or parts[1] != "router" or parts[3] != "wol" or parts[4] != "devices": @@ -17266,6 +17561,9 @@ exit 127 self.send_json(400, {"ok": False, "error": str(exc), "router_id": router_id, "devices": []}) return if path.startswith("/router/"): + if path.endswith('/logs'): + self.router_logs_page(self.router_id_from_path('/router/')) + return if "/notes-media/" in path: self.router_note_media_page(path) return @@ -17302,6 +17600,9 @@ exit 127 if path.startswith("/api/ssh-session/"): self.ssh_session_action(path) return + if path == '/api/router-logs': + self.receive_router_logs_api() + return if path == "/api/heartbeat": if not self.agent_ok(): self.send_json(401, {"ok": False, "error": "bad agent token"}) @@ -17310,6 +17611,8 @@ exit 127 payload = self.read_payload() with self.app.conn() as conn: router = heartbeat(conn, payload) + if router and router.get('_became_online'): + record_router_connection_log(conn, router['id'], True) if router and router.pop("_became_online", False): notify_router_online(router) xray_reload = None @@ -17347,6 +17650,10 @@ exit 127 return if not self.require_admin(): return + log_match = re.fullmatch(r'/api/router/([^/]+)/logs/clear', path) + if log_match: + self.router_logs_api(urllib.parse.unquote(log_match[1]), 'clear') + return if path == "/api/auth": if not self.require_owner(): return @@ -17901,6 +18208,7 @@ exit 127 "update routers set deleted_at = ?, updated_at = ? where id = ?", (ts, ts, router_id), ) + conn.execute('delete from router_logs where router_id = ?', (router_id,)) conn.commit() deleted = True if deleted: