Documentation
¶
Overview ¶
Package virtual implements an in-process, real-listener fake NETGEAR switch: seeded, deterministic in-memory device state plus real SNMP, NSDP, HTTP and SSH/Telnet listeners bound to loopback sockets, so a *netgearswitch.Switch (or any other client of packages snmp/nsdp/webui/ fastpath) can talk to it exactly as it would to real hardware, with no hardware required. Every runnable Example function in this module's root package and in package capabilities is built on it, and it backs this module's own integration tests and its gngsw-virtual command.
Starting a fake switch ¶
NewVirtualSwitch(modelKey, ...Option) builds a VirtualSwitch for one registered model.SwitchModel, seeded via BuildState (which dispatches to that model's own SeedXxx function, e.g. SeedGSM7252PS, when one exists, or an empty-but-valid NewState otherwise). Start binds a real loopback listener for every protocol face the model's Backends declare -- SnmpFace/NsdpFace/HTTPFace/SSHFace/TelnetFace, each backed by the SAME State -- and records the bound port on the VirtualSwitch's SnmpPort/ NsdpPort/HTTPPort/SSHPort/TelnetPort fields (0 for any face the model does not have, or before Start). Stop tears every bound face down (idempotent; safe before Start or more than once). CliSession returns an in-process fastpath.Session talking to this switch's CLI face directly, with no socket at all -- useful where a real SSH/Telnet round trip is unnecessary. Option (WithCommunity, WithHost, WithHTTPPassword, WithCLIUsername, WithCLIPassword, WithPort, WithHTTPPort) overrides a VirtualSwitch's defaults at construction.
EndpointProvider and GoFakeProvider are the conformance-harness seam: StartModel starts (or reuses) a VirtualSwitch for a model key and returns its Endpoints, for a test harness that wants "give me a live switch for this model" without caring about VirtualSwitch's own API.
Device state and protocol faces ¶
State (NewState/BuildState) holds everything a simulated switch "knows" about itself -- port link/admin/speed, counters, VLANs, PVIDs, PoE, sensors, the MAC/FDB table, LLDP neighbours, users/services, syslog and management IP -- as small mutable *Sim structs (PortSim, VlanSim, PoeSim, ...). It is shared, live, mutable state: a write accepted by one face is immediately visible to a read from any other face against the same VirtualSwitch, exactly as a real switch's own state is protocol- agnostic.
MibView/NewMibView and OIDMap project State onto the flat numeric OID -> (type, value) view SnmpFace serves and writes into; the Render* functions (RenderXUI*, RenderGoAhead*, ...) render State back out as the HTML/XML pages HTTPFace serves, mirroring each of package webui's dialects; CliFace/NewCliFace implements the FASTPATH `show`/configure command surface NewSSHFace/NewTelnetFace's socket-level faces wrap.
Ported field-for-field from src/netgear_switch/virtual/ (the normative source; that repo is read-only from here). Any discrepancy between this package and the pinned Python source is a bug in this package, not a deliberate deviation, unless called out in a comment.
Index ¶
- func ApplyFastpathMgmtIP(state *State, spec *webui.HTTPModelSpec, form map[string]string) string
- func ApplyFastpathPortAdmin(state *State, form map[string]string, checkbox string, ports []int) string
- func ApplyFastpathVlanMembership(state *State, form map[string]string)
- func ApplyGS110EMXPortSettings(state *State, form map[string]string) string
- func ApplyGS110EMXSysinfo(state *State, token string, form map[string]string) string
- func ApplyM4300PoE(state *State, form map[string]string) string
- func ApplyM4300Ports(state *State, form map[string]string) string
- func ApplyS3300PoE(state *State, form map[string]string) string
- func ApplyS3300Ports(state *State, form map[string]string) string
- func ApplyXEPoE(state *State, form map[string]string) string
- func ApplyXEPoEWith(state *State, form map[string]string, checkbox string, unitRequired bool) string
- func ApplyXEPorts(state *State, form map[string]string) string
- func ApplyXEPortsWith(state *State, form map[string]string, checkbox string) string
- func ApplyXUISyslogRows(state *State, form map[string]string) string
- func FastpathVlanRefusal(state *State, form map[string]string) string
- func RenderFastpathMgmtIP(state *State, spec *webui.HTTPModelSpec, errMsg string) string
- func RenderFastpathVlanMembership(state *State, spec *webui.HTTPModelSpec, form map[string]string, errMsg string) string
- func RenderFormServicePage(state *State, path, service string) string
- func RenderGS105PEPortStatistics(state *State) string
- func RenderGS105PEPvid(state *State) string
- func RenderGS105PEStatus(state *State) string
- func RenderGS105PESwitchInfo(state *State) string
- func RenderGS105PEVlanConfig(state *State) string
- func RenderGS105PEVlanMembership(state *State, selectedVid int) string
- func RenderGS110EMXCf8021q(state *State, token string) string
- func RenderGS110EMXInterfaceStats(state *State, token string) string
- func RenderGS110EMXLogin(rand string) string
- func RenderGS110EMXPortSettings(state *State, token string) string
- func RenderGS110EMXPvid(state *State, token string) string
- func RenderGS110EMXRedirect(token string) string
- func RenderGS110EMXSysinfo(state *State, token string) string
- func RenderGS110EMXVlanMembership(state *State, token string, selectedVid int) string
- func RenderGS728TPPDeviceInfoAndSensors(state *State) string
- func RenderGS728TPPLLDP(state *State) string
- func RenderGS728TPPMacs(state *State) string
- func RenderGS728TPPMgmtIP(state *State) string
- func RenderGS728TPPPoE(state *State) string
- func RenderGS728TPPPorts(state *State) string
- func RenderGS728TPPPvidsMembership(state *State) string
- func RenderGS728TPPVlans(state *State) string
- func RenderGS728TPPWcd(state *State, query string) (string, bool)
- func RenderM4300MacTable(state *State) string
- func RenderM4300PoE(state *State, errMsg string) string
- func RenderM4300PortStatistics(state *State) string
- func RenderM4300Ports(state *State, errMsg string) string
- func RenderM4300Pvids(state *State) string
- func RenderM4300Sysinfo(state *State) string
- func RenderM4300Vlans(state *State) string
- func RenderS3300MacTable(state *State) string
- func RenderS3300PoE(state *State, errMsg string) string
- func RenderS3300Ports(state *State, errMsg string) string
- func RenderS3300Sysinfo(state *State) string
- func RenderS3300Vlans(state *State) string
- func RenderXELLDP(state *State) string
- func RenderXEMacTable(state *State) string
- func RenderXEPoE(state *State, errMsg string) string
- func RenderXEPoEWith(state *State, watts bool, errMsg string, iface func(int) string, ...) string
- func RenderXEPortStatistics(state *State) string
- func RenderXEPorts(state *State, errMsg string) string
- func RenderXEPortsWith(state *State, errMsg string, iface func(int) string, checkbox, path string) string
- func RenderXEPvids(state *State) string
- func RenderXESysinfo(state *State) string
- func RenderXEVlans(state *State) string
- func RenderXUIServicePage(state *State, path, service string) string
- func RenderXUISyslog(state *State, path, errMsg string) string
- func RenderXUIUsers(state *State, path string) string
- func UnauthenticatedResponse() string
- type CliFace
- func (f *CliFace) Close() error
- func (f *CliFace) InterfaceName() (string, bool)
- func (f *CliFace) Mode() string
- func (f *CliFace) Run(ctx context.Context, command string) (string, error)
- func (f *CliFace) RunSCPCopy(ctx context.Context, command, _ string) (string, error)
- func (f *CliFace) RunWriteMemory(ctx context.Context, command string, _ bool) (string, error)
- type EndpointProvider
- type Endpoints
- type EntitySim
- type GoFakeProvider
- type HTTPFace
- type LldpSim
- type MacSim
- type MgmtSim
- type MibView
- func (v *MibView) ApplyWrite(oid string, value any)
- func (v *MibView) ApplyWriteUncommitted(oid string, value any)
- func (v *MibView) Get(oid []int) (entry *ViewEntry, ok bool)
- func (v *MibView) GetNext(oid []int) (entry *ViewEntry, ok bool)
- func (v *MibView) IsImplemented(oid []int) bool
- func (v *MibView) IsWritableOID(oid string) bool
- func (v *MibView) LockState()
- func (v *MibView) Rebuild()
- func (v *MibView) RestoreState(snapshot *State)
- func (v *MibView) SnapshotState() *State
- func (v *MibView) UnlockState()
- type NsdpFace
- type OIDEntry
- type Option
- type PoeSim
- type PortSim
- type SSHFace
- type ScpCertDeploySim
- type ScpCopy
- type SensorSim
- type ServiceSim
- type SnmpFace
- type State
- func (s *State) ApplyNsdpWrite(tag nsdp.Tag, value []byte)
- func (s *State) ApplyPoeAdmin(port int, on bool)
- func (s *State) ApplyWrite(oid string, value any)
- func (s *State) IsOIDImplemented(oid string) bool
- func (s *State) IsWritableOID(oid string) bool
- func (s *State) LockState()
- func (s *State) NsdpTlvs(tags map[nsdp.Tag]bool) []nsdp.TLVEntry
- func (s *State) OIDMap() map[string]OIDEntry
- func (s *State) Restore(snap *State)
- func (s *State) Snapshot() *State
- func (s *State) SysinfoSensors() []SensorSim
- func (s *State) UnlockState()
- type SyslogCollectorSim
- type SyslogSim
- type TelnetFace
- type UserSim
- type ViewEntry
- type VirtualSwitch
- type VlanMembershipPageSim
- type VlanSim
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApplyFastpathMgmtIP ¶
ApplyFastpathMgmtIP applies a management-IP form, returning the firmware's err_msg ("" = ok), mirroring Python web_fastpath_xui.apply_mgmt_ip. Reproduces the real page's validator rather than accepting anything: the firmware answers a malformed address with HTTP 200 + err_flag=1 + a human "IP address should be in x.x.x.x form" message.
func ApplyFastpathPortAdmin ¶
func ApplyFastpathPortAdmin(state *State, form map[string]string, checkbox string, ports []int) string
ApplyFastpathPortAdmin applies portsConfiguration.html's Admin Mode column, honouring the per-row checkboxes. Returns the firmware err_msg ("" = accepted). Mirrors Python web_fastpath_xui.apply_port_admin.
func ApplyFastpathVlanMembership ¶
ApplyFastpathVlanMembership applies a membership POST -- but ONLY when submt is the apply flag. submt=0 is the VLAN <select>'s own re-render POST and must not mutate anything. A port set Excluded loses its CURRENT membership too; a port set tagged/untagged becomes a current member. ConfiguredOnly is cleared for a port the caller explicitly set. Mirrors Python web_fastpath_vlan.apply_membership.
func ApplyGS110EMXPortSettings ¶
ApplyGS110EMXPortSettings applies a port_settings.html POST; returns the page's reply BODY. Mirrors Python web_gs110emx.apply_port_settings: the real page answers an AJAX apply with a bare "SUCCESS" (its own JS checks resText != "SUCCESS"), not a re-rendered page. PORT_NO is the SEMICOLON-TERMINATED selected-port list its saveSelectedPorts() builds ("3;"), and a body that sends a bare number selects nothing and applies nothing -- reproduced here, because that is exactly the mistake that a lenient mock would have hidden (it was caught on real hardware instead).
func ApplyGS110EMXSysinfo ¶
ApplyGS110EMXSysinfo applies a sysInfo.html POST (GS110EMXSwitchInfoForm's shape -- switch_name/dhcp_mode/IP_ADDRESS/SUBNET_MASK/GATEWAY_ADDRESS/ ACTION) and returns the freshly re-rendered page. Unlike ApplyGS110EMXPortSettings' bare "SUCCESS" (that page's own JS is an AJAX apply), this page's submitSwitchInfoForm() does a plain `form1.submit()` -- an ordinary whole-form POST-back -- so re-rendering the page here is the more faithful response shape for that mechanism, even though (like ApplyGS110EMXPortSettings) no direct capture of THIS specific response exists; both are consistent with this model's OWN two established firmware conventions for its two apply forms.
Applying EVERY field this form carries (not just switch_name) is deliberate and load-bearing: webui.Writer.SetHostname's GS110EMX path (the DANGEROUS read-modify-write) re-POSTs the CURRENT dhcp_mode/ IP_ADDRESS/SUBNET_MASK/GATEWAY_ADDRESS alongside the new name specifically so this fake's own round trip can prove those fields survive unchanged -- a fake that silently ignored them would never catch a caller (or a future regression in that writer) that stopped echoing them.
func ApplyM4300PoE ¶
ApplyM4300PoE mirrors Python web_m4300.apply_poe: unit_required=false -- like the gsm7228ps and unlike the gsm7252ps, this firmware's PoE rows carry their own hidden v_1_2_21 "Unit" key, so the apply lands with no page-level unit field.
func ApplyM4300Ports ¶
ApplyM4300Ports applies a /v1/portsConfiguration.html POST; returns the firmware err_msg. Mirrors Python web_m4300.apply_ports.
func ApplyS3300PoE ¶
ApplyS3300PoE mirrors Python web_gsm7228ps.apply_poe: unitRequired=false -- this firmware's PoE rows carry their own hidden v_1_2_21 "Unit" key, so the row is self-identifying and the apply lands with no page-level unit field.
func ApplyS3300Ports ¶
ApplyS3300Ports mirrors Python web_gsm7228ps.apply_ports.
func ApplyXEPoE ¶
ApplyXEPoE applies a poeInterfaceConfiguration.html POST for the GSM7252PS's own checkbox with unit_required=true. Mirrors Python web_gsm7252ps.apply_poe's default-argument call shape.
func ApplyXEPoEWith ¶
func ApplyXEPoEWith(state *State, form map[string]string, checkbox string, unitRequired bool) string
ApplyXEPoEWith is the full parametrized form the M4300/S3300 appliers share. Two distinct operations share the page, exactly as on hardware: APPLY (v_2_1_2) writes the Admin Mode column, RESET (v_2_1_3) consumes the write-only v_1_2_20 column and re-runs detection. Only CHECKED rows are touched.
unitRequired reproduces a MEASURED per-firmware difference, not a guess. The GSM7252PS PoE rows carry no hidden Unit key column, so its firmware takes the list scope from the page's urlListUnit field and refuses the whole row without it (unitRequired=true -- this model's own renderer). The gsm7228ps and both M4300 PoE pages DO render a per-row v_1_2_21 "Unit" key and accept the same body with no page-level unit at all, so those callers pass false. Mirrors Python web_gsm7252ps.apply_poe.
func ApplyXEPorts ¶
ApplyXEPorts applies a portsConfiguration.html POST for the GSM7252PS's own checkbox; returns the firmware err_msg. Mirrors Python web_gsm7252ps.apply_ports's default-argument call shape.
func ApplyXEPortsWith ¶
ApplyXEPortsWith is the full parametrized form the M4300/S3300 appliers share. Mirrors Python web_gsm7252ps.apply_ports.
func ApplyXUISyslogRows ¶
ApplyXUISyslogRows applies a syslog-page row ADD or DELETE, returning errMsg ("" = ok), mirroring Python web_fastpath_xui.apply_syslog_rows.
Reproduces what the live M4300 page does, both halves:
- ADD -- the v_g_2_1_* template row with its write-only row-status (v_g_2_1_5) set to "Active". THE ADD IS REFUSED, and the fake must refuse it too: driven live against m4300-24x 10.1.5.13 on 2026-08-05, the firmware answers a filled template row with HTTP 200 and "Error! Failed to Set 'Host Address' with '<addr>'", leaving the table unchanged (verified through the switch's own CLI). A fake that accepted the add would make webui.Writer's refusal look like a library limitation rather than the device's answer.
- DELETE -- a data row whose own v_2_1_5 is set to "Delete". Addressed by the row's OWN v_2_1_1 (Host Address) field, not its index -- no index arithmetic is involved on this path, unlike the CLI/SNMP routes.
A template row submitted WITHOUT the row-status is ignored, exactly as the firmware ignores a blank global row that was never activated.
func FastpathVlanRefusal ¶
FastpathVlanRefusal is the err_msg this apply would be refused with, or "" if allowed. Reproduces the M4300 firmware's precondition: a port whose switchport mode is access or trunk cannot be given explicit VLAN membership, and the web UI reports that as err_flag=1 + err_msg on an otherwise-200 page rather than an HTTP error. Mirrors Python web_fastpath_vlan.refusal.
func RenderFastpathMgmtIP ¶
func RenderFastpathMgmtIP(state *State, spec *webui.HTTPModelSpec, errMsg string) string
RenderFastpathMgmtIP renders the model's management-IP page from state.Mgmt, mirroring Python web_fastpath_xui.render_mgmt_ip. Caller must have already checked spec.MgmtIPFields != nil and spec.MgmtIPPath != "".
func RenderFastpathVlanMembership ¶
func RenderFastpathVlanMembership(state *State, spec *webui.HTTPModelSpec, form map[string]string, errMsg string) string
RenderFastpathVlanMembership renders the VLAN Membership page for the VLAN form selected. Mirrors Python web_fastpath_vlan.render_membership.
func RenderFormServicePage ¶
RenderFormServicePage renders one service's config page in the PLAIN NAMED FORM shape (the M4300's http/https pages), mirroring Python render_service_form.
Reproduces the firmware's double-checked radio group verbatim: BOTH radios carry a checked attribute, spelled `checked="checked"` on the first and a bare uppercase `CHECKED` on the second, and a browser takes the LAST. A mock that marked only the true one would let a first-match parser pass here and then misreport every real switch -- see webui.checkedRadio's doc comment for the same trap on the reader side.
func RenderGS105PEPortStatistics ¶
RenderGS105PEPortStatistics renders GET /portStatistics.cgi -- reproduces the real page's quirks: rows are <tr class="portID" name="portID">, the Bytes-Received cell is rendered EMPTY, and each counter is a hidden (hi, lo) 32-bit pair. Mirrors Python web_gs105pe.render_port_statistics.
func RenderGS105PEPvid ¶
RenderGS105PEPvid renders GET /portPVID.cgi -- [1]=port, [2]=PVID. Mirrors Python web_gs105pe.render_pvid.
func RenderGS105PEStatus ¶
RenderGS105PEStatus renders GET /status.cgi -- per-port link + speed, the columns webui.ParseGS105PEPortStatus reads ([1]=port, [2]=link, [4]=speed). Mirrors Python web_gs105pe.render_status.
func RenderGS105PESwitchInfo ¶
RenderGS105PESwitchInfo renders GET /switch_info.cgi -- device identity + mgmt-IP, in the labelled-cell and lowercase-input shape webui.ParseGS105PESysInfo reads. Mirrors Python web_gs105pe.render_switch_info.
func RenderGS105PEVlanConfig ¶
RenderGS105PEVlanConfig renders GET /8021qCf.cgi -- the VLAN list as vlanckN checkboxes (the shape gs305ep's webui.ParseVLANIDs reads, which gs105pe shares). Mirrors Python web_gs105pe.render_vlan_config.
func RenderGS105PEVlanMembership ¶
RenderGS105PEVlanMembership renders GET/POST /8021qMembe.cgi -- the per-port hiddenMem wire codes (1=untagged, 2=tagged, 3=excluded) for selectedVid, plus the CSRF hash and a <option ... selected> marking which VLAN is shown. Mirrors Python web_gs105pe.render_vlan_membership.
func RenderGS110EMXCf8021q ¶
RenderGS110EMXCf8021q renders GET Cf8021q.html -- the VLAN list (with member ports) from state. The reader only scrapes the VID column (webui.ParseGS110EMXVlanIDs); the member list is rendered for fidelity. Mirrors Python web_gs110emx.render_cf8021q.
func RenderGS110EMXInterfaceStats ¶
RenderGS110EMXInterfaceStats renders GET /iss/specific/interface_stats.html?Gambit=<token> -- byte-identical to gs110emx_interface_stats.html but for the per-port counters. The real device NEVER closes a <tr class="portID"> with </tr> (rows run on until the next <tr> or the table close); this reproduces that exact malformed-but-real shape row-for-row, which is why webui.ParseInterfaceStats (not gs305ep's ParsePortStats) is needed to read it back. Missing counters (nil) render as 0, matching the real device's own zeroed idle-port rows. Mirrors Python web_gs110emx.render_interface_stats.
func RenderGS110EMXLogin ¶
RenderGS110EMXLogin renders the GET / login page, byte-identical to gs110emx_login.html but for the rand nonce. Mirrors Python web_gs110emx.render_login.
func RenderGS110EMXPortSettings ¶
RenderGS110EMXPortSettings renders GET port_settings.html -- port link/speed/description from state, so the HTTP port-status read matches the NSDP PORT_STATUS read on this switch. Mirrors Python web_gs110emx.render_port_settings.
func RenderGS110EMXPvid ¶
RenderGS110EMXPvid renders GET vlan_pvidsetting.html -- per-port PVID from state. Mirrors Python web_gs110emx.render_pvid.
func RenderGS110EMXRedirect ¶
RenderGS110EMXRedirect renders the POST /redirect.html login response, byte-identical to gs110emx_redirect.html but for the Gambit token. token=="" (a rejected login) renders a Gambit field with an empty value, which webui.ParseGambitToken reads back as falsy. Mirrors Python web_gs110emx.render_redirect.
func RenderGS110EMXSysinfo ¶
RenderGS110EMXSysinfo renders GET /iss/specific/sysInfo.html?Gambit=<token>, byte-identical to gs110emx_sysinfo.html but for the state-driven device identity/mgmt-IP fields. dhcpSelect mirrors the captured page's data-select-value attribute (0=static/Disable, 1=DHCP/Enable) -- see webui.ParseSysInfo's read-side grounding of this convention. Mirrors Python web_gs110emx.render_sysinfo.
func RenderGS110EMXVlanMembership ¶
RenderGS110EMXVlanMembership renders POST vlanMembership.html (VLAN_ID=<selectedVid>) -- the per-port hiddenMem wire codes (1=untagged, 2=tagged, 3=excluded) for the selected VLAN, plus the full VLAN <option> list. The wire codes are the SAME scheme gs305ep's 8021qMembe.cgi uses, so webui.ParseMembership reads it back and the resulting VLANInfo matches the NSDP VLAN_MEMBERS read. Mirrors Python web_gs110emx.render_vlan_membership.
func RenderGS728TPPDeviceInfoAndSensors ¶
RenderGS728TPPDeviceInfoAndSensors renders DeviceBasicInfo (cosmetic identity) + DiagnosticsUnitList (the sensors the library actually reads back via webui.ParseGoAheadSensors). The DiagnosticsUnitList fields come from state.SysinfoSensors() (each SensorSim carries the XML tag in Instance and the wire code in Raw). Mirrors Python web_gs728tpp.render_device_info_and_sensors.
func RenderGS728TPPLLDP ¶
RenderGS728TPPLLDP renders the LLDPMEDNeighborList wcd section. Mirrors Python web_gs728tpp.render_lldp.
func RenderGS728TPPMacs ¶
RenderGS728TPPMacs renders the ForwardingTable wcd section. Mirrors Python web_gs728tpp.render_macs.
func RenderGS728TPPMgmtIP ¶
RenderGS728TPPMgmtIP renders the IPv4InterfaceList/IPv4GatewayList wcd sections. Mirrors Python web_gs728tpp.render_mgmt_ip.
func RenderGS728TPPPoE ¶
RenderGS728TPPPoE renders the PoEPSEInterfaceList wcd section. Mirrors Python web_gs728tpp.render_poe.
func RenderGS728TPPPorts ¶
RenderGS728TPPPorts renders the Standard802_3List wcd section. Mirrors Python web_gs728tpp.render_ports/_port_entry.
func RenderGS728TPPPvidsMembership ¶
RenderGS728TPPPvidsMembership renders the VLANInterfaceList wcd section (PVID + per-VLAN join list per port). Mirrors Python web_gs728tpp.render_pvids_membership.
func RenderGS728TPPVlans ¶
RenderGS728TPPVlans renders the VLANList wcd section. Mirrors Python web_gs728tpp.render_vlans.
func RenderGS728TPPWcd ¶
RenderGS728TPPWcd routes a (percent-decoded) wcd?{file=..}{Object}.. query to its renderer, ok=false if this face serves no such wcd query (the caller 404s, never fabricating a page). Mirrors Python web_gs728tpp.render_wcd.
func RenderM4300MacTable ¶
RenderM4300MacTable renders /v1/basicAddressTable.html -- the learned MAC/FDB table. Mirrors Python web_m4300.render_mac_table.
func RenderM4300PoE ¶
RenderM4300PoE renders /v1/poeInterfaceConfiguration.html (M4300-16X only; the 24X has no PoE and its spec leaves the path unset). The cell grid is byte-identical to the gsm7252ps XE page, so that renderer is reused -- but with THREE M4300-specific differences, each live-measured: the power column is decimal watts, the row checkbox is gecb_1_2, and the reset button reads "Power Cycle Port(s)" rather than "RESET". Mirrors Python web_m4300.render_poe.
func RenderM4300PortStatistics ¶
RenderM4300PortStatistics renders /v1/portStatistics.html -- FRAME counters (this UI has no octets). The virtual state stores octet counters, so the frame columns are seeded from the packet counters when present and 0 otherwise. Mirrors Python web_m4300.render_port_statistics.
The row instance is the LITERAL "1.<port>.24" (not a row-index/count pair) -- reproduced exactly as the real capture shows, even though "24" does not track the actual rendered row count; this page is read-only, so no writer depends on that number being accurate.
G2C-1 (docs/hardware-findings.md): this renders only 6 of the ~16 fields the real capture `webui/testdata/http/m4300_portstats.html` carries, under a different xid scheme than that capture's own `1_1_*` columns. Verified harmless and deliberate: webui/parse_m4300.go's ParseM4300Stats keys cells by field-name comment, never by xid, and consumes only these same 6 fields (model.PortStats has no columns for the rest); the pinned Python reference's render_port_statistics renders this identical reduced set under this identical xid scheme. Not a Go-behind-Python gap.
func RenderM4300Ports ¶
RenderM4300Ports renders /v1/portsConfiguration.html -- per-port admin/link/speed. Mirrors Python web_m4300.render_ports.
func RenderM4300Pvids ¶
RenderM4300Pvids renders /v1/portPvidConfiguration.html -- per-port PVID. Mirrors Python web_m4300.render_pvids.
func RenderM4300Sysinfo ¶
RenderM4300Sysinfo renders /v1/base/system/management/sysInfo.html -- mgmt IP, base MAC and the temperature block. Plain labelled cells (this page has no xid cells). Mirrors Python web_m4300.render_sysinfo.
func RenderM4300Vlans ¶
RenderM4300Vlans renders /v1/vlanStatus.html -- VLANs with their egress port list. The egress list is rendered in the real firmware's format, including the "lag N" entries that must NOT be expanded into physical ports. Mirrors Python web_m4300.render_vlans.
func RenderS3300MacTable ¶
RenderS3300MacTable renders /basicAddressTable.html -- the learned MAC/FDB table (S3300 columns): VLAN in v_1_2_2, MAC in v_1_2_3, escaped port ifName in v_1_2_4, status in v_1_2_5 -- the shifted layout webui.ParseS3300Macs reads. Mirrors Python web_gsm7228ps.render_mac_table.
func RenderS3300PoE ¶
RenderS3300PoE renders /poeInterfaceConfiguration.html in the Smart firmware's spelling. Mirrors Python web_gsm7228ps.render_poe.
func RenderS3300Ports ¶
RenderS3300Ports renders /portsConfiguration.html in the Smart firmware's spelling -- same XE grid as gsm7252ps, but the Port cell is "1/g12"/"1/xg49", not "1/0/12". Mirrors Python web_gsm7228ps.render_ports.
func RenderS3300Sysinfo ¶
RenderS3300Sysinfo renders /base/system/management/sysInfo.html -- Base MAC Address only. The S3300 Smart UI's statically-reachable sysInfo exposes the switch's base MAC but NOT the IPv4 management address (that page is behind a JS-only menu), and carries no live fan/temp sensor table. Mirrors Python web_gsm7228ps.render_sysinfo.
func RenderS3300Vlans ¶
RenderS3300Vlans renders /vlanStatus.html -- VLANs with their egress port list (S3300 ifNames), with LAG ifIndexes rendered "lag N" -- not expanded into physical ports. Mirrors Python web_gsm7228ps.render_vlans.
func RenderXELLDP ¶
RenderXELLDP renders /lldpRemoteInventory.html -- LLDP neighbours. This page has NO remote-port-DESCRIPTION column, so LldpSim.PortDesc is deliberately not rendered. Mirrors Python web_gsm7252ps.render_lldp.
func RenderXEMacTable ¶
RenderXEMacTable renders /basicAddressTable.html -- the learned MAC/FDB table. The "Total MAC Addresses" scalar the real page carries is rendered too, with the true row count. Mirrors Python web_gsm7252ps.render_mac_table.
func RenderXEPoE ¶
RenderXEPoE renders /poeInterfaceConfiguration.html for the GSM7252PS's own watts/iface/checkbox/reset-label/path. Mirrors Python web_gsm7252ps.render_poe's default-argument call shape.
func RenderXEPoEWith ¶
func RenderXEPoEWith(state *State, watts bool, errMsg string, iface func(int) string, checkbox, resetLabel, path string) string
RenderXEPoEWith is the full parametrized form the M4300/S3300 renderers share -- per-port PoE admin/status/power. watts selects the "Output Power" cell format to MATCH the emulated firmware: the gsm7252ps renders integer milliwatts (watts=false, e.g. "3500"); the M4300-16X renders watts with two decimals (watts=true, e.g. "4.60"). Both decode back to the same milliwatts via webui's PoE power parser.
Also the WRITE page (set_poe/cycle_poe/clear_poe_fault), so it carries the real scaffolding INCLUDING the hidden write-only "Port Reset" column v_1_2_20 that every row renders as "Reset" on real hardware, and the extra RESET button v_2_1_3 its APPLY-sibling page does not have. Mirrors Python web_gsm7252ps.render_poe.
func RenderXEPortStatistics ¶
RenderXEPortStatistics renders /portStatistics.html -- PACKET counters (this page has no octets). Mirrors Python web_gsm7252ps.render_port_statistics.
func RenderXEPorts ¶
RenderXEPorts renders /portsConfiguration.html -- per-port admin/link/ speed + ifindex, using the GSM7252PS's own iface/checkbox/path. Mirrors Python web_gsm7252ps.render_ports's default-argument call shape.
func RenderXEPortsWith ¶
func RenderXEPortsWith(state *State, errMsg string, iface func(int) string, checkbox, path string) string
RenderXEPortsWith is the full parametrized form RenderXEPorts and the M4300/S3300 renderers share -- this IS the write page as well as the read page (set_port_enabled), so it is rendered with the real XUI scaffolding: two forms, <TR p=...> rows each carrying their own gecb checkbox, the redirection block and the CANCEL/APPLY buttons. Mirrors Python web_gsm7252ps.render_ports.
func RenderXEPvids ¶
RenderXEPvids renders /portPvidConfiguration.html -- Configured + Current PVID columns. Mirrors Python web_gsm7252ps.render_pvids.
func RenderXESysinfo ¶
RenderXESysinfo renders /base/system/management/sysInfo.html -- mgmt IP, base MAC and the three status tables. Renders the model's HTTP sysInfo sensor set (state.SysinfoSensors()), which on this device is DIFFERENT from its SNMP set. Mirrors Python web_gsm7252ps.render_sysinfo.
func RenderXEVlans ¶
RenderXEVlans renders /vlanStatus.html -- VLANs with their egress port list. Mirrors Python web_gsm7252ps.render_vlans.
func RenderXUIServicePage ¶
RenderXUIServicePage renders one service's config page in the XUI labelled-scalar shape, mirroring Python render_service_xui. sim.CLIPort is deliberately never consulted here: it is CLI-only state, extending beyond Python's own ServiceSim -- see ServiceSim's doc comment.
func RenderXUISyslog ¶
RenderXUISyslog renders syslogConfiguration.html from state.Syslog, mirroring Python web_fastpath_xui.render_syslog. Counters (Messages Received/Relayed/Ignored) are rendered as the live pages do but are NOT part of model.SyslogConfig; they exist so the page the mock serves has the same field set as the real one. errMsg ("" = ok) renders the write refusal the way the firmware does -- HTTP 200 with err_flag=1 -- exactly like every other fastpathPage caller; see ApplyXUISyslogRows.
func RenderXUIUsers ¶
RenderXUIUsers renders userManagement.html from state.Users, mirroring Python web_fastpath_xui.render_users. Shared by both managed dialects (gsm7252ps and the M4300s): userManagement.html's row-grid coordinates are identical on both live-captured pages (webui.ParseXUIUsers's xuiUserNameCoord/xuiUserAccessModeCoord), so one renderer serves both, exactly as one parser reads both. A model whose State.Users is empty (m4300-16x/gsm7228ps -- unmeasured, see SeedM4300_16X/SeedGSM7228PS) renders a header-only page with zero data rows, which webui.ParseXUIUsers then honestly refuses ("no user rows on page") rather than this mock fabricating accounts it was never seeded with.
func UnauthenticatedResponse ¶
func UnauthenticatedResponse() string
UnauthenticatedResponse renders what the switch answers a "wcd" request with no valid session, mirroring Python web_gs728tpp.unauthenticated_ response (parity commit 64ac7c7).
CAPTURED from the live GS728TPP (10.2.5.10, firmware 6.0.1.30) by issuing a request with a stale sessionID cookie. Note what it is NOT: not a 302, not a 401, and not an empty body -- it is HTTP 200 carrying a normal <ResponseData> envelope whose ActionStatus says statusCode 4. That detail is the whole point of reproducing it: a mock that redirected instead (this one used to) would let a client's session-expiry handling look correct while missing the case real hardware actually produces -- webui.HTTPClient's own session-expiry detection (client.go's xmlAPISessionLost) keys off exactly this status code.
Types ¶
type CliFace ¶
type CliFace struct {
// contains filtered or unexported fields
}
CliFace is an in-process fastpath.Session serving a *State, mirroring Python VirtualCliFace. Construct with NewCliFace.
func NewCliFace ¶
func NewCliFace(state *State, spec *fastpath.CliModelSpec) *CliFace
NewCliFace constructs an in-process CLI session over state, dispatching show commands through spec's per-model command strings, mirroring Python VirtualCliFace.__init__.
func (*CliFace) Close ¶
Close implements fastpath.Session. A no-op, mirroring Python VirtualCliFace.close (dossier §3.10, "def close(self) -> None: pass"): there is no socket, no host key, nothing to drain or leak-check here.
func (*CliFace) InterfaceName ¶
InterfaceName returns the device interface name (e.g. "1/0/7") of the port currently selected via `interface <iface>`, and true -- only while Mode() == cliModeInterface; ("", false) otherwise, including the (unreachable in practice) case of a selected port no longer present in state.Ports.
Holds State's lock for the whole call (Go-only; see State.mu's own doc comment): unlike Mode() (f.modes is session-local, never touched by another goroutine), this reads f.state.Ports -- the SAME shared *State every other face's goroutine can mutate. Called from cli_socket.go's cliPrompt on the SSH/Telnet per-connection goroutine, AFTER CliFace.Run's own critical section has already ended (cliListenerLoop calls cliPrompt only once face.Run has fully returned) -- so this is never nested inside another State.mu acquisition; it is its own, independent, outermost critical section, safe to lock directly.
func (*CliFace) Mode ¶
Mode returns the current command-mode label: "exec" (the zero/top-level mode) or one of cliModeVlanDB/cliModeConfig/cliModeInterface.
func (*CliFace) Run ¶
Run implements fastpath.Session.
Holds State's lock for the whole call (Go-only; see State.mu's own doc comment): a *CliFace is constructed fresh per SSH/Telnet session (SSHFace.handleSession/TelnetFace.serveConn), but every session over the same VirtualSwitch -- CLI or otherwise -- shares the SAME *State, mutated concurrently from each session's own goroutine. f.run and everything it calls (configCommand, interfaceCommand, vlanDBCommand, the render* helpers, applyPoeAdmin/applyPoeReset) must NEVER lock again (this mutex is not reentrant); Run/RunSCPCopy/RunWriteMemory are their only callers (fastpath.Session's three write/command entry points), each locking independently since none of the three ever calls another.
func (*CliFace) RunSCPCopy ¶
RunSCPCopy implements fastpath.Session as an in-process stand-in for the interactive `copy scp://...` step (dossier §3.9): it directly parses `copy <src> <dest>`, records into ScpCertDeploySim, and always reports success -- there is no byte stream here to drive the real TOFU/ password/(y/n) handshake fastpath.ShellDriver.RunSCPCopy drives.
Holds State's lock for the whole call -- see Run's own doc comment for why (same reasoning, independent lock: RunSCPCopy never calls Run or vice versa).
func (*CliFace) RunWriteMemory ¶
RunWriteMemory implements fastpath.Session as an in-process stand-in for a command with a `(y/n)` confirm (dossier §3.9/§3.10 area, mirrors Python run_write_memory). "reload" and "write memory" are NOT interchangeable: a reload must never look like a config save. A real reload also tears the session down; this mock cannot restart itself, so it records the request (State.Reboots) and returns, which is what lets a test prove the right command was issued. prestuff is accepted for Session-interface parity but has no observable effect here -- there is no byte stream to pre-stuff a "y" answer into.
Holds State's lock for the whole call -- see Run's own doc comment for why (same reasoning, independent lock: RunWriteMemory never calls Run or vice versa).
type EndpointProvider ¶
type EndpointProvider interface {
// StartModel starts a virtual switch for modelKey and returns its
// endpoints. The switch this call started keeps running until ctx is
// done (see GoFakeProvider's doc comment for this Go implementation's
// exact cancellation contract) or the provider's CloseAll is called.
StartModel(ctx context.Context, modelKey string) (Endpoints, error)
}
EndpointProvider is the conformance-harness seam a cross-language test suite (slice 10) drives against: start a named model's virtual switch and get back the endpoints to connect a client to, without needing to import this package's concrete VirtualSwitch type at all.
type Endpoints ¶
type Endpoints struct {
Host string
SnmpPort int
NsdpPort int
Community string
HTTPPort int
HTTPPassword string
SSHPort int
TelnetPort int
}
Endpoints is the set of listening endpoints a started VirtualSwitch exposes, for a caller (e.g. a cross-language conformance-harness client, slice 10) that wants only connection details, not this package's concrete VirtualSwitch type. NsdpPort mirrors VirtualSwitch.NsdpPort; HTTPPort/HTTPPassword mirror VirtualSwitch.HTTPPort/httpPassword; SSHPort/TelnetPort mirror VirtualSwitch.SSHPort/TelnetPort (this slice) -- every port field is 0 when the model the provider started has no such backend (or, for a provider that only serves a subset of backends, e.g. a future Python fake with no CLI listener, when this provider simply never bound that face at all): a cross-language harness reads a 0 port as "this provider does not serve that backend" and skips triples needing it, exactly like it already does for SnmpPort/NsdpPort/HTTPPort.
type EntitySim ¶
EntitySim is one ENTITY-MIB entPhysicalTable component (index plus class/name/descr). Used only by models whose SNMP agent exposes fan/PSU inventory via the standard ENTITY-MIB instead of a Netgear vendor column (verified: GS728TPP). PhysClass is the entPhysicalClass int enum (6=powerSupply, 7=fan). No live value/status on the wire -- inventory only.
type GoFakeProvider ¶
type GoFakeProvider struct {
// contains filtered or unexported fields
}
GoFakeProvider is the Go EndpointProvider implementation backing this package's VirtualSwitch: each StartModel call starts one VirtualSwitch and tracks it so CloseAll can stop every switch this provider has ever started. Ownership is intentionally minimal for this slice: there is no per-endpoint stop handle in the EndpointProvider interface itself (a cross-language harness client has no Go object to hold one on), so a started switch's teardown path is exactly one of: its ctx being cancelled/timing out, or an explicit CloseAll -- watched on a dedicated per-switch goroutine that exits on whichever comes first (never leaked waiting on a ctx, e.g. context.Background(), that's never cancelled: see trackedSwitch.stopCh). The zero value is ready to use.
func (*GoFakeProvider) CloseAll ¶
func (p *GoFakeProvider) CloseAll() error
CloseAll stops every VirtualSwitch this provider has ever started via StartModel, regardless of whether its ctx was ever cancelled, and forgets them (a later CloseAll call is a no-op). Closes each tracked switch's stopCh first so its StartModel watcher goroutine exits promptly too, rather than leaking until (or forever, for an uncancelled context.Background()) its ctx is done. Safe to call more than once: VirtualSwitch.Stop is itself idempotent.
func (*GoFakeProvider) StartModel ¶
StartModel implements EndpointProvider: builds and starts a VirtualSwitch for modelKey (propagating NewVirtualSwitch/Start's errors, e.g. model.ErrUnknownModel or model.ErrUnsupportedCapability, unwrapped), then spawns a goroutine that stops it once EITHER ctx is done OR CloseAll runs -- whichever happens first -- so a caller that only ever calls CloseAll (never cancelling ctx, e.g. context.Background()) doesn't leak that goroutine forever.
type HTTPFace ¶
type HTTPFace struct {
// contains filtered or unexported fields
}
HTTPFace is a net/http.Server web-UI face serving a *State, mirroring Python VirtualHttpFace. Construct with NewHTTPFace; call Start to bind and begin serving, Stop to tear down (idempotent; safe to call before Start or more than once).
func NewHTTPFace ¶
func NewHTTPFace(state *State, spec *webui.HTTPModelSpec, password, host string) *HTTPFace
NewHTTPFace builds an HTTPFace serving state per spec, accepting only a login whose credential matches password, bound to host (typically "127.0.0.1") once Start is called.
func (*HTTPFace) SetPort ¶
SetPort pins the TCP port Start binds to, mirroring the Python reference's VirtualSwitch(http_port=...) constructor argument (server.py's own "self.http_port"). The default, 0, asks the OS for an ephemeral port, same as before this method existed. Call before Start; a call after Start has no effect until the next Start following a Stop.
func (*HTTPFace) SimulateGoAheadSessionExpiry ¶
SimulateGoAheadSessionExpiry arms this face to answer the next `times` authenticated GoAhead wcd requests (read or write) with UnauthenticatedResponse -- HTTP 200 + statusCode 4 -- exactly as if the switch's own session had died server-side mid-run, then resumes normal service once the count is exhausted. times=1 models a session that comes back the moment the caller re-authenticates; times=2 models one that still refuses the caller even after re-authenticating (covering webui.HTTPClient.GetPage's one retry attempt, which makes exactly two wcd requests when the first is expired).
Test-only: real hardware's session dies on its own; a same-process net/http test has no equivalent of Python's test reaching into the client's private cookie jar (`client._client.cookies.set("sessionID", "stale")`, tests/virtual/test_virtual_http_face.py's test_expired_session_recovers_on_a_read_but_never_resends_a_write), so this simulates the same OBSERVABLE effect from the server side instead.
func (*HTTPFace) Start ¶
Start binds f.host:f.port (an ephemeral port when f.port is 0, the default) and begins serving on a background goroutine, returning the bound port. Calling Start twice without an intervening Stop is an error.
type LldpSim ¶
type LldpSim struct {
TimeMark int
LocalPort int
RemIdx int
Chassis string
PortID string
PortDesc string
SysName string
}
LldpSim is one lldpRemTable neighbour row group.
type MibView ¶
type MibView struct {
// contains filtered or unexported fields
}
MibView is a sorted view of a State's OID map supporting GET and GETNEXT. Construct with NewMibView; call Rebuild after any write that bypassed ApplyWrite/ApplyWriteUncommitted (those two already rebuild appropriately themselves).
func NewMibView ¶
NewMibView builds a MibView over state, loading its initial sorted snapshot from state.OIDMap().
func (*MibView) ApplyWrite ¶
ApplyWrite mutates the underlying state via a single committed write, then rebuilds the sorted view so subsequent reads reflect it.
func (*MibView) ApplyWriteUncommitted ¶
ApplyWriteUncommitted mutates the underlying state WITHOUT rebuilding the sorted view. For an atomic multi-varbind SET (snmpface.go's handleSet): the comparatively expensive Rebuild is deferred until the whole PDU has committed successfully, once, rather than once per varbind. Callers MUST call Rebuild themselves once every varbind in the PDU has applied without error.
func (*MibView) Get ¶
Get performs an exact-match lookup: bisect_left plus an equality check. ok=false means "no instance at this exact OID within an IMPLEMENTED subtree" (-> the caller's face maps that to NoSuchInstance); callers MUST check IsImplemented(oid) FIRST -- see the package doc's three-way exception rule (D-VIRT §2.9).
func (*MibView) GetNext ¶
GetNext performs GETNEXT lookup: bisect_right (strictly greater -- GETNEXT never returns the same OID it was asked about). ok=false means "past the end of the view" (-> the caller's face maps that to EndOfMibView); same IsImplemented-first caveat as Get.
func (*MibView) IsImplemented ¶
IsImplemented reports false if oid falls under a subtree root this model's SNMP agent has no registration for at all (e.g. the RFC3621 PoE MIB on a non-PoE model) -- see State.IsOIDImplemented. A face checks this BEFORE calling Get/GetNext: a real agent answers noSuchObject for such a request rather than this view's flat bisect silently finding whatever unrelated OID happens to sort next.
func (*MibView) IsWritableOID ¶
IsWritableOID is a passthrough to State.IsWritableOID.
func (*MibView) LockState ¶
func (v *MibView) LockState()
LockState is a passthrough to State.LockState: a face's SET handler must hold this across a whole atomic write (snapshot, per-varbind apply, rebuild), not just the individual State mutations inside it, so no other goroutine (another face, or a test reading State directly) ever observes a partial write or races with one. See State.LockState's own doc comment for the full contract -- this is a Go-only concern with no Python equivalent.
func (*MibView) Rebuild ¶
func (v *MibView) Rebuild()
Rebuild recomputes the sorted view from the current State.OIDMap(). Called by NewMibView, by ApplyWrite (every write), and once by a SET face's caller after an atomic multi-varbind PDU commits fully (see ApplyWriteUncommitted). The sort key is the numeric []int OID compared with slices.Compare -- NEVER a lexicographic string compare of the OID text, since e.g. ".8.2" must sort before ".8.10".
func (*MibView) RestoreState ¶
RestoreState restores the underlying state in place from a prior SnapshotState result, discarding any writes applied since. The sorted view itself needs no rebuild after a restore: if the caller took the snapshot before making any changes and only ever reaches this on a failed atomic SET, the state (and thus the view) is back to exactly what it was before that SET began.
func (*MibView) SnapshotState ¶
SnapshotState snapshots the underlying state, for atomic multi-varbind SET rollback. See State.Snapshot/RestoreState.
func (*MibView) UnlockState ¶
func (v *MibView) UnlockState()
UnlockState is a passthrough to State.UnlockState, releasing the lock LockState acquired.
type NsdpFace ¶
type NsdpFace struct {
// contains filtered or unexported fields
}
NsdpFace is a UDP NSDP command-responder agent serving a State. Runs its receive loop on a dedicated goroutine, bound to an ephemeral UDP port on host. Construct with NewNsdpFace; call Start to bind and begin serving, Stop to tear down (idempotent; safe to call before Start or more than once).
func NewNsdpFace ¶
NewNsdpFace builds an NsdpFace serving state, bound to host (typically "127.0.0.1") once Start is called. The write-auth password is read live from state.NsdpPassword at each WRITE_REQUEST (not captured here at construction), mirroring Python's _write_response reading self._state.nsdp_password fresh on every call -- a test that mutates state mid-test sees the new password take effect immediately.
func (*NsdpFace) SetPort ¶
SetPort pins the UDP port Start binds to, mirroring the Python reference's VirtualSwitch(port=...) constructor argument (server.py's own "self.port" -- see D-VIRT §5's shared-port-field note; SnmpFace.SetPort carries the same doc comment). The default, 0, asks the OS for an ephemeral port, same as before this method existed. Call before Start; a call after Start has no effect until the next Start following a Stop.
type OIDEntry ¶
OIDEntry is one projected OID's SNMP type token plus its wire value. Value is byte-transparent: a Go string is already a raw byte sequence (unlike Python's Unicode str, which needed an explicit latin-1 encode/decode step to stay wire-exact), so every OCTETSTR/IPADDR/OID value here is exactly string(rawBytes) with no further transcoding.
type Option ¶
type Option func(*VirtualSwitch)
Option configures a VirtualSwitch at construction time.
func WithCLIPassword ¶
WithCLIPassword overrides the password the bound SSH/Telnet CLI faces require (default "password", matching WithHTTPPassword's own default).
func WithCLIUsername ¶
WithCLIUsername overrides the username the bound SSH/Telnet CLI faces require (default "admin", mirroring the dossier's own note that "the default CLI username is hardcoded 'admin'" -- transport dossier §7.6).
func WithCommunity ¶
WithCommunity overrides the SNMP community string every bound face requires (default "public").
func WithHTTPPassword ¶
WithHTTPPassword overrides the HTTP admin password the bound HTTP face requires (default "password", mirroring Python VirtualSwitch's own http_password="password" constructor default).
func WithHTTPPort ¶
WithHTTPPort pins the TCP port Start binds its HTTP face to (default 0, an ephemeral port). Mirrors the Python reference's VirtualSwitch(http_port=...) constructor argument.
func WithHost ¶
WithHost overrides the loopback address every bound face listens on (default "127.0.0.1").
func WithPort ¶
WithPort pins the UDP port Start binds its SNMP-or-NSDP face to (default 0, an ephemeral port). Mirrors the Python reference's VirtualSwitch(port=...) constructor argument. Applies to whichever of SnmpPort/NsdpPort the model actually binds -- no registered model has both backends, so, like the Python reference's single shared self.port, there is never an ambiguity about which one this pins.
type PoeSim ¶
type PoeSim struct {
Admin bool
Detect int
PowerMw int
// CliStatusLagReads is how many more CLI `show poe port info all` reads
// still report the pre-enable "Disabled" status after PoE was
// administratively re-enabled, ported from Python PoeSim's
// cli_status_lag_reads: int = 0 (state.py:253).
//
// MEASURED ON HARDWARE (M4300-16X, 10.1.5.20, FASTPATH 12.0.19.15,
// 2026-07-30): right after `poe` re-enabled port 1/0/1 the table still
// said "Disabled"; the same port read "Searching" moments later. That
// column is a DETECTION state, and it lags the admin write -- which
// made a single immediate read-back report a perfectly good SetPoE as
// a verification failure. The mock reproduces the lag (one stale read)
// so fastpath.Writer.SetPoE's polling is actually exercised instead of
// passing by accident.
//
// Set by State.ApplyPoeAdmin on an off->on transition REGARDLESS of
// which backend drove the write -- the SNMP SET path (ApplyWrite's
// pethPsePortAdminEnable branch) and the CLI `poe` command both funnel
// through that one shared method (mirroring pin state.py's own
// apply_poe_admin, state.py:1135-1157), so a port re-enabled over SNMP
// shows the SAME CLI status lag on the next CLI read as one re-enabled
// over the CLI directly. Only CONSUMED (decremented) by cliPoeStatusText
// in cliface_render.go, since the lag is specifically a `show poe port
// info all` rendering artifact -- SNMP reads of PETH-PSE-MIB
// (pethPsePortDetectionStatus) are NOT gated by this counter and see
// Detect's new value immediately, matching the pin (which has no
// SNMP-side equivalent of cli_status_lag_reads consumption either).
CliStatusLagReads int
}
PoeSim is one PoE port: RFC 3621 admin/detect state plus vendor delivered power. Detect is the raw RFC3621 pethPsePortDetectionStatus wire int (1=disabled/unused, 2=searching, 3=deliveringPower, ...), not the higher-level model.PoEDetect enum.
type PortSim ¶
type PortSim struct {
Name string
Admin bool
Link bool
Speed int
// IfType (IF-MIB): 6=ethernetCsmacd (a physical port -- the default via
// NewPortSim). Real hardware also exposes non-physical rows in the same
// ifTable -- LAGs (161=ieee8023adLag), the CPU interface (1=other),
// VLAN routing interfaces (135=l2vlan) -- which the read path filters
// OUT. A seed that adds those interfaces sets IfType directly so the
// mock's SNMP reads drop them exactly as real hardware does.
IfType int
RxOctets *uint64
TxOctets *uint64
RxUcast *uint64
TxUcast *uint64
RxErrors *uint64
TxErrors *uint64
// SwitchportMode is the FASTPATH CLI-only "switchport mode
// access|general|trunk" running-config value (slice-07, ported from
// Python PortSim.switchport_mode: str = "general", state.py:143), which
// gates whether a per-port `vlan participation`/`vlan tagging`/`vlan
// pvid` CLI write actually takes effect (see virtual/cliface.go's
// general() gate) -- live-proven on an M4300-24X: those commands are
// ACCEPTED but INERT while the port is in "switchport mode access".
// NOT part of any SNMP/NSDP/HTTP projection: no captured MIB/TLV/web
// page exposes it.
//
// Go has no per-field struct-literal defaults, unlike Python's
// dataclass default, and every seed in this package builds its (very
// large) port tables via bare struct literals rather than NewPortSim
// (see seed.go's own doc comment), so this field's Go zero value ""
// deliberately stands in for "not yet explicitly configured over CLI"
// on every existing seed, rather than requiring every port literal in
// every seed to spell out `SwitchportMode: "general"`. cliface.go's
// general() gate treats "" the same as an explicit "general" UNLESS
// the model/port has a measured VlanMembershipLockedPorts entry
// documenting it as access/trunk instead (e.g. every M4300-24X port,
// live-proven -- see that field's own seed.go doc comment): the SAME
// underlying live finding, observed over the HTTP VLAN-membership page
// there and over the CLI here. Once this face executes an explicit
// "switchport mode <mode>" command, this field holds that literal
// mode string ("access"/"general"/"trunk") and takes precedence over
// both defaults.
SwitchportMode string
// Description is ifAlias. nil means this port's ifAlias column instance
// is entirely absent (never configured) -- never a fabricated "".
Description *string
// FlowControl is IEEE 802.3x flow control, as reported in the FASTPATH
// CLI's "Flow Mode" column, the GoAhead web UI's flowControlOperType/
// flowControlAdminType, AND (as of the NSDP flow-control slice) NSDP
// PORT_STATUS byte 2 -- the SAME field Python's PortSim.flow_control
// drives for all three (pin virtual/state.py:164-170: "IEEE 802.3x flow
// control, as reported in NSDP PORT_STATUS byte 2 and in the Plus web
// UI's 'Flow Control' column").
//
// Zero value (false) matches every FASTPATH/GoAhead model this field
// drove before that slice: MEASURED False on all 28 GS728TPP ports
// (2026-08-03, both the SNMP dot3PauseOperMode walk and the GoAhead wcd
// page agreed) and False in every captured `show port all` Flow Mode
// column (gsm7252ps/gsm7228ps/m4300-16x/m4300-24x).
//
// UNLIKE those models, Python's dataclass default for this field is
// `True` (pin state.py:170), not False -- the factory default the two
// GS110EMX units 10.1.5.25/.26 are still on. Go has no per-field
// struct-literal default, so any Plus-family (NSDP) seed that wants that
// same True default must set FlowControl: true explicitly per port
// (e.g. SeedGS110EMX) rather than relying on the Go zero value, which
// would silently disagree with the pin's implicit default for that
// family. FASTPATH/GoAhead-only seeds are unaffected: their measured
// value already IS false, so leaving this field unset still agrees with
// the pin there.
FlowControl bool
// ServesEtherlike reports whether this model's SNMP agent publishes the
// EtherLike-MIB dot3StatsDuplexStatus/dot3Pause{Admin,Oper}Mode columns
// for this interface. Per-model, MEASURED 2026-08-03: the GS728TPP
// serves them for all 28 physical ports; the GSM7252PS's dot3StatsTable
// stops at column 16 (no 19) and its dot3PauseTable serves only the
// counters, not AdminMode/OperMode. Default false so no model's mock
// gains an OID its hardware was never observed to answer -- a seed
// opts in. Where false, SNMP GetPorts reports FullDuplex/FlowControl as
// nil, the honest reading of an absent column.
ServesEtherlike bool
// PhysicalMode is the FASTPATH CLI's "Physical Mode" column raw text --
// the port's CONFIGURED speed/duplex, as opposed to Speed/Link above
// (the NEGOTIATED rate the "Physical Status" column reports). Kept as
// raw device text, like SwitchportMode, so the mock does not re-derive
// the cell with the same helper the parser uses. Empty string (the Go
// zero value) is treated as "Auto" by the CLI renderer -- "Auto" is
// what every real port on every switch captured here reports, so no
// seed needs to set this explicitly today.
PhysicalMode string
// AutonegAdmin/SpeedAdmin/DuplexAdminMode are the GoAhead web UI's own
// three-field encoding of the SAME configured speed/duplex PhysicalMode
// carries for the CLI -- kept as separate raw fields, for the same
// "don't re-derive what the parser decodes" reason. Wire codes: 1 =
// negotiating, 2 = forced (autoneg); 2 = half, 3 = full (duplex). Empty
// string defaults to "1"/"1000"/"3" respectively -- what the live
// GS728TPP (10.2.5.10, firmware 6.0.1.30) returned for EVERY port
// (2026-08-03): autoneg 1 with speedAdmin 1000 sitting beside it
// (meaningful only while autoneg is 2). No FASTPATH model serves these
// fields and no GoAhead model serves PhysicalMode, so the two never
// disagree on one device.
AutonegAdmin string
SpeedAdmin string
DuplexAdminMode string
}
PortSim is one switch port's link/admin/speed/name plus optional HC counters. Counters are *uint64: nil means "this port does not expose this counter" and must round-trip to an absent row in OIDMap (never a fabricated zero).
type SSHFace ¶
type SSHFace struct {
// contains filtered or unexported fields
}
SSHFace is a real loopback SSH server serving the FASTPATH shell over a *State, mirroring HTTPFace's shape (bind-on-Start/deterministic- idempotent-Stop) but with gliderlabs/ssh's *Server standing in for net/http.Server. Construct with NewSSHFace; call Start to bind and begin serving, Stop to tear down (idempotent; safe to call before Start or more than once).
func NewSSHFace ¶
func NewSSHFace(state *State, spec *fastpath.CliModelSpec, username, password, host string) *SSHFace
NewSSHFace builds an SSHFace serving state per spec (the model's FASTPATH CLI command spec, fastpath.CLISpec), accepting only a login whose username/password match username/password, bound to host (typically "127.0.0.1") once Start is called. Each accepted connection dispatches through its OWN fresh *CliFace (independent mode stack) over the SAME state (task brief: "each connection gets its own session/mode-stack but shares the ONE VirtualSwitchState") -- mirroring VirtualSwitch.CliSession's own in-process equivalent exactly.
func (*SSHFace) Start ¶
Start binds an ephemeral TCP port on f.host and begins serving on a background goroutine, returning the bound port. Calling Start twice without an intervening Stop is an error. Generates a fresh, ephemeral RSA host key on every Start call (dossier §7.7: "ephemeral host key generation per fake instance ... any key satisfies parity" since the real Python client, mirroring paramiko.Transport directly, never validates the host key at all).
func (*SSHFace) Stop ¶
Stop tears the server down deterministically (transport dossier §5's leak-free contract): srv.Close() force-closes every SSH connection gliderlabs itself has FINISHED handshaking (unlike srv.Shutdown, which only waits for existing connections to disconnect on their own -- an indefinite hang if a caller forgot to close its client first). That alone is NOT sufficient for a bounded Stop, though -- two gaps, both closed below:
- srv.Close()'s own force-close only reaches listeners gliderlabs has itself registered via its internal trackListener, which Start's background `go srv.Serve(ln)` goroutine calls asynchronously, with NO happens-before relationship to Stop. If Stop (and its srv.Close()) runs before that goroutine reaches trackListener, srv.Close() closes ZERO listeners -- a silent no-op -- and the Serve goroutine's own l.Accept() call, whenever it does start, blocks forever (nothing will ever close ln again), hanging f.wg.Wait() below on the Serve goroutine's own f.wg.Done() that never comes. Fix: close the SAME *net.Listener object (ln, captured directly by Start, independent of gliderlabs' own bookkeeping) ourselves too -- this unblocks l.Accept() unconditionally, whether or not trackListener ever ran.
- Symmetrically, gliderlabs' own srv.conns (what srv.Close() force- closes) is only populated AFTER a connection's SSH handshake completes (server.go's HandleConn calls srv.trackConn only once gossh.NewServerConn returns) -- a connection accepted moments before Stop runs, still mid-handshake when srv.Close() takes its one-time pass over srv.conns, is invisible to it and never force-closed. If that connection's handshake later succeeds, its handleSession invocation (tracked on f.wg, see that method's own doc comment) can block forever reading a command nobody will ever send, hanging f.wg.Wait() the same way. Fix: trackConn (ConnCallback, wired in Start) records every accepted raw connection in f.conns the moment gliderlabs hands it to us -- BEFORE any handshake is attempted -- so Stop can force-close it directly too, independent of whether gliderlabs' own handshake-gated bookkeeping ever caught up.
f.wg.Wait() then blocks until the Serve goroutine AND every handleSession invocation have actually returned, not merely been asked to -- now unconditionally bounded by the two direct closes above, not merely by however much of gliderlabs' own internal state happened to be populated when srv.Close() ran. Idempotent: a Stop before Start, or a second Stop, is a no-op.
type ScpCertDeploySim ¶
type ScpCertDeploySim struct {
Commands []string
Copies []ScpCopy
HTTPSDisabled bool
HTTPSEnabled bool
Saved bool
}
ScpCertDeploySim records a FASTPATH "copy scp://" SSL-cert deploy the mock CLI face received. Purely a record of the EXEC sequence the library issued -- not part of any SNMP/NSDP/HTTP projection; CLI/HTTP-face concern only, carried on State for completeness (see State.ScpCertDeploy).
type ScpCopy ¶
ScpCopy is one (source_url, dest) pair of an SCP cert-deploy copy command, part of ScpCertDeploySim.
type SensorSim ¶
SensorSim is one box sensor reading (fan RPM / PSU watts / temperature). Raw is the literal wire text: either a decimal integer string or Netgear's "Not Supported" placeholder for an unpopulated slot.
type ServiceSim ¶
ServiceSim is one management service's admin state, as its own config page / CLI show command reports it, mirroring Python's ServiceSim dataclass (state.py:233-245) plus one field Python's fake does not yet have.
Port is nil where the HTTP config page carries NO port field -- which is a real per-page difference, not a gap in the mock: the m4300 SSH page publishes v_1_10_1="22" while the gsm7252ps SSH page has no such coordinate at all (measured 2026-08-03). Seeding 22 there would make the fake claim a field the device does not print.
CLIPort extends beyond the pinned Python source, for the same reason UserSim.CLIAccessMode does: Python's virtual CLI face has no `show ip http`/`show telnetcon`/`show ip ssh` renderer at this pin, only HTTP-page ServiceSim values. The port VALUES here are still measured, via Python commit 2c7ddff ("feat(cli): read which management services are enabled")'s live-verified table --
m4300-24x http=on:80 https=on:443 telnet=on:23 ssh=on:22 gsm7252ps http=on:None https=on:443 telnet=off ssh=on:None
-- prose in a commit message, not a fixture file; flagged per principle 5 the same way CLIAccessMode is. Enabled state is NOT duplicated per face: every measured case has the CLI and HTTP page agreeing on admin state ("HTTP<->CLI agree exactly" / "agreeing on every state"), so ServiceSim carries one Enabled field for both.
type SnmpFace ¶
type SnmpFace struct {
// contains filtered or unexported fields
}
SnmpFace is an SNMPv2c command-responder agent serving a MibView. Runs its receive loop on a dedicated goroutine, bound to an ephemeral UDP port on host (or a caller-pinned one, see SetPort). Construct with NewSnmpFace; call Start to bind and begin serving, Stop to tear down (idempotent; safe to call before Start or more than once).
func NewSnmpFace ¶
NewSnmpFace builds an SnmpFace serving view, accepting only requests whose community string matches community, bound to host (typically "127.0.0.1") once Start is called.
func (*SnmpFace) SetPort ¶
SetPort pins the UDP port Start binds to, mirroring the Python reference's VirtualSwitch(port=...) constructor argument (server.py's own "self.port" -- see D-VIRT §5's shared-port-field note). The default, 0, asks the OS for an ephemeral port, same as before this method existed. Call before Start; a call after Start has no effect until the next Start following a Stop.
type State ¶
type State struct {
ModelKey string
Ports map[int]*PortSim
Vlans map[int]*VlanSim
Pvids map[int]int
Poe map[int]*PoeSim
Sensors []SensorSim
HTTPSensors []SensorSim
EntityComponents []EntitySim
Macs []MacSim
BridgePorts map[int]int
Lldp []LldpSim
Mgmt MgmtSim
// Users/Services back GetUsers/GetServices, mirroring Python's
// VirtualSwitchState.users: list[UserSim] = field(default_factory=list)
// / .services: dict[str, ServiceSim] = field(default_factory=dict)
// (state.py:525/529). Populated only by SeedGSM7252PS/SeedM4300_24X --
// see those functions' own doc comments for exactly why not the other
// managed-model seeds. Services is keyed "http"/"https"/"ssh"/"telnet".
Users []UserSim
Services map[string]ServiceSim
// Syslog is remote-logging state, projected under <vendor base>.14 only
// for a model with a vendor OID subtree (see OIDMap) -- which is what
// makes gs728tpp (no vendor OIDs) correctly unable to answer GetSyslog.
// Mirrors Python's VirtualSwitchState.syslog: SyslogSim =
// field(default_factory=SyslogSim) (state.py:521); NewState sets it to
// that dataclass's own default (AdminMode 2, LocalPort 514, no
// collectors), not Go's struct zero value.
Syslog SyslogSim
ModelName string
Serial string
Firmware string
Hostname string
NsdpPassword string
NsdpMac [6]byte
// NsdpAuthV2, when true, makes a fake serving this state require NSDP v2
// salted write auth (AUTH_V2_ENCPASS reads 0x10; AUTH_V2_SALT is a rotating
// readable challenge; AUTH_V2_PASSWORD is a write-only token) instead of v1
// XOR -- LIVE-MEASURED on a GS110EMX (fw 1.0.2.8). The rotating salt itself
// is transient per-connection challenge state, so it lives on NsdpFace, not
// here (Snapshot copies logical switch state, not a serving session).
NsdpAuthV2 bool
SysDescr string
SysObjectID string
Dot1dBaseMacASCII bool
// VLANPortListWidth is the model's REAL, live-measured wire byte-width
// of dot1qVlanStaticEgressPorts/UntaggedPorts (D-REC Topic B), nil when
// unmeasured. A Netgear switch's Q-BRIDGE PortList covers LAG and CPU
// pseudo-ports too, so its width is a hardware-fixed constant wider
// than max(8, ceil(port_count/8)) -- e.g. GSM7252PS = 79 bytes,
// GSM7228PS = 45, both M4300s = 131 (see the four managed seeds).
// OIDMap prefers this field over snmp.VlanBitmapWidth(port_count) so
// the mock is an INDEPENDENT source of truth for the wire width, not a
// re-derivation of the writer's own formula -- the whole point being
// that a mock sharing the writer's formula can never catch the writer
// re-encoding a bitmap at the wrong width (the historical bug this
// field exists to trap). nil (Plus-class models, gs728tpp) falls back
// to the formula. Ported from Python's State.vlan_portlist_width.
VLANPortListWidth *int
// NSDP-extra fields (D-VIRT §1.3), nil-able/unseeded semantics
// mirroring the Python dataclass exactly. Projected READ-ONLY: NsdpTlvs
// (below) emits QOS_ENGINE/PORT_MIRRORING/IGMP_SNOOPING/
// BROADCAST_FILTERING/LOOP_DETECTION TLVs from these fields when a
// caller's tag set asks for them and the field is non-nil, but
// ApplyNsdpWrite never mutates any of the seven -- faithful to the
// pinned Python reference, whose own to_tlvs (state.py:1552-1598)
// projects the same five tags and whose apply_nsdp_write likewise never
// writes them.
NsdpQosEngine *int
NsdpPortMirroringDest *int
NsdpPortMirroringSources map[int]bool
NsdpIgmpSnoopingEnabled *bool
NsdpIgmpSnoopingVlan *int
NsdpBroadcastFiltering *bool
NsdpLoopDetection *bool
// HTTP/CLI-only fields -- not part of any SNMP/NSDP projection, carried
// here for completeness only (see ScpCertDeploySim doc comment above).
UploadedCert *string
ScpCertDeploy *ScpCertDeploySim
// VlanMembershipPage/VlanMembershipLockedPorts are the FASTPATH "VLAN
// Membership" page's state (D-HTTP-F §5.2) -- see VlanMembershipPageSim's
// doc comment. VlanMembershipLockedPorts is the PER-PORT set of ports
// whose switchport mode (access/trunk) makes this model's firmware
// refuse an explicit VLAN-membership apply over HTTP, returning HTTP 200
// with err_flag=1 rather than applying -- empty (the default) means
// every port on this model accepts the apply. Only m4300-24x's seed
// populates this (every port on that live-captured unit is
// access/trunk); m4300-16x's ports 1-8 have no switchport mode line at
// all, so its seed leaves this empty, letting the apply succeed there --
// a deliberate live counter-example pair, not an oversight.
VlanMembershipPage *VlanMembershipPageSim
VlanMembershipLockedPorts map[int]bool
// FASTPATH vendor switchport state, for a model whose registry entry
// says SnmpVlanWrite == model.SNMPVlanWriteFastpathSwitchport (the
// M4300s), mirroring Python VirtualSwitchState's switchport_mode/
// switchport_access_vlan/switchport_native_vlan/switchport_allowed_vlans/
// switchport_general_untagged/switchport_general_tagged fields
// (state.py:624-643, pin b26eb1f). Per-port mode
// (access=1/trunk=2/general=3), access VLAN, native (trunk untagged)
// VLAN, and the writable allowed-VLAN bitmap. Empty maps mean
// "unseeded": switchportDefaults fills a port in on first use so the
// mock answers these columns for every port, exactly like the real
// agent (which has a row per interface). Defaults are the LIVE-measured
// factory shape of an untouched M4300 port: access VLAN 1, native
// VLAN 1, all 4093 VLANs allowed.
SwitchportMode map[int]int
SwitchportAccessVlan map[int]int
SwitchportNativeVlan map[int]int
SwitchportAllowedVlans map[int][]byte
// SwitchportGeneralUntagged/SwitchportGeneralTagged are the GENERAL-mode
// per-VLAN participation lists (columns 7 and 8). These are INDEPENDENT
// stored config, NOT a mirror of effective membership: measured live on
// m4300-24x port 1/0/15, which is access-mode on VLAN 10 (so really
// untagged in 10) while column 7 still read VLAN 1 -- the general-mode
// config it would fall back to. They are only in force while
// mode == general(3), and a SET of either answers notWritable on real
// hardware.
SwitchportGeneralUntagged map[int]map[int]bool
SwitchportGeneralTagged map[int]map[int]bool
// PDUEgressWrites is TRANSIENT (per-SET-PDU, not device state): VLAN ids
// whose egress PortList was written by the PDU currently being applied.
// Only used by a model with SnmpVlanSplitMembershipWrites, to reproduce
// the S3300's ordering quirk: its egress write auto-untags the port, and
// that side effect beats an untagged varbind carried in the SAME PDU.
// Reset by Snapshot, which SnmpFace calls exactly once per PDU. Mirrors
// Python's pdu_egress_writes: set[int] (state.py:644-650).
PDUEgressWrites map[int]bool
// Reboots is the number of reboots requested through a protocol face
// (slice-07: the FASTPATH CLI's "reload", virtual/cliface.go's
// RunWriteMemory), ported from Python's VirtualSwitchState.reboots: int
// = 0 (state.py:448). A reload cannot actually restart this mock, so
// this counter is the only observable record that the request was
// issued -- not part of any SNMP/NSDP/HTTP projection.
Reboots int
// contains filtered or unexported fields
}
State is the one authoritative in-memory virtual-switch device state. A mutable holder (ApplyWrite mutates it to simulate an SNMP SET); pure data plus the OIDMap SNMP projection, no network here.
func BuildState ¶
BuildState returns a seeded State for modelKey when this slice has a hand-authored seed for it (the five SNMP-capable models: gsm7252ps, gsm7228ps, m4300-24x, m4300-16x, gs728tpp; plus, as of slice 05, the three NSDP/HTTP-only Plus models: gs110emx, gs305ep, gs105pe), or a blank-but-valid State (NewState's defaults) for every other registered model key.
An unrecognized modelKey also gets a blank state: model-key validation is the caller's job (model.GetModel), mirroring the Python reference's _build_state, which likewise never validates the key itself.
func NewState ¶
NewState builds a blank-but-valid State for modelKey, with the same defaults as the Python dataclass: NsdpPassword "password", NsdpMac 28:c6:8e:00:00:01, and Mgmt 0.0.0.0/dhcp (an unconfigured static-IP-less device). Every map/slice field starts non-nil and empty.
func SeedGS105PE ¶
func SeedGS105PE() *State
SeedGS105PE builds a GS105PE (5-port Plus, NSDP+HTTP) State transcribed field-for-field from the pinned Python seed_gs105pe (D-NSDP §7.3), whose own docstring cites a REAL live capture (host 10.1.5.30 / poe-micro3, 2026-07-21): ports 3 (100M) and 5 (1G) up, the rest down; VLANs 1/41/90 with their real member/untagged sets; real PVIDs; DHCP mgmt-IP (address still the captured 10.1.5.30); and the QoS/mirroring/IGMP engine tags.
Port mirroring is OFF on this unit (dest 0, no sources) -- the exact 3-byte PORT_MIRRORING TLV shape (dest byte + a narrow, model-sized source bitmap) that historically exposed a fixed-width parser bug in the pinned Python reference (see nsdp.ParsePortMirroring's own doc comment); kept here as a regression fixture for that same class of bug. No PoE (registry: PoEPortCount 0 -- "PoE pass-through" only, not PSE), no box sensors, no MAC/FDB over ANY interface (a confirmed firmware limitation), no LLDP.
func SeedGS110EMX ¶
func SeedGS110EMX() *State
SeedGS110EMX builds a GS110EMX (10-port Plus, NSDP+HTTP) State transcribed field-for-field from the pinned Python seed_gs110emx (D-NSDP §7.3), whose own docstring cites REAL captures of this exact model's own web UI (host 10.1.5.25: tests/fixtures/http/gs110emx_{sysinfo, port_settings,interface_stats,vlanmembership,pvid}.html at the Python pin): ports 6/8/9/10 up at 100M/1G/10G/10G with port 8 described "rumpus", the rest down; static 10.1.5.25/24 via 10.1.5.1; MAC bc:a5:11:b8:ec:f1. VLAN 1's membership (ports 1-8 untagged, 9-10 tagged) and every port's PVID (all 1) are likewise transcribed from that capture.
STILL ILLUSTRATIVE (no capture exists, and this doc comment says so rather than implying otherwise): VLAN 90's member/untagged sets -- only VLAN 1's membership page was ever captured, and VLAN 90 is merely one of the 12 VLAN IDs the real Cf8021q capture lists -- and the QoS/mirroring/IGMP/broadcast/loop-detection tag values below, which are test fixtures chosen so a caller decoding this seed's NSDP tags has something non-vacuous on every one of them, NOT observed hardware values. No PoE (registry: PoEPortCount 0), no box sensors/MAC-FDB/LLDP (the Plus family exposes none of these over any face).
func SeedGS305EP ¶
func SeedGS305EP() *State
SeedGS305EP builds an ILLUSTRATIVE GS305EP (5-port, PoE ports 1-4) State, transcribed field-for-field from the pinned Python seed_gs305ep (D-NSDP §7.3). HAND-INVENTED: no capture of any kind exists for gs305ep -- the port speeds, the 12800 mW PoE reading, VLAN 90 and the PVIDs are all structural test data, NOT observed values (same convention as SeedGSM7228PS, which says so explicitly). Only the shape is grounded: the Plus family genuinely has no MAC/FDB, no box sensors and no LLDP over its web UI.
GENUINE GAP, ported deliberately, not filled in: the pinned Python constructor call passes no model_name/serial/firmware/hostname/nsdp_mac/ nsdp_password/QoS/mirroring/IGMP/broadcast/loop-detection kwargs at all, so every one of those -- and Mgmt -- falls through to the VirtualSwitchState dataclass default (empty identity strings, the default NsdpMac/NsdpPassword, every NSDP-extra field nil/unseeded, Mgmt "0.0.0.0"/dhcp). This function therefore leaves every one of those fields at NewState's own matching defaults rather than inventing plausible-looking values gs305ep never actually had in the pinned reference -- doing so would silently diverge from a future Go<->Python cross-fake-equivalence test (roadmap slice 10). See D-NSDP §7.3/§10.6#7.
func SeedGS728TPP ¶
func SeedGS728TPP() *State
SeedGS728TPP builds a GS728TPP (28-port Smart Managed Pro, SNMP+HTTP) State transcribed field-for-field from the pinned Python seed_gs728tpp, whose own docstring cites REAL captures of the live switch 10.2.5.10 (2026-07-29 SNMP walk, 2026-07-29 HTTP capture) -- but see this file's package doc comment: unlike the other four seeds, no testdata/captures/gs728tpp.json was ever committed to the Python repo at this pin, so this seed is grounded ONLY via the values already transcribed into seed.py itself (which this function copies verbatim) and via direct structural pins in seed_test.go (TestSeedGS728TPP*), not the assertSeedMatchesCapture harness.
This model's SNMP agent implements ZERO Netgear vendor OIDs (model.SwitchModel.SNMPVendorBase == ""): Sensors stays empty (the SNMP face has no vendor box-sensor column to report), and the fan/PSU INVENTORY is instead exposed via the standard ENTITY-MIB EntityComponents (two PSUs, two fans -- entPhysicalIndex/Class/Name/ Descr rows from the capture, inventory only, no live value). The HTTP sysInfo sensors (with live health status) live in HTTPSensors instead. Ports g1-g28 (7 up), the real 12 VLANs, real PVIDs, 24 PoE+ ports (all Searching/0mW on this idle unit -- PowerMw stays nil over SNMP since this model has no vendor mW column either), a subset of the real dynamic FDB, 4 LLDP neighbours, and the static mgmt-IP. SysObjectID ("1.3.6.1.4.1.4526.100.4.27") is the REAL captured value: a bare identifier under 4526.100, NOT a vendor OID subtree this agent serves -- a walk of 1.3.6.1.4.1.4526 answers noSuchObject on this switch.
func SeedGSM7228PS ¶
func SeedGSM7228PS() *State
SeedGSM7228PS builds a GSM7228PS / S3300-52X-PoE+ (52-port, 48-PoE Smart Managed Pro) State transcribed field-for-field from this model's OWN real hardware capture testdata/captures/gsm7228ps.json (SNMP host 10.1.5.11 = sw-netgear-s3300-1, sysObjectID 1.3.6.1.4.1.4526.100.10.19, captured 2026-07-30) via the pinned Python seed_gsm7228ps: every physical port's name/admin/link/speed and counters, every PVID, all 5 VLANs with their exact member/untagged ifIndex sets (including the lag 1..lag 26 ifIndexes 314-339 VLAN 1 carries), all 48 PoE ports (2 delivering, 1 fault, the rest searching), the box sensors (3 fan RPM + PSU watts + temperature), the management IP (10.1.5.11) and base MAC.
IMPORTANT: this is the CURRENT, real-capture-based seed -- D-VIRT §4.2's text describes an OLDER, hand-invented illustrative seed that was superseded on the pinned Python branch; that dossier section is documented there as stale and does not apply here. This function transcribes seed.py as it exists on the pin, not the dossier.
Genuinely ILLUSTRATIVE (regression traps the capture cannot express): Mgmt.Mode/Gateway (same static-DHCP-mode-OID reasoning as SeedGSM7252PS -- the real capture reports mode "unknown" and no gateway route). MAC/FDB and LLDP rows ARE transcribed from the capture but are inherently volatile point-in-time facts, so assertSeedMatchesCapture deliberately does not pin them (see its own doc comment).
func SeedGSM7252PS ¶
func SeedGSM7252PS() *State
SeedGSM7252PS builds a GSM7252PS (52-port, 48-PoE) State transcribed field-for-field from the real hardware capture testdata/captures/gsm7252ps.json (SNMP, host 10.1.5.22) via the pinned Python seed_gsm7252ps: every port's admin/link/speed/ifAlias and counters, every PVID, all 14 VLANs' exact member/untagged ifIndex sets (including the per-VLAN lag 1..lag 64 aggregation ifIndexes and the genuine hardware quirk that Untagged is NOT a subset of Member for several VLANs, e.g. VLAN 6), all 48 PoE ports, the SNMP-face box sensors (fan RPM + PSU watts, no temperature) and a separate HTTPSensors set the web sysInfo page reports instead (temperatures + fan/PSU health text), the management IP/base MAC, serial and firmware. Two of the capture's 65 non-physical ifIndexes (417 "CPU Interface", 418 "lag 1") are carried too so a renderer that forgets the web UI lists only physical ports is caught -- see assertSeedMatchesCapture in seed_test.go for the strict parity check this holds to (ports/PVIDs/VLANs/PoE/sensors/mgmt-IP).
Genuinely ILLUSTRATIVE (regression traps the capture cannot express): the MAC/FDB entries and their non-identity bridge-port -> ifIndex join (BridgePorts[10]=110, deliberately not 10, proving get_macs must use the join and never the bare bridge-port number), the single LLDP neighbour, and Mgmt.Mode/Gateway (the real capture reports mode "unknown" and no gateway route; this mock needs a definite writable DHCP-mode OID to serve, so "static" + the subnet's router are structural stand-ins, never a claim about the real device).
func SeedM4300_16X ¶
func SeedM4300_16X() *State
SeedM4300_16X builds a realistic M4300-16X (16-port, all-16 PoE Fully Managed) State transcribed field-for-field from testdata/captures/m4300-16x. json via the pinned Python seed_m4300_16x: port name/admin/link/speed and counters, the same 14 VLANs as the 24X, every PVID, all 16 PoE ports (2 verified-live delivering: 11 at 5000mW, 12 at 2100mW), the box sensors, and the real base MAC.
The real capture's mgmt_ip.address is None (no static IP was ever discovered over this OID chain on that device) -- honestly left unseeded (NewState's default blank 0.0.0.0/dhcp Mgmt) rather than inventing one; assertSeedMatchesCapture's mgmt check skips the address/netmask/gateway comparison in exactly this case (see its own doc comment), so get_mgmt_ip().BaseMac is still checked and still real. Dot1dBaseMacASCII is NOT set here: only the M4300-24X's ASCII-text quirk has been captured/verified -- this model uses the standard raw-6-bytes encoding.
func SeedM4300_24X ¶
func SeedM4300_24X() *State
SeedM4300_24X builds a realistic M4300-24X (24-port, non-PoE Fully Managed) State transcribed field-for-field from testdata/captures/m4300-24x.json (SNMP host 10.1.5.13) via the pinned Python seed_m4300_24x: port name/admin/link/speed/description/counters, all 14 real VLANs with their full real member/untagged ifIndex sets (including the 128-wide LAG range 770-897 every VLAN's trunk carries), every PVID, the box sensors, and the base MAC. The real switch exposes 155 ifIndexes (24 physical + a CPU interface + 128 LAG placeholders + 2 VLAN interfaces); only a representative slice of the non-physical ones is seeded (the one real in-use LAG plus one unused placeholder, the CPU interface, and both VLAN interfaces) rather than all 128 mostly-identical unused LAGs -- the model's CAPABILITIES (port count/names/speeds, VLANs, PVIDs, sensors, mgmt-IP, and CRUCIALLY the absence of PoE, Poe stays the zero map) match the capture exactly.
dot1dBaseBridgeAddress is VERIFIED to come back as ASCII colon-hex text on this exact model (see snmp.ParseBaseMac's macFromASCIIText), so Dot1dBaseMacASCII is true here specifically -- NOT on SeedM4300_16X, where no such quirk has been captured. MAC/FDB rows are a representative slice of the real (30-capped) captured table, identity-mapped bridge-port -> ifIndex (see SeedGSM7252PS for the non-identity-mapping case). LLDP neighbours mix MAC-shaped (raw-bytes) and plain-text port-id subtypes on purpose.
RxUcast/TxUcast (gate-2 hardware-fidelity fix, 2026-08-20): every physical port's unicast packet counters, transcribed from the SAME already-committed testdata/captures/m4300-24x.json "stats" section this function's RxOctets/TxOctets/RxErrors/TxErrors already came from -- simply never wired up here before. Real hardware always answers RxPackets/TxPackets (live-verified: port 1 read live off 10.1.5.13 during gate-2 read RxPackets~=20455434750/TxPackets~=18675057818, a larger-but-consistent count than this older capture's snapshot, exactly what a live incrementing counter looks like weeks later), so a fake that leaves them nil was diverging from every real switch's own behaviour -- see docs/hardware-findings.md. Using this capture's own packet counts (rather than the fresher live-session numbers, which exist only for port 1) keeps every port's RxOctets/TxOctets/RxUcast/ TxUcast internally consistent as one real snapshot moment, matching SeedGSM7252PS's own shape.
func (*State) ApplyNsdpWrite ¶
ApplyNsdpWrite mutates this State from one authenticated NSDP WRITE_REQUEST TLV (a subsequent read, i.e. verify-after-write, observes the mutation), mirroring Python's apply_nsdp_write (D-NSDP §7.1). Unknown, read-only (REBOOT/FACTORY_RESET), and unrecognized tags are a deliberate no-op.
Deliberate Go-safety divergence from the pinned Python reference: a malformed VALUE for a known tag (too short to hold its fixed fields) is ALSO treated as a no-op here, guarded by an explicit length check before any indexing/parsing. Python's equivalent branches have no such guard and are themselves inconsistent about what happens: PORT_PVID's `value[0]`/ `struct.unpack_from` raises IndexError/struct.error, and IP_ADDRESS/ NETMASK/GATEWAY's `socket.inet_ntoa` raises OSError on a wrong-length value -- none of those three are a ValueError, so faces/nsdp.py's `_serve` (which only catches ValueError around `_handle`) does NOT catch them, silently killing that one Python mock's serve thread permanently. VLAN_MEMBERS is the one exception that's already safe in Python: parse_vlan_members explicitly raises a plain ValueError for a too-short buffer, which `_serve` DOES catch (response silently dropped, thread survives). A Go panic from an unrecovered out-of-range access in this package's background serve goroutine would be strictly worse than even the thread-killing cases above: it crashes the entire process, not just one mock's request loop. Go therefore guards every branch uniformly rather than mirroring Python's per-tag mix.
DHCP_MODE is a related but distinct case: neither language ever panics on an empty value here (indexing `value[:1]`/`value[0]==0x01` guarded by `len(value) > 0` doesn't raise/index-fault on empty in either language). But Python's `value[:1] == b"\x01"` is simply False for an empty value, so Python's else branch sets Mode="static" -- a spurious mutation of a known tag from a too-short (here, zero-length) value, violating the same "too-short value = no-op" contract this comment documents for the other tags above. Go deliberately does NOT mirror that inconsistency: an empty DHCP_MODE value is guarded to a no-op up front, same as every other known tag's too-short value.
See docs/cross-language-divergences.md, "Slice 05", entry 4, for the full call-out; nothing here changes the wire encoding of any well-formed write, only how a malformed one degrades.
func (*State) ApplyPoeAdmin ¶
ApplyPoeAdmin switches a PSE port's admin state, with the coherence a real PoE switch shows: admin off -> detect=1 (unused) and the data link drops; admin on -> detect=3 (delivering). ONE rule shared by EVERY protocol face -- the SNMP SET path (ApplyWrite's pethPsePortAdminEnable branch below) and the CLI `poe`/`no poe` commands (CliFace.applyPoeAdmin, cliface.go) both come through here, so the mock cannot behave differently depending on which backend a test drove (which would make cross-backend write parity meaningless) -- mirroring Python State.apply_poe_admin verbatim (pin state.py:1135-1157), including its own docstring's framing: "ONE rule shared by every protocol face -- the SNMP SET path (apply_write) and the CLI poe/no poe commands both come through here."
On an off->on transition, PoeSim.CliStatusLagReads is set to 1 REGARDLESS of which backend drove the write -- Python does not special-case this per protocol either: it is one dataclass field mutated by one shared method (state.py:1152-1155). MEASURED ON HARDWARE (M4300-16X, 10.1.5.20, FASTPATH 12.0.19.15, 2026-07-30) that a re-enabled port's `show poe port info all` Status column still reads "Disabled" for one more read before catching up -- see PoeSim.CliStatusLagReads's own doc comment. Unknown port: deliberate no-op.
func (*State) ApplyWrite ¶
ApplyWrite mutates this state from one SNMP SET varbind, with device coherence. Applies the same coherence a real PoE switch shows so a cycle_poe operation (later slice) terminates against the mock: admin off -> detect=1 (unused) + data-port link down; admin on -> detect=3 (delivering). See the section doc comment above for the full dispatch contract.
func (*State) IsOIDImplemented ¶
IsOIDImplemented reports whether oid does NOT fall under a subtree root this model's real SNMP agent never registers at all (e.g. the RFC3621 PoE MIB on a non-PoE model). Delegates entirely to snmp.IsOIDImplemented.
func (*State) IsWritableOID ¶
IsWritableOID reports whether oid is one this mock recognizes as SNMP-writable. See the section doc comment above for why this is a separate, stricter gate than ApplyWrite's own always-succeeding dispatch.
func (*State) LockState ¶
func (s *State) LockState()
LockState acquires this State's mutex -- see mu's own doc comment for the full contract (Go-only; no Python equivalent). A face's write path holds this across a whole atomic operation, not just the individual field assignments inside it (see SnmpFace.handleSet). Code reading State fields directly from outside a face's own single-threaded request handling -- e.g. a test inspecting SwitchportMode right after a synchronous SNMP write completes -- must hold it too, for exactly the same reason: without it, the read and the face's write are unsynchronized concurrent accesses to the same map, even though the protocol round trip enforces real ordering in practice.
Named LockState/UnlockState, not Lock/Unlock: naming them Lock/Unlock would make *State satisfy sync.Locker while State (the value type) does not -- exactly the shape go vet's copylocks check flags on any value copy of State, e.g. a State{...} struct literal (Snapshot builds one).
func (*State) NsdpTlvs ¶
NsdpTlvs projects this State onto NSDP READ_RESPONSE TLVs for exactly the requested tags, mirroring Python's nsdp_tlvs (D-NSDP §7.1).
STRICT (the load-bearing behavior D-NSDP §7.1/§10.6#6 calls out): answers with ONLY the tags actually present in tags -- real Plus hardware does exactly this (a read omitting MODEL gets a MODEL-less response). This deliberately does NOT special-case MODEL/MAC/PORT_COUNT as "always included" despite the pinned Python source's own docstring first line claiming that: the pinned CODE gates all three on `if Tag.X in tags` exactly like every other tag (confirmed by an inline "STRICT" comment in that source and pinned by its own test_nsdp_tlvs_projects_ports_and_identity, which requires a PORT_STATUS-only request to NOT also return MODEL) -- the docstring's first line is stale prose, not the contract. Port the code, not that one sentence.
func (*State) OIDMap ¶
OIDMap projects this state onto the full numeric OID -> (type, value) view, built directly from the exact OID layouts in package snmp so a protocol face can serve it. See D-VIRT §1.4 for the full conditional- emission rule set this mirrors line-for-line.
func (*State) Restore ¶
Restore restores this state in place from a prior Snapshot result.
This copies every OTHER field from snap onto *s field-by-field (never a whole-struct `*s = *snap`) rather than replacing s itself, so existing holders of this exact *State pointer keep seeing the restored data -- the critical porting detail from the Python reference's restore(), which sets attributes on self rather than reassigning the variable holding it. Safe because Snapshot deep-copied every map/slice/pointer field: after this assignment s's fields alias snap's already-independent data, never anything still shared with whatever was mutated between Snapshot and Restore.
mu is the one field deliberately NEVER assigned here -- not even to snap.mu, which (see Snapshot) is bit-identical to s.mu already. A single `*s = *snap` was tried first and is WRONG, proven by -race: that statement writes to EVERY field's memory, mu included, even when the value being written back is identical, and Restore always runs from inside a face's own LockState/UnlockState critical section (e.g. SnmpFace.handleSet's rollback path) while a DIFFERENT goroutine can be concurrently calling LockState for the first time on this same *State (e.g. CliFace.InterfaceName from a live SSH/Telnet session) -- which READS s.mu to find the mutex to lock. A concurrent unsynchronized write-that-happens-not-to-change-the-value is still a write; the race detector (correctly) does not know or care that the bytes matched. Skipping mu here entirely, rather than writing-then-fixing-up afterward, is what actually closes that gap: fixing it up after a bulk `*s = *snap` would still execute the racy write as part of that bulk copy first.
func (*State) Snapshot ¶
Snapshot deep-copies this state, for atomic multi-varbind SET rollback.
A single SNMP SET PDU can carry several varbinds (e.g. a VLAN-membership write touching both the egress AND untagged bitmaps in one call) and a real agent guarantees they apply all-or-nothing: the (later-slice) face snapshots the state before applying a PDU's varbinds and calls Restore on this snapshot if any of them fails, so a partial mutation is never observable. Every map/slice/pointer field is deep-copied by hand here (no gob/reflection) -- see Restore.
Also marks a PDU boundary: s.PDUEgressWrites (which tracks same-PDU egress writes for the S3300's auto-untag ordering quirk) is cleared here -- on s itself, BEFORE the deep copy below, so the returned snapshot starts with an empty set too -- mirroring Python VirtualSwitchState.snapshot() (state.py:1106-1122: `self.pdu_egress_writes = set()` then `return copy.deepcopy(self)`), since SnmpFace snapshots exactly once per PDU.
func (*State) SysinfoSensors ¶
SysinfoSensors returns the sensor set the HTTP sysInfo page renders: HTTPSensors when a model's web UI exposes a different sensor set than SNMP (e.g. gsm7252ps), else Sensors, so a model whose two faces agree (M4300) is unchanged. Mirrors the Python sysinfo_sensors property.
func (*State) UnlockState ¶
func (s *State) UnlockState()
UnlockState releases the lock acquired by LockState.
type SyslogCollectorSim ¶
type SyslogCollectorSim struct {
Host string
Port int
Severity int
Status int
// Index is the row's index in the switch's own host table. SPARSE on
// real hardware -- m4300-24x 10.1.5.13 held Index 1 and Index 3 with
// nothing at 2 (2026-08-05) -- so this is stored rather than derived
// from a row's position. A fake that renumbered densely could never
// catch a position-for-index bug, which is exactly the bug that got
// shipped.
Index int
}
SyslogCollectorSim is one remote syslog collector row, as the vendor host table reports it, mirroring Python's SyslogCollectorSim dataclass (state.py:248-267).
Field values are SEEDED from a live switch, never computed: Severity is the standard syslog number the device actually returns (6 for "info" on m4300-24x, cross-checked against its own `show logging hosts`), and Status 1 is what that command prints as "Active".
type SyslogSim ¶
type SyslogSim struct {
AdminMode int
LocalPort int
Collectors []SyslogCollectorSim
}
SyslogSim is the switch's remote-logging state, as the vendor ".14" subtree reports it, mirroring Python's SyslogSim dataclass (state.py: 270-282). AdminMode is the device's own enum (1=enabled, 2=disabled), kept as the raw integer rather than a bool so the mock emits exactly what a real agent emits and the reader's own decoding is what gets exercised. NewState's zero value is AdminMode 2 / LocalPort 514 / no collectors -- the Python dataclass default -- not the Go struct zero value; see NewState.
type TelnetFace ¶
type TelnetFace struct {
// contains filtered or unexported fields
}
TelnetFace is a real loopback Telnet server serving the FASTPATH shell over a *State, mirroring SSHFace's shape (bind-on-Start/deterministic- idempotent-Stop) with a hand-rolled accept loop standing in for gliderlabs/ssh's *Server (there is no telnet-server framework dependency in this repo, matching fastpath/telnet.go's own hand-rolled client choice). Construct with NewTelnetFace; call Start to bind and begin serving, Stop to tear down (idempotent; safe to call before Start or more than once).
func NewTelnetFace ¶
func NewTelnetFace(state *State, spec *fastpath.CliModelSpec, username, password, host string) *TelnetFace
NewTelnetFace builds a TelnetFace serving state per spec, accepting only a login whose username/password match username/password, bound to host (typically "127.0.0.1") once Start is called. Each accepted connection dispatches through its OWN fresh *CliFace (independent mode stack) over the SAME state -- see SSHFace's matching doc comment; the two listeners share this exact per-connection-isolation/shared-state contract.
func (*TelnetFace) Start ¶
func (f *TelnetFace) Start() (port int, err error)
Start binds an ephemeral TCP port on f.host and begins accepting on a background goroutine, returning the bound port. Calling Start twice without an intervening Stop is an error.
func (*TelnetFace) Stop ¶
func (f *TelnetFace) Stop() error
Stop tears the server down deterministically (transport dossier §5's leak-free contract): closes the listener (unblocking acceptLoop's Accept) and force-closes every currently-tracked connection (unblocking any in-flight per-connection Read in serveConn/cliListenerLoop) BEFORE waiting, then f.wg.Wait() blocks until acceptLoop and every serveConn goroutine have actually returned. Idempotent: a Stop before Start, or a second Stop, is a no-op.
type UserSim ¶
type UserSim struct {
Name string
HTTPAccessMode string
CLIAccessMode string
// SNMPv3Access/SNMPv3Auth/SNMPv3Encryption are the three SNMPv3 columns
// `show users` also carries. "" (the default, for every row but one --
// see SeedM4300_24X) means unmeasured, rendered as a blank cell rather
// than a guess: only ONE row anywhere in the pinned Python source has a
// measured value here (parse_users' own docstring transcript, which is
// m4300-24x's admin row).
SNMPv3Access string
SNMPv3Auth string
SNMPv3Encryption string
}
UserSim is one local login account, as the switch's own pages/CLI word it, mirroring Python's UserSim dataclass (state.py:212-230) plus one field Python's fake does not yet have.
HTTPAccessMode is stored VERBATIM rather than derived from a privilege flag, because the same account is worded DIFFERENTLY depending on which face is asked -- measured on 10.1.5.22 and 10.1.5.13, where admin reads "Super User" on userManagement.html but "Read/Write" and "Privilege-15" respectively through each switch's own `show users`. A mock that stored one level and rendered it per face would be inventing the wording; storing what each page really emits means the reader's own word-to- privilege mapping is what gets exercised.
CLIAccessMode extends beyond the pinned Python source (pin b26eb1f): Python's own state.py docstring for this type says "The CLI face has no `show users` yet. When it gains one it needs its own field here, NOT this one: the two faces genuinely disagree" -- i.e. Python has never built the CLI `show users` virtual-fake renderer this slice's task explicitly requires, so there is no existing Go-side Python field to port for it. The VALUES below are still measured, not invented: Python commit 4619e3c ("feat(cli): read the switch's local user accounts") records the live-verified table this field's seed values are transcribed from --
m4300-24x admin=Privilege-15 guest=Privilege-1 gsm7252ps admin=Read/Write guest=Read Only
-- but that commit message is prose, not a checked-in fixture file or a Python fake seed, so per this project's principle 5 this is flagged explicitly here rather than silently claimed as "ported from Python's fake" the way HTTPAccessMode is.
type ViewEntry ¶
ViewEntry is one MibView row: a numeric OID plus the SNMP type token and wire value State.OIDMap() projected for it (see OIDEntry).
type VirtualSwitch ¶
type VirtualSwitch struct {
// State is this switch's in-memory device state (D-VIRT §1), seeded (or
// left blank-but-valid) for the model NewVirtualSwitch was constructed
// with.
State *State
// Host is the loopback address every bound face listens on (default
// "127.0.0.1"; override with WithHost).
Host string
// SnmpPort is the bound SNMP face's UDP port once Start has bound it (0
// otherwise). Deliberately a field distinct from every other backend's
// port below -- unlike the Python reference, which reuses self.port for
// BOTH the SNMP and NSDP faces (they're never both live at once on any
// real registered model, but sharing one field is still a latent trap
// D-VIRT §5 calls out explicitly). See D-VIRT §8.2.
SnmpPort int
// NsdpPort is the bound NSDP face's UDP port once Start has bound it (0
// otherwise; 0 before Start, or on a model with no BackendNSDP). See
// SnmpPort's own doc comment for why this is a field distinct from
// every other backend's port.
NsdpPort int
// HTTPPort is the bound HTTP face's TCP port once Start has bound it (0
// otherwise; 0 before Start, or on a model with no BackendHTTP). See
// SnmpPort's own doc comment for why this is a field distinct from
// every other backend's port -- confirmed by D-HTTP-F §6.1 to match the
// Python reference's independent self.http_port field exactly (a
// {NSDP, HTTP} model such as gs305ep/gs110emx/gs105pe binds BOTH its
// NSDP face (NsdpPort) and its HTTP face (HTTPPort) CONCURRENTLY).
HTTPPort int
// SSHPort is the bound SSH CLI face's TCP port once Start has bound it
// (0 otherwise; 0 before Start, or on a model with no BackendSSH). See
// SnmpPort's own doc comment for why this is a field distinct from
// every other backend's port.
SSHPort int
// TelnetPort is the bound Telnet CLI face's TCP port once Start has
// bound it (0 otherwise; 0 before Start, or on a model with no
// BackendTelnet). See SnmpPort's own doc comment for why this is a
// field distinct from every other backend's port.
TelnetPort int
// contains filtered or unexported fields
}
VirtualSwitch is a mock switch server: a seeded State plus its bound protocol faces. Construct with NewVirtualSwitch; call Start to bind whichever protocol faces this slice implements and the model supports, Stop to tear them down (idempotent; safe to call before Start or more than once).
func NewVirtualSwitch ¶
func NewVirtualSwitch(modelKey string, opts ...Option) (*VirtualSwitch, error)
NewVirtualSwitch builds a VirtualSwitch for modelKey: resolves modelKey against the model registry FIRST (an unknown key returns an error wrapping model.ErrUnknownModel immediately, before any state is built or option is applied), then seeds (or, for a model with no hand-authored seed, default-blanks) its State via BuildState. Call Start to bind protocol faces.
Example ¶
ExampleNewVirtualSwitch starts an in-process virtual GSM7252PS switch -- no real hardware, no external process, just a goroutine and a loopback UDP socket -- and reads its identity with the snmp package directly, the same client code a caller would point at a real switch.
package main
import (
"context"
"fmt"
"time"
"github.com/mithro/go-netgear-switch-library/snmp"
"github.com/mithro/go-netgear-switch-library/virtual"
)
func main() {
vsw, err := virtual.NewVirtualSwitch("gsm7252ps")
if err != nil {
panic(err)
}
if err := vsw.Start(); err != nil {
panic(err)
}
defer func() { _ = vsw.Stop() }()
client := snmp.NewGoSNMPClient(fmt.Sprintf("%s:%d", vsw.Host, vsw.SnmpPort), "public")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
info, err := snmp.ReadSystemInfo(ctx, client)
if err != nil {
panic(err)
}
fmt.Println("sysDescr:", *info.SysDescr)
}
Output: sysDescr: NETGEAR GSM7252PS Managed Switch, firmware 8.0.6.6
func (*VirtualSwitch) CliSession ¶
func (v *VirtualSwitch) CliSession() (fastpath.Session, error)
CliSession returns an in-process fastpath.Session (CliFace) bound to this switch's State, mirroring Python VirtualSwitch.cli_session(): "Unlike the SNMP/NSDP/HTTP faces (real sockets bound in start()), the CLI face is an in-process CliSession needing no socket" (server.py: 130-140) -- so, unlike SnmpPort/NsdpPort/HTTPPort/SSHPort/TelnetPort, this needs no Start call at all; it is available immediately after NewVirtualSwitch. Errors exactly like fastpath.NewReader/NewWriter would for a model with no CLI backend or no registered fastpath.CliModelSpec (fastpath.CLISpec's own two-stage guard). The real SSH/Telnet listeners bound during Start (SSHPort/TelnetPort, sshface.go/telnetface.go, Task 12) each construct their OWN fresh *CliFace per connection the same way this accessor does -- this one remains the unit-test-path seam cliface_test.go drives the real fastpath.Reader/Writer against, with no socket in the way at all.
func (*VirtualSwitch) Start ¶
func (v *VirtualSwitch) Start() error
Start binds every protocol face this package implements that the model supports: SNMP (bound iff the model's registry entry has model.BackendSNMP), NSDP (bound iff it has model.BackendNSDP, slice 05), HTTP (bound iff it has model.BackendHTTP, slice 06), and, as of slice 07 Task 12, SSH (bound iff it has model.BackendSSH) and Telnet (bound iff it has model.BackendTelnet) -- each an independent `if` block, exactly mirroring the Python reference's start(). A Plus-class model such as gs110emx/gs305ep/gs105pe (registry backends {NSDP, HTTP}) binds BOTH its NSDP face (NsdpPort) AND its HTTP face (HTTPPort) CONCURRENTLY (D-HTTP-F §6.1), exactly like a managed model (SNMP, HTTP, SSH, Telnet) binds all four of its own ports at once. A model with no face at all (none of BackendSNMP/BackendNSDP/BackendHTTP/BackendSSH/BackendTelnet) returns an error wrapping model.ErrUnsupportedCapability.
SELF-CLEANING ON A PARTIAL FAILURE: a later face's bind can fail after an earlier one already succeeded (most reachably via cmd/gngsw-virtual's --port/--http-port pinning a face onto an address that's already taken). Every error path below therefore routes through fail, which calls this same switch's own Stop() -- idempotent, and already tears down exactly whichever faces are non-nil -- BEFORE returning the error, so a caller never has to distinguish "Start failed, nothing to clean up" from "Start failed after partially succeeding, something is still bound"; either way every socket and goroutine Start opened before the failure is already closed by the time it returns.
func (*VirtualSwitch) Stop ¶
func (v *VirtualSwitch) Stop() error
Stop stops every bound face. Idempotent: safe to call if Start failed, was never called, or Stop was already called. Stops the SNMP face first, then NSDP, then HTTP, then SSH, then Telnet, regardless of whether an earlier stop errored, so a failure stopping one face never leaks the others; only the first error (if any) is returned.
type VlanMembershipPageSim ¶
type VlanMembershipPageSim struct {
// Slots is the page's hiddenMem/hiddenTagged/hiddenUnTagged grid width in
// slots (physical ports plus trailing LAG pseudo-interfaces) -- a
// hardware-fixed constant PER MODEL, wider than the port count.
Slots int
// LagSlot is the 1-based slot number the first LAG pseudo-interface
// occupies (LAG slots run from here through Slots).
LagSlot int
// Grid is which firmware-generation rendering variant this model's page
// uses: "gif" (older XE, gsm7252ps -- toggleImageFirst()/grey_[btu].gif,
// 0-based hiddenMem index) or "png" (newer jQuery, gsm7228ps/both
// M4300s -- togImg()/switch_*.png, 1-based index).
Grid string
// TrailingComma is whether this model's hiddenMem/hiddenTagged/
// hiddenUnTagged strings carry a trailing comma.
TrailingComma bool
// CSRF is whether this model's page requires its own per-page CSRF token
// (the "virtualcsrf" literal, D-HTTP-F §4.1 -- a THIRD distinct CSRF-shaped
// constant from web.py's "virtualhash" and gs105pe's "18007") riding
// along on every apply.
CSRF bool
// Escape is whether this model's page HTML-escapes ifNames in the
// rendered grid (e.g. "1/0/1" -> "1/0/1").
Escape bool
}
VlanMembershipPageSim records the MEASURED byte-shape of one managed FASTPATH model's "VLAN Membership" page (dossier D-HTTP-F §5.2), mirroring Python's VlanMembershipPageSim dataclass. Populated only by the four managed models' Seed*() functions (gsm7252ps, gsm7228ps, m4300-24x, m4300-16x) -- State.VlanMembershipPage stays nil for every other model (every Plus-class/GoAhead model has no such page at all). Consumed by the (slice-06 Task 9/10) FASTPATH VLAN-membership renderer, not by anything in this slice's Task 8 HTTP-face skeleton.
type VlanSim ¶
type VlanSim struct {
Name string
Member map[int]bool
Untagged map[int]bool
// ConfiguredOnly is the set of ports CONFIGURED into this VLAN but NOT
// currently participating -- “show vlan“ prints them as "Current:
// Exclude / Configured: Include". A REAL, MEASURED divergence, not a
// theoretical one: on GSM7252PS @10.1.5.22, VLAN 1 lists ports 1/0/50
// and 1/0/51 exactly that way, so the switch reports them in
// dot1qVlanStaticEgressPorts (the STATIC/configured table) and in the
// web UI's hiddenMem grid, while omitting them from the CLI's current
// list, from vlanStatus.html and from hiddenTagged/hiddenUnTagged.
// Keeping the two views separate is what lets the mock reproduce that
// split -- collapsing them would make the mock's SNMP and HTTP faces
// agree with each other while both disagree with hardware. Empty (the
// default) = configured and current coincide, the normal case. Mirrors
// Python VlanSim.configured_only.
ConfiguredOnly map[int]bool
// NoStaticRow is true when this VLAN has NO dot1qVlanStaticTable row at
// all -- present only in dot1qVlanCurrentTable. Mirrors Python
// VlanSim.static_row, INVERTED (Python defaults True; Go's bool zero
// value is false) so the Go zero value is the normal case and every
// existing seed is unaffected without touching it.
//
// MEASURED on the GS728TPP (sw-netgear-gs728tpp.monarto.mithis.com /
// 10.2.5.10, firmware 6.0.1.30, 2026-08-02): its default VLAN 1 does
// NOT have one. A walk of dot1qVlanStaticName/Egress/Untagged/
// RowStatus returns exactly 12 rows -- ids 2,3,4,5,6,7,10,20,31,41,90,99
// -- while dot1qVlanCurrentTable returns 13, the extra one being VLAN 1
// with dot1qVlanStatus = 1 (other) where every other VLAN reads 2
// (permanent). The web UI lists VLAN 1, so a reader that consults only
// the static table loses it; see snmp.ParseVlans, which reads both
// tables because of this.
//
// False (the default) is itself measured as the normal case: the
// GSM7252PS, both M4300s and the S3300-52X all publish a static VLAN 1
// row.
NoStaticRow bool
}
VlanSim is one dot1q VLAN: display name plus egress-member and untagged port sets. Member/Untagged represent sets: a port is a member iff its map value is true (see sliceFromPortSet, snmp.EncodePortBitmap).
func (*VlanSim) Configured ¶
Configured returns the CONFIGURED egress set: current members plus ConfiguredOnly, mirroring Python VlanSim.configured (a computed property there; a method here since Go has no property syntax).
Source Files
¶
- cli_socket.go
- cliface.go
- cliface_render.go
- doc.go
- httpface.go
- mibview.go
- nsdpface.go
- seed.go
- server.go
- snmpface.go
- sshface.go
- state.go
- state_oidmap.go
- state_switchport.go
- telnetface.go
- web_fastpath_vlan.go
- web_fastpath_xui.go
- web_gs105pe.go
- web_gs110emx.go
- web_gs110emx_templates.go
- web_gs728tpp.go
- web_gsm7228ps.go
- web_gsm7252ps.go
- web_m4300.go