From 79b18ba7be42be70d39eca994fdf0be1e217edc1 Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 1 Dec 2026 21:43:24 +0300 Subject: [PATCH 1/7] Add Unix domain socket support for Firebird 6 --- README.md | 11 +++++++++++ conn_test.go | 36 ++++++++++++++++++++++++++++++++++++ fbconn/config.go | 7 ++++++- fbconn/config_test.go | 15 +++++++++++++++ fbconn/events_channel.go | 35 ++++++++++++++++++++--------------- fbconn/fbconn.go | 6 ++++++ 6 files changed, 94 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 6a798899..098bd473 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,17 @@ func main() { See documentation and more usage examples at https://pkg.go.dev/github.com/firebirdsql/fbx +To connect to Firebird 6 over a Unix domain socket, configure +`RemoteServiceUnixSocket` on the server and pass its path in the connection string: + +```text +user=sysdba password=masterkey socket=/run/firebird/firebird.sock database=employee +``` + +You can also use `?socket=/run/firebird/firebird.sock` in a connection URL or +set the `FBSOCKET` environment variable. A configured socket takes precedence +over TCP connection addresses. + Wire compression is disabled by default. Enable it with `wire_compression=true` in the connection string (`wire_compress` and `wireCompression` are accepted aliases) or with `FBWIRECOMPRESSION=true`. diff --git a/conn_test.go b/conn_test.go index cbcf1e37..8cb24f2a 100644 --- a/conn_test.go +++ b/conn_test.go @@ -16,6 +16,7 @@ import ( "github.com/firebirdsql/fbx" "github.com/firebirdsql/fbx/fbconn" + "github.com/firebirdsql/fbx/fbevent" "github.com/firebirdsql/fbx/fbproto" "github.com/firebirdsql/fbx/fbtype" "github.com/firebirdsql/fbx/fbxtest" @@ -23,6 +24,41 @@ import ( "github.com/stretchr/testify/require" ) +func TestConnectUnixSocket(t *testing.T) { + connString := os.Getenv("FBX_TEST_UNIX_DATABASE") + if connString == "" { + t.Skip("set FBX_TEST_UNIX_DATABASE to a Firebird 6 connection string with socket configured") + } + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn, err := fbx.Connect(ctx, connString) + require.NoError(t, err) + defer closeConn(t, conn) + + var protocol string + err = conn.QueryRow(ctx, "select rdb$get_context('SYSTEM', 'NETWORK_PROTOCOL') from rdb$database").Scan(&protocol) + require.NoError(t, err) + require.Equal(t, "UNIX", protocol) + + manager, err := fbevent.Connect(ctx, connString) + require.NoError(t, err) + defer func() { require.NoError(t, manager.Close(context.Background())) }() + + subscription, err := manager.Subscribe("fbx_unix_socket_test", 1) + require.NoError(t, err) + defer func() { require.NoError(t, subscription.Close()) }() + + _, err = conn.Exec(ctx, "execute block as begin post_event 'fbx_unix_socket_test'; end") + require.NoError(t, err) + select { + case event := <-subscription.Events(): + require.Equal(t, "fbx_unix_socket_test", event.EventName) + case <-ctx.Done(): + t.Fatal("did not receive Firebird event over Unix socket") + } +} + func TestConnect(t *testing.T) { t.Parallel() diff --git a/fbconn/config.go b/fbconn/config.go index c5f46cbe..8f84ed1e 100644 --- a/fbconn/config.go +++ b/fbconn/config.go @@ -30,6 +30,7 @@ const DefaultFetchBatchSize = 400 type Config struct { Host string Port uint16 + Socket string // Unix socket path. When set, it takes precedence over Host, Port, and Fallbacks. Database string CreateDatabase bool User string @@ -266,6 +267,7 @@ func NetworkAddress(host string, port uint16) (network, address string) { // // # Keyword/Value // user=sysdba password=masterkey host=localhost port=3050 database=employee.fdb +// user=sysdba password=masterkey socket=/run/firebird/firebird.sock database=employee // user=sysdba password=masterkey host=localhost port=3050 database=new.fdb create_database=true // // # URL @@ -275,7 +277,7 @@ func NetworkAddress(host string, port uint16) (network, address string) { // // ParseConfig recognizes the following environment variables (and their equivalents in the connection string): // -// FBHOST, FBPORT, FBDATABASE, FBUSER, FBPASSWORD +// FBHOST, FBPORT, FBSOCKET, FBDATABASE, FBUSER, FBPASSWORD // FBAPPNAME, FBTZ, FBCONNECT_TIMEOUT, FBFETCH_BATCH_SIZE, FBWIRECOMPRESSION // FBTARGETSESSIONATTRS, FBOPTIONS // @@ -352,6 +354,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con config := &Config{ createdByParseConfig: true, + Socket: settings["socket"], Database: settings["database"], CreateDatabase: convertToBool(settings["create_database"], false), User: settings["user"], @@ -452,6 +455,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con notRuntimeParams := map[string]struct{}{ "host": {}, "port": {}, + "socket": {}, "database": {}, "create_database": {}, "user": {}, @@ -561,6 +565,7 @@ func parseEnvSettings() map[string]string { nameMap := map[string]string{ "FBHOST": "host", "FBPORT": "port", + "FBSOCKET": "socket", "FBDATABASE": "database", "FBUSER": "user", "FBPASSWORD": "password", diff --git a/fbconn/config_test.go b/fbconn/config_test.go index e610c39f..822e7c05 100644 --- a/fbconn/config_test.go +++ b/fbconn/config_test.go @@ -648,6 +648,21 @@ func TestConfigCopyCanBeUsedToConnect(t *testing.T) { assert.NoError(t, err) } +func TestParseConfigUnixSocket(t *testing.T) { + const socket = "/run/firebird/firebird.sock" + + for _, connString := range []string{ + "socket=" + socket + " database=employee", + "firebird://localhost/employee?socket=" + socket, + } { + config, err := fbconn.ParseConfig(connString) + require.NoError(t, err) + assert.Equal(t, socket, config.Socket) + assert.Equal(t, "employee", config.Database) + assert.NotContains(t, config.RuntimeParams, "socket") + } +} + func TestNetworkAddress(t *testing.T) { tests := []struct { name string diff --git a/fbconn/events_channel.go b/fbconn/events_channel.go index 2f0ea9b5..346d9ff5 100644 --- a/fbconn/events_channel.go +++ b/fbconn/events_channel.go @@ -42,7 +42,7 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er return channel, nil } - existingChannel, auxPort, err := fbConn.requestAuxEventPort(ctx) + existingChannel, network, address, err := fbConn.requestAuxEventAddress(ctx) if err != nil { return nil, err } @@ -50,9 +50,7 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er return existingChannel, nil } - host := fbConn.eventDialHost() - address := net.JoinHostPort(host, strconv.Itoa(auxPort)) - auxConn, err := fbConn.config.DialFunc(ctx, "tcp", address) + auxConn, err := fbConn.config.DialFunc(ctx, network, address) if err != nil { return nil, err } @@ -78,16 +76,16 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er return channel, nil } -func (fbConn *FbConn) requestAuxEventPort(ctx context.Context) (*eventChannel, int, error) { +func (fbConn *FbConn) requestAuxEventAddress(ctx context.Context) (*eventChannel, string, string, error) { if err := fbConn.lockEventOperation(ctx); err != nil { - return nil, 0, err + return nil, "", "", err } defer fbConn.unlock() if ctx != context.Background() { select { case <-ctx.Done(): - return nil, 0, newContextAlreadyDoneError(ctx) + return nil, "", "", newContextAlreadyDoneError(ctx) default: } fbConn.contextWatcher.Watch(ctx) @@ -98,35 +96,42 @@ func (fbConn *FbConn) requestAuxEventPort(ctx context.Context) (*eventChannel, i channel := fbConn.eventChannel fbConn.eventMu.Unlock() if channel != nil { - return channel, 0, nil + return channel, "", "", nil } if err := fbConn.client.WriteMessage(&fbproto.OpConnectRequest{}); err != nil { fbConn.asyncClose() - return nil, 0, err + return nil, "", "", err } if err := fbConn.flushWithPotentialWriteReadDeadlock(); err != nil { fbConn.asyncClose() - return nil, 0, err + return nil, "", "", err } msg, err := fbConn.receiveMessage() if err != nil { fbConn.asyncCloseAfterRead(err) - return nil, 0, normalizeTimeoutError(ctx, err) + return nil, "", "", normalizeTimeoutError(ctx, err) } switch m := msg.(type) { case *fbproto.OpResponse: + if fbConn.eventNetwork == "unix" { + // Firebird sends the auxiliary socket path as raw bytes for Unix connections. + if len(m.Data) == 0 { + return nil, "", "", errors.New("empty auxiliary event socket path") + } + return nil, "unix", string(m.Data), nil + } auxPort, parseErr := parseAuxEventPort(m.Data) if parseErr != nil { - return nil, 0, parseErr + return nil, "", "", parseErr } - return nil, auxPort, nil + return nil, "tcp", net.JoinHostPort(fbConn.eventDialHost(), strconv.Itoa(auxPort)), nil case *fbproto.ErrorResponse: - return nil, 0, ErrorResponseToFbError(m) + return nil, "", "", ErrorResponseToFbError(m) default: - return nil, 0, fmt.Errorf("unexpected response message type %T while requesting event channel", m) + return nil, "", "", fmt.Errorf("unexpected response message type %T while requesting event channel", m) } } diff --git a/fbconn/fbconn.go b/fbconn/fbconn.go index e55a22e1..b0774bf7 100644 --- a/fbconn/fbconn.go +++ b/fbconn/fbconn.go @@ -107,6 +107,7 @@ type FbConn struct { eventChannel *eventChannel eventHandles map[int]*EventHandle eventHost string + eventNetwork string eventErr error // eventErrHandler is notified when the first asynchronous event-channel // error is captured. It should be non-blocking and thread-safe. @@ -553,6 +554,10 @@ func (fbConn *FbConn) sendContAuth(authData []byte, pluginName string, pluginLis // slice of successfully resolved connectOneConfigs and a slice of errors. It is possible for both slices to contain // values if some hosts were successfully resolved and others were not. func buildConnectOneConfigs(ctx context.Context, config *Config) ([]*connectOneConfig, []error) { + if config.Socket != "" { + return []*connectOneConfig{{network: "unix", address: config.Socket}}, nil + } + // Simplify usage by treating primary config and fallbacks the same. fallbackConfigs := []*FallbackConfig{ { @@ -692,6 +697,7 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo fbConn := new(FbConn) fbConn.config = config fbConn.target = target + fbConn.eventNetwork = connectConfig.network fbConn.eventHost = connectConfig.originalHostname if fbConn.eventHost == "" { fbConn.eventHost = config.Host From 2e8ea923b9186b328dd72668b45416852509e76b Mon Sep 17 00:00:00 2001 From: Pavel Date: Wed, 2 Dec 2026 15:55:35 +0300 Subject: [PATCH 2/7] Use host paths for Unix sockets and preserve connection fallbacks --- README.md | 8 ++------ conn_test.go | 36 ------------------------------------ fbconn/config.go | 18 +++++------------- fbconn/config_test.go | 29 ++++++++++------------------- fbconn/events_channel.go | 35 ++++++++++++++++++----------------- fbconn/fbconn.go | 9 --------- fbconn/fbconn_test.go | 13 ++++++++++++- 7 files changed, 47 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index 098bd473..fb02e576 100644 --- a/README.md +++ b/README.md @@ -86,16 +86,12 @@ func main() { See documentation and more usage examples at https://pkg.go.dev/github.com/firebirdsql/fbx To connect to Firebird 6 over a Unix domain socket, configure -`RemoteServiceUnixSocket` on the server and pass its path in the connection string: +`RemoteServiceUnixSocket` on the server and use its absolute path as the host. ```text -user=sysdba password=masterkey socket=/run/firebird/firebird.sock database=employee +user=sysdba password=masterkey host=/run/firebird/firebird.sock database=employee ``` -You can also use `?socket=/run/firebird/firebird.sock` in a connection URL or -set the `FBSOCKET` environment variable. A configured socket takes precedence -over TCP connection addresses. - Wire compression is disabled by default. Enable it with `wire_compression=true` in the connection string (`wire_compress` and `wireCompression` are accepted aliases) or with `FBWIRECOMPRESSION=true`. diff --git a/conn_test.go b/conn_test.go index 8cb24f2a..cbcf1e37 100644 --- a/conn_test.go +++ b/conn_test.go @@ -16,7 +16,6 @@ import ( "github.com/firebirdsql/fbx" "github.com/firebirdsql/fbx/fbconn" - "github.com/firebirdsql/fbx/fbevent" "github.com/firebirdsql/fbx/fbproto" "github.com/firebirdsql/fbx/fbtype" "github.com/firebirdsql/fbx/fbxtest" @@ -24,41 +23,6 @@ import ( "github.com/stretchr/testify/require" ) -func TestConnectUnixSocket(t *testing.T) { - connString := os.Getenv("FBX_TEST_UNIX_DATABASE") - if connString == "" { - t.Skip("set FBX_TEST_UNIX_DATABASE to a Firebird 6 connection string with socket configured") - } - - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - conn, err := fbx.Connect(ctx, connString) - require.NoError(t, err) - defer closeConn(t, conn) - - var protocol string - err = conn.QueryRow(ctx, "select rdb$get_context('SYSTEM', 'NETWORK_PROTOCOL') from rdb$database").Scan(&protocol) - require.NoError(t, err) - require.Equal(t, "UNIX", protocol) - - manager, err := fbevent.Connect(ctx, connString) - require.NoError(t, err) - defer func() { require.NoError(t, manager.Close(context.Background())) }() - - subscription, err := manager.Subscribe("fbx_unix_socket_test", 1) - require.NoError(t, err) - defer func() { require.NoError(t, subscription.Close()) }() - - _, err = conn.Exec(ctx, "execute block as begin post_event 'fbx_unix_socket_test'; end") - require.NoError(t, err) - select { - case event := <-subscription.Events(): - require.Equal(t, "fbx_unix_socket_test", event.EventName) - case <-ctx.Done(): - t.Fatal("did not receive Firebird event over Unix socket") - } -} - func TestConnect(t *testing.T) { t.Parallel() diff --git a/fbconn/config.go b/fbconn/config.go index 8f84ed1e..17c184b1 100644 --- a/fbconn/config.go +++ b/fbconn/config.go @@ -30,7 +30,6 @@ const DefaultFetchBatchSize = 400 type Config struct { Host string Port uint16 - Socket string // Unix socket path. When set, it takes precedence over Host, Port, and Fallbacks. Database string CreateDatabase bool User string @@ -241,16 +240,12 @@ func isAbsolutePath(path string) bool { } // NetworkAddress converts host and port into network and address suitable for use with net.Dial. -// If host is an absolute path, it falls back to a local TCP connection using the provided port. +// An absolute host path identifies a Unix domain socket. func NetworkAddress(host string, port uint16) (network, address string) { if isAbsolutePath(host) { - network = "tcp" - address = net.JoinHostPort("localhost", strconv.Itoa(int(port))) - } else { - network = "tcp" - address = net.JoinHostPort(host, strconv.Itoa(int(port))) + return "unix", host } - return network, address + return "tcp", net.JoinHostPort(host, strconv.Itoa(int(port))) } // ParseConfig builds a *Config from connString. @@ -267,7 +262,7 @@ func NetworkAddress(host string, port uint16) (network, address string) { // // # Keyword/Value // user=sysdba password=masterkey host=localhost port=3050 database=employee.fdb -// user=sysdba password=masterkey socket=/run/firebird/firebird.sock database=employee +// user=sysdba password=masterkey host=/run/firebird/firebird.sock database=employee // user=sysdba password=masterkey host=localhost port=3050 database=new.fdb create_database=true // // # URL @@ -277,7 +272,7 @@ func NetworkAddress(host string, port uint16) (network, address string) { // // ParseConfig recognizes the following environment variables (and their equivalents in the connection string): // -// FBHOST, FBPORT, FBSOCKET, FBDATABASE, FBUSER, FBPASSWORD +// FBHOST, FBPORT, FBDATABASE, FBUSER, FBPASSWORD // FBAPPNAME, FBTZ, FBCONNECT_TIMEOUT, FBFETCH_BATCH_SIZE, FBWIRECOMPRESSION // FBTARGETSESSIONATTRS, FBOPTIONS // @@ -354,7 +349,6 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con config := &Config{ createdByParseConfig: true, - Socket: settings["socket"], Database: settings["database"], CreateDatabase: convertToBool(settings["create_database"], false), User: settings["user"], @@ -455,7 +449,6 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con notRuntimeParams := map[string]struct{}{ "host": {}, "port": {}, - "socket": {}, "database": {}, "create_database": {}, "user": {}, @@ -565,7 +558,6 @@ func parseEnvSettings() map[string]string { nameMap := map[string]string{ "FBHOST": "host", "FBPORT": "port", - "FBSOCKET": "socket", "FBDATABASE": "database", "FBUSER": "user", "FBPASSWORD": "password", diff --git a/fbconn/config_test.go b/fbconn/config_test.go index 822e7c05..8bc3bc61 100644 --- a/fbconn/config_test.go +++ b/fbconn/config_test.go @@ -648,21 +648,6 @@ func TestConfigCopyCanBeUsedToConnect(t *testing.T) { assert.NoError(t, err) } -func TestParseConfigUnixSocket(t *testing.T) { - const socket = "/run/firebird/firebird.sock" - - for _, connString := range []string{ - "socket=" + socket + " database=employee", - "firebird://localhost/employee?socket=" + socket, - } { - config, err := fbconn.ParseConfig(connString) - require.NoError(t, err) - assert.Equal(t, socket, config.Socket) - assert.Equal(t, "employee", config.Database) - assert.NotContains(t, config.RuntimeParams, "socket") - } -} - func TestNetworkAddress(t *testing.T) { tests := []struct { name string @@ -672,11 +657,17 @@ func TestNetworkAddress(t *testing.T) { wantAddress string }{ { - name: "Absolute local database path uses provided port", - host: "/var/lib/firebird/data/employee.fdb", + name: "Unix socket path", + host: "/run/firebird/firebird.sock", port: 3051, - wantNet: "tcp", - wantAddress: "localhost:3051", + wantNet: "unix", + wantAddress: "/run/firebird/firebird.sock", + }, + { + name: "Windows Unix socket path", + host: `C:\firebird\firebird.sock`, + wantNet: "unix", + wantAddress: `C:\firebird\firebird.sock`, }, { name: "Assume TCP for unknown formats", diff --git a/fbconn/events_channel.go b/fbconn/events_channel.go index 346d9ff5..02764da1 100644 --- a/fbconn/events_channel.go +++ b/fbconn/events_channel.go @@ -7,7 +7,6 @@ import ( "fmt" "io" "net" - "strconv" "sync" "github.com/firebirdsql/fbx/fbproto" @@ -42,7 +41,7 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er return channel, nil } - existingChannel, network, address, err := fbConn.requestAuxEventAddress(ctx) + existingChannel, host, port, err := fbConn.requestAuxEventAddress(ctx) if err != nil { return nil, err } @@ -50,6 +49,7 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er return existingChannel, nil } + network, address := NetworkAddress(host, port) auxConn, err := fbConn.config.DialFunc(ctx, network, address) if err != nil { return nil, err @@ -76,16 +76,16 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er return channel, nil } -func (fbConn *FbConn) requestAuxEventAddress(ctx context.Context) (*eventChannel, string, string, error) { +func (fbConn *FbConn) requestAuxEventAddress(ctx context.Context) (*eventChannel, string, uint16, error) { if err := fbConn.lockEventOperation(ctx); err != nil { - return nil, "", "", err + return nil, "", 0, err } defer fbConn.unlock() if ctx != context.Background() { select { case <-ctx.Done(): - return nil, "", "", newContextAlreadyDoneError(ctx) + return nil, "", 0, newContextAlreadyDoneError(ctx) default: } fbConn.contextWatcher.Watch(ctx) @@ -96,42 +96,43 @@ func (fbConn *FbConn) requestAuxEventAddress(ctx context.Context) (*eventChannel channel := fbConn.eventChannel fbConn.eventMu.Unlock() if channel != nil { - return channel, "", "", nil + return channel, "", 0, nil } if err := fbConn.client.WriteMessage(&fbproto.OpConnectRequest{}); err != nil { fbConn.asyncClose() - return nil, "", "", err + return nil, "", 0, err } if err := fbConn.flushWithPotentialWriteReadDeadlock(); err != nil { fbConn.asyncClose() - return nil, "", "", err + return nil, "", 0, err } msg, err := fbConn.receiveMessage() if err != nil { fbConn.asyncCloseAfterRead(err) - return nil, "", "", normalizeTimeoutError(ctx, err) + return nil, "", 0, normalizeTimeoutError(ctx, err) } switch m := msg.(type) { case *fbproto.OpResponse: - if fbConn.eventNetwork == "unix" { + if isAbsolutePath(fbConn.eventHost) { // Firebird sends the auxiliary socket path as raw bytes for Unix connections. - if len(m.Data) == 0 { - return nil, "", "", errors.New("empty auxiliary event socket path") + path := string(m.Data) + if !isAbsolutePath(path) { + return nil, "", 0, errors.New("invalid auxiliary event socket path") } - return nil, "unix", string(m.Data), nil + return nil, path, 0, nil } auxPort, parseErr := parseAuxEventPort(m.Data) if parseErr != nil { - return nil, "", "", parseErr + return nil, "", 0, parseErr } - return nil, "tcp", net.JoinHostPort(fbConn.eventDialHost(), strconv.Itoa(auxPort)), nil + return nil, fbConn.eventDialHost(), uint16(auxPort), nil case *fbproto.ErrorResponse: - return nil, "", "", ErrorResponseToFbError(m) + return nil, "", 0, ErrorResponseToFbError(m) default: - return nil, "", "", fmt.Errorf("unexpected response message type %T while requesting event channel", m) + return nil, "", 0, fmt.Errorf("unexpected response message type %T while requesting event channel", m) } } diff --git a/fbconn/fbconn.go b/fbconn/fbconn.go index b0774bf7..bc6b35d6 100644 --- a/fbconn/fbconn.go +++ b/fbconn/fbconn.go @@ -107,7 +107,6 @@ type FbConn struct { eventChannel *eventChannel eventHandles map[int]*EventHandle eventHost string - eventNetwork string eventErr error // eventErrHandler is notified when the first asynchronous event-channel // error is captured. It should be non-blocking and thread-safe. @@ -554,10 +553,6 @@ func (fbConn *FbConn) sendContAuth(authData []byte, pluginName string, pluginLis // slice of successfully resolved connectOneConfigs and a slice of errors. It is possible for both slices to contain // values if some hosts were successfully resolved and others were not. func buildConnectOneConfigs(ctx context.Context, config *Config) ([]*connectOneConfig, []error) { - if config.Socket != "" { - return []*connectOneConfig{{network: "unix", address: config.Socket}}, nil - } - // Simplify usage by treating primary config and fallbacks the same. fallbackConfigs := []*FallbackConfig{ { @@ -697,14 +692,10 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo fbConn := new(FbConn) fbConn.config = config fbConn.target = target - fbConn.eventNetwork = connectConfig.network fbConn.eventHost = connectConfig.originalHostname if fbConn.eventHost == "" { fbConn.eventHost = config.Host } - if isAbsolutePath(fbConn.eventHost) { - fbConn.eventHost = "localhost" - } fbConn.cleanupDone = make(chan struct{}) fbConn.customData = make(map[string]any) fbConn.activeTransactions = make(map[*FBTransaction]struct{}) diff --git a/fbconn/fbconn_test.go b/fbconn/fbconn_test.go index 8814e089..ea1951bb 100644 --- a/fbconn/fbconn_test.go +++ b/fbconn/fbconn_test.go @@ -29,6 +29,7 @@ func TestConnect(t *testing.T) { env string }{ {"TCP", "FBX_TEST_DATABASE"}, + {"Unix", "FBX_TEST_UNIX_SOCKET_DATABASE"}, } for _, tt := range tests { @@ -44,8 +45,18 @@ func TestConnect(t *testing.T) { conn, err := fbconn.Connect(ctx, connString) require.NoError(t, err) + defer closeConn(t, conn) - closeConn(t, conn) + if tt.name == "Unix" { + if conn.ServerVersion().Major < 6 { + t.Skip("Unix domain sockets require Firebird 6 or later") + } + result := conn.Exec(ctx, "select rdb$get_context('SYSTEM', 'NETWORK_PROTOCOL') from rdb$database").Read() + require.NoError(t, result.Err) + require.Len(t, result.Rows, 1) + require.Len(t, result.Rows[0], 1) + require.Equal(t, "UNIX", string(result.Rows[0][0])) + } }) } } From 62517c10e233f4491dcf03d269470eb563b8a7ea Mon Sep 17 00:00:00 2001 From: Pavel <113603127+Pavlushechko@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:42:13 +0300 Subject: [PATCH 3/7] Test Unix socket managers and enable Red Database 6 CI --- .github/workflows/go.yml | 13 ++++++++++--- README.md | 2 ++ fbconn/config.go | 1 + fbconn/parse_url_test.go | 15 +++++++++++++++ fbevent/manager_integration_test.go | 26 ++++++++++++++++++++++++++ fbservice/manager_integration_test.go | 22 ++++++++++++++++++++++ fbxtest/fbxtest.go | 26 ++++++++++++++++++++++++++ 7 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 fbservice/manager_integration_test.go diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index cbb9c966..1e2381c9 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -84,13 +84,20 @@ jobs: ./installer --mode unattended --sysdba_password masterkey echo Configure RDB cp ci/firebird.conf ci/fbtrace.conf /opt/RedDatabase + service_action=start + if [ "${{ matrix.RDB_PROJECT }}" = "rdb60" ]; then + socket=/tmp/fbx-firebird.sock + printf '\nRemoteServiceUnixSocket = %s\n' "$socket" >> /opt/RedDatabase/firebird.conf + printf 'FBX_TEST_UNIX_SOCKET_DATABASE=database=employee host=%s user=sysdba password=masterkey\n' "$socket" >> "$GITHUB_ENV" + service_action=restart + fi g++ -o libfbxci.so -shared -fPIC ci/udrs.cpp -I/opt/RedDatabase/include cp libfbxci.so /opt/RedDatabase/plugins/udr echo Start RDB if [ -e /etc/init.d/reddatabase ]; then - /etc/init.d/reddatabase start + /etc/init.d/reddatabase "$service_action" else - /etc/init.d/firebird start + /etc/init.d/firebird "$service_action" fi else echo Install dependencies @@ -168,4 +175,4 @@ jobs: with: file: coverage.xml language: Go - label: code-coverage/gotest \ No newline at end of file + label: code-coverage/gotest diff --git a/README.md b/README.md index fb02e576..a9c2fea3 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,8 @@ To connect to Firebird 6 over a Unix domain socket, configure user=sysdba password=masterkey host=/run/firebird/firebird.sock database=employee ``` +In a URI, use `firebird:///employee?host=/run/firebird/firebird.sock`. + Wire compression is disabled by default. Enable it with `wire_compression=true` in the connection string (`wire_compress` and `wireCompression` are accepted aliases) or with `FBWIRECOMPRESSION=true`. diff --git a/fbconn/config.go b/fbconn/config.go index 17c184b1..515b9304 100644 --- a/fbconn/config.go +++ b/fbconn/config.go @@ -268,6 +268,7 @@ func NetworkAddress(host string, port uint16) (network, address string) { // # URL // // firebird://sysdba:masterkey@localhost:3050/employee.fdb +// firebird://sysdba:masterkey@/employee?host=/run/firebird/firebird.sock // firebird://sysdba:masterkey@localhost:3050/new.fdb?create_database=true // // ParseConfig recognizes the following environment variables (and their equivalents in the connection string): diff --git a/fbconn/parse_url_test.go b/fbconn/parse_url_test.go index d33d6106..a6e61f9e 100644 --- a/fbconn/parse_url_test.go +++ b/fbconn/parse_url_test.go @@ -83,6 +83,21 @@ func TestParseConfigURIHostPorts(t *testing.T) { hosts: []string{"localhost"}, ports: []uint16{3060}, }, + { + query: "?host=/run/firebird/firebird.sock", + hosts: []string{"/run/firebird/firebird.sock"}, + ports: []uint16{3060}, + }, + { + query: `?host=C:\firebird\firebird.sock`, + hosts: []string{`C:\firebird\firebird.sock`}, + ports: []uint16{3060}, + }, + { + list: "%2Frun%2Ffirebird%2Ffirebird.sock", + hosts: []string{"/run/firebird/firebird.sock"}, + ports: []uint16{3060}, + }, } for _, scheme := range []string{"firebird", "firebirdsql"} { diff --git a/fbevent/manager_integration_test.go b/fbevent/manager_integration_test.go index dbccab53..f630fe81 100644 --- a/fbevent/manager_integration_test.go +++ b/fbevent/manager_integration_test.go @@ -14,11 +14,37 @@ import ( "github.com/firebirdsql/fbx/fbconn" "github.com/firebirdsql/fbx/fbevent" "github.com/firebirdsql/fbx/fbproto" + "github.com/firebirdsql/fbx/fbxtest" "github.com/stretchr/testify/require" ) var eventNameCounter atomic.Uint64 +func TestManagerUnixSocket(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + connString := fbxtest.RequireUnixSocketDatabase(ctx, t) + manager, err := fbevent.Connect(ctx, connString) + require.NoError(t, err) + defer func() { require.NoError(t, manager.Close(context.Background())) }() + + eventName := nextEventName("UNIX") + sub, err := manager.Subscribe(eventName, 1) + require.NoError(t, err) + defer func() { require.NoError(t, sub.Close()) }() + + notifier, err := fbx.Connect(ctx, connString) + require.NoError(t, err) + defer func() { require.NoError(t, notifier.Close(context.Background())) }() + require.NoError(t, postEvents(ctx, notifier, eventName)) + select { + case event := <-sub.Events(): + require.Equal(t, eventName, event.EventName) + case <-ctx.Done(): + t.Fatal("timed out waiting for Unix socket event") + } +} + func TestManagerWaitForEventTimeout(t *testing.T) { connString := requireIntegrationConnString(t) diff --git a/fbservice/manager_integration_test.go b/fbservice/manager_integration_test.go new file mode 100644 index 00000000..53b66e9a --- /dev/null +++ b/fbservice/manager_integration_test.go @@ -0,0 +1,22 @@ +package fbservice_test + +import ( + "context" + "io" + "testing" + "time" + + "github.com/firebirdsql/fbx/fbservice" + "github.com/firebirdsql/fbx/fbxtest" + "github.com/stretchr/testify/require" +) + +func TestManagerUnixSocket(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + connString := fbxtest.RequireUnixSocketDatabase(ctx, t) + + manager, err := fbservice.NewManager(connString) + require.NoError(t, err) + require.NoError(t, manager.TraceList(ctx, fbservice.TraceOptions{Output: io.Discard})) +} diff --git a/fbxtest/fbxtest.go b/fbxtest/fbxtest.go index 64be5b56..c6e985da 100644 --- a/fbxtest/fbxtest.go +++ b/fbxtest/fbxtest.go @@ -4,13 +4,39 @@ package fbxtest import ( "context" "fmt" + "os" "reflect" "testing" "github.com/firebirdsql/fbx" + "github.com/firebirdsql/fbx/fbconn" "github.com/stretchr/testify/require" ) +// RequireUnixSocketDatabase returns the Unix socket test DSN for a server +// supporting Unix sockets. If present, FBX_TEST_DATABASE must point to the +// same server and is used to check its version before trying the socket. +func RequireUnixSocketDatabase(ctx context.Context, t testing.TB) string { + t.Helper() + connString := os.Getenv("FBX_TEST_UNIX_SOCKET_DATABASE") + if connString == "" { + t.Skip("set FBX_TEST_UNIX_SOCKET_DATABASE to test Unix socket connections") + } + + probe := os.Getenv("FBX_TEST_DATABASE") + if probe == "" { + probe = connString + } + conn, err := fbconn.Connect(ctx, probe) + require.NoError(t, err) + version := conn.ServerVersion() + require.NoError(t, conn.Close(ctx)) + if version.Major < 6 { + t.Skipf("Unix domain sockets require server version 6 or later, found %s", version) + } + return connString +} + var AllQueryExecModes = []fbx.QueryExecMode{ fbx.QueryExecModeCacheStatement, fbx.QueryExecModeExec, From 8a0fc946be085f78a16fe57de65f869fa96f4790 Mon Sep 17 00:00:00 2001 From: Pavel <113603127+Pavlushechko@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:57:18 +0300 Subject: [PATCH 4/7] Preserve the event host when reconstructing a connection --- fbconn/events_internal_test.go | 32 ++++++++++++++++++++++++++++++++ fbconn/fbconn.go | 3 +++ 2 files changed, 35 insertions(+) diff --git a/fbconn/events_internal_test.go b/fbconn/events_internal_test.go index 279c8c9e..ea11194f 100644 --- a/fbconn/events_internal_test.go +++ b/fbconn/events_internal_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "os" "testing" "time" @@ -20,6 +21,37 @@ func (h *testEventHandler) EventOccurred(*EventHandle) { h.calls++ } +func TestQueueEventAfterConstructUnix(t *testing.T) { + connString := os.Getenv("FBX_TEST_UNIX_SOCKET_DATABASE") + if connString == "" { + t.Skip("set FBX_TEST_UNIX_SOCKET_DATABASE to test Unix socket connections") + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + conn, err := Connect(ctx, connString) + require.NoError(t, err) + defer func() { require.NoError(t, conn.Close(ctx)) }() + if conn.ServerVersion().Major < 6 { + t.Skip("Unix domain sockets require Firebird 6 or later") + } + + require.NoError(t, conn.SyncConn(ctx)) + hijacked, err := conn.Hijack() + require.NoError(t, err) + restored, err := Construct(hijacked) + if err != nil { + require.NoError(t, hijacked.Conn.Close()) + } + require.NoError(t, err) + defer func() { require.NoError(t, restored.Close(ctx)) }() + + handle, err := restored.CreateEventHandle("FBX_CONSTRUCT_UNIX", &testEventHandler{}) + require.NoError(t, err) + require.NoError(t, restored.QueueEvent(ctx, handle)) + require.NoError(t, restored.CancelEvent(ctx, handle)) +} + func TestEventHandleToEventBlockAndCount(t *testing.T) { t.Parallel() diff --git a/fbconn/fbconn.go b/fbconn/fbconn.go index bc6b35d6..59deb91f 100644 --- a/fbconn/fbconn.go +++ b/fbconn/fbconn.go @@ -3204,6 +3204,7 @@ type HijackedConn struct { InlineBlobSize int Config *Config CustomData map[string]any + eventHost string // host or socket path selected when the connection was opened } // Hijack extracts the internal connection data. fbConn must be in an idle state with no active transactions, @@ -3244,6 +3245,7 @@ func (fbConn *FbConn) Hijack() (*HijackedConn, error) { InlineBlobSize: fbConn.inlineBlobSize, Config: fbConn.config, CustomData: fbConn.customData, + eventHost: fbConn.eventHost, }, nil } @@ -3272,6 +3274,7 @@ func Construct(hc *HijackedConn) (*FbConn, error) { inlineBlobSize: hc.InlineBlobSize, config: hc.Config, customData: hc.CustomData, + eventHost: hc.eventHost, Encoding: hc.Client.Encoding, status: connStatusIdle, From 18f77664db9489bdd6b29238a140da9bf1da1181 Mon Sep 17 00:00:00 2001 From: Pavel <113603127+Pavlushechko@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:32:27 +0300 Subject: [PATCH 5/7] Abort failed auxiliary connects to prevent subsequent requests from hanging --- fbconn/events_channel.go | 51 +++++--- fbconn/events_integration_test.go | 41 +++++++ fbconn/events_internal_test.go | 187 +++++++++++++++++++++++++----- fbproto/op_connect_request.go | 7 ++ 4 files changed, 240 insertions(+), 46 deletions(-) create mode 100644 fbconn/events_integration_test.go diff --git a/fbconn/events_channel.go b/fbconn/events_channel.go index 02764da1..3a8003a5 100644 --- a/fbconn/events_channel.go +++ b/fbconn/events_channel.go @@ -8,6 +8,7 @@ import ( "io" "net" "sync" + "time" "github.com/firebirdsql/fbx/fbproto" "github.com/firebirdsql/fbx/fbproto/vax" @@ -41,6 +42,13 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er return channel, nil } + // Keep the main connection busy until the server accepts the auxiliary + // connection or we cancel it. + if err := fbConn.lockEventOperation(ctx); err != nil { + return nil, err + } + defer fbConn.unlock() + existingChannel, host, port, err := fbConn.requestAuxEventAddress(ctx) if err != nil { return nil, err @@ -52,19 +60,12 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er network, address := NetworkAddress(host, port) auxConn, err := fbConn.config.DialFunc(ctx, network, address) if err != nil { + fbConn.abortAuxEventConnection() return nil, err } channel = newEventChannel(auxConn) fbConn.eventMu.Lock() - if fbConn.eventChannel != nil { - existingChannel = fbConn.eventChannel - fbConn.eventMu.Unlock() - if closeErr := channel.close(); closeErr != nil { - fbConn.setEventError(fmt.Errorf("event channel close failed: %w", closeErr)) - } - return existingChannel, nil - } fbConn.eventChannel = channel fbConn.eventErr = nil if fbConn.eventHandles == nil { @@ -77,11 +78,6 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er } func (fbConn *FbConn) requestAuxEventAddress(ctx context.Context) (*eventChannel, string, uint16, error) { - if err := fbConn.lockEventOperation(ctx); err != nil { - return nil, "", 0, err - } - defer fbConn.unlock() - if ctx != context.Background() { select { case <-ctx.Done(): @@ -99,11 +95,9 @@ func (fbConn *FbConn) requestAuxEventAddress(ctx context.Context) (*eventChannel return channel, "", 0, nil } - if err := fbConn.client.WriteMessage(&fbproto.OpConnectRequest{}); err != nil { - fbConn.asyncClose() - return nil, "", 0, err - } - if err := fbConn.flushWithPotentialWriteReadDeadlock(); err != nil { + if err := fbConn.withWriteLockAndFlush(func() error { + return fbConn.client.WriteMessage(&fbproto.OpConnectRequest{}) + }); err != nil { fbConn.asyncClose() return nil, "", 0, err } @@ -120,22 +114,43 @@ func (fbConn *FbConn) requestAuxEventAddress(ctx context.Context) (*eventChannel // Firebird sends the auxiliary socket path as raw bytes for Unix connections. path := string(m.Data) if !isAbsolutePath(path) { + fbConn.abortAuxEventConnection() return nil, "", 0, errors.New("invalid auxiliary event socket path") } return nil, path, 0, nil } auxPort, parseErr := parseAuxEventPort(m.Data) if parseErr != nil { + fbConn.abortAuxEventConnection() return nil, "", 0, parseErr } return nil, fbConn.eventDialHost(), uint16(auxPort), nil case *fbproto.ErrorResponse: return nil, "", 0, ErrorResponseToFbError(m) default: + fbConn.asyncClose() return nil, "", 0, fmt.Errorf("unexpected response message type %T while requesting event channel", m) } } +// abortAuxEventConnection is called with the connection locked after the server +// has supplied an auxiliary address. The main connection is discarded even +// when the server does not support aborting the pending accept. +func (fbConn *FbConn) abortAuxEventConnection() { + defer fbConn.asyncClose() + if fbConn.protocolVersion < fbproto.PROTOCOL_VERSION13 { + return + } + + fbConn.contextWatcher.Unwatch() + if err := fbConn.conn.SetWriteDeadline(time.Now().Add(cleanupGracePeriod)); err != nil { + return + } + _ = fbConn.withWriteLockAndFlush(func() error { + return fbConn.client.WriteMessage(&fbproto.OpAbortAuxConnection{}) + }) +} + func (fbConn *FbConn) eventDialHost() string { host := fbConn.eventHost if host == "" { diff --git a/fbconn/events_integration_test.go b/fbconn/events_integration_test.go new file mode 100644 index 00000000..3c1e292f --- /dev/null +++ b/fbconn/events_integration_test.go @@ -0,0 +1,41 @@ +package fbconn + +import ( + "context" + "os" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestQueueEventAfterConstructUnix(t *testing.T) { + connString := os.Getenv("FBX_TEST_UNIX_SOCKET_DATABASE") + if connString == "" { + t.Skip("set FBX_TEST_UNIX_SOCKET_DATABASE to test Unix socket connections") + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + conn, err := Connect(ctx, connString) + require.NoError(t, err) + defer func() { require.NoError(t, conn.Close(ctx)) }() + if conn.ServerVersion().Major < 6 { + t.Skip("Unix domain sockets require Firebird 6 or later") + } + + require.NoError(t, conn.SyncConn(ctx)) + hijacked, err := conn.Hijack() + require.NoError(t, err) + restored, err := Construct(hijacked) + if err != nil { + require.NoError(t, hijacked.Conn.Close()) + } + require.NoError(t, err) + defer func() { require.NoError(t, restored.Close(ctx)) }() + + handle, err := restored.CreateEventHandle("FBX_CONSTRUCT_UNIX", &testEventHandler{}) + require.NoError(t, err) + require.NoError(t, restored.QueueEvent(ctx, handle)) + require.NoError(t, restored.CancelEvent(ctx, handle)) +} diff --git a/fbconn/events_internal_test.go b/fbconn/events_internal_test.go index ea11194f..eca72398 100644 --- a/fbconn/events_internal_test.go +++ b/fbconn/events_internal_test.go @@ -3,8 +3,10 @@ package fbconn import ( "bytes" "context" + "encoding/binary" "errors" - "os" + "io" + "net" "testing" "time" @@ -21,35 +23,164 @@ func (h *testEventHandler) EventOccurred(*EventHandle) { h.calls++ } -func TestQueueEventAfterConstructUnix(t *testing.T) { - connString := os.Getenv("FBX_TEST_UNIX_SOCKET_DATABASE") - if connString == "" { - t.Skip("set FBX_TEST_UNIX_SOCKET_DATABASE to test Unix socket connections") +func TestQueueEventClosesConnectionAfterAuxFailure(t *testing.T) { + dialErr := errors.New("auxiliary dial failed") + for _, tt := range []struct { + name string + version int + eventHost string + address string + wantError string + wantDial bool + }{ + {"dial failure", fbproto.PROTOCOL_VERSION13, "/tmp/main.sock", "/tmp/events.sock", dialErr.Error(), true}, + {"invalid socket path", fbproto.PROTOCOL_VERSION13, "/tmp/main.sock", "relative.sock", "invalid auxiliary event socket path", false}, + {"invalid TCP port", fbproto.PROTOCOL_VERSION13, "localhost", "\x00\x00\x00\x00", "invalid aux event port", false}, + {"legacy protocol", fbproto.PROTOCOL_VERSION12, "localhost", "\x00\x00\x00\x01", dialErr.Error(), true}, + } { + t.Run(tt.name, func(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + require.NoError(t, server.SetDeadline(time.Now().Add(3*time.Second))) + + conn := newDetachTestConn(client) + conn.protocolVersion = tt.version + conn.eventHost = tt.eventHost + encoding, err := fbproto.NewEncoding("UTF8") + require.NoError(t, err) + conn.Encoding = encoding + var dialed bool + conn.config.DialFunc = func(context.Context, string, string) (net.Conn, error) { + dialed = true + return nil, dialErr + } + + serverDone := make(chan error, 1) + go func() { + serverDone <- func() error { + var request [16]byte + if _, err := io.ReadFull(server, request[:]); err != nil { + return err + } + if binary.BigEndian.Uint32(request[:4]) != fbproto.Op_connect_request { + return errors.New("expected auxiliary connection request") + } + if err := writeProbeResponseData(fbproto.NewXDRWriter(server), 0, []byte(tt.address)); err != nil { + return err + } + + reader := fbproto.NewXDRReader(server) + if tt.version >= fbproto.PROTOCOL_VERSION13 { + op, err := reader.ReadInt32() + if err != nil { + return err + } + if op != fbproto.Op_abort_aux_connection { + return errors.New("expected auxiliary connection abort") + } + } + if _, err := reader.ReadInt32(); err != io.EOF { + return errors.New("expected the main connection to close without another request") + } + return nil + }() + }() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + handle, err := newEventHandle("FBX_AUX_FAILURE", &testEventHandler{}, conn.Encoding) + require.NoError(t, err) + require.ErrorContains(t, conn.QueueEvent(ctx, handle), tt.wantError) + require.Equal(t, tt.wantDial, dialed) + + pingCtx, cancelPing := context.WithTimeout(context.Background(), time.Second) + defer cancelPing() + require.ErrorContains(t, conn.Ping(pingCtx), "conn closed") + require.NoError(t, pingCtx.Err()) + require.NoError(t, <-serverDone) + }) } - ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) - defer cancel() - - conn, err := Connect(ctx, connString) - require.NoError(t, err) - defer func() { require.NoError(t, conn.Close(ctx)) }() - if conn.ServerVersion().Major < 6 { - t.Skip("Unix domain sockets require Firebird 6 or later") - } - - require.NoError(t, conn.SyncConn(ctx)) - hijacked, err := conn.Hijack() - require.NoError(t, err) - restored, err := Construct(hijacked) - if err != nil { - require.NoError(t, hijacked.Conn.Close()) - } - require.NoError(t, err) - defer func() { require.NoError(t, restored.Close(ctx)) }() - handle, err := restored.CreateEventHandle("FBX_CONSTRUCT_UNIX", &testEventHandler{}) - require.NoError(t, err) - require.NoError(t, restored.QueueEvent(ctx, handle)) - require.NoError(t, restored.CancelEvent(ctx, handle)) + t.Run("server error response keeps connection open", func(t *testing.T) { + const serverError = "auxiliary connection rejected" + client, server := net.Pipe() + defer func() { _ = client.Close() }() + defer func() { _ = server.Close() }() + require.NoError(t, server.SetDeadline(time.Now().Add(3*time.Second))) + + conn := newDetachTestConn(client) + conn.protocolVersion = fbproto.PROTOCOL_VERSION13 + conn.eventHost = "/tmp/main.sock" + encoding, err := fbproto.NewEncoding("UTF8") + require.NoError(t, err) + conn.Encoding = encoding + conn.client.Encoding = encoding + var dialed bool + conn.config.DialFunc = func(context.Context, string, string) (net.Conn, error) { + dialed = true + return nil, dialErr + } + + serverDone := make(chan error, 1) + go func() { + serverDone <- func() error { + var request [16]byte + if _, err := io.ReadFull(server, request[:]); err != nil { + return err + } + if binary.BigEndian.Uint32(request[:4]) != fbproto.Op_connect_request { + return errors.New("expected auxiliary connection request") + } + + writer := fbproto.NewXDRWriter(server) + // ErrorResponse is an op_response with an error status vector. + for _, word := range []int{fbproto.Op_response, 0, 0, 0, 0, + fbproto.Isc_arg_gds, fbproto.Isc_random, fbproto.Isc_arg_string} { + if err := writer.WriteInt32(word); err != nil { + return err + } + } + if err := writer.WriteString(serverError, encoding); err != nil { + return err + } + if err := writer.WriteInt32(fbproto.Isc_arg_end); err != nil { + return err + } + + reader := fbproto.NewXDRReader(server) + op, err := reader.ReadInt32() + if err != nil { + return err + } + if op != fbproto.Op_ping { + return errors.New("expected ping immediately after the server error") + } + if err := writeProbeResponse(writer, 0); err != nil { + return err + } + if _, err := reader.ReadInt32(); err != io.EOF { + return errors.New("expected the main connection to close after ping") + } + return nil + }() + }() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + handle, err := conn.CreateEventHandle("FBX_AUX_REJECTED", &testEventHandler{}) + require.NoError(t, err) + var fbErr *FbError + require.ErrorAs(t, conn.QueueEvent(ctx, handle), &fbErr) + require.Equal(t, serverError, fbErr.Message) + require.False(t, dialed) + + pingCtx, cancelPing := context.WithTimeout(context.Background(), time.Second) + defer cancelPing() + require.NoError(t, conn.Ping(pingCtx)) + conn.asyncClose() + require.NoError(t, <-serverDone) + }) } func TestEventHandleToEventBlockAndCount(t *testing.T) { diff --git a/fbproto/op_connect_request.go b/fbproto/op_connect_request.go index 6d919c38..8120deaa 100644 --- a/fbproto/op_connect_request.go +++ b/fbproto/op_connect_request.go @@ -5,6 +5,13 @@ package fbproto // OpConnectRequest requests auxiliary connection information (eg event channel port). type OpConnectRequest struct{} +// OpAbortAuxConnection cancels an outstanding auxiliary connection request. +type OpAbortAuxConnection struct{} + +func (op *OpAbortAuxConnection) Write(x *XDRWriter) error { + return x.WriteInt32(Op_abort_aux_connection) +} + func (op *OpConnectRequest) Write(x *XDRWriter) error { var err error From e1eed3e3bc994e094694f788ddc9be9ccefb6c33 Mon Sep 17 00:00:00 2001 From: Pavel <113603127+Pavlushechko@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:51:59 +0300 Subject: [PATCH 6/7] Accept relative Unix socket paths returned for event notifications --- fbconn/events_channel.go | 8 ++++++-- fbconn/events_internal_test.go | 31 +++++++++++++++++-------------- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/fbconn/events_channel.go b/fbconn/events_channel.go index 3a8003a5..7460ac2b 100644 --- a/fbconn/events_channel.go +++ b/fbconn/events_channel.go @@ -57,7 +57,11 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er return existingChannel, nil } - network, address := NetworkAddress(host, port) + // A zero port identifies the Unix path returned by Firebird, which may be relative. + network, address := "unix", host + if port != 0 { + network, address = NetworkAddress(host, port) + } auxConn, err := fbConn.config.DialFunc(ctx, network, address) if err != nil { fbConn.abortAuxEventConnection() @@ -113,7 +117,7 @@ func (fbConn *FbConn) requestAuxEventAddress(ctx context.Context) (*eventChannel if isAbsolutePath(fbConn.eventHost) { // Firebird sends the auxiliary socket path as raw bytes for Unix connections. path := string(m.Data) - if !isAbsolutePath(path) { + if path == "" { fbConn.abortAuxEventConnection() return nil, "", 0, errors.New("invalid auxiliary event socket path") } diff --git a/fbconn/events_internal_test.go b/fbconn/events_internal_test.go index eca72398..c68bbdae 100644 --- a/fbconn/events_internal_test.go +++ b/fbconn/events_internal_test.go @@ -26,17 +26,19 @@ func (h *testEventHandler) EventOccurred(*EventHandle) { func TestQueueEventClosesConnectionAfterAuxFailure(t *testing.T) { dialErr := errors.New("auxiliary dial failed") for _, tt := range []struct { - name string - version int - eventHost string - address string - wantError string - wantDial bool + name string + version int + eventHost string + address string + wantError string + wantNetwork string + wantAddress string }{ - {"dial failure", fbproto.PROTOCOL_VERSION13, "/tmp/main.sock", "/tmp/events.sock", dialErr.Error(), true}, - {"invalid socket path", fbproto.PROTOCOL_VERSION13, "/tmp/main.sock", "relative.sock", "invalid auxiliary event socket path", false}, - {"invalid TCP port", fbproto.PROTOCOL_VERSION13, "localhost", "\x00\x00\x00\x00", "invalid aux event port", false}, - {"legacy protocol", fbproto.PROTOCOL_VERSION12, "localhost", "\x00\x00\x00\x01", dialErr.Error(), true}, + {"dial failure", fbproto.PROTOCOL_VERSION13, "/tmp/main.sock", "/tmp/events.sock", dialErr.Error(), "unix", "/tmp/events.sock"}, + {"relative socket path", fbproto.PROTOCOL_VERSION13, "/tmp/main.sock", "sockets/events.sock", dialErr.Error(), "unix", "sockets/events.sock"}, + {"empty socket path", fbproto.PROTOCOL_VERSION13, "/tmp/main.sock", "", "invalid auxiliary event socket path", "", ""}, + {"invalid TCP port", fbproto.PROTOCOL_VERSION13, "localhost", "\x00\x00\x00\x00", "invalid aux event port", "", ""}, + {"legacy protocol", fbproto.PROTOCOL_VERSION12, "localhost", "\x00\x00\x00\x01", dialErr.Error(), "tcp", "localhost:1"}, } { t.Run(tt.name, func(t *testing.T) { client, server := net.Pipe() @@ -50,9 +52,9 @@ func TestQueueEventClosesConnectionAfterAuxFailure(t *testing.T) { encoding, err := fbproto.NewEncoding("UTF8") require.NoError(t, err) conn.Encoding = encoding - var dialed bool - conn.config.DialFunc = func(context.Context, string, string) (net.Conn, error) { - dialed = true + var dialNetwork, dialAddress string + conn.config.DialFunc = func(_ context.Context, network, address string) (net.Conn, error) { + dialNetwork, dialAddress = network, address return nil, dialErr } @@ -92,7 +94,8 @@ func TestQueueEventClosesConnectionAfterAuxFailure(t *testing.T) { handle, err := newEventHandle("FBX_AUX_FAILURE", &testEventHandler{}, conn.Encoding) require.NoError(t, err) require.ErrorContains(t, conn.QueueEvent(ctx, handle), tt.wantError) - require.Equal(t, tt.wantDial, dialed) + require.Equal(t, tt.wantNetwork, dialNetwork) + require.Equal(t, tt.wantAddress, dialAddress) pingCtx, cancelPing := context.WithTimeout(context.Background(), time.Second) defer cancelPing() From d1942ae32813a35fee391b0f06f3ef85fe867e27 Mon Sep 17 00:00:00 2001 From: Pavel <113603127+Pavlushechko@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:52:00 +0300 Subject: [PATCH 7/7] Start Red Database after configuring its Unix socket in CI --- .github/workflows/go.yml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 1e2381c9..95d288ed 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -84,20 +84,18 @@ jobs: ./installer --mode unattended --sysdba_password masterkey echo Configure RDB cp ci/firebird.conf ci/fbtrace.conf /opt/RedDatabase - service_action=start if [ "${{ matrix.RDB_PROJECT }}" = "rdb60" ]; then socket=/tmp/fbx-firebird.sock printf '\nRemoteServiceUnixSocket = %s\n' "$socket" >> /opt/RedDatabase/firebird.conf printf 'FBX_TEST_UNIX_SOCKET_DATABASE=database=employee host=%s user=sysdba password=masterkey\n' "$socket" >> "$GITHUB_ENV" - service_action=restart fi g++ -o libfbxci.so -shared -fPIC ci/udrs.cpp -I/opt/RedDatabase/include cp libfbxci.so /opt/RedDatabase/plugins/udr echo Start RDB if [ -e /etc/init.d/reddatabase ]; then - /etc/init.d/reddatabase "$service_action" + /etc/init.d/reddatabase start else - /etc/init.d/firebird "$service_action" + /etc/init.d/firebird start fi else echo Install dependencies