detached 3b975b0

#130 fix(wayland): publish the socket only once it listens

state
merged · 057e460 · merge commit
branch
fix/wayland-socket-race → main
opened
bnema ·
updated

listen() bound wayland-N before calling listen, so the socket file existed while connect() still returned ECONNREFUSED. Tests that wait for the file then connect (TestPointerCLI, also seen on main run 1297) flaked in CI, and a client started at session start could hit the same window.

The socket is now bound as a hidden .wl-N, put in listening state, then renamed to wayland-N. Public paths too long for sun_path are rejected before any file is created.

Checks: make check, make race, make mocks-check, staticcheck ./..., TestPointerCLI x20, headless smoke test.

Not covered: Xwayland sockets bind before listening too; tracked separately.

CommitSubjectAuthorDateSignatureStatus
3b975b0fix(wayland): publish the socket only once it listensbrice GPG Verified

Checks 1

2 files · +127 -2
1/1
M internal/adapters/wayland/socket.go +18 -2
@@ -12,6 +12,14 @@ func listen(runtimeDir string) (name string, fd int, cleanup func(), err error)
1212 for n := 1; n <= 32; n++ {
1313 name = fmt.Sprintf("wayland-%d", n)
1414 path := filepath.Join(runtimeDir, name)
15+ // Validate the public address, not just the shorter staging address.
16+ // Leave room for the terminating NUL, as unix.Bind would require.
17+ if len(path) >= len(unix.RawSockaddrUnix{}.Path) {
18+ return "", -1, nil, fmt.Errorf("wayland socket path too long: %s: %w", path, unix.EINVAL)
19+ }
20+ // Keep the staging basename shorter than wayland-N: adding a suffix
21+ // would reject otherwise valid paths at the Unix sun_path limit.
22+ tmp := filepath.Join(runtimeDir, fmt.Sprintf(".wl-%d", n))
1523 lock := path + ".lock"
1624 l, e := unix.Open(lock, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0660)
1725 if e != nil {
@@ -24,18 +32,26 @@ func listen(runtimeDir string) (name string, fd int, cleanup func(), err error)
2432 }
2533 return "", -1, nil, e
2634 }
27- cleanup = func() { os.Remove(path); os.Remove(lock); unix.Close(l) }
35+ cleanup = func() { os.Remove(tmp); os.Remove(path); os.Remove(lock); unix.Close(l) }
36+ if e = os.Remove(tmp); e != nil && !os.IsNotExist(e) {
37+ cleanup()
38+ return "", -1, nil, e
39+ }
2840 if e = os.Remove(path); e != nil && !os.IsNotExist(e) {
2941 cleanup()
3042 return "", -1, nil, e
3143 }
3244 fd, e = unix.Socket(unix.AF_UNIX, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)
3345 if e == nil {
34- e = unix.Bind(fd, &unix.SockaddrUnix{Name: path})
46+ e = unix.Bind(fd, &unix.SockaddrUnix{Name: tmp})
3547 }
3648 if e == nil {
3749 e = unix.Listen(fd, 128)
3850 }
51+ if e == nil {
52+ // Publish only a listening socket to clients watching wayland-N.
53+ e = unix.Rename(tmp, path)
54+ }
3955 if e != nil {
4056 if fd >= 0 {
4157 unix.Close(fd)
@@ -12,6 +12,14 @@ func listen(runtimeDir string) (name string, fd int, cleanup func(), err error)
12 for n := 1; n <= 32; n++ {12 for n := 1; n <= 32; n++ {
13 name = fmt.Sprintf("wayland-%d", n)13 name = fmt.Sprintf("wayland-%d", n)
14 path := filepath.Join(runtimeDir, name)14 path := filepath.Join(runtimeDir, name)
15+ // Validate the public address, not just the shorter staging address.
16+ // Leave room for the terminating NUL, as unix.Bind would require.
17+ if len(path) >= len(unix.RawSockaddrUnix{}.Path) {
18+ return "", -1, nil, fmt.Errorf("wayland socket path too long: %s: %w", path, unix.EINVAL)
19+ }
20+ // Keep the staging basename shorter than wayland-N: adding a suffix
21+ // would reject otherwise valid paths at the Unix sun_path limit.
22+ tmp := filepath.Join(runtimeDir, fmt.Sprintf(".wl-%d", n))
15 lock := path + ".lock"23 lock := path + ".lock"
16 l, e := unix.Open(lock, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0660)24 l, e := unix.Open(lock, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0660)
17 if e != nil {25 if e != nil {
@@ -24,18 +32,26 @@ func listen(runtimeDir string) (name string, fd int, cleanup func(), err error)
24 }32 }
25 return "", -1, nil, e33 return "", -1, nil, e
26 }34 }
27- cleanup = func() { os.Remove(path); os.Remove(lock); unix.Close(l) }35+ cleanup = func() { os.Remove(tmp); os.Remove(path); os.Remove(lock); unix.Close(l) }
36+ if e = os.Remove(tmp); e != nil && !os.IsNotExist(e) {
37+ cleanup()
38+ return "", -1, nil, e
39+ }
28 if e = os.Remove(path); e != nil && !os.IsNotExist(e) {40 if e = os.Remove(path); e != nil && !os.IsNotExist(e) {
29 cleanup()41 cleanup()
30 return "", -1, nil, e42 return "", -1, nil, e
31 }43 }
32 fd, e = unix.Socket(unix.AF_UNIX, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)44 fd, e = unix.Socket(unix.AF_UNIX, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)
33 if e == nil {45 if e == nil {
34- e = unix.Bind(fd, &unix.SockaddrUnix{Name: path})46+ e = unix.Bind(fd, &unix.SockaddrUnix{Name: tmp})
35 }47 }
36 if e == nil {48 if e == nil {
37 e = unix.Listen(fd, 128)49 e = unix.Listen(fd, 128)
38 }50 }
51+ if e == nil {
52+ // Publish only a listening socket to clients watching wayland-N.
53+ e = unix.Rename(tmp, path)
54+ }
39 if e != nil {55 if e != nil {
40 if fd >= 0 {56 if fd >= 0 {
41 unix.Close(fd)57 unix.Close(fd)
M internal/adapters/wayland/socket_test.go +109 -0
@@ -1,8 +1,10 @@
11 package wayland
22
33 import (
4+ "fmt"
45 "os"
56 "path/filepath"
7+ "strings"
68 "testing"
79
810 "golang.org/x/sys/unix"
@@ -37,3 +39,110 @@ func TestListen(t *testing.T) {
3739 }
3840 }
3941 }
42+
43+// No real-time waits: connect completes against the kernel listening backlog.
44+func TestListenPublishedSocket(t *testing.T) {
45+ for _, long := range []bool{false, true} {
46+ t.Run(fmt.Sprint(long), func(t *testing.T) {
47+ dir := t.TempDir()
48+ if long {
49+ dir = socketPathDir(t, 107)
50+ }
51+ tmp := filepath.Join(dir, ".wl-1")
52+ if err := os.WriteFile(tmp, []byte("stale"), 0600); err != nil {
53+ t.Fatal(err)
54+ }
55+ name, fd, cleanup, err := listen(dir)
56+ if err != nil {
57+ t.Fatal(err)
58+ }
59+ defer unix.Close(fd)
60+ defer cleanup()
61+ entries, err := os.ReadDir(dir)
62+ if err != nil {
63+ t.Fatal(err)
64+ }
65+ if len(entries) != 2 || entries[0].Name() != name || entries[1].Name() != name+".lock" {
66+ t.Fatalf("unexpected published files: %v", entries)
67+ }
68+ path := filepath.Join(dir, name)
69+ info, err := os.Stat(path)
70+ if err != nil {
71+ t.Fatal(err)
72+ }
73+ if info.Mode()&os.ModeSocket == 0 {
74+ t.Fatalf("not a socket: %v", info.Mode())
75+ }
76+ client, err := unix.Socket(unix.AF_UNIX, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)
77+ if err != nil {
78+ t.Fatal(err)
79+ }
80+ defer unix.Close(client)
81+ if err := unix.Connect(client, &unix.SockaddrUnix{Name: path}); err != nil {
82+ t.Fatal(err)
83+ }
84+ })
85+ }
86+}
87+
88+// socketPathDir avoids depending on TMPDIR or the length of the test name.
89+func socketPathDir(t *testing.T, pathLen int) string {
90+ t.Helper()
91+ root, err := os.MkdirTemp("/tmp", "wl")
92+ if err != nil {
93+ t.Fatal(err)
94+ }
95+ t.Cleanup(func() { os.RemoveAll(root) })
96+ padding := pathLen - len(root) - len("//wayland-1")
97+ if padding < 1 {
98+ t.Skip("temporary root too long for socket boundary fixture")
99+ }
100+ dir := filepath.Join(root, strings.Repeat("x", padding))
101+ if err := os.Mkdir(dir, 0700); err != nil {
102+ t.Fatal(err)
103+ }
104+ if got := len(filepath.Join(dir, "wayland-1")); got != pathLen {
105+ t.Fatalf("public path length = %d, want %d", got, pathLen)
106+ }
107+ return dir
108+}
109+
110+func TestListenRejectsUnreachablePath(t *testing.T) {
111+ dir := socketPathDir(t, 108)
112+ _, fd, cleanup, err := listen(dir)
113+ if err == nil || fd != -1 || cleanup != nil {
114+ t.Fatalf("unexpected result: fd=%d err=%v", fd, err)
115+ }
116+ entries, err := os.ReadDir(dir)
117+ if err != nil {
118+ t.Fatal(err)
119+ }
120+ if len(entries) != 0 {
121+ t.Fatalf("rejected path left files: %v", entries)
122+ }
123+}
124+
125+func TestListenErrorCleansStaging(t *testing.T) {
126+ dir := t.TempDir()
127+ // A nonempty destination cannot be removed before binding.
128+ path := filepath.Join(dir, "wayland-1")
129+ if err := os.Mkdir(path, 0700); err != nil {
130+ t.Fatal(err)
131+ }
132+ if err := os.WriteFile(filepath.Join(path, "keep"), nil, 0600); err != nil {
133+ t.Fatal(err)
134+ }
135+ tmp := filepath.Join(dir, ".wl-1")
136+ if err := os.WriteFile(tmp, nil, 0600); err != nil {
137+ t.Fatal(err)
138+ }
139+ _, fd, cleanup, err := listen(dir)
140+ if err == nil || fd != -1 || cleanup != nil {
141+ t.Fatalf("unexpected result: fd=%d err=%v", fd, err)
142+ }
143+ for _, p := range []string{tmp, path + ".lock"} {
144+ if _, err := os.Stat(p); !os.IsNotExist(err) {
145+ t.Fatalf("%s still exists: %v", p, err)
146+ }
147+ }
148+}
@@ -1,8 +1,10 @@
1 package wayland1 package wayland
2 2
3 import (3 import (
4+ "fmt"
4 "os"5 "os"
5 "path/filepath"6 "path/filepath"
7+ "strings"
6 "testing"8 "testing"
7 9
8 "golang.org/x/sys/unix"10 "golang.org/x/sys/unix"
@@ -37,3 +39,110 @@ func TestListen(t *testing.T) {
37 }39 }
38 }40 }
39 }41 }
42+
43+// No real-time waits: connect completes against the kernel listening backlog.
44+func TestListenPublishedSocket(t *testing.T) {
45+ for _, long := range []bool{false, true} {
46+ t.Run(fmt.Sprint(long), func(t *testing.T) {
47+ dir := t.TempDir()
48+ if long {
49+ dir = socketPathDir(t, 107)
50+ }
51+ tmp := filepath.Join(dir, ".wl-1")
52+ if err := os.WriteFile(tmp, []byte("stale"), 0600); err != nil {
53+ t.Fatal(err)
54+ }
55+ name, fd, cleanup, err := listen(dir)
56+ if err != nil {
57+ t.Fatal(err)
58+ }
59+ defer unix.Close(fd)
60+ defer cleanup()
61+ entries, err := os.ReadDir(dir)
62+ if err != nil {
63+ t.Fatal(err)
64+ }
65+ if len(entries) != 2 || entries[0].Name() != name || entries[1].Name() != name+".lock" {
66+ t.Fatalf("unexpected published files: %v", entries)
67+ }
68+ path := filepath.Join(dir, name)
69+ info, err := os.Stat(path)
70+ if err != nil {
71+ t.Fatal(err)
72+ }
73+ if info.Mode()&os.ModeSocket == 0 {
74+ t.Fatalf("not a socket: %v", info.Mode())
75+ }
76+ client, err := unix.Socket(unix.AF_UNIX, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)
77+ if err != nil {
78+ t.Fatal(err)
79+ }
80+ defer unix.Close(client)
81+ if err := unix.Connect(client, &unix.SockaddrUnix{Name: path}); err != nil {
82+ t.Fatal(err)
83+ }
84+ })
85+ }
86+}
87+
88+// socketPathDir avoids depending on TMPDIR or the length of the test name.
89+func socketPathDir(t *testing.T, pathLen int) string {
90+ t.Helper()
91+ root, err := os.MkdirTemp("/tmp", "wl")
92+ if err != nil {
93+ t.Fatal(err)
94+ }
95+ t.Cleanup(func() { os.RemoveAll(root) })
96+ padding := pathLen - len(root) - len("//wayland-1")
97+ if padding < 1 {
98+ t.Skip("temporary root too long for socket boundary fixture")
99+ }
100+ dir := filepath.Join(root, strings.Repeat("x", padding))
101+ if err := os.Mkdir(dir, 0700); err != nil {
102+ t.Fatal(err)
103+ }
104+ if got := len(filepath.Join(dir, "wayland-1")); got != pathLen {
105+ t.Fatalf("public path length = %d, want %d", got, pathLen)
106+ }
107+ return dir
108+}
109+
110+func TestListenRejectsUnreachablePath(t *testing.T) {
111+ dir := socketPathDir(t, 108)
112+ _, fd, cleanup, err := listen(dir)
113+ if err == nil || fd != -1 || cleanup != nil {
114+ t.Fatalf("unexpected result: fd=%d err=%v", fd, err)
115+ }
116+ entries, err := os.ReadDir(dir)
117+ if err != nil {
118+ t.Fatal(err)
119+ }
120+ if len(entries) != 0 {
121+ t.Fatalf("rejected path left files: %v", entries)
122+ }
123+}
124+
125+func TestListenErrorCleansStaging(t *testing.T) {
126+ dir := t.TempDir()
127+ // A nonempty destination cannot be removed before binding.
128+ path := filepath.Join(dir, "wayland-1")
129+ if err := os.Mkdir(path, 0700); err != nil {
130+ t.Fatal(err)
131+ }
132+ if err := os.WriteFile(filepath.Join(path, "keep"), nil, 0600); err != nil {
133+ t.Fatal(err)
134+ }
135+ tmp := filepath.Join(dir, ".wl-1")
136+ if err := os.WriteFile(tmp, nil, 0600); err != nil {
137+ t.Fatal(err)
138+ }
139+ _, fd, cleanup, err := listen(dir)
140+ if err == nil || fd != -1 || cleanup != nil {
141+ t.Fatalf("unexpected result: fd=%d err=%v", fd, err)
142+ }
143+ for _, p := range []string{tmp, path + ".lock"} {
144+ if _, err := os.Stat(p); !os.IsNotExist(err) {
145+ t.Fatalf("%s still exists: %v", p, err)
146+ }
147+ }
148+}

Comments11 unresolved

  1. bnema

    Review (go-reviewer): GO-001 public path longer than sun_path accepted via the shorter staging name — fixed (validated before any file is created, boundary tests 107/108). GO-002 boundary test fragile on long TMPDIR and off by one — fixed (short /tmp root, exact 107 bytes).

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. On pages with a side panel: into the panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit; in a file, click a line number to select it, shift-click for a range
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
l
merge request: the list of files (j k move, enter opens, esc back)
M
merge request: the merge menu; there 1–3 pick the mode, D deletes the branch, enter merges
R
merge request: mark the head read
esc
close a dialog, leave a field

Branches 33

Tags 15

↑↓ moveenter openesc close