control

package
v0.1.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: AGPL-3.0 Imports: 38 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Accounts: read only, on purpose, with no exception carved out anywhere in this file.

Message 59 ("Set user cfg") turned out to be sitting in the same read sweep this codebase's own probe uses: `get all` was, for a time, sending a user config write with an empty body at live cameras. Nobody has established what that write does. baichuan.WriteConfig refuses an empty body now, which is the guard that would have stopped it, and this file does not add a second, different check that could disagree with that one. Instead this file adds no write path at all: no POST, PUT, PATCH or DELETE route exists for accounts anywhere in camctl.go, not behind a confirmation and not behind a flag. A page that can rewrite a camera's accounts is a page that can lock an operator out of their own camera, with no way back short of a factory reset, and that risk is not worth taking until somebody deliberately establishes what message 59 does.

Package control serves the daemon's one web page: what every stream is doing, what the config says, what the log says, a first run flow, and per camera control over Baichuan and CGI.

It listens on its own socket, never the streaming one. The streaming listener is unauthenticated because a recorder points at it, and this page can read and write camera credentials, so the two must not share a port or a firewall rule.

Flash: the one line a write leaves behind for the page it sends the operator back to.

Every write on this page used to land on result.html, a full page of outcome, detail, the whole Before document and the whole After document, whose only way onward was a "restore previous" button. There was no way back to the thing being configured, and a refresh re-POSTed the write. A curated setting, the floodlight and the NTP form now write, stash one of these, and redirect back to the page the setting belongs to, so a refresh is a plain GET and the operator is left looking at the control they just changed. The raw block editor (serveWrite) deliberately keeps result.html: seeing the exact before/after XML is the entire point of that page.

The flash is held here, server side, and never in the redirect URL. The undo value is the camera's previous document; a query string would write it into browser history and into every access log between here and the browser, and this project's rule is that values do not reach URLs.

Lights and IR: the curated controls whose write is not a document field but a physical effect a person or a camera can see happen. That is what separates this file from settings.go's own groups: every control here confirms before acting, every time, not once per session, because a light switching on in a shop at two in the morning should never be a stray click.

The OSD overlay flags, read on their own so the status page can stay free.

Status has always contacted nothing: it reads stream state out of memory and renders. The two overlay switches an operator flips most often (the timestamp and the camera name) do not live in memory, they live on the camera, and reading them is a real Baichuan connection each. Putting that read in serveDashboard would have made the page cost one connection per camera before a byte of it rendered, which on an eight camera fleet is the difference between instant and tens of seconds, and one unreachable camera would have held up the whole page.

So the page renders with both switches unknown, and fetches this endpoint once per camera afterwards. Each camera's answer arrives, or fails, on its own.

Curated settings: a small number of fields a person actually changes, picked out of the raw blocks blocks.html already exposes wholesale, so changing the camera's name or its timestamp overlay does not require editing an XML document by hand.

Time: the clock, and nothing else. The project this task belongs to started from one camera's OSD clock drifting, and keeping a fleet's clocks in step is the point of curating this at all.

This goes over CGI, not Baichuan. The recovered message table (see docs/control.md, and the id/name pairs in internal/baichuan/msgids.go) carries no set-time message at all: nothing that writes NTP configuration or the clock exists in it, so there is nothing to pair a Get with here the way settings.go pairs "osd get" with "osd set". SetNtp and SetTime are real CGI commands and they are the only way this codebase has found to change either setting.

Both forms on this page carry an "apply to every camera" checkbox, unticked. Ticking it runs that same single-camera write once per camera through applyAll in fleet.go and reports every camera's own answer, one row each. It replaced a separate /fleet/apply page that carried a second copy of these two forms, always targeted the whole fleet, and had no way to write one camera at all.

Accounts share this file's route wiring in camctl.go but not this file: they get their own, accounts.go, because they are read only for a different and much sharper reason than "no message id was recovered".

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DataDirWritable added in v0.1.7

func DataDirWritable(dir string) error

DataDirWritable reports whether the daemon can create files in dir, which the first save (the claim) needs. A bind mount to a host folder made by Docker or Unraid is owned by root, and this daemon runs as nonroot, so this is the usual first-run failure; startup calls it to warn before anyone gets as far as the claim page.

Types

type Alert added in v0.1.2

type Alert struct {
	Camera   string
	Sentence string
	Detail   string
}

Alert is a fleet-level line above the dashboard grid, one per camera that is down: a plain sentence and the exact detail behind it.

type Block

type Block struct {
	Name   string
	ID     uint32
	Status int16
	XML    string
	// HungUp mirrors BlockProbe.HungUp: the camera dropped the connection
	// or stayed silent past readTimeout, which is not the same fact as an
	// answered status and must not be reported as one.
	HungUp bool
}

Block is one readable message as this program actually saw it: the raw XML the camera answered with, or the fact that it did not answer 200.

type BlockProbe

type BlockProbe struct {
	Name        string
	ID          uint32
	Status      int16
	Supported   bool
	WantsParams bool
	Absent      bool
	HungUp      bool
}

BlockProbe is what one config read established about a camera.

Supported, WantsParams and Absent are mutually exclusive and come from classify. HungUp is set instead of any of them when this message got no answer at all, which is a fourth, real outcome docs/control.md's own probe table tracks separately from 405 ("hung up"): the camera dropping the session, or simply staying silent past readTimeout, is not the same fact as answering 405. probeCamera cannot always tell those two apart (see its own comment on the error branch that sets this), so a rendered page should describe HungUp as "no answer" rather than claim a disconnect it did not necessarily observe.

type Camera

type Camera struct {
	Name     string
	Address  string
	Username string
	Password string
	Channel  int
}

Camera is one camera this page can talk to.

type CameraReport

type CameraReport struct {
	Model   string
	Streams []StreamReport
	Err     string
}

CameraReport is what a camera answered when asked what it is. Err is a message for a person, not an error value: this is rendered, never inspected.

type Choice added in v0.1.2

type Choice struct {
	Value string
	Label string
}

Choice is one stop on a Kind "choice" field.

type Confidence

type Confidence string

Confidence is what this codebase knows about a write, not what the camera claims. It is a fact about our evidence, recorded in docs/control.md, and it should change only when the evidence does: moving a pair up a level requires observing an effect on real hardware, never just reading a 200.

const (
	// Proven: changed, read back on a fresh connection, and restored.
	// docs/control.md names exactly three: osd set, led set, email cfg set.
	Proven Confidence = "proven"
	// Unverified: the write path has the right shape and nobody has
	// observed an effect either way. Most of the 55 pairs are here.
	Unverified Confidence = "unverified"
	// KnownInert: answers 200 with any field changed and re-reads
	// identical, on more than one model. The write is accepted and does
	// nothing. md set is the instructive case: the camera implements the
	// matching read, hands over a full document, accepts it back with any
	// field changed, answers 200, and re-reads unchanged.
	KnownInert Confidence = "known inert"
	// UnsafeToRewrite: the write probably works, and that is the problem.
	// Re-applying an encoder or image configuration makes the camera
	// reconfigure its pipeline, which interrupts the stream. That is a
	// stronger warning than "unverified", so it takes priority over it.
	UnsafeToRewrite Confidence = "unsafe to rewrite"
)

func (Confidence) Slug

func (c Confidence) Slug() string

Slug renders a Confidence as a CSS class fragment. "known inert" and "unsafe to rewrite" carry spaces, which are not legal inside a single CSS class token.

type DiscoverResult

type DiscoverResult struct {
	Range      string
	Scanned    int
	Found      []DiscoveredCamera
	Configured int
	Err        string
}

DiscoverResult is one sweep's report. Configured counts addresses that answered but are already in the config: they are deliberately not probed and not offered, since probing a configured camera is exactly what probeGuarded exists to refuse, but an operator who swept and found "nothing" deserves to know the reason was that everything found is already added.

type DiscoveredCamera

type DiscoveredCamera struct {
	Address string
	Report  CameraReport
}

DiscoveredCamera is one address that answered on the Baichuan port, with whatever the existing setup probe then made of it.

There is no password field here, and there must never be one. The credentials a sweep probes with arrive in the request, live in a local variable, and go no further: not into this struct, not into the template that renders it, not into a log line, and not into the URL the browser is left sitting on.

type Field

type Field struct {
	Label string
	XPath string
	Kind  string

	// YPath is the second element a control that edits a PAIR of elements
	// changes alongside XPath. It is empty for every ordinary field, which
	// edits exactly one element.
	//
	// It exists for Kind "position": an overlay's corner is not one value
	// on these cameras, it is topLeftX and topLeftY, and either one on its
	// own is a corner nobody chose. XPath addresses the X, YPath the Y,
	// and serveApplySetting applies both inside a single read-modify-write
	// -- see parseEdits.
	YPath string

	// Slug is a stable id for the field's row. Governs, on a toggle, is
	// the Slug of the row that toggle switches on and off.
	Slug    string
	Governs string

	// Choices, on a Kind "choice" field, are the values offered as stops.
	// Only the value the camera was seen holding is observed; the rest are
	// the firmware's documented spellings. The camera's own value is always
	// offered too, so a camera holding something unlisted keeps it.
	Choices []Choice
}

Field is one curated control: a human label, the path to the element it edits, and how to present it.

XPath is a "/"-separated chain of element names, read from a document's root and matched wherever that exact chain occurs, so a caller never has to spell out the wrapping <body> (or a channel container) a read happens to come back inside. "Osd/osdChannel/name" is the whole address; it does not change if the camera wraps its reply differently than expected.

Kind is never a Go type. "warning" fields carry no XPath at all: they exist only to put text next to a control, which is how the UnsafeToRewrite label from Task 5 surfaces here without hiding the control it warns about.

func (Field) FormXPath

func (f Field) FormXPath() string

FormXPath is what the settings form posts as this field's xpath: the one element it edits, or the comma-separated list of elements it changes together. A single-element field posts exactly the string it always did, so nothing about an existing form's wire format changes.

func (Field) Paths

func (f Field) Paths() []string

Paths lists every element this field edits, primary first: one path for an ordinary field, two for a position. A "warning" field, which carries no XPath at all, edits nothing and lists nothing.

type Flash

type Flash struct {
	Outcome string
	Message string

	// UndoAction, when non-empty, renders a small form posting
	// UndoValue as UndoParam (plus UndoHidden) to UndoAction: the same
	// verified write path result.html's "restore previous" button uses,
	// just presented as one word beside the message rather than as a
	// section of its own.
	//
	// There is no confirm dialog on it. It is one click, and it is
	// reversible the same way the write that produced it was. The confirm
	// gates that do exist -- Group.ConfirmReason on Lights and IR, and
	// the floodlight's own -- are about a physical effect and stay where
	// they are.
	UndoAction string
	UndoParam  string
	UndoValue  string
	UndoHidden map[string]string
}

Flash is what a banner renders: which of the three write outcomes this was, one line of text, and optionally the undo that puts the previous value back.

Outcome is the same vocabulary WriteResult uses -- confirmed, accepted, refused -- because the banner must not soften a refusal into a tick. The template picks its colour from it, out of the same three variables style.css already spends on write outcomes.

type FleetFlash

type FleetFlash struct {
	// Target names which setting the rows belong to ("ntp", "timezone").
	// The two settings go out as two different CGI commands, and a camera
	// refusing one must not be read as it refusing the other.
	Target  string
	Results []FleetResult
}

FleetFlash is what an every-camera apply leaves behind: one row per camera, and which setting those rows are about.

It is stashed here rather than rendered straight onto the POST response for exactly the reason a single write is: a rendered POST means refresh re-submits, and re-submitting this one writes the whole fleet a second time. The blast radius is what makes it worth carrying rows through a redirect at all -- a banner is one line and rows are as many lines as there are cameras, but the rule about refresh does not care about size.

Results is never collapsed into a summary on the way here; see applyAll in fleet.go for why a fleet of three models cannot honestly be reduced to one line.

type FleetResult

type FleetResult struct {
	Camera  string
	Outcome string
	Detail  string
}

FleetResult is what happened when a fleet apply reached one camera.

Outcome carries the same confirmed/accepted/refused vocabulary WriteResult uses everywhere else in this package: a fleet apply is not a different kind of write, it is the same write attempted once per camera, and it must not grow a second vocabulary to describe the same three things.

type Group

type Group struct {
	Title  string
	Blocks []string
	Fields []Field
	// ConfirmReason, when non-empty, is shown next to the group's heading
	// and used as the confirmation prompt every one of its forms asks
	// through before it submits. Empty for a group like Picture and OSD,
	// where nothing switches anything a person or a camera can see happen;
	// set for Lights and IR, where every field is an emitter.
	ConfirmReason string
	// InterruptsStream tags the heading of a group whose write makes the
	// camera rebuild its pipeline. Blurb is the one plain line under it.
	InterruptsStream bool
	Blurb            string
}

Group is one curated section of the settings page, every field editing the same raw block.

Blocks lists candidate blocks, by name exactly as baichuan.ConfigPair.Name gives it ("osd get", "get osd"), most preferred first. More than one candidate exists only for OSD: docs/control.md records "osd get" (44) and "get osd" (29) as two independently recovered pairs for the same settings, and normalising them onto one name is what pairs a write to the wrong message id (see ConfigPairs' own comment). Which one a given camera actually implements is not assumed; resolveGroupBlock discovers it by trying each candidate and taking the first that reads back 200.

A defaults-only read such as "osd def get" (110) can never end up in Blocks by accident and do damage if it did: ConfigPairs only pairs a "X get" with a "X set" that shares its exact name, and no "osd def set" exists, so pairForName can never resolve a defaults read to a writable pair at all. That is what makes it safe for this list to be no more careful than "every writable candidate for this setting, most likely first": the factory-defaults trap is closed by construction, not by caution here.

type LogBuffer

type LogBuffer struct {
	// contains filtered or unexported fields
}

LogBuffer keeps the most recent log lines in memory and fans new ones out to live readers.

It is a tee, not a replacement: the standard logger keeps writing to stderr, so docker logs and journald continue to work exactly as they did. Nothing here writes a file. Rotation and retention belong to whatever supervises the process, and a daemon that manages its own logfile brings a class of disk full failures this does not need.

func NewLogBuffer

func NewLogBuffer(n int) *LogBuffer

func (*LogBuffer) Lines

func (b *LogBuffer) Lines() []string

Lines returns the buffered history, oldest first.

func (*LogBuffer) Subscribe

func (b *LogBuffer) Subscribe() (<-chan string, func())

Subscribe returns a channel of new lines and a function that stops it.

func (*LogBuffer) Write

func (b *LogBuffer) Write(p []byte) (int, error)

type Options

type Options struct {
	Password        string
	AllowNoPassword bool
	Status          StatusSource
	Logs            *LogBuffer
	Hubs            server.HubSource
	StreamBase      string
	ConfigPath      string
	Supervisor      Reloader

	// Probe asks a camera what it is, for the setup flow. Nil means
	// probeCamera; tests substitute their own so they never dial a real
	// camera.
	Probe func(ctx context.Context, addr, user, pass string) CameraReport

	// Dial opens one connection to a camera for camera control (support,
	// abilities, the raw block probe, curated settings, writes). Nil means
	// baichuan.Dial against the camera's own address and credentials,
	// which is what every real deployment wants; a test supplies its own
	// so it can probe a fake camera instead of reaching for a real one.
	Dial func(ctx context.Context, cam Camera) (*baichuan.Conn, error)

	// CGIDial opens a CGI session to a camera, for the handful of settings
	// reachable only over the camera's HTTP API: the floodlight, the
	// clock. Nil means cgi.Dial against the camera's own address and
	// credentials; a test supplies its own so it can substitute a fake
	// HTTP server instead of reaching for a real camera.
	CGIDial func(cam Camera) (*cgi.Client, error)
}

Options is everything the control server needs from the rest of the daemon. Nothing here reaches back into streaming except through these.

type PairRow

type PairRow struct {
	Name string
	// Title is the human name for the document, falling back to Name;
	// SetName is the write's firmware description, for the ids line; and
	// Effect is Confidence said as a sentence.
	Title      string
	SetName    string
	Effect     string
	Get, Set   uint32
	Confidence Confidence
	Seed       string
	Editable   bool
}

PairRow is one writable pair as blocks.html renders it: the label this codebase can back up, and the read that seeds its editor. Seed is empty, and Editable false, whenever the matching read did not come back as a usable 200 document on this probe: the page must never offer an editor for a document it did not itself read, because a composed document is exactly the thing that breaks models nobody here has tested against.

type RecorderURLs

type RecorderURLs struct {
	Frigate string
	RTSP    []string
	HTTP    []string

	// StreamHTTP is the same HTTP output, but every stream a camera
	// carries rather than only its main, keyed by camera name and then
	// stream name. The status page shows a stream's URL next to that
	// stream's own state, and it reads it from here rather than building
	// one itself: two builders for the same URL drift, and the one an
	// operator pastes into a recorder must be the one the page shows.
	StreamHTTP map[string]map[string]string
}

RecorderURLs is the paste-ready output of setup. The Frigate block uses the sub stream for detect and main for record and audio, which is what the README documents and what the fleet actually runs.

type Reloader

type Reloader interface {
	Reload(cams []config.Camera) (supervisor.ReloadResult, error)

	// Validate reports whether cams would be accepted by Reload, without
	// applying anything. writeAndApply calls this before the config file
	// is written, so a change Reload would refuse is never persisted in
	// the first place; see Supervisor.Validate's own doc comment for the
	// one class of check (RTSP wiring) that only this method, not
	// config.Config.Validate alone, can catch.
	Validate(cams []config.Camera) error
}

Reloader applies a new camera list to the running fleet. An interface so this package does not import the supervisor's construction, only its behaviour.

type Server

type Server struct {
	// contains filtered or unexported fields
}

func New

func New(opts Options) (*Server, error)

New builds the control server. It returns an error rather than panicking on a template parse failure so a caller can report it cleanly, rather than a process that has not opened a listener yet crashing outright.

func (*Server) ClaimToken

func (s *Server) ClaimToken() string

ClaimToken is the token an unclaimed install will accept, for the caller that has to print it: main logs it at startup and repeats it while the install stays unclaimed. It is the ONLY way the token leaves this process. It must not reach a response body, a URL, an error or a template -- anyone who could read it there could claim the install, and the whole point of the token is that only someone who can read the daemon's logs can.

func (*Server) Close

func (s *Server) Close()

Close releases any handler waiting on the server's done channel. Safe to call more than once.

func (*Server) Handler

func (s *Server) Handler() http.Handler

type StatusSource

type StatusSource interface {
	StreamStats() map[string]server.StreamStatus
}

StatusSource is the daemon's live stream status. It is an interface so this package does not construct or own anything in the streaming path.

type StreamReport

type StreamReport struct {
	Name   string
	Codec  string
	Width  int
	Height int

	Absent       bool
	Undetermined bool
	Reason       string
}

StreamReport is one stream this page asked a camera about, and what asking it established.

There are three outcomes, not two, and conflating any pair of them is exactly the kind of misleading symptom this task exists to stop:

  • present: Codec, Width and Height came back from the camera's own media.
  • Absent: the camera itself said so. On this path that is only ever Support's noExternStream flag; nothing else here has an equivalent of a config read's 405 for "this model does not have that", because GetStreamInfo learns a stream's shape by opening it and reading real media rather than by asking a config message (see GetStreamInfo's own doc comment on why). Report Absent only where the wire actually says so.
  • Undetermined: asking failed for some other reason -- a timeout, a held session, a stream this daemon is already using -- and Reason says what. This is not the same as Absent: a working camera whose main stream is merely busy must never be reported the same way as one that genuinely lacks it, or an operator will go reconfigure a camera that was fine.

type WriteResult

type WriteResult struct {
	Outcome string
	Detail  string
	Before  []byte
	After   []byte
}

WriteResult is what actually happened when this codebase tried to change one block, as distinct from what the camera claimed.

Outcome is one of three words, and the words carry the whole point of this file:

  • "confirmed": the write was made, the block was read back on a fresh connection, and the field holds the new value.
  • "accepted": the camera answered 200. No claim is made about effect. Message 47 (md set) and message 288 (floodlight set) both do this on models that implement the matching read, and change nothing.
  • "refused": the camera rejected the write. Detail explains what the status actually means, because 421 reads like "not supported" and means the message was built wrong instead.

Before is the document this block held before the write, captured on the same connection the write went out on, so a caller can offer to restore it byte identical. After is the document actually observed afterward: the fresh-connection read-back when one was taken, empty otherwise. It is never the body this codebase merely sent, because what was sent is not evidence of what is now on the camera.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL