Skip to content

Commit

Permalink
Bugfix: use filepath package when connecting to UNIX sockets
Browse files Browse the repository at this point in the history
The code before this commit is non-portable: it only works on
UNIX systems where path.Join() is close enough to filepath.Join().
However, path.Join() is the wrong choice: UNIX domain sockets
are identified via their file system name, so — conceptually
and in practice — we need to use the filepath package instead.

This commit fixes connecting to a PostgreSQL database
that is listening on a UNIX domain socket on Windows.
If you are surprised to see UNIX domain sockets on Windows,
they were introduced with Windows 10, i.e. are widely available now:
https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows/

filepath.IsAbs() is equivalent to strings.HasPrefix(s, "/") on UNIX,
but also works on Windows, where absolute paths start with e.g. C:\
Similarly, filepath.Join() uses the correct path separator.

Also recognize UNIX domain sockets in the abstract name space
(represented by a leading @ character) while here.

related to zombiezen/postgrestest#3
  • Loading branch information
stapelberg committed Nov 16, 2024
1 parent 3d61320 commit b7ffbd3
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (
"net"
"os"
"os/user"
"path"
"path/filepath"
"strconv"
"strings"
Expand Down Expand Up @@ -437,8 +436,10 @@ func dial(ctx context.Context, d Dialer, o values) (net.Conn, error) {
func network(o values) (string, string) {
host := o["host"]

if strings.HasPrefix(host, "/") {
sockPath := path.Join(host, ".s.PGSQL."+o["port"])
// UNIX domain sockets are either represented by an (absolute) file system
// path or they live in the abstract name space (starting with an @).
if filepath.IsAbs(host) || strings.HasPrefix(host, "@") {
sockPath := filepath.Join(host, ".s.PGSQL."+o["port"])
return "unix", sockPath
}

Expand Down

0 comments on commit b7ffbd3

Please sign in to comment.