Debian Codegraph @

x11_test.go

raw symbols SCIP
1 // Copyright 2026 The golang.design Initiative Authors.
2 // All rights reserved. Use of this source code is governed
3 // by a MIT license that can be found in the LICENSE file.
4 //
5 // Written by Changkun Ou <changkun.de>
6
7 package x11
8
9 import (
10 "bytes"
11 "encoding/binary"
12 "testing"
13 )
14
15 func TestParseDisplay(t *testing.T) {
16 for _, tt := range []struct {
17 in string
18 net string
19 addr string
20 num int
21 wantErr bool
22 }{
23 {in: ":0", net: "unix", addr: "/tmp/.X11-unix/X0", num: 0},
24 {in: ":1", net: "unix", addr: "/tmp/.X11-unix/X1", num: 1},
25 {in: ":0.0", net: "unix", addr: "/tmp/.X11-unix/X0", num: 0},
26 {in: "unix:2", net: "unix", addr: "/tmp/.X11-unix/X2", num: 2},
27 {in: "localhost:0", net: "tcp", addr: "localhost:6000", num: 0},
28 {in: "192.168.0.5:3.1", net: "tcp", addr: "192.168.0.5:6003", num: 3},
29 {in: "", wantErr: true},
30 {in: "nope", wantErr: true},
31 {in: ":x", wantErr: true},
32 } {
33 got, err := ParseDisplay(tt.in)
34 if tt.wantErr {
35 if err == nil {
36 t.Errorf("ParseDisplay(%q) = %+v, want error", tt.in, got)
37 }
38 continue
39 }
40 if err != nil {
41 t.Errorf("ParseDisplay(%q) error: %v", tt.in, err)
42 continue
43 }
44 if got.Net != tt.net || got.Addr != tt.addr || got.Num != tt.num {
45 t.Errorf("ParseDisplay(%q) = %+v, want {%s %s %d}", tt.in, got, tt.net, tt.addr, tt.num)
46 }
47 }
48 }
49
50 // authRecord builds one .Xauthority record.
51 func authRecord(family uint16, addr, num, name string, data []byte) []byte {
52 var b bytes.Buffer
53 put := func(v uint16) { binary.Write(&b, binary.BigEndian, v) }
54 putStr := func(s []byte) { put(uint16(len(s))); b.Write(s) }
55 put(family)
56 putStr([]byte(addr))
57 putStr([]byte(num))
58 putStr([]byte(name))
59 putStr(data)
60 return b.Bytes()
61 }
62
63 func TestParseXauthorityAndChooseCookie(t *testing.T) {
64 local := bytes.Repeat([]byte{0xAA}, 16)
65 wild := bytes.Repeat([]byte{0xBB}, 16)
66 file := append(authRecord(FamilyLocal, "myhost", "0", MITCookie, local),
67 authRecord(FamilyWild, "", "0", MITCookie, wild)...)
68
69 entries, err := ParseXauthority(file)
70 if err != nil {
71 t.Fatalf("ParseXauthority: %v", err)
72 }
73 if len(entries) != 2 {
74 t.Fatalf("got %d entries, want 2", len(entries))
75 }
76
77 // Local match for this host wins.
78 name, data := ChooseCookie(entries, 0, "myhost")
79 if name != MITCookie || !bytes.Equal(data, local) {
80 t.Errorf("ChooseCookie(myhost) = %q %x, want local cookie", name, data)
81 }
82
83 // Different host falls back to the wild entry.
84 name, data = ChooseCookie(entries, 0, "otherhost")
85 if name != MITCookie || !bytes.Equal(data, wild) {
86 t.Errorf("ChooseCookie(otherhost) = %q %x, want wild cookie", name, data)
87 }
88
89 // Wrong display number → no cookie (caller connects without auth).
90 if name, _ := ChooseCookie(entries, 9, "myhost"); name != "" {
91 t.Errorf("ChooseCookie(display 9) = %q, want no cookie", name)
92 }
93
94 // No entries at all → no cookie.
95 if name, _ := ChooseCookie(nil, 0, "myhost"); name != "" {
96 t.Errorf("ChooseCookie(nil) = %q, want no cookie", name)
97 }
98 }
99
100 func TestParseXauthorityTruncated(t *testing.T) {
101 if _, err := ParseXauthority([]byte{0x01}); err == nil {
102 t.Error("expected error for truncated authority")
103 }
104 }
105
106 func TestSetupRequest(t *testing.T) {
107 cookie := bytes.Repeat([]byte{0x11}, 16)
108 b := SetupRequest(MITCookie, cookie)
109 if b[0] != 'l' {
110 t.Errorf("byte order = %q, want 'l'", b[0])
111 }
112 if got := binary.LittleEndian.Uint16(b[2:]); got != 11 {
113 t.Errorf("major = %d, want 11", got)
114 }
115 if got := binary.LittleEndian.Uint16(b[6:]); got != uint16(len(MITCookie)) {
116 t.Errorf("name length = %d, want %d", got, len(MITCookie))
117 }
118 if got := binary.LittleEndian.Uint16(b[8:]); got != 16 {
119 t.Errorf("data length = %d, want 16", got)
120 }
121 if len(b)%4 != 0 {
122 t.Errorf("setup request length %d not 4-aligned", len(b))
123 }
124 // MIT-MAGIC-COOKIE-1 is 18 bytes → padded to 20; cookie at 12+20.
125 if !bytes.Equal(b[32:48], cookie) {
126 t.Errorf("cookie not placed at expected offset")
127 }
128 // No auth: just the 12-byte header.
129 if got := SetupRequest("", nil); len(got) != 12 {
130 t.Errorf("no-auth setup len = %d, want 12", len(got))
131 }
132 }
133
134 // setupAdditional builds a minimal successful setup "additional data" block
135 // with the given id base/mask and root window, one screen and no formats.
136 func setupAdditional(idBase, idMask, root uint32, vendor string) []byte {
137 v := pad4(len(vendor))
138 add := make([]byte, 32+v+4) // +4 for the single screen's root field
139 binary.LittleEndian.PutUint32(add[4:], idBase)
140 binary.LittleEndian.PutUint32(add[8:], idMask)
141 binary.LittleEndian.PutUint16(add[16:], uint16(len(vendor)))
142 add[20] = 1 // one screen
143 add[21] = 0 // no pixmap formats
144 copy(add[32:], vendor)
145 binary.LittleEndian.PutUint32(add[32+v:], root)
146 return add
147 }
148
149 func TestParseSetupAdditional(t *testing.T) {
150 add := setupAdditional(0x04600000, 0x001fffff, 0x000005a3, "The X.Org Foundation")
151 s, err := parseSetupAdditional(add)
152 if err != nil {
153 t.Fatalf("parseSetupAdditional: %v", err)
154 }
155 if s.IDBase != 0x04600000 || s.IDMask != 0x001fffff || s.Root != 0x000005a3 {
156 t.Errorf("got %+v", s)
157 }
158 }
159
160 func TestReadSetupSuccess(t *testing.T) {
161 add := setupAdditional(0x100, 0x1ff, 0x42, "vendor")
162 hdr := make([]byte, 8)
163 hdr[0] = 1
164 binary.LittleEndian.PutUint16(hdr[6:], uint16(len(add)/4))
165 s, err := ReadSetup(bytes.NewReader(append(hdr, add...)))
166 if err != nil {
167 t.Fatalf("ReadSetup: %v", err)
168 }
169 if s.Root != 0x42 || s.IDBase != 0x100 {
170 t.Errorf("got %+v", s)
171 }
172 }
173
174 func TestReadSetupFailed(t *testing.T) {
175 reason := "no protocol specified"
176 add := make([]byte, pad4(len(reason)))
177 copy(add, reason)
178 hdr := make([]byte, 8)
179 hdr[0] = 0 // failed
180 hdr[1] = byte(len(reason))
181 binary.LittleEndian.PutUint16(hdr[6:], uint16(len(add)/4))
182 _, err := ReadSetup(bytes.NewReader(append(hdr, add...)))
183 if err == nil {
184 t.Fatal("expected error on failed setup")
185 }
186 }
187
188 func TestIDGen(t *testing.T) {
189 g := NewIDGen(Setup{IDBase: 0x0a00000, IDMask: 0x1fffff})
190 a, b := g.Next(), g.Next()
191 if a == b {
192 t.Errorf("IDGen returned duplicate id %#x", a)
193 }
194 if a&^0x1fffff != 0x0a00000 {
195 t.Errorf("id %#x not within base", a)
196 }
197 }
198
199 func TestRequestEncoders(t *testing.T) {
200 checkHdr := func(name string, b []byte, op byte) {
201 if b[0] != op {
202 t.Errorf("%s opcode = %d, want %d", name, b[0], op)
203 }
204 if got := int(binary.LittleEndian.Uint16(b[2:])) * 4; got != len(b) {
205 t.Errorf("%s length field = %d, want %d", name, got, len(b))
206 }
207 if len(b)%4 != 0 {
208 t.Errorf("%s length %d not 4-aligned", name, len(b))
209 }
210 }
211 checkHdr("InternAtom", InternAtom("CLIPBOARD", false), opInternAtom)
212 checkHdr("InternAtom(image/png)", InternAtom("image/png", true), opInternAtom)
213 checkHdr("CreateWindow", CreateWindow(2, 3), opCreateWindow)
214 checkHdr("SetSelectionOwner", SetSelectionOwner(1, 2, 0), opSetSelectionOwner)
215 checkHdr("GetSelectionOwner", GetSelectionOwner(2), opGetSelectionOwner)
216 checkHdr("ConvertSelection", ConvertSelection(1, 2, 3, 4, 0), opConvertSelection)
217 checkHdr("ChangeProperty8", ChangeProperty(1, 2, 3, 8, []byte("hello")), opChangeProperty)
218 checkHdr("ChangePropertyAtoms", ChangeProperty(1, 2, AtomATOM, 32, AtomList(4, 5)), opChangeProperty)
219 checkHdr("GetProperty", GetProperty(true, 1, 2, 0, 0, 0xffffffff), opGetProperty)
220 checkHdr("DeleteProperty", DeleteProperty(1, 2), opDeleteProperty)
221 checkHdr("GetInputFocus", GetInputFocus(), opGetInputFocus)
222 checkHdr("SendSelectionNotify", SendSelectionNotify(SelectionNotify{Requestor: 9}), opSendEvent)
223
224 // ChangeProperty format-8 length field is the byte count.
225 cp := ChangeProperty(1, 2, 3, 8, []byte("hello"))
226 if got := binary.LittleEndian.Uint32(cp[20:]); got != 5 {
227 t.Errorf("ChangeProperty8 nItems = %d, want 5", got)
228 }
229 // Format-32 atom list length field is the atom count.
230 cpa := ChangeProperty(1, 2, AtomATOM, 32, AtomList(4, 5, 6))
231 if got := binary.LittleEndian.Uint32(cpa[20:]); got != 3 {
232 t.Errorf("ChangePropertyAtoms nItems = %d, want 3", got)
233 }
234 }
235
236 func TestGetAtomName(t *testing.T) {
237 // Encoder: opcode 17, 8-byte request with the atom in bytes 4..8.
238 b := GetAtomName(0x123)
239 if b[0] != opGetAtomName {
240 t.Fatalf("opcode = %d, want %d", b[0], opGetAtomName)
241 }
242 if len(b) != 8 || int(binary.LittleEndian.Uint16(b[2:]))*4 != len(b) {
243 t.Fatalf("bad length: len=%d field=%d", len(b), binary.LittleEndian.Uint16(b[2:]))
244 }
245 if got := binary.LittleEndian.Uint32(b[4:]); got != 0x123 {
246 t.Fatalf("atom = %#x, want 0x123", got)
247 }
248
249 // Decoder: a reply carrying a name decodes back to it.
250 const name = "text/html"
251 raw := make([]byte, 32+len(name))
252 raw[0] = 1 // reply
253 binary.LittleEndian.PutUint16(raw[8:], uint16(len(name)))
254 copy(raw[32:], name)
255 if got := (Packet{Raw: raw}).AtomName(); got != name {
256 t.Fatalf("AtomName = %q, want %q", got, name)
257 }
258
259 // Empty and truncated replies decode to "".
260 if got := (Packet{Raw: make([]byte, 32)}).AtomName(); got != "" {
261 t.Fatalf("empty AtomName = %q, want \"\"", got)
262 }
263 if got := (Packet{Raw: make([]byte, 10)}).AtomName(); got != "" {
264 t.Fatalf("short AtomName = %q, want \"\"", got)
265 }
266 }
267
268 // makeReply builds a 32-byte reply with optional trailing value bytes.
269 func makeReply(value []byte) []byte {
270 b := make([]byte, 32+pad4(len(value)))
271 b[0] = 1
272 binary.LittleEndian.PutUint32(b[4:], uint32(pad4(len(value))/4))
273 copy(b[32:], value)
274 return b
275 }
276
277 func TestReadPacketReplyWithValue(t *testing.T) {
278 val := []byte("clipboard data")
279 r := bytes.NewReader(makeReply(val))
280 p, err := ReadPacket(r)
281 if err != nil {
282 t.Fatalf("ReadPacket: %v", err)
283 }
284 if !p.IsReply() {
285 t.Fatal("expected reply")
286 }
287 if len(p.Raw) != 32+pad4(len(val)) {
288 t.Errorf("reply length = %d", len(p.Raw))
289 }
290 }
291
292 // errorPacket builds a 32-byte X11 error with the given error code.
293 func errorPacket(code byte) []byte {
294 b := make([]byte, 32)
295 b[0] = 0
296 b[1] = code
297 return b
298 }
299
300 // eventPacket builds a 32-byte event with the given code.
301 func eventPacket(code byte) []byte {
302 b := make([]byte, 32)
303 b[0] = code
304 return b
305 }
306
307 // TestNextEventIgnoresErrors is the pure-Go regression for #61: an X11 protocol
308 // error must never abort the process. NextEvent decodes and drops the error and
309 // returns the following event, proving the crash class is impossible.
310 func TestNextEventIgnoresErrors(t *testing.T) {
311 stream := append(errorPacket(9 /*BadDrawable*/), eventPacket(EventSelectionRequest)...)
312 p, err := NextEvent(bytes.NewReader(stream))
313 if err != nil {
314 t.Fatalf("NextEvent: %v", err)
315 }
316 if p.EventCode() != EventSelectionRequest {
317 t.Errorf("event code = %d, want %d", p.EventCode(), EventSelectionRequest)
318 }
319 }
320
321 func TestNextEventMasksSendEventBit(t *testing.T) {
322 p, err := NextEvent(bytes.NewReader(eventPacket(EventSelectionNotify | 0x80)))
323 if err != nil {
324 t.Fatalf("NextEvent: %v", err)
325 }
326 if p.EventCode() != EventSelectionNotify {
327 t.Errorf("event code = %d, want %d", p.EventCode(), EventSelectionNotify)
328 }
329 }
330
331 func TestSequenceAndErrorCode(t *testing.T) {
332 b := errorPacket(11)
333 binary.LittleEndian.PutUint16(b[2:], 1234)
334 p := Packet{Raw: b}
335 if p.Sequence() != 1234 {
336 t.Errorf("Sequence = %d, want 1234", p.Sequence())
337 }
338 if p.ErrorCode() != 11 {
339 t.Errorf("ErrorCode = %d, want 11", p.ErrorCode())
340 }
341 }
342
343 func TestNextReplyFailsOnError(t *testing.T) {
344 if _, err := NextReply(bytes.NewReader(errorPacket(2))); err == nil {
345 t.Error("NextReply should fail on an error packet")
346 }
347 }
348
349 func TestPropertyValueDecode(t *testing.T) {
350 // format 8, 5 items -> "hello"
351 b := makeReply([]byte("hello\x00\x00\x00"))
352 b[1] = 8
353 binary.LittleEndian.PutUint32(b[16:], 5)
354 p := Packet{Raw: b}
355 if got := string(p.PropertyValue()); got != "hello" {
356 t.Errorf("PropertyValue = %q, want hello", got)
357 }
358 // format 0 -> no data
359 z := makeReply(nil)
360 z[1] = 0
361 if got := (Packet{Raw: z}).PropertyValue(); got != nil {
362 t.Errorf("PropertyValue(format 0) = %v, want nil", got)
363 }
364 }
365
366 func TestAtomAndOwnerDecode(t *testing.T) {
367 b := make([]byte, 32)
368 b[0] = 1
369 binary.LittleEndian.PutUint32(b[8:], 0x123)
370 if got := (Packet{Raw: b}).Atom(); got != 0x123 {
371 t.Errorf("Atom = %#x", got)
372 }
373 if got := (Packet{Raw: b}).SelectionOwner(); got != 0x123 {
374 t.Errorf("SelectionOwner = %#x", got)
375 }
376 }
377
378 func TestSelectionRequestDecode(t *testing.T) {
379 ev := SendSelectionNotify(SelectionNotify{
380 Time: 7, Requestor: 0x10, Selection: 0x20, Target: 0x30, Property: 0x40,
381 })
382 // The event body sits at offset 12 of a SendEvent request; feed just the
383 // 32-byte event back through the decoder.
384 p := Packet{Raw: ev[12:44]}
385 if p.EventCode() != EventSelectionNotify {
386 t.Fatalf("event code = %d", p.EventCode())
387 }
388 sn := p.SelectionNotify()
389 if sn.Requestor != 0x10 || sn.Selection != 0x20 || sn.Target != 0x30 || sn.Property != 0x40 {
390 t.Errorf("SelectionNotify decode = %+v", sn)
391 }
392 }