Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ jobs:
./installer --mode unattended --sysdba_password masterkey
echo Configure RDB
cp ci/firebird.conf ci/fbtrace.conf /opt/RedDatabase
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"
fi
g++ -o libfbxci.so -shared -fPIC ci/udrs.cpp -I/opt/RedDatabase/include
cp libfbxci.so /opt/RedDatabase/plugins/udr
echo Start RDB
Expand Down Expand Up @@ -168,4 +173,4 @@ jobs:
with:
file: coverage.xml
language: Go
label: code-coverage/gotest
label: code-coverage/gotest
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,15 @@ 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 use its absolute path as the host.

```text
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`.

Expand Down
12 changes: 5 additions & 7 deletions fbconn/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,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.
Expand All @@ -266,11 +262,13 @@ 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 host=/run/firebird/firebird.sock database=employee

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also support URI syntax when connecting with socket. Some pgx tests were cleaned up, but now can be restored or used as reference to check if we properly parse URI.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked the original pgx cases. The existing parser already accepts firebird:///employee?host=/run/firebird/firebird.sock. I documented that form and added parsing tests for Linux and Windows paths, plus a percent-encoded path in the URI host.

// user=sysdba password=masterkey host=localhost port=3050 database=new.fdb create_database=true
//
// # 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):
Expand Down
14 changes: 10 additions & 4 deletions fbconn/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -657,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",
Expand Down
89 changes: 57 additions & 32 deletions fbconn/events_channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import (
"fmt"
"io"
"net"
"strconv"
"sync"
"time"

"github.com/firebirdsql/fbx/fbproto"
"github.com/firebirdsql/fbx/fbproto/vax"
Expand Down Expand Up @@ -42,31 +42,34 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er
return channel, nil
}

existingChannel, auxPort, err := fbConn.requestAuxEventPort(ctx)
// 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
}
if existingChannel != nil {
return existingChannel, nil
}

host := fbConn.eventDialHost()
address := net.JoinHostPort(host, strconv.Itoa(auxPort))
auxConn, err := fbConn.config.DialFunc(ctx, "tcp", address)
// 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once Firebird has returned the auxiliary address, it is waiting for the second connection. If FBX rejects the address or the dial fails here, QueueEvent returns an error but the next Ping on the same attachment reaches its deadline. This reproduced with a one-second timeout.

On protocols 13+, libfbclient sends op_abort_aux_connection on a failed auxiliary connect and marks the attachment broken. Could we cancel the pending accept on both error paths and test that the next operation completes promptly?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both paths now close the connection and send op_abort_aux_connection on protocol 13+. The tests verify that Ping returns a connection-closed error before its deadline. I also covered the case where Firebird rejects the request before returning an address. In that case, Ping still succeeds.

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 {
Expand All @@ -78,16 +81,11 @@ func (fbConn *FbConn) ensureEventChannel(ctx context.Context) (*eventChannel, er
return channel, nil
}

func (fbConn *FbConn) requestAuxEventPort(ctx context.Context) (*eventChannel, int, error) {
if err := fbConn.lockEventOperation(ctx); err != nil {
return nil, 0, err
}
defer fbConn.unlock()

func (fbConn *FbConn) requestAuxEventAddress(ctx context.Context) (*eventChannel, string, uint16, error) {
if ctx != context.Background() {
select {
case <-ctx.Done():
return nil, 0, newContextAlreadyDoneError(ctx)
return nil, "", 0, newContextAlreadyDoneError(ctx)
default:
}
fbConn.contextWatcher.Watch(ctx)
Expand All @@ -98,38 +96,65 @@ func (fbConn *FbConn) requestAuxEventPort(ctx context.Context) (*eventChannel, i
channel := fbConn.eventChannel
fbConn.eventMu.Unlock()
if channel != nil {
return channel, 0, nil
return channel, "", 0, nil
}

if err := fbConn.client.WriteMessage(&fbproto.OpConnectRequest{}); err != nil {
if err := fbConn.withWriteLockAndFlush(func() error {
return fbConn.client.WriteMessage(&fbproto.OpConnectRequest{})
}); err != nil {
fbConn.asyncClose()
return nil, 0, err
}
if err := fbConn.flushWithPotentialWriteReadDeadlock(); err != nil {
fbConn.asyncClose()
return nil, 0, err
return nil, "", 0, err
}

msg, err := fbConn.receiveMessage()
if err != nil {
fbConn.asyncCloseAfterRead(err)
return nil, 0, normalizeTimeoutError(ctx, err)
return nil, "", 0, normalizeTimeoutError(ctx, err)
}

switch m := msg.(type) {
case *fbproto.OpResponse:
if isAbsolutePath(fbConn.eventHost) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After Hijack followed by Construct on a working Unix connection, the first QueueEvent calls DialFunc with tcp localhost:28016. Construct does not restore eventHost, so this branch reads the m and p bytes of /tmp/. as a TCP port.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hijack now saves the selected host, and Construct restores it. I added a regression test that queues an event after reconstructing a Unix connection.

// Firebird sends the auxiliary socket path as raw bytes for Unix connections.
path := string(m.Data)
if 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 {
return nil, 0, parseErr
fbConn.abortAuxEventConnection()
return nil, "", 0, parseErr
}
return nil, auxPort, nil
return nil, fbConn.eventDialHost(), uint16(auxPort), nil
case *fbproto.ErrorResponse:
return nil, 0, ErrorResponseToFbError(m)
return nil, "", 0, ErrorResponseToFbError(m)
default:
return nil, 0, fmt.Errorf("unexpected response message type %T while requesting event channel", m)
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 == "" {
Expand Down
41 changes: 41 additions & 0 deletions fbconn/events_integration_test.go
Original file line number Diff line number Diff line change
@@ -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))
}
Loading