menu

package
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 73 Imported by: 0

Documentation

Overview

Package menu drives a caller's session once they are connected: it loads ViSiON/2-style menus and runs them, and it implements the built-in commands those menus invoke.

A menu is a .MNU record (MenuRecord) plus a command list (CommandRecord), read from the active menu set by LoadMenu and LoadCommands. MenuExecutor, built once at startup by NewExecutor, holds the shared managers and the hot-reloadable configuration; the server calls its RunChallengeGate, RunMatrixScreen, RunLoginSequence and Run methods for each session. Run displays a menu, reads the caller's input and dispatches the matched command: GOTO switches menus, LOGOFF ends the session, DOOR launches an external door, and RUN calls a RunnableFunc from RunRegistry. Those runnables make up most of the package: login and new-user flows, message and file areas, private mail, doors, chat, oneliners, voting, V3Net and sysop administration screens. Access to menus and commands is gated by ACS strings, which CheckUserACS evaluates outside a running menu.

Index

Constants

View Source
const ChatScreenBuiltin = "builtin"

ChatScreenBuiltin names the fixed layout: a divider across the middle with the sysop above and the caller below. A sysop picks it from the WFC to override a menu set whose default is a designed screen.

View Source
const ChatScreenRandom = "random"

ChatScreenRandom picks one of the menu set's chat screens each time, as the default or the sysop's choice.

Variables

View Source
var ErrDoorBusy = errors.New("door is currently in use by another node")

ErrDoorBusy is returned when a single-instance door is already in use.

Functions

func CanAccessSponsorMenu

func CanAccessSponsorMenu(u *user.User, area *message.MessageArea, cfg config.ServerConfig) bool

CanAccessSponsorMenu returns true if u is permitted to enter the sponsor menu for the given message area.

Access is granted when any of the following is true:

  • u.AccessLevel >= cfg.SysOpLevel (full sysop)
  • u.AccessLevel >= cfg.CoSysOpLevel (co-sysop)
  • area.Sponsor is non-empty and matches u.Handle (case-insensitive)

func ChatCredit added in v0.9.5

func ChatCredit(s ssh.Session) time.Duration

ChatCredit returns the sysop chat time credited to s, for time-left values computed outside the menu package.

func ChatScreens added in v0.9.6

func ChatScreens(m menuset.Set) []string

ChatScreens lists the chat screens a menu set defines: the stems of the .json files in its cfg directory, overlay included, sorted by name.

func CheckChatScreen added in v0.9.6

func CheckChatScreen(m menuset.Set, name string) error

CheckChatScreen loads the chat screen called name the way chat would and returns why it cannot be used, for the doctor.

func CheckUserACS

func CheckUserACS(acsString string, u *user.User) bool

CheckUserACS evaluates an ACS string against a user without requiring a session or terminal. Use this for access checks outside of menu execution (e.g., selecting default areas on login).

func ClearSessionIdleTimeout added in v0.9.4

func ClearSessionIdleTimeout(s ssh.Session)

ClearSessionIdleTimeout is clearSessionIdleTimeout for the session handler, which can set a timeout (SSH pre-auth, login sequence) before any menu runs and so before MenuExecutor.Run's own deferred cleanup is in place. It drops the session's time-limit deadline and any type-ahead kept for it too.

func ClearSessionOutput added in v0.9.4

func ClearSessionOutput(s ssh.Session)

ClearSessionOutput drops the remembered writer when a session ends.

func ClearSessionOutputMode added in v0.5.0

func ClearSessionOutputMode(s ssh.Session)

ClearSessionOutputMode drops the remembered output mode when a session ends, mirroring clearSessionIdleTimeout above so sessionOutputModes does not accumulate an entry per connection for the life of the process.

func ClearStringHookSession added in v0.9.5

func ClearStringHookSession(t *term.Terminal)

ClearStringHookSession drops t's session when the session ends.

func ClearTerminalPhysicalWidth added in v0.9.4

func ClearTerminalPhysicalWidth(t *term.Terminal)

ClearTerminalPhysicalWidth drops the remembered width when a session ends.

func ConvertChatArt added in v0.9.6

func ConvertChatArt(data []byte) []byte

ConvertChatArt turns a Vision/2 CHAT.n background into a chat screen's art: the |U and |S codes it used for the caller's and sysop's names become the @CALLER@ and @SYSOP@ placeholders. Everything else is kept byte for byte.

func ConvertChatNfo added in v0.9.6

func ConvertChatNfo(r io.Reader) ([]byte, error)

ConvertChatNfo reads a Vision/2 CHATNFO.n layout and returns the equivalent chat screen layout as JSON for cfg/NAME.json. The old format is one setting per line: TIME=x,y, DATE=x,y, ELAPSED=x,y, SYSOPNAME=x,y and USERNAME=x,y place the fields; STATCOLOR=, SYSOPCOLOR= and USERCOLOR= set DOS attributes; the lines after SYSOPLINES or USERLINES each give a typing line as "n x1,y1 x2,y2" until the other heading or the end. USER_CLEAR_LINE and SYSOP_CLEAR_LINE chose how a line was blanked and have no counterpart. The art file CHAT.n is used as it is, except that the |U and |S name codes become @CALLER@ and @SYSOP@; see ConvertChatArt.

func DetachToasts added in v0.9.6

func DetachToasts(s ssh.Session)

DetachToasts drops what AttachToasts stored when a session ends.

func HasBarFile

func HasBarFile(menuName string, menus menuset.Set) (bool, error)

HasBarFile returns true if a .BAR lightbar definition file exists for the given menu name inside the menu set's bar/ directory, in either layer.

func IsKnownRunnableTarget added in v0.9.5

func IsKnownRunnableTarget(target string) bool

IsKnownRunnableTarget reports whether target is registered for a RUN: menu command. Built-in placeholders count because they are intentionally registered runtime handlers, even when their behavior is not implemented.

func ProbeSessionEncoding added in v0.9.5

func ProbeSessionEncoding(s ssh.Session, timeout time.Duration) ansi.OutputMode

ProbeSessionEncoding asks the caller's terminal whether it decodes UTF-8 by drawing a box-drawing glyph and reading back how far the cursor moved. It returns OutputModeAuto when the terminal does not answer within timeout or the answer settles nothing; the caller then falls back to the terminal type.

It runs at connect, before sessionHandler reads from the session directly, so it stops the session input handler it reads through; anything the caller typed during the probe is dropped with it.

func QWKWriteAuthorizer added in v0.2.0

func QWKWriteAuthorizer(u *user.User) func(area *message.MessageArea) bool

QWKWriteAuthorizer returns a per-area write-ACS gate for use outside a terminal session (the QWK packet API). ACS is evaluated headlessly: with no ssh.Session, session-only conditions (L, A) are false, so only user-intrinsic conditions (security level, flags, SYSOP) can grant access. Empty ACSWrite allows the area, matching the terminal path.

func RegisterStringHookSession added in v0.9.5

func RegisterStringHookSession(t *term.Terminal, s ssh.Session, userMgr *user.UserMgr, bbs *session.BbsSession)

RegisterStringHookSession records the session behind t so strings written to t can run scripts. The user is read from bbs when a script runs, so it follows the caller through login.

func RegisterTerminalPhysicalWidth added in v0.9.4

func RegisterTerminalPhysicalWidth(t *term.Terminal, width *atomic.Int32)

RegisterTerminalPhysicalWidth associates t with the width the session keeps up to date from the client. The caller owns width and stores new values into it on resize, so updates never touch the map and cannot re-add an entry after ClearTerminalPhysicalWidth.

func RenderANSIArtToLines

func RenderANSIArtToLines(text string, width, height int) []string

RenderANSIArtToLines takes ANSI art text and renders it to scrollable lines The text is rendered into a virtual buffer where cursor positioning is relative to the buffer, not the terminal screen. This allows ANSI art with absolute positioning to display correctly.

func ResolveQWKID added in v0.2.0

func ResolveQWKID(cfg config.ServerConfig) string

ResolveQWKID exposes the package's QWK BBS-ID resolution for callers outside the terminal flow (e.g. the packet API).

func SetSessionOutput added in v0.9.4

func SetSessionOutput(s ssh.Session, w io.Writer)

SetSessionOutput records w as the output writer for s.

func SetSessionOutputMode added in v0.5.0

func SetSessionOutputMode(s ssh.Session, mode ansi.OutputMode)

SetSessionOutputMode records the output mode for s. Call this once the mode is finalized for the session (see cmd/vision3/main.go, alongside the other per-session setup) so later input reads decode extended characters with the same encoding the terminal is using for output.

func SetStringHookUser added in v0.9.7

func SetStringHookUser(t *term.Terminal, u *user.User)

SetStringHookUser publishes u as the user record strings written to t resolve placeholders from and run scripts for. The menu loop calls it with the record it refreshes each time round, which the session's own User, set at login, does not follow: areas and conferences the caller changes are on the loop's copy. Call it on the goroutine that writes to t.

func SetSysopChatEnv added in v0.9.5

func SetSysopChatEnv(env chatEnv)

SetSysopChatEnv installs the chat environment.

func WarnIfNewsUnwired added in v0.9.0

func WarnIfNewsUnwired(dataDir string, loginSequence []config.LoginItem)

WarnIfNewsUnwired logs a one-time startup warning when the system has news items to show but no PRINTNEWS step to show them with.

PRINTNEWS ships in the default login sequence, but setup only copies a template config when the target file does not already exist, so a system installed before PRINTNEWS was added keeps its old configs/login.json and silently never displays news. There is no config migration framework, and rewriting a sysop-owned file to add the step would not be able to tell "never had it" from "deliberately removed it" — so this only reports.

Types

type ANSICell

type ANSICell struct {
	Char  rune   // Message bodies reach the renderer as UTF-8 (bodyAsUTF8)
	Style string // ANSI escape sequence for this cell's style
}

ANSICell represents a single character cell with its attributes

type ANSIRenderer

type ANSIRenderer struct {
	Width        int
	Height       int
	Buffer       [][]ANSICell
	CursorX      int
	CursorY      int
	CurrentStyle string
	// contains filtered or unexported fields
}

ANSIRenderer renders ANSI art into a 2D buffer

func NewANSIRenderer

func NewANSIRenderer(width, height int) *ANSIRenderer

NewANSIRenderer creates a new renderer with given dimensions

func (*ANSIRenderer) ExtractLines

func (r *ANSIRenderer) ExtractLines() []string

ExtractLines converts the buffer into an array of strings with ANSI codes

func (*ANSIRenderer) Render

func (r *ANSIRenderer) Render(text string)

Render processes ANSI text and renders it into the buffer

type BBSListing

type BBSListing struct {
	ID          int       `json:"id"`
	Name        string    `json:"name"`        // BBS name (V2: Name/Mstr)
	Sysop       string    `json:"sysop"`       // SysOp name
	Address     string    `json:"address"`     // Hostname or IP (V2: Phone)
	TelnetPort  string    `json:"telnet_port"` // Telnet port (blank = none)
	SSHPort     string    `json:"ssh_port"`    // SSH port (blank = none)
	Web         string    `json:"web"`         // Web URL
	Software    string    `json:"software"`    // BBS software (V2: Ware/Sstr)
	Description string    `json:"description"` // Extended description
	AddedBy     string    `json:"added_by"`    // Username who added it (V2: Leftby)
	AddedDate   time.Time `json:"added_date"`
	Verified    bool      `json:"verified"` // SysOp-verified flag
}

BBSListing represents a single BBS entry in the directory. Modernized from V2's BBSRec (GENTYPES.PAS): dropped baud, replaced phone with hostname + separate ports for telnet/SSH, plus web URL.

type CentralNetworkInfo added in v0.9.7

type CentralNetworkInfo struct {
	Network string
	HubURL  string
	// Enabled is the sysop's participation switch; Publishing the listing
	// switch.
	Enabled    bool
	Publishing bool
	// SupportKnown is whether the hub's feature list has been read, and
	// Supported whether it names the directory.
	SupportKnown bool
	Supported    bool
	// Connected is whether the event stream to the hub is open.
	Connected bool
	// LastPublished is when the listing last reached the hub (zero if not
	// this run); Withdrawn whether this run withdrew it; LastError the
	// latest publish or withdrawal failure.
	LastPublished time.Time
	Withdrawn     bool
	LastError     string
	// DirectoryFetched is when the directory was last fetched (zero if
	// never) and DirectoryCount how many boards it held.
	DirectoryFetched time.Time
	DirectoryCount   int
}

CentralNetworkInfo is one subscription's V3Net Central state as the screens need it. The service fills it from the leaf (see v3net.Service.CentralNetworks).

func (CentralNetworkInfo) Available added in v0.9.7

func (n CentralNetworkInfo) Available() bool

Available reports whether callers can use the directory on this network: the sysop enabled Central and the hub serves it.

type ChatLeafInfo

type ChatLeafInfo struct {
	NetworkName string
	NewSession  func(handle string) chat.ChatService
}

ChatLeafInfo describes a single V3Net chat leaf that can create sessions.

type ChatLeafProvider

type ChatLeafProvider interface {
	ActiveChatLeaves() []ChatLeafInfo
}

ChatLeafProvider supplies active V3Net chat leaf connections.

type CommandRecord

type CommandRecord struct {
	Keys         string `json:"KEYS"`                    // Input key(s) to trigger command (space-separated)
	Command      string `json:"CMD"`                     // Command string (e.g., GOTO:MENU, RUN:PROG, LOGOFF)
	ACS          string `json:"ACS"`                     // Access Control String
	Hidden       bool   `json:"HIDDEN"`                  // Whether the command is hidden (H flag)
	AutoRun      string `json:"AUTORUN,omitempty"`       // Type of auto-run (e.g., "ONCE_PER_SESSION")
	NodeActivity string `json:"NODE_ACTIVITY,omitempty"` // Descriptive activity text for Who's Online
}

CommandRecord holds the definition of a single command from a .CFG file.

func LoadCommands

func LoadCommands(menuName string, menus menuset.Set) ([]CommandRecord, error)

LoadCommands reads a .CFG file (assumed JSON) for the given menu name from the menu set's cfg/ directory, overlay first.

func (*CommandRecord) GetHidden

func (cr *CommandRecord) GetHidden() bool

GetHidden is a helper method to safely access the Hidden field. (Kept for potential future use, though direct access is fine)

type DoorCtx

type DoorCtx struct {
	Executor         *MenuExecutor
	Session          ssh.Session
	Terminal         *term.Terminal
	User             doorUserInfo
	UserManager      *user.UserMgr // For V3 scripts that need user DB access
	CurrentUser      *user.User    // Live pointer to current session's user record
	NodeNumber       int
	SessionStartTime time.Time
	OutputMode       ansi.OutputMode
	Config           config.DoorConfig
	DoorName         string
	// Pre-computed values
	NodeNumStr  string
	PortStr     string
	TimeLeftMin int
	TimeLeftStr string
	// IdleTimeout is how long the caller may send nothing before the door
	// is ended and the caller logged off; 0 for a caller exempt from the
	// idle timeout.
	IdleTimeout time.Duration
	BaudStr     string
	UserIDStr   string
	Subs        map[string]string

	// Prompt is the kind of prompt a string's script stands in for (see
	// scripting.PromptYesNo); "" for a door run from a menu. Answer and
	// Answered carry back what the script passed to v3.prompt.answer.
	Prompt   string
	Answer   any
	Answered bool
	// contains filtered or unexported fields
}

DoorCtx holds all context needed to execute a door program.

type IPLockoutChecker

type IPLockoutChecker interface {
	IsIPLockedOut(ip string) (bool, time.Time, int)
	RecordFailedLoginAttempt(ip string) bool
	ClearFailedLoginAttempts(ip string)
}

IPLockoutChecker defines the interface for IP-based authentication lockout. This allows the menu system to check and record failed login attempts without depending on the specific implementation in main.

type InfoFormConfig

type InfoFormConfig struct {
	Descriptions  [5]string `json:"descriptions"`   // Form descriptions (V2: InfoformStr)
	MinLevels     [5]int    `json:"min_levels"`     // Minimum access level per form (V2: Infoformlvl)
	RequiredForms string    `json:"required_forms"` // Which forms are required, e.g. "15" = forms 1 and 5
}

InfoFormConfig holds sysop-configured infoform settings. Maps to V2's Cfg.InfoformStr[1..5], Cfg.Infoformlvl[1..5], Cfg.RequiredForms.

type InfoFormResponse

type InfoFormResponse struct {
	UserID      int       `json:"user_id"`
	Handle      string    `json:"handle"`
	FormNum     int       `json:"form_num"`
	FilledOutAt time.Time `json:"filled_out_at"`
	Answers     []string  `json:"answers"` // One entry per * field in the template
}

InfoFormResponse holds a user's completed answers for a specific form. Maps to V2's FORMS.TXT/FORMS.MAP entries.

type LightbarOption

type LightbarOption struct {
	X, Y           int    // Screen coordinates
	Text           string // Display text
	HotKey         string // Command hotkey
	ReturnValue    string // Return value (often same as hotkey, but can differ)
	HighlightColor int    // Color code when highlighted
	RegularColor   int    // Color code when not highlighted
}

LightbarOption represents a single option in a lightbar menu

type MenuExecutor struct {
	ConfigPath      string                        // DEPRECATED: Use MenuSetPath + "/cfg" or RootConfigPath
	AssetsPath      string                        // DEPRECATED: Use MenuSetPath + "/ansi" or RootAssetsPath
	MenuSetPath     string                        // NEW: Path to the active menu set (e.g., "menus/v3")
	RootConfigPath  string                        // NEW: Path to global configs (e.g., "configs")
	RootAssetsPath  string                        // NEW: Path to global assets (e.g., "assets")
	RunRegistry     map[string]RunnableFunc       // Map RUN: targets to functions (Use local RunnableFunc)
	OneLiners       []string                      // Loaded oneliners (Consider if these should be menu-set specific)
	MessageMgr      *message.MessageManager       // <-- ADDED FIELD
	FileMgr         *file.FileManager             // <-- ADDED FIELD: File manager instance
	ConferenceMgr   *conference.ConferenceManager // Conference grouping manager
	IPLockoutCheck  IPLockoutChecker              // IP-based authentication lockout checker
	SessionRegistry *session.SessionRegistry      // Session registry for who's online
	ChatLeaves      ChatLeafProvider              // V3Net chat leaf provider (nil = local only)
	V3NetReload     func() error                  // Applies v3net.json subscription changes live (nil = restart required)
	V3NetStatus     V3NetStatusProvider           // V3Net service status (nil if disabled)
	V3NetCentral    V3NetCentralProvider          // V3Net Central: board directory and per-network state (nil if disabled)
	Pager           SysopPager                    // WFC side of PAGESYSOP (nil = no console)
	Nodelists       *ftn.NodelistIndex            // Compiled FTN nodelists (nil = netmail addresses are not looked up)
	// contains filtered or unexported fields
}

MenuExecutor handles the loading and execution of ViSiON/2 menus.

func NewExecutor

func NewExecutor(menuSetPath, rootConfigPath, rootAssetsPath string, oneLiners []string, doorRegistry map[string]config.DoorConfig, loadedStrings config.StringsConfig, theme config.ThemeConfig, serverCfg config.ServerConfig, msgMgr *message.MessageManager, fileMgr *file.FileManager, confMgr *conference.ConferenceManager, ipLockoutCheck IPLockoutChecker, loginSequence []config.LoginItem, sessionRegistry *session.SessionRegistry, protocols []transfer.ProtocolConfig) *MenuExecutor

NewExecutor creates a new MenuExecutor.

func (e *MenuExecutor) AdmitPreAuthenticatedUser(
	s ssh.Session,
	terminal *term.Terminal,
	userManager *user.UserMgr,
	u *user.User,
	nodeNumber int,
	outputMode ansi.OutputMode,
	termWidth, termHeight int,
) (admitted bool, err error)

AdmitPreAuthenticatedUser applies the post-password login checks to a caller whose password was already verified at the SSH layer, so that path skips the LOGIN prompt without also skipping what the prompt enforces: the required new-user intro gate, then the logon-level check.

Returns admitted=false with io.EOF when the caller left the intro gate without sending, and admitted=false with a nil error when their level is too low to log on. Either way the session must end: falling back to the LOGIN prompt would authenticate the same account a second time, recording a second call for one connection, only to refuse it again.

func (e *MenuExecutor) AnnounceLogoff(sess *session.BbsSession, u *user.User)

AnnounceLogoff tells other online callers that u has logged off (#206).

func (e *MenuExecutor) AnnounceLogon(sess *session.BbsSession, u *user.User)

AnnounceLogon tells other online callers that u has logged on (#206).

func (e *MenuExecutor) ApplyUserIdleTimeout(s ssh.Session, u *user.User)

ApplyUserIdleTimeout applies u's idle timeout (including the SysOp exemption) to the session. The session handler calls it once a caller is authenticated, so the login sequence runs under their timeout rather than the pre-login one the login screens installed.

func (e *MenuExecutor) ApplyUserTimeLimit(s ssh.Session, u *user.User, sessionStart time.Time)

ApplyUserTimeLimit arms u's time limit (including the CoSysOp exemption) for a session that started at sessionStart. Like ApplyUserIdleTimeout, the session handler calls it once the caller is authenticated, so the login sequence counts against their time; Run re-arms it on every menu.

func (e *MenuExecutor) AttachToasts(s ssh.Session, sess *session.BbsSession)

AttachToasts lets s show toasts for sess during key waits. Call it on the session's goroutine.

func (e *MenuExecutor) DeliverLoginToasts(s ssh.Session, terminal *term.Terminal, u *user.User, nodeNumber int, outputMode ansi.OutputMode, termWidth, termHeight int)

DeliverLoginToasts shows what was queued while the caller was away, and holds the screen so the first menu does not wipe it.

func (e *MenuExecutor) DoorRegistry() map[string]config.DoorConfig

DoorRegistry returns a copy of the current door registry, safe for the caller to hold or mutate. Per-door lookups should use GetDoorConfig, which reads the shared snapshot without copying.

func (e *MenuExecutor) GetDoorConfig(name string) (config.DoorConfig, bool)

GetDoorConfig atomically retrieves a door configuration.

func (e *MenuExecutor) GetLoginSequence() []config.LoginItem

GetLoginSequence returns a copy of the login sequence, safe for the caller to hold or mutate.

func (e *MenuExecutor) GetServerConfig() config.ServerConfig

GetServerConfig atomically retrieves the server configuration.

Returns a copy, unlike the other accessors: callers routinely assign the result to a local and some adjust fields on it before use, which would corrupt the shared snapshot if they held a pointer into it.

func (e *MenuExecutor) Menus() menuset.Set

Menus returns the menu set the executor reads from: the shipped set at MenuSetPath with its overlay (menus.d/<set>) searched first, file by file. It is derived rather than stored so a MenuExecutor built as a struct literal — every test does this — behaves the same as one from NewExecutor.

func (e *MenuExecutor) NoteV3NetKeyChange(userManager *user.UserMgr, network, kind string) int

NoteV3NetKeyChange is the V3Net service's key-change observer. A leaf calls it when a hub offers a coordinator or hub key (kind) for network that differs from the key pinned in v3net.json. The leaf has already rejected the key and logged both keys; this queues a login warning for every sysop so the change is not missed in the log. A sysop who already has the same warning queued is not given a second one. It returns the number of notices queued.

func (e *MenuExecutor) NoteV3NetKeyHandover(userManager *user.UserMgr, network, kind string) int

NoteV3NetKeyHandover tells every sysop at login that a leaf moved the pinned coordinator or hub key (kind) for network along a signed coordinator handover and saved the new key in v3net.json. The service calls it once per stored move; as with NoteV3NetKeyChange, a sysop who already has the same notice queued (after two moves in a row, say) is not given a second one. It returns the number of notices queued.

func (e *MenuExecutor) NoteV3NetNAL(userManager *user.UserMgr, network string, n *protocol.NAL, nodeID string) int

NoteV3NetNAL is the V3Net service's NAL observer. It records the network's areas and queues an "Add?" notice for every sysop about each area that is new since the last NAL, unless the BBS already carries it or the area is closed to this node. nodeID is this node's V3Net ID. It returns the number of notices queued.

If the notices cannot all be queued, the areas are not recorded as seen, so the next NAL offers them again; a sysop who already has a notice for an area is not given a second one.

func (e *MenuExecutor) PromptYesNo(s ssh.Session, terminal *term.Terminal, promptText string, outputMode ansi.OutputMode, nodeNumber int, termWidth int, termHeight int, defaultYes bool) (bool, error)

PromptYesNo is the canonical Yes/No prompt entrypoint for menu flows. defaultYes controls which option is pre-selected (true = Yes, false = No). Keep all call sites routed here so prompt behavior can be changed in one place.

promptText is printed as text. A prompt that is a strings.json value goes through PromptYesNoString or PromptYesNof instead, so the value can run a script or show a file in its place (see string_hooks.go); text built from anything else, such as a handle or a subject, must not be read as one.

func (e *MenuExecutor) PromptYesNoString(s ssh.Session, terminal *term.Terminal, value string, outputMode ansi.OutputMode, nodeNumber int, termWidth int, termHeight int, defaultYes bool) (bool, error)

PromptYesNoString is PromptYesNo for a prompt that is a strings.json value.

func (e *MenuExecutor) PromptYesNof(s ssh.Session, terminal *term.Terminal, outputMode ansi.OutputMode, nodeNumber int, termWidth int, termHeight int, defaultYes bool, format string, args ...any) (bool, error)

PromptYesNof is PromptYesNoString for a value the call site formats with args. The format comes after the fixed arguments so the stringformat call-site check can count what is passed to it.

func (e *MenuExecutor) Protocols() []transfer.ProtocolConfig

Protocols returns a copy of the transfer protocol configurations, safe for the caller to hold or mutate.

func (e *MenuExecutor) QWKAPILoginDenial(u *user.User) string

QWKAPILoginDenial is the QWK API's counterpart to AdmitPreAuthenticatedUser: it applies the same post-password checks to an API login, returning why the account is refused or "" to admit it. The API has no terminal to run the intro gate in, so an account that still owes its introduction is refused rather than sent through it.

func (e *MenuExecutor) Run(s ssh.Session, terminal *term.Terminal, userManager *user.UserMgr, currentUser *user.User, startMenu string, nodeNumber int, sessionStartTime time.Time, autoRunLog types.AutoRunTracker, outputMode ansi.OutputMode, currentAreaName string, termWidth int, termHeight int) (string, *user.User, error)

Run executes the menu logic for a given starting menu name. Reverted s parameter back to ssh.Session Added outputMode parameter Added currentAreaName parameter

func (e *MenuExecutor) RunChallengeGate(
	s ssh.Session,
	terminal *term.Terminal,
	nodeNumber int,
	outputMode ansi.OutputMode,
	termWidth int,
	termHeight int,
) (bool, error)

RunChallengeGate shows the pre-login bot challenge. It returns true if the caller passed (pressed the configured key the required number of times before the timeout), false to disconnect. An io.EOF error indicates the caller hung up. Modeled on RunMatrixScreen; safe to call only when EnableChallengeGate.

func (e *MenuExecutor) RunLoginSequence(s ssh.Session, terminal *term.Terminal, userManager *user.UserMgr, currentUser *user.User, nodeNumber int, sessionStartTime time.Time, outputMode ansi.OutputMode, termWidth int, termHeight int) (string, error)

RunLoginSequence is the exported entry point for running the login sequence from main.go. Returns the next menu name to enter (e.g., "MAIN") or "LOGOFF".

func (e *MenuExecutor) RunMatrixScreen(
	s ssh.Session,
	terminal *term.Terminal,
	userManager *user.UserMgr,
	nodeNumber int,
	outputMode ansi.OutputMode,
	termWidth int,
	termHeight int,
) (string, *user.User, error)

RunMatrixScreen displays the pre-login matrix menu and returns the selected action. Actions: "LOGIN", "NEWUSER", "CHECKACCESS", "DISCONNECT" Called from main.go sessionHandler before the login loop for telnet users. Uses standard .BAR/.CFG menu files (PDMATRIX.BAR, PDMATRIX.CFG) for configuration.

func (e *MenuExecutor) SetDoorRegistry(doors map[string]config.DoorConfig)

SetDoorRegistry atomically updates the door registry. The map is cloned on store, so the caller keeping (and mutating) its own reference cannot reach the shared snapshot.

func (e *MenuExecutor) SetLoginSequence(sequence []config.LoginItem)

SetLoginSequence atomically updates the login sequence. The slice is cloned on store, so the caller keeping its own reference cannot reach the shared snapshot.

func (e *MenuExecutor) SetProtocols(protocols []transfer.ProtocolConfig)

SetProtocols atomically updates the transfer protocol configurations. The slice is cloned on store, so the caller keeping its own reference cannot reach the shared snapshot.

func (e *MenuExecutor) SetServerConfig(serverCfg config.ServerConfig)

SetServerConfig atomically updates the server configuration. The sysop levels are sanitized here as well as at load, since configs also arrive from the config editor and reloads, and the handlers and ACS keywords must agree on them.

func (e *MenuExecutor) SetStrings(strings config.StringsConfig)

SetStrings atomically updates the strings configuration.

func (e *MenuExecutor) SetTheme(theme config.ThemeConfig)

SetTheme atomically updates the theme configuration.

func (e *MenuExecutor) Strings() *config.StringsConfig

Strings returns the current strings configuration.

A pointer, not a copy: StringsConfig is several hundred fields and this is the hottest accessor in the package, called once per displayed string. The value behind it is shared and must not be mutated.

func (e *MenuExecutor) Theme() *config.ThemeConfig

Theme returns the current theme configuration. Read-only.

func (e *MenuExecutor) TimeLimit(u *user.User) int

TimeLimit is timeLimit for callers outside the menu package, such as the WFC console's time-left column.

func (e *MenuExecutor) TwitMatcher(um *user.UserMgr, u *user.User) *user.TwitMatcher

TwitMatcher is twitMatcher for callers outside the menu package, such as the QWK API, so every export applies the same board settings.

func (e *MenuExecutor) WriteString(terminal *term.Terminal, outputMode ansi.OutputMode, value string) error

WriteString is writeString for code outside the menu package.

type MenuRecord struct {
	Title string `json:"TITLE"`
	// Fields expected from JSON .MNU
	ClrScrBefore bool   `json:"CLR"`
	ClsScrBefore bool   `json:"CLS"`
	UsePrompt    bool   `json:"USEPROMPT"`
	Prompt1      string `json:"PROMPT1"`
	Prompt2      string `json:"PROMPT2"`
	Fallback     string `json:"FALLBACK"`
	ACS          string `json:"ACS"`
	Password     string `json:"PASS"`
	// ForceHotKey makes the menu take single-key input for every caller,
	// whatever their Hot Keys setting.
	ForceHotKey bool `json:"FORCEHOTKEY"`
}

MenuRecord adapted for JSON parsing of .MNU files. Assumes JSON keys match the tags.

func LoadMenu

func LoadMenu(menuName string, menus menuset.Set) (*MenuRecord, error)

LoadMenu reads a .MNU file (assumed JSON) for the given menu name from the menu set's mnu/ directory, overlay first.

func (mr *MenuRecord) GetClrScrBefore() bool

GetClrScrBefore reports whether the screen is cleared before the menu is shown; either the CLR or the CLS key in the menu file turns it on.

func (mr *MenuRecord) GetUsePrompt() bool

GetUsePrompt reports whether the menu displays its prompt (Prompt1/Prompt2) before reading a command; it reflects the USEPROMPT key in the menu file.

type MessageHeaderTemplate

type MessageHeaderTemplate struct {
	Number      int    // Template number (e.g., 1, 2, 15)
	Filename    string // Full filename (e.g., "MSGHDR.15.ans")
	DisplayName string // Human-readable name (e.g., "Header Style 15")
}

MessageHeaderTemplate represents a discovered message header template file.

type MessageListEntry

type MessageListEntry struct {
	MsgNum    int
	Subject   string
	From      string
	To        string
	Date      time.Time // When the message was written; blank in the list if zero
	IsPrivate bool
	IsRead    bool // Based on JAM lastread pointer

	// Threaded mode only (buildThreadedMessageList).
	Threaded    bool   // drawn as a threaded row: tree prefix and a Thread column
	Depth       int    // depth in the reply tree; 0 for a root
	Prefix      string // tree glyphs before the text, as threadRow.Prefix
	Excerpt     string // the message's first line of its own text
	OwnSubject  bool   // show the subject rather than the excerpt: a root, or a changed subject
	Placeholder bool   // a deleted message a reply hangs from: "#n deleted", never selectable
}

MessageListEntry represents a single message in the list view

type MessageListState

type MessageListState struct {
	AreaID        int
	TotalMessages int // rows in Entries, placeholders included; the page info counts messages
	Entries       []MessageListEntry
	CurrentPage   int
	ItemsPerPage  int
	SelectedIndex int // Index within current page (0-based)
	LastRead      int
	Threaded      bool // the list is in threaded mode
}

MessageListState manages the list display and navigation

type MsgLightbarOption

type MsgLightbarOption struct {
	Label   string // Display text including padding, e.g. " Next "
	HotKey  byte   // Single-char hotkey, e.g. 'N'
	LoColor int    // Override unselected color (0 = use default loColor)
}

MsgLightbarOption defines an option in the message reader lightbar.

type NUVCandidate

type NUVCandidate struct {
	Handle string    `json:"handle"`
	When   time.Time `json:"when"`
	Votes  []NUVVote `json:"votes"`
}

NUVCandidate represents a new user pending community voting. Maps to V2's NuvRec.

type NUVData

type NUVData struct {
	Candidates []NUVCandidate `json:"candidates"`
}

NUVData holds all NUV candidates.

type NUVVote

type NUVVote struct {
	Voter   string    `json:"voter"`
	Yes     bool      `json:"yes"`
	Comment string    `json:"comment,omitempty"`
	VotedAt time.Time `json:"votedAt,omitempty"`
}

NUVVote represents a single vote cast on a NUV candidate.

type NewsData

type NewsData struct {
	Items []NewsItem `json:"items"`
	// NextID is the monotonic ID allocator. IDs must never be reused: users
	// carry seen-state keyed by ID, and handing a deleted item's ID to a new
	// one would hide the new item from everyone who had seen the old.
	// Deriving IDs from the live list alone is not enough, because deleting
	// the highest-numbered item frees its ID again.
	NextID int `json:"next_id,omitempty"`
}

NewsData holds all news items.

type NewsItem

type NewsItem struct {
	ID       int       `json:"id"`
	Title    string    `json:"title"` // max 28 chars (V2 String[28])
	From     string    `json:"from"`  // author handle
	When     time.Time `json:"when"`
	Level    int       `json:"level"`     // min access level
	MaxLevel int       `json:"max_level"` // max access level (0 = no max / all)
	Always   bool      `json:"always"`    // true = show every login; false = once (new since last login)
	Body     string    `json:"body"`      // news text body
}

NewsItem represents a single news item (maps to V2's newsrec).

type PlaceholderMatch

type PlaceholderMatch struct {
	Code      string         // Single letter (T, F, S, etc.)
	Width     int            // 0 = no width constraint
	MaxWidth  int            // 0 = no limit; otherwise truncate to this width without padding
	AutoWidth bool           // true = use auto-calculated width from context
	Align     ansi.Alignment // AlignLeft (default), AlignRight, AlignCenter
	FullMatch string         // Complete matched text "@T###@"
	StartPos  int            // Byte offset in template
	EndPos    int            // End byte offset
}

PlaceholderMatch represents a parsed placeholder from a template.

type RegionCondition added in v0.9.7

type RegionCondition struct {
	ACS  string // the text between {{ and }}
	Line int    // 1-based line of the opening marker
}

RegionCondition is the condition of one {{acs}} region in menu art.

func RegionConditions added in v0.9.7

func RegionConditions(content []byte) []RegionCondition

RegionConditions lists the ACS conditions of the {{acs}}...{{/}} regions in menu ANSI content, in order, as applyConditionalRegions would find them: keyword conditions (regionKeywords), literal tokens such as {{PENDING_VALIDATIONS}}, stray {{/}} and decorative braces spanning lines are left out. vision3 doctor uses it to check every region's ACS.

type RumorRecord

type RumorRecord struct {
	ID       int       `json:"id"`
	Author   string    `json:"author"`            // Displayed author (may be anonymous)
	RealUser string    `json:"real_user"`         // Actual handle (V2: Author2); legacy entries may contain old username
	UserID   int       `json:"user_id,omitempty"` // Stable owner ID for ownership checks (0 = legacy record)
	Text     string    `json:"text"`              // Rumor text
	PostedAt time.Time `json:"posted_at"`         // When posted
	MinLevel int       `json:"min_level"`         // Minimum access level to view
}

RumorRecord represents a single rumor entry. Simplified from V2's RumorRec — title dropped in favor of text-only graffiti wall.

type RunnableFunc

type RunnableFunc func(c *cmdCtx, args string) (authenticatedUser *user.User, nextAction string, err error)

RunnableFunc is the signature of a built-in command that a menu reaches with a "RUN:<TARGET> args" action (and of the "DOOR:" handler); implementations are registered in MenuExecutor.RunRegistry under the upper-cased target. args is whatever followed the target on the command line. The returned user replaces the session's current user (login runnables use it to report who authenticated). nextAction may be "GOTO:<MENU>" or "LOGOFF"; anything else, including "", stays on the current menu. An io.EOF or idle-timeout error logs the caller off; any other error is shown to the caller and the menu continues.

type ScanConfig

type ScanConfig struct {
	ScanDate       int64  // scanDateNewOnly, scanDateAll, or unix time of local midnight on the chosen day
	SearchTo       string // case-insensitive substring the To field must contain ("" = any)
	SearchFrom     string // case-insensitive substring the From field must contain ("" = any)
	RangeStart     int    // first message number to scan (0 = from the computed start)
	RangeEnd       int    // last message number to scan (0 = to the end of the area)
	UpdatePointers bool   // keep last-read pointer changes made while reading
	WhichAreas     int    // 1=tagged/marked, 2=all in conference, 3=current only
	Aborted        bool
}

ScanConfig holds the scan parameters configured by runGetScanType.

Every field here is honoured by the scan: SearchTo/SearchFrom, a date and a range become a per-message filter (see ScanConfig.filter) that both the start-message calculation and the message reader apply, and UpdatePointers controls whether the last-read pointers the reader advances are kept.

type SysopPager added in v0.9.5

type SysopPager interface {
	Consoles() int
	RaisePage(nodeID int, handle, reason string)
	ClearPage(nodeID int, handle, why string)
}

SysopPager is the WFC side of PAGESYSOP; *admin.Server satisfies it.

type V3NetCentralProvider added in v0.9.7

type V3NetCentralProvider interface {
	// CentralNetworks returns every running subscription's Central state.
	CentralNetworks() []CentralNetworkInfo
	// CentralDirectory returns network's verified board directory; force
	// skips the leaf's short cache. It returns an error wrapping
	// leaf.ErrCentralDisabled or leaf.ErrCentralUnsupported when the
	// directory cannot be offered on the network.
	CentralDirectory(ctx context.Context, network string, force bool) ([]protocol.CentralDirectoryEntry, error)
}

V3NetCentralProvider is what the Central screens need from the V3Net service. The concrete implementation is an adapter over *v3net.Service, injected from cmd/vision3.

type V3NetStatusProvider

type V3NetStatusProvider interface {
	NodeID() string
	HubActive() bool
	LeafCount() int
	LeafNetworks() []string
	NetworkForArea(areaID int) string
	FetchNALForNetwork(ctx context.Context, network string) (*protocol.NAL, error)
	HubURLForNetwork(network string) string
	ProposeArea(network string, req protocol.AreaProposalRequest) (*protocol.ProposalResponse, error)
	RegistryURL() string

	// Coordinator and area-manager operations. The hub authorizes each call
	// from the signed node ID, so a caller that lacks the role gets an error
	// carrying the hub's message.
	ListProposals(ctx context.Context, network string) ([]protocol.AreaProposal, error)
	ApproveProposal(ctx context.Context, network, proposalID string, req protocol.ProposalApproveRequest) error
	RejectProposal(ctx context.Context, network, proposalID string, req protocol.ProposalRejectRequest) error
	SetAreaManager(ctx context.Context, network, tag, nodeID string) error
	ListAccessRequests(ctx context.Context, network, tag string) ([]protocol.AccessRequest, error)
	ApproveAccess(ctx context.Context, network, tag string, nodeIDs []string) error
	DenyAccess(ctx context.Context, network, tag string, nodeIDs []string, reason string) error
}

V3NetStatusProvider is an interface for querying V3Net service status. The concrete implementation is *v3net.Service, injected from cmd/vision3.

type VoteTopic

type VoteTopic struct {
	ID        int                 `json:"id"`
	Question  string              `json:"question"`
	Options   []string            `json:"options"`
	Mandatory bool                `json:"mandatory,omitempty"`
	AddLevel  int                 `json:"add_level,omitempty"` // min sec level to add choices; 0=disabled
	Votes     map[string][]string `json:"votes"`               // option index → []handle
}

VoteTopic represents a single voting topic.

type VotingData

type VotingData struct {
	Topics []VoteTopic `json:"topics"`
	// NextID is the monotonic topic ID allocator. IDs are never reused: a
	// session that listed a topic before another deleted it must find the
	// topic gone, not a newer topic that took over its ID. Deriving IDs from
	// the live topics alone would free the highest ID again on delete.
	NextID int `json:"next_id,omitempty"`
}

VotingData holds all voting topics.

type WantListEntry

type WantListEntry struct {
	ID       int    `json:"id"`
	Handle   string `json:"handle"`
	Filename string `json:"filename"`
	Reason   string `json:"reason"`
	Date     string `json:"date"`
}

WantListEntry represents a single file request from a user.

Source Files

Jump to

Keyboard shortcuts

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