mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-10-19 21:22:50 +03:00
CI / AMD64 Build (push) Waiting to run
CI / AMD64 Smoke Test (push) Blocked by required conditions
CI / ARM Build (push) Waiting to run
CI / Jetson Jetpack 6 (push) Waiting to run
CI / AMD64 Extra Build (push) Blocked by required conditions
CI / ARM Extra Build (push) Blocked by required conditions
CI / Synaptics Build (push) Blocked by required conditions
CI / Assemble and push default build (push) Blocked by required conditions
* keep /config out of the root environment in the frigate run script
The script exported HOME=/config and prepended /config/.local/lib to LD_LIBRARY_PATH while still root, then ran python3, ffmpeg, grep, and opt_in_out as root. The runtime user owns /config, so it could plant a .pth file in the user site-packages or a library on the loader path and get code run as root on the next start. Root helpers now run with root's environment (and python3 -I), and HOME, LD_LIBRARY_PATH, and PATH reach only the dropped process through env on the s6-setuidgid line. opt_in_out runs as the runtime user, so the openvino marker no longer gets written into /config by root.
* don't follow a planted symlink when writing /dev/shm/go2rtc.yaml
After the first start the go2rtc user owned /dev/shm/go2rtc.yaml and could swap it for a dangling symlink. The run script's -f test was false for a dangling link, so the link survived, and root's create_config.py then created the link target and the chown handed it to go2rtc. The run script now removes any existing entry, create_config.py creates the file with O_EXCL and O_NOFOLLOW at mode 0640, and the chown uses -h.
* run root python helpers in isolated mode and keep HOME=/config for non-root containers
The previous commit only set HOME=/config when dropping from root, so a container started with --user lost it. The other root-run helpers in the go2rtc, nginx, and certsync scripts now use python3 -I too, so they never load user site-packages or PYTHON* variables.
* validate networking.listen values before rendering them into nginx config
ListenConfig and get_nginx_settings.py only checked that the text after the last colon parsed as an int, and tempio rendered the raw string into the listen directive, so a value like "5000; location /x/ { alias /; } #:5000" injected nginx directives. Both now go through parse_listen_address, which accepts only a port, IPv4:port, or [IPv6]:port with a 1 to 65535 port and rebuilds the value from the parsed parts. get_nginx_settings.py falls back to the default port on an invalid value so nginx still serves the safe-mode UI.
* tighten comments
* accept hostnames, wildcards, and padded values in networking.listen
The stricter parser broke localhost:5000, *:5000, and values with surrounding whitespace that the old int() parsing accepted. parse_listen_address now strips the value and accepts RFC 1123 hostnames and *, still rebuilding the rendered value from the parsed parts. The ListenConfig validator runs in before mode, because pydantic coerced true to port 1 while get_nginx_settings.py rejected it and fell back to 5000, so the auth internal port and nginx disagreed.
* always create go2rtc.yaml after removing it and don't let opt_in_out stop frigate
The go2rtc else-branch was only reachable when a regular file was planted between rm and the test, and then loaded that file as go2rtc's config. create_config.py now runs unconditionally and its exclusive create fails closed. opt_in_out runs after s6-svc -O, so a failure there was terminal under errexit.
* fall back to default listen ports when either is invalid or they collide
* keep valid listen values and refuse to start nginx when the ports collide
211 lines
8.1 KiB
Python
211 lines
8.1 KiB
Python
"""Creates a go2rtc config file."""
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
from typing import Any
|
|
|
|
from ruamel.yaml import YAML
|
|
|
|
sys.path.insert(0, "/opt/frigate")
|
|
from frigate.const import (
|
|
BIRDSEYE_PIPE,
|
|
LIBAVFORMAT_VERSION_MAJOR,
|
|
)
|
|
from frigate.ffmpeg_presets import parse_preset_hardware_acceleration_encode
|
|
from frigate.util.config import find_config_file, resolve_ffmpeg_path
|
|
from frigate.util.env import apply_config_env_vars, substitute_frigate_vars
|
|
from frigate.util.live_streams import raw_transcode_streams
|
|
from frigate.util.services import (
|
|
is_go2rtc_arbitrary_exec_allowed,
|
|
is_restricted_go2rtc_source,
|
|
)
|
|
|
|
sys.path.remove("/opt/frigate")
|
|
|
|
yaml = YAML()
|
|
|
|
config_file = find_config_file()
|
|
|
|
try:
|
|
with open(config_file) as f:
|
|
raw_config = f.read()
|
|
|
|
if config_file.endswith((".yaml", ".yml")):
|
|
config: dict[str, Any] = yaml.load(raw_config)
|
|
elif config_file.endswith(".json"):
|
|
config: dict[str, Any] = json.loads(raw_config)
|
|
except FileNotFoundError:
|
|
config: dict[str, Any] = {}
|
|
|
|
# No validator runs here, so install environment_vars ourselves. FRIGATE_
|
|
# names only: anything else lands in os.environ, where the exec gate reads
|
|
# GO2RTC_ALLOW_ARBITRARY_EXEC.
|
|
config_env_vars = config.get("environment_vars")
|
|
apply_config_env_vars(
|
|
{
|
|
key: value
|
|
for key, value in config_env_vars.items()
|
|
if str(key).startswith("FRIGATE_")
|
|
}
|
|
if isinstance(config_env_vars, dict)
|
|
else {}
|
|
)
|
|
|
|
go2rtc_config: dict[str, Any] = config.get("go2rtc", {})
|
|
|
|
# Need to enable CORS for go2rtc so the frigate integration / card work automatically
|
|
if go2rtc_config.get("api") is None:
|
|
go2rtc_config["api"] = {"origin": "*"}
|
|
elif go2rtc_config["api"].get("origin") is None:
|
|
go2rtc_config["api"]["origin"] = "*"
|
|
|
|
# Need to set default location for HA config
|
|
if go2rtc_config.get("hass") is None:
|
|
go2rtc_config["hass"] = {"config": "/homeassistant"}
|
|
|
|
# we want to ensure that logs are easy to read
|
|
if go2rtc_config.get("log") is None:
|
|
go2rtc_config["log"] = {"format": "text"}
|
|
elif go2rtc_config["log"].get("format") is None:
|
|
go2rtc_config["log"]["format"] = "text"
|
|
|
|
# ensure there is a default webrtc config
|
|
if go2rtc_config.get("webrtc") is None:
|
|
go2rtc_config["webrtc"] = {}
|
|
|
|
if go2rtc_config["webrtc"].get("candidates") is None:
|
|
default_candidates = []
|
|
# use internal candidate if it was discovered when running through the add-on
|
|
internal_candidate = os.environ.get("FRIGATE_GO2RTC_WEBRTC_CANDIDATE_INTERNAL")
|
|
if internal_candidate is not None:
|
|
default_candidates.append(internal_candidate)
|
|
# should set default stun server so webrtc can work
|
|
default_candidates.append("stun:8555")
|
|
|
|
go2rtc_config["webrtc"]["candidates"] = default_candidates
|
|
|
|
if go2rtc_config.get("rtsp", {}).get("username") is not None:
|
|
go2rtc_config["rtsp"]["username"] = substitute_frigate_vars(
|
|
go2rtc_config["rtsp"]["username"]
|
|
)
|
|
|
|
if go2rtc_config.get("rtsp", {}).get("password") is not None:
|
|
go2rtc_config["rtsp"]["password"] = substitute_frigate_vars(
|
|
go2rtc_config["rtsp"]["password"]
|
|
)
|
|
|
|
# ensure ffmpeg path is set correctly
|
|
path = config.get("ffmpeg", {}).get("path", "default")
|
|
ffmpeg_path = resolve_ffmpeg_path(path, "ffmpeg")
|
|
|
|
if go2rtc_config.get("ffmpeg") is None:
|
|
go2rtc_config["ffmpeg"] = {"bin": ffmpeg_path}
|
|
elif go2rtc_config["ffmpeg"].get("bin") is None:
|
|
go2rtc_config["ffmpeg"]["bin"] = ffmpeg_path
|
|
|
|
# need to replace ffmpeg command when using ffmpeg4
|
|
if LIBAVFORMAT_VERSION_MAJOR < 59:
|
|
rtsp_args = "-fflags nobuffer -flags low_delay -stimeout 10000000 -user_agent go2rtc/ffmpeg -rtsp_transport tcp -i {input}"
|
|
if go2rtc_config.get("ffmpeg") is None:
|
|
go2rtc_config["ffmpeg"] = {"rtsp": rtsp_args}
|
|
elif go2rtc_config["ffmpeg"].get("rtsp") is None:
|
|
go2rtc_config["ffmpeg"]["rtsp"] = rtsp_args
|
|
|
|
|
|
for name in list(go2rtc_config.get("streams", {})):
|
|
stream = go2rtc_config["streams"][name]
|
|
|
|
if isinstance(stream, str):
|
|
try:
|
|
formatted_stream = substitute_frigate_vars(stream)
|
|
if is_restricted_go2rtc_source(formatted_stream):
|
|
print(
|
|
f"[ERROR] Stream '{name}' uses a restricted source (echo/expr/exec) which is disabled by default for security. "
|
|
f"Set GO2RTC_ALLOW_ARBITRARY_EXEC=true to enable arbitrary exec sources."
|
|
)
|
|
del go2rtc_config["streams"][name]
|
|
continue
|
|
go2rtc_config["streams"][name] = formatted_stream
|
|
except ValueError as e:
|
|
print(
|
|
"[ERROR] Invalid substitution found, see https://docs.frigate.video/configuration/restream#advanced-restream-configurations for more info."
|
|
)
|
|
sys.exit(e)
|
|
|
|
elif isinstance(stream, list):
|
|
filtered_streams = []
|
|
for i, stream_item in enumerate(stream):
|
|
try:
|
|
formatted_stream = substitute_frigate_vars(stream_item)
|
|
if is_restricted_go2rtc_source(formatted_stream):
|
|
print(
|
|
f"[ERROR] Stream '{name}' item {i + 1} uses a restricted source (echo/expr/exec) which is disabled by default for security. "
|
|
f"Set GO2RTC_ALLOW_ARBITRARY_EXEC=true to enable arbitrary exec sources."
|
|
)
|
|
continue
|
|
|
|
filtered_streams.append(formatted_stream)
|
|
except ValueError as e:
|
|
print(
|
|
"[ERROR] Invalid substitution found, see https://docs.frigate.video/configuration/restream#advanced-restream-configurations for more info."
|
|
)
|
|
sys.exit(e)
|
|
|
|
if filtered_streams:
|
|
go2rtc_config["streams"][name] = filtered_streams
|
|
else:
|
|
print(
|
|
f"[ERROR] Stream '{name}' was removed because all sources were restricted (echo/expr/exec). "
|
|
f"Set GO2RTC_ALLOW_ARBITRARY_EXEC=true to enable arbitrary exec sources."
|
|
)
|
|
del go2rtc_config["streams"][name]
|
|
|
|
elif isinstance(stream, dict):
|
|
# The map form ({"url": ...}) lets go2rtc resolve the source
|
|
# recursively, so it is effectively a dynamic way to generate the URL
|
|
# for a stream. That can only be backed by an exec source, so it cannot
|
|
# be allowed unless arbitrary exec is explicitly enabled. When it is
|
|
# enabled, leave the map untouched for go2rtc to resolve.
|
|
if not is_go2rtc_arbitrary_exec_allowed():
|
|
print(
|
|
f"[ERROR] Stream '{name}' uses a dynamic source format which is disabled by default for security. "
|
|
f"Set GO2RTC_ALLOW_ARBITRARY_EXEC=true to enable arbitrary exec sources."
|
|
)
|
|
del go2rtc_config["streams"][name]
|
|
continue
|
|
|
|
# add transcoded live streams; a user stream with the same name wins here and
|
|
# fails Frigate's config validation
|
|
transcoded_streams = raw_transcode_streams(config)
|
|
|
|
if transcoded_streams:
|
|
if go2rtc_config.get("streams") is None:
|
|
go2rtc_config["streams"] = {}
|
|
|
|
for name, source in transcoded_streams.items():
|
|
go2rtc_config["streams"].setdefault(name, source)
|
|
|
|
# add birdseye restream stream if enabled
|
|
if config.get("birdseye", {}).get("restream", False):
|
|
birdseye: dict[str, Any] = config.get("birdseye")
|
|
|
|
input = f"-f rawvideo -pix_fmt yuv420p -video_size {birdseye.get('width', 1280)}x{birdseye.get('height', 720)} -r 10 -i {BIRDSEYE_PIPE}"
|
|
ffmpeg_cmd = f"exec:{parse_preset_hardware_acceleration_encode(ffmpeg_path, config.get('ffmpeg', {}).get('hwaccel_args', ''), input, '-rtsp_transport tcp -f rtsp {output}')}"
|
|
|
|
if go2rtc_config.get("streams"):
|
|
go2rtc_config["streams"]["birdseye"] = ffmpeg_cmd
|
|
else:
|
|
go2rtc_config["streams"] = {"birdseye": ffmpeg_cmd}
|
|
|
|
# The run script removes the old file first. Exclusive create never follows a
|
|
# link the go2rtc user planted in sticky /dev/shm. The config contains camera
|
|
# credentials, so it is not world-readable.
|
|
fd = os.open(
|
|
"/dev/shm/go2rtc.yaml",
|
|
os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
|
|
0o640,
|
|
)
|
|
with os.fdopen(fd, "w") as f:
|
|
yaml.dump(go2rtc_config, f)
|