From 172abe165693fe3c1f1fde58ffb77525f73f2ef7 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 25 Oct 2026 14:17:19 +0100 Subject: [PATCH 1/2] fix(ocpp): a port Core cannot open fails Start and shows on each charger ws.Server.Start opens its own socket in a goroutine and drops a listen error into a logger Core does not read, so a taken port left the OCPP server not listening while Start reported success. Start now opens and closes each enabled port first, loads the TLS pair that ServeTLS would load later, and on any failure records the error on every charger the site names. Co-Authored-By: Claude Opus 5.5 --- .changeset/ocpp-port-taken.md | 5 +++ go/internal/ocpp/auth_test.go | 11 +++++++ go/internal/ocpp/charger_socket_test.go | 11 +++++-- go/internal/ocpp/config.go | 9 +++--- go/internal/ocpp/server.go | 41 ++++++++++++++++++++++++- go/internal/ocpp/server_test.go | 36 ++++++++++++++++++++++ 6 files changed, 104 insertions(+), 9 deletions(-) create mode 100644 .changeset/ocpp-port-taken.md diff --git a/.changeset/ocpp-port-taken.md b/.changeset/ocpp-port-taken.md new file mode 100644 index 000000000..06914a54f --- /dev/null +++ b/.changeset/ocpp-port-taken.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +If Core cannot open its OCPP port, because another program holds it or the TLS certificate and key do not load, the OCPP server now fails to start with that error instead of saying it started. The error appears in the log and in the help report, and each charger the site names shows it as its last error, so a charger that never connects has a reason beside it. diff --git a/go/internal/ocpp/auth_test.go b/go/internal/ocpp/auth_test.go index 9b6efece3..0fa21a91f 100644 --- a/go/internal/ocpp/auth_test.go +++ b/go/internal/ocpp/auth_test.go @@ -238,6 +238,7 @@ func TestTLSMisconfigurationRefusesToStart(t *testing.T) { {name: "cert without key", tls: &TLSConfig{CertFile: "cert.pem"}}, {name: "key without cert", tls: &TLSConfig{KeyFile: "key.pem"}}, {name: "cert file missing", tls: &TLSConfig{CertFile: "no-such-cert.pem", KeyFile: "no-such-key.pem"}}, + {name: "cert does not load", tls: &TLSConfig{CertFile: unreadablePEM(t, "cert.pem"), KeyFile: unreadablePEM(t, "key.pem")}}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -249,6 +250,16 @@ func TestTLSMisconfigurationRefusesToStart(t *testing.T) { } } +// unreadablePEM writes a file that exists but holds no PEM block. +func unreadablePEM(t *testing.T, name string) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + if err := os.WriteFile(path, []byte("not a certificate"), 0o600); err != nil { + t.Fatal(err) + } + return path +} + func TestSchemeFollowsTLS(t *testing.T) { if got := (&Config{}).Scheme(); got != "ws" { t.Errorf("plaintext scheme: got %q, want ws", got) diff --git a/go/internal/ocpp/charger_socket_test.go b/go/internal/ocpp/charger_socket_test.go index 538459b43..45944e13b 100644 --- a/go/internal/ocpp/charger_socket_test.go +++ b/go/internal/ocpp/charger_socket_test.go @@ -156,9 +156,10 @@ func dialChargingStation201(t *testing.T, url, id string, setup func(ocpp201.Cha // after the chargers a test dials later. // // freePort hands back a port the kernel just released, and another socket can -// take it before the library binds it. The library then gives up on that -// listener without an error, so a listener goroutine that exits early means -// the port was lost: try fresh ones. +// take it before Start checks it, or between that check and the library's +// bind. Start fails in the first case; in the second the library gives up on +// that listener without an error, so a listener goroutine that exits early +// means the port was lost. Either way, try fresh ones. func startOCPP(t *testing.T, cfg Config, tel *telemetry.Store, v201 bool) *Server { t.Helper() const attempts = 5 @@ -169,6 +170,10 @@ func startOCPP(t *testing.T, cfg Config, tel *telemetry.Store, v201 bool) *Serve c.PortV201 = freePort(t) } srv, err := Start(context.Background(), &c, tel) + var taken *net.OpError + if errors.As(err, &taken) && attempt < attempts { + continue // another test took the port after freePort gave it back + } if err != nil { t.Fatalf("start: %v", err) } diff --git a/go/internal/ocpp/config.go b/go/internal/ocpp/config.go index 9a6fa9fad..c8f581ab0 100644 --- a/go/internal/ocpp/config.go +++ b/go/internal/ocpp/config.go @@ -94,11 +94,10 @@ func (t *TLSConfig) serverTLS() (*tls.Config, error) { if !t.Enabled() { return nil, errors.New("ocpp: tls needs both cert_file and key_file") } - if _, err := os.Stat(t.CertFile); err != nil { - return nil, fmt.Errorf("ocpp: tls cert_file: %w", err) - } - if _, err := os.Stat(t.KeyFile); err != nil { - return nil, fmt.Errorf("ocpp: tls key_file: %w", err) + // ServeTLS loads the pair again inside the listener goroutine, where a + // failure stops the listener with no error anyone sees. + if _, err := tls.LoadX509KeyPair(t.CertFile, t.KeyFile); err != nil { + return nil, fmt.Errorf("ocpp: tls cert_file and key_file: %w", err) } cfg := &tls.Config{MinVersion: tls.VersionTLS12} if t.ClientCAFile == "" { diff --git a/go/internal/ocpp/server.go b/go/internal/ocpp/server.go index 39ed1ac1b..c566bd800 100644 --- a/go/internal/ocpp/server.go +++ b/go/internal/ocpp/server.go @@ -36,6 +36,7 @@ import ( "errors" "fmt" "log/slog" + "net" "net/http" "sync" "time" @@ -70,9 +71,12 @@ type Server struct { // immediately once the listener is up; the WebSocket loop runs in its own // goroutine until ctx is cancelled or Stop() is called. // +// An error means no charger can connect, so it is also recorded as the last +// error of each charger the site names, where its device status is read. +// // The returned Server is the handle for shutdown — main.go is expected to // call Stop() during graceful drain. -func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (*Server, error) { +func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (_ *Server, err error) { if cfg == nil { return nil, errors.New("ocpp: nil config") } @@ -80,6 +84,16 @@ func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (*Server, err return nil, errors.New("ocpp: nil telemetry store") } cfg.Defaults() + defer func() { + if err != nil { + for _, id := range cfg.ApprovedIDs { + tel.RecordDriverError(id, err.Error()) + } + } + }() + if err := checkPorts(cfg); err != nil { + return nil, err + } auth := newAuthorizer(cfg) sockets := newSocketSessions() @@ -184,6 +198,31 @@ func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (*Server, err return s, nil } +// checkPorts opens and closes each enabled port, on every interface as +// ws.Server.Start does. That Start runs in a goroutine and, when its own +// listen fails, returns with the error sent to a logger nobody reads, so a +// taken port has to fail here or the chargers stay away with no reason given. +func checkPorts(cfg *Config) error { + ports := []int{cfg.Port} + if cfg.PortV201 > 0 { + ports = append(ports, cfg.PortV201) + } + var open []net.Listener + defer func() { + for _, l := range open { + l.Close() + } + }() + for _, port := range ports { + l, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + if err != nil { + return fmt.Errorf("ocpp: %w", err) + } + open = append(open, l) + } + return nil +} + // newListener builds one version's WebSocket server — TLS when configured — // with both authorization gates wired. // diff --git a/go/internal/ocpp/server_test.go b/go/internal/ocpp/server_test.go index f500b54cb..05338b6c6 100644 --- a/go/internal/ocpp/server_test.go +++ b/go/internal/ocpp/server_test.go @@ -1,7 +1,10 @@ package ocpp import ( + "context" + "fmt" "net" + "strings" "sync" "testing" "time" @@ -35,6 +38,39 @@ func startServer(t *testing.T, tel *telemetry.Store, approved ...string) (int, * return srv.cfg.Port, srv } +// A port another process holds fails Start, and each charger the site names +// carries the reason in its health. The library gives up on the port inside +// a goroutine and logs nowhere we read, so without this the chargers stay +// away and nothing says why. +func TestStartFailsWhenAPortIsTaken(t *testing.T) { + for _, v201 := range []bool{false, true} { + t.Run(fmt.Sprintf("v201=%v", v201), func(t *testing.T) { + held, err := net.Listen("tcp", ":0") + if err != nil { + t.Fatal(err) + } + defer held.Close() + taken := held.Addr().(*net.TCPAddr).Port + + cfg := &Config{Enabled: true, Bind: "127.0.0.1", Port: taken, ApprovedIDs: []string{"garage"}} + if v201 { + cfg.Port = freePort(t) + cfg.PortV201 = taken + } + tel := telemetry.NewStore() + if _, err := Start(context.Background(), cfg, tel); err == nil { + t.Fatalf("Start succeeded with port %d taken", taken) + } else if !strings.Contains(err.Error(), fmt.Sprint(taken)) { + t.Errorf("error %q does not name port %d", err, taken) + } + h := tel.DriverHealth("garage") + if h == nil || !strings.Contains(h.LastError, fmt.Sprint(taken)) { + t.Fatalf("the charger's health does not say why it cannot connect: %+v", h) + } + }) + } +} + func TestStopIsConcurrentAndIdempotent(t *testing.T) { _, srv := startServer(t, telemetry.NewStore()) From db93a32c39f3cebfc27307787bf5ddb80f1059a9 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 25 Oct 2026 14:32:17 +0100 Subject: [PATCH 2/2] fix(ocpp): a taken 2.0.1 port leaves the 1.6 listener running Review note: failing all of Start for a taken 2.0.1 port also stopped the 1.6 listener that came up before, leaving 1.6 chargers unsteered. Start now fails only for the 1.6 port. A taken 2.0.1 port is logged, that listener is skipped, and the reason goes on each named charger, which its first 1.6 message clears. The Start comment no longer says it returns once the listener is up, and startOCPP retries when a 2.0.1 listener it asked for did not start. Co-Authored-By: Claude Opus 5.5 --- .changeset/ocpp-port-taken.md | 2 +- go/internal/ocpp/auth_test.go | 2 +- go/internal/ocpp/charger_socket_test.go | 9 +-- go/internal/ocpp/server.go | 63 ++++++++++----------- go/internal/ocpp/server_test.go | 73 ++++++++++++++++--------- 5 files changed, 86 insertions(+), 63 deletions(-) diff --git a/.changeset/ocpp-port-taken.md b/.changeset/ocpp-port-taken.md index 06914a54f..24ab004b9 100644 --- a/.changeset/ocpp-port-taken.md +++ b/.changeset/ocpp-port-taken.md @@ -2,4 +2,4 @@ "ftw": patch --- -If Core cannot open its OCPP port, because another program holds it or the TLS certificate and key do not load, the OCPP server now fails to start with that error instead of saying it started. The error appears in the log and in the help report, and each charger the site names shows it as its last error, so a charger that never connects has a reason beside it. +If Core cannot open its OCPP port, because another program holds it or the TLS certificate and key do not load, the OCPP server now fails to start with that error instead of saying it started. If only the OCPP 2.0.1 port is taken, the 1.6 server still starts for the chargers that use it. The error appears in the log and in the help report, and each charger the site names shows it as its last error until it connects, so a charger that never connects has a reason beside it. diff --git a/go/internal/ocpp/auth_test.go b/go/internal/ocpp/auth_test.go index 0fa21a91f..7c0031b33 100644 --- a/go/internal/ocpp/auth_test.go +++ b/go/internal/ocpp/auth_test.go @@ -244,7 +244,7 @@ func TestTLSMisconfigurationRefusesToStart(t *testing.T) { t.Run(tc.name, func(t *testing.T) { cfg := &Config{Enabled: true, Bind: "127.0.0.1", Port: freePort(t), TLS: tc.tls} if _, err := Start(context.Background(), cfg, telemetry.NewStore()); err == nil { - t.Fatal("a broken TLS config started anyway, serving plaintext") + t.Fatal("a broken TLS config started anyway") } }) } diff --git a/go/internal/ocpp/charger_socket_test.go b/go/internal/ocpp/charger_socket_test.go index 45944e13b..207c8deeb 100644 --- a/go/internal/ocpp/charger_socket_test.go +++ b/go/internal/ocpp/charger_socket_test.go @@ -157,9 +157,10 @@ func dialChargingStation201(t *testing.T, url, id string, setup func(ocpp201.Cha // // freePort hands back a port the kernel just released, and another socket can // take it before Start checks it, or between that check and the library's -// bind. Start fails in the first case; in the second the library gives up on -// that listener without an error, so a listener goroutine that exits early -// means the port was lost. Either way, try fresh ones. +// bind. In the first case Start fails, or for 2.0.1 starts without that +// listener; in the second the library gives up on the listener without an +// error, so a listener goroutine that exits early means the port was lost. +// Either way, try fresh ones. func startOCPP(t *testing.T, cfg Config, tel *telemetry.Store, v201 bool) *Server { t.Helper() const attempts = 5 @@ -177,7 +178,7 @@ func startOCPP(t *testing.T, cfg Config, tel *telemetry.Store, v201 bool) *Serve if err != nil { t.Fatalf("start: %v", err) } - if listening(t, srv) { + if (!v201 || srv.csms != nil) && listening(t, srv) { t.Cleanup(srv.Stop) return srv } diff --git a/go/internal/ocpp/server.go b/go/internal/ocpp/server.go index c566bd800..6769bf6a5 100644 --- a/go/internal/ocpp/server.go +++ b/go/internal/ocpp/server.go @@ -67,12 +67,15 @@ type Server struct { stopOnce sync.Once } -// Start brings up the OCPP CS on the configured bind:port. Returns -// immediately once the listener is up; the WebSocket loop runs in its own +// Start brings up the OCPP CS on the configured bind:port. It returns once +// the ports have been found free; each WebSocket loop runs in its own // goroutine until ctx is cancelled or Stop() is called. // -// An error means no charger can connect, so it is also recorded as the last -// error of each charger the site names, where its device status is read. +// An error means no charger can connect. A 2.0.1 port that cannot be opened +// is logged instead, and the 1.6 listener still runs for the chargers that +// dial it. Either way the reason is recorded as the last error of each +// charger the site names, where its device status is read; a charger's first +// message on the 1.6 listener clears it. // // The returned Server is the handle for shutdown — main.go is expected to // call Stop() during graceful drain. @@ -84,16 +87,27 @@ func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (_ *Server, e return nil, errors.New("ocpp: nil telemetry store") } cfg.Defaults() + unreachable := func(err error) { + for _, id := range cfg.ApprovedIDs { + tel.RecordDriverError(id, err.Error()) + } + } defer func() { if err != nil { - for _, id := range cfg.ApprovedIDs { - tel.RecordDriverError(id, err.Error()) - } + unreachable(err) } }() - if err := checkPorts(cfg); err != nil { + if err := checkPort(cfg.Port); err != nil { return nil, err } + v201 := cfg.PortV201 > 0 + if v201 { + if err := checkPort(cfg.PortV201); err != nil { + slog.Error("ocpp: 2.0.1 listener not started; chargers that dial it cannot connect", "port", cfg.PortV201, "err", err) + unreachable(err) + v201 = false + } + } auth := newAuthorizer(cfg) sockets := newSocketSessions() @@ -121,7 +135,7 @@ func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (_ *Server, e // OCPP 2.0.1 on its own port, when configured. Same handler and therefore // the same charger state and telemetry — only the message encoding differs. - if cfg.PortV201 > 0 { + if v201 { wsServer201, err := newListener(cfg, auth, sockets) if err != nil { return nil, err @@ -198,29 +212,16 @@ func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (_ *Server, e return s, nil } -// checkPorts opens and closes each enabled port, on every interface as -// ws.Server.Start does. That Start runs in a goroutine and, when its own -// listen fails, returns with the error sent to a logger nobody reads, so a -// taken port has to fail here or the chargers stay away with no reason given. -func checkPorts(cfg *Config) error { - ports := []int{cfg.Port} - if cfg.PortV201 > 0 { - ports = append(ports, cfg.PortV201) - } - var open []net.Listener - defer func() { - for _, l := range open { - l.Close() - } - }() - for _, port := range ports { - l, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) - if err != nil { - return fmt.Errorf("ocpp: %w", err) - } - open = append(open, l) +// checkPort opens and closes port on every interface, as ws.Server.Start +// does. That Start runs in a goroutine and, when its own listen fails, +// returns with the error sent to a logger nobody reads, so a taken port has +// to be found here or the chargers stay away with no reason given. +func checkPort(port int) error { + l, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + if err != nil { + return fmt.Errorf("ocpp: %w", err) } - return nil + return l.Close() } // newListener builds one version's WebSocket server — TLS when configured — diff --git a/go/internal/ocpp/server_test.go b/go/internal/ocpp/server_test.go index 05338b6c6..e8bed69f7 100644 --- a/go/internal/ocpp/server_test.go +++ b/go/internal/ocpp/server_test.go @@ -42,35 +42,56 @@ func startServer(t *testing.T, tel *telemetry.Store, approved ...string) (int, * // carries the reason in its health. The library gives up on the port inside // a goroutine and logs nowhere we read, so without this the chargers stay // away and nothing says why. -func TestStartFailsWhenAPortIsTaken(t *testing.T) { - for _, v201 := range []bool{false, true} { - t.Run(fmt.Sprintf("v201=%v", v201), func(t *testing.T) { - held, err := net.Listen("tcp", ":0") - if err != nil { - t.Fatal(err) - } - defer held.Close() - taken := held.Addr().(*net.TCPAddr).Port - - cfg := &Config{Enabled: true, Bind: "127.0.0.1", Port: taken, ApprovedIDs: []string{"garage"}} - if v201 { - cfg.Port = freePort(t) - cfg.PortV201 = taken - } - tel := telemetry.NewStore() - if _, err := Start(context.Background(), cfg, tel); err == nil { - t.Fatalf("Start succeeded with port %d taken", taken) - } else if !strings.Contains(err.Error(), fmt.Sprint(taken)) { - t.Errorf("error %q does not name port %d", err, taken) - } - h := tel.DriverHealth("garage") - if h == nil || !strings.Contains(h.LastError, fmt.Sprint(taken)) { - t.Fatalf("the charger's health does not say why it cannot connect: %+v", h) - } - }) +func TestStartFailsWhenItsPortIsTaken(t *testing.T) { + taken := holdPort(t) + tel := telemetry.NewStore() + cfg := &Config{Enabled: true, Bind: "127.0.0.1", Port: taken, ApprovedIDs: []string{"garage"}} + if _, err := Start(context.Background(), cfg, tel); err == nil { + t.Fatalf("Start succeeded with port %d taken", taken) + } else if !strings.Contains(err.Error(), fmt.Sprint(taken)) { + t.Errorf("error %q does not name port %d", err, taken) + } + if h := tel.DriverHealth("garage"); h == nil || !strings.Contains(h.LastError, fmt.Sprint(taken)) { + t.Fatalf("the charger's health does not say why it cannot connect: %+v", h) + } +} + +// A taken 2.0.1 port leaves the 1.6 listener running, so the chargers that +// dial 1.6 are still steered. The reason stays on each charger that has not +// connected. +func TestATaken201PortLeavesThe16ListenerRunning(t *testing.T) { + taken := holdPort(t) + tel := telemetry.NewStore() + srv := startOCPP(t, Config{Enabled: true, Bind: "127.0.0.1", PortV201: taken, HeartbeatIntervalS: 60, ApprovedIDs: []string{"garage", "carport"}}, tel, false) + if srv.csms != nil { + t.Fatalf("a 2.0.1 listener started on taken port %d", taken) + } + cp, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), "garage", nil, nil) + if err != nil { + t.Fatalf("a 1.6 charger could not connect: %v", err) + } + if _, err := cp.BootNotification("Home", "Easee"); err != nil { + t.Fatal(err) + } + if h := tel.DriverHealth("garage"); h == nil || h.LastError != "" { + t.Errorf("the connected 1.6 charger still shows an error: %+v", h) + } + if h := tel.DriverHealth("carport"); h == nil || !strings.Contains(h.LastError, fmt.Sprint(taken)) { + t.Errorf("the charger that has not connected does not say why: %+v", h) } } +// holdPort takes a port on every interface until the test ends. +func holdPort(t *testing.T) int { + t.Helper() + l, err := net.Listen("tcp", ":0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { l.Close() }) + return l.Addr().(*net.TCPAddr).Port +} + func TestStopIsConcurrentAndIdempotent(t *testing.T) { _, srv := startServer(t, telemetry.NewStore())