Debian Codegraph @

x11.go

raw
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 is a minimal, dependency-free client for the X11 wire protocol:
8 // connection setup and authentication, atom interning, window and property
9 // requests, the selection (clipboard) protocol, and packet decoding. It is
10 // pure Go — no Cgo and no libX11 — and contains only the encoding/decoding and
11 // parsing logic (no sockets), so callers supply their own transport and it can
12 // be unit tested on any platform.
13 //
14 // It was extracted from golang.design/x/clipboard, where it backs the Cgo-free
15 // X11 clipboard on Linux and the BSDs.
16 //
17 // References: the X Window System Protocol, version 11
18 // (https://www.x.org/releases/current/doc/xproto/x11protocol.html).
19 package x11
20
21 import (
22 "encoding/binary"
23 "fmt"
24 "io"
25 "strconv"
26 "strings"
27 )
28
29 // X11 request opcodes (subset).
30 const (
31 opCreateWindow = 1
32 opChangeProperty = 18
33 opDeleteProperty = 19
34 opGetProperty = 20
35 opSetSelectionOwner = 22
36 opGetSelectionOwner = 23
37 opConvertSelection = 24
38 opSendEvent = 25
39 opInternAtom = 16
40 opGetAtomName = 17
41 opGetInputFocus = 43
42 )
43
44 // X11 event codes (subset).
45 const (
46 EventSelectionClear = 29
47 EventSelectionRequest = 30
48 EventSelectionNotify = 31
49 )
50
51 // Predefined atoms and constants from the core protocol.
52 const (
53 None uint32 = 0 // no atom / no window / no property
54 CurrentTime uint32 = 0
55 AtomATOM uint32 = 4 // XA_ATOM
56 classInOut = 1 // InputOutput window class
57 modeReplace = 0 // PropModeReplace
58 )
59
60 // le is the little-endian byte order used on supported targets; the byte order
61 // is declared in the connection setup request (see SetupRequest).
62 var le = binary.LittleEndian
63
64 // pad4 rounds n up to a multiple of four (X11 pads all variable fields).
65 func pad4(n int) int { return (n + 3) &^ 3 }
66
67 // ---------------------------------------------------------------------------
68 // $DISPLAY parsing
69 // ---------------------------------------------------------------------------
70
71 // Display describes where to reach the X server.
72 type Display struct {
73 Net string // "unix" or "tcp"
74 Addr string // socket path or host:port
75 Num int // display number
76 }
77
78 // ParseDisplay parses a $DISPLAY value of the form
79 // "[host]:display[.screen]". An empty or "unix" host selects the unix-domain
80 // socket /tmp/.X11-unix/X<display>; any other host selects TCP at
81 // host:(6000+display).
82 func ParseDisplay(display string) (Display, error) {
83 if display == "" {
84 return Display{}, fmt.Errorf("x11: empty DISPLAY")
85 }
86 colon := strings.LastIndex(display, ":")
87 if colon < 0 {
88 return Display{}, fmt.Errorf("x11: invalid DISPLAY %q", display)
89 }
90 host := display[:colon]
91 rest := display[colon+1:]
92 if dot := strings.IndexByte(rest, '.'); dot >= 0 {
93 rest = rest[:dot] // drop the optional screen number
94 }
95 num, err := strconv.Atoi(rest)
96 if err != nil {
97 return Display{}, fmt.Errorf("x11: invalid display number in %q", display)
98 }
99 if host == "" || host == "unix" {
100 return Display{Net: "unix", Addr: "/tmp/.X11-unix/X" + strconv.Itoa(num), Num: num}, nil
101 }
102 return Display{Net: "tcp", Addr: host + ":" + strconv.Itoa(6000+num), Num: num}, nil
103 }
104
105 // ---------------------------------------------------------------------------
106 // .Xauthority parsing and cookie selection
107 // ---------------------------------------------------------------------------
108
109 // Authority family values (.Xauthority stores these big-endian).
110 const (
111 FamilyInternet uint16 = 0
112 FamilyLocal uint16 = 256
113 FamilyWild uint16 = 65535
114 )
115
116 // AuthEntry is one record from an .Xauthority file.
117 type AuthEntry struct {
118 Family uint16
119 Address string
120 Number string
121 Name string
122 Data []byte
123 }
124
125 // ParseXauthority parses the binary .Xauthority format: a sequence of records,
126 // each a big-endian uint16 family followed by four (uint16 length, bytes)
127 // fields: address, number, name, data.
128 func ParseXauthority(b []byte) ([]AuthEntry, error) {
129 var entries []AuthEntry
130 for len(b) > 0 {
131 if len(b) < 2 {
132 return nil, fmt.Errorf("x11: truncated .Xauthority")
133 }
134 var e AuthEntry
135 e.Family = binary.BigEndian.Uint16(b)
136 b = b[2:]
137 fields := make([][]byte, 4)
138 for i := range fields {
139 if len(b) < 2 {
140 return nil, fmt.Errorf("x11: truncated .Xauthority field")
141 }
142 n := int(binary.BigEndian.Uint16(b))
143 b = b[2:]
144 if len(b) < n {
145 return nil, fmt.Errorf("x11: truncated .Xauthority value")
146 }
147 fields[i] = b[:n]
148 b = b[n:]
149 }
150 e.Address = string(fields[0])
151 e.Number = string(fields[1])
152 e.Name = string(fields[2])
153 e.Data = fields[3]
154 entries = append(entries, e)
155 }
156 return entries, nil
157 }
158
159 // MITCookie is the authorization protocol name X uses for cookies.
160 const MITCookie = "MIT-MAGIC-COOKIE-1"
161
162 // ChooseCookie selects the MIT-MAGIC-COOKIE-1 entry matching the given display
163 // number and hostname, preferring a Local entry for this host, then a Wild
164 // entry, then any cookie for the display. It returns ("", nil) when no cookie
165 // applies, in which case the caller connects without authorization (common and
166 // often authorized for local unix sockets).
167 func ChooseCookie(entries []AuthEntry, displayNum int, hostname string) (name string, data []byte) {
168 want := strconv.Itoa(displayNum)
169 var wild, any []byte
170 for _, e := range entries {
171 if e.Name != MITCookie {
172 continue
173 }
174 if e.Number != "" && e.Number != want {
175 continue
176 }
177 switch {
178 case e.Family == FamilyLocal && e.Address == hostname:
179 return MITCookie, e.Data // best match
180 case e.Family == FamilyWild && wild == nil:
181 wild = e.Data
182 case any == nil:
183 any = e.Data
184 }
185 }
186 if wild != nil {
187 return MITCookie, wild
188 }
189 if any != nil {
190 return MITCookie, any
191 }
192 return "", nil
193 }
194
195 // ---------------------------------------------------------------------------
196 // Connection setup
197 // ---------------------------------------------------------------------------
198
199 // SetupRequest builds the connection setup request declaring little-endian byte
200 // order, protocol 11.0, and the given authorization protocol name and data.
201 func SetupRequest(authName string, authData []byte) []byte {
202 n, d := len(authName), len(authData)
203 b := make([]byte, 12+pad4(n)+pad4(d))
204 b[0] = 'l' // little-endian
205 le.PutUint16(b[2:], 11)
206 le.PutUint16(b[4:], 0)
207 le.PutUint16(b[6:], uint16(n))
208 le.PutUint16(b[8:], uint16(d))
209 copy(b[12:], authName)
210 copy(b[12+pad4(n):], authData)
211 return b
212 }
213
214 // Setup holds the fields parsed from a successful connection setup reply.
215 type Setup struct {
216 IDBase uint32
217 IDMask uint32
218 Root uint32
219 MaxReqLen uint16
220 }
221
222 // ReadSetup reads and parses the connection setup reply from r.
223 func ReadSetup(r io.Reader) (Setup, error) {
224 h := make([]byte, 8)
225 if _, err := io.ReadFull(r, h); err != nil {
226 return Setup{}, err
227 }
228 add := make([]byte, int(le.Uint16(h[6:]))*4)
229 if _, err := io.ReadFull(r, add); err != nil {
230 return Setup{}, err
231 }
232 switch h[0] {
233 case 1: // success
234 return parseSetupAdditional(add)
235 case 0: // failed
236 return Setup{}, fmt.Errorf("x11: server refused connection: %s", string(trimReason(add, int(h[1]))))
237 case 2: // authenticate
238 return Setup{}, fmt.Errorf("x11: server requires authentication: %s", string(add))
239 default:
240 return Setup{}, fmt.Errorf("x11: unexpected setup reply code %d", h[0])
241 }
242 }
243
244 func trimReason(add []byte, n int) []byte {
245 if n > len(add) {
246 n = len(add)
247 }
248 return add[:n]
249 }
250
251 // parseSetupAdditional parses the "additional data" of a successful setup
252 // reply. The fixed header is 32 bytes; the first screen's root window follows
253 // the padded vendor string and the pixmap formats.
254 func parseSetupAdditional(add []byte) (Setup, error) {
255 if len(add) < 32 {
256 return Setup{}, fmt.Errorf("x11: short setup reply")
257 }
258 var s Setup
259 s.IDBase = le.Uint32(add[4:])
260 s.IDMask = le.Uint32(add[8:])
261 vendorLen := int(le.Uint16(add[16:]))
262 s.MaxReqLen = le.Uint16(add[18:])
263 numFormats := int(add[21])
264 screenOff := 32 + pad4(vendorLen) + 8*numFormats
265 if screenOff+4 > len(add) {
266 return Setup{}, fmt.Errorf("x11: setup reply missing screen")
267 }
268 s.Root = le.Uint32(add[screenOff:])
269 return s, nil
270 }
271
272 // ---------------------------------------------------------------------------
273 // Resource ID allocator
274 // ---------------------------------------------------------------------------
275
276 // IDGen allocates client resource IDs from the base/mask in the setup reply.
277 type IDGen struct {
278 base, mask, last uint32
279 }
280
281 // NewIDGen returns an allocator for the given setup.
282 func NewIDGen(s Setup) *IDGen { return &IDGen{base: s.IDBase, mask: s.IDMask} }
283
284 // Next returns the next free resource ID.
285 func (g *IDGen) Next() uint32 {
286 g.last++
287 return g.base | (g.last & g.mask)
288 }
289
290 // ---------------------------------------------------------------------------
291 // Request encoders
292 // ---------------------------------------------------------------------------
293
294 // reqHeader writes the standard request header (opcode, one data byte, and the
295 // length in 4-byte units) into b, whose length must be the full request size.
296 func reqHeader(b []byte, opcode, data byte) {
297 b[0] = opcode
298 b[1] = data
299 le.PutUint16(b[2:], uint16(len(b)/4))
300 }
301
302 // InternAtom builds an InternAtom request for the given name.
303 func InternAtom(name string, onlyIfExists bool) []byte {
304 b := make([]byte, 8+pad4(len(name)))
305 var oie byte
306 if onlyIfExists {
307 oie = 1
308 }
309 reqHeader(b, opInternAtom, oie)
310 le.PutUint16(b[4:], uint16(len(name)))
311 copy(b[8:], name)
312 return b
313 }
314
315 // GetAtomName builds a GetAtomName request, the inverse of InternAtom: it
316 // resolves an atom id back to its string name. The reply is decoded with
317 // Packet.AtomName.
318 func GetAtomName(atom uint32) []byte {
319 b := make([]byte, 8)
320 reqHeader(b, opGetAtomName, 0)
321 le.PutUint32(b[4:], atom)
322 return b
323 }
324
325 // CreateWindow builds a CreateWindow request for a 1x1 InputOutput window with
326 // no value list, inheriting depth and visual from the parent.
327 func CreateWindow(wid, parent uint32) []byte {
328 b := make([]byte, 32)
329 reqHeader(b, opCreateWindow, 0) // depth = CopyFromParent
330 le.PutUint32(b[4:], wid)
331 le.PutUint32(b[8:], parent)
332 // x, y, border-width = 0 (already zero)
333 le.PutUint16(b[16:], 1) // width
334 le.PutUint16(b[18:], 1) // height
335 le.PutUint16(b[22:], classInOut)
336 // visual = CopyFromParent (0), value-mask = 0 (already zero)
337 return b
338 }
339
340 // SetSelectionOwner builds a SetSelectionOwner request.
341 func SetSelectionOwner(owner, selection, time uint32) []byte {
342 b := make([]byte, 16)
343 reqHeader(b, opSetSelectionOwner, 0)
344 le.PutUint32(b[4:], owner)
345 le.PutUint32(b[8:], selection)
346 le.PutUint32(b[12:], time)
347 return b
348 }
349
350 // GetSelectionOwner builds a GetSelectionOwner request.
351 func GetSelectionOwner(selection uint32) []byte {
352 b := make([]byte, 8)
353 reqHeader(b, opGetSelectionOwner, 0)
354 le.PutUint32(b[4:], selection)
355 return b
356 }
357
358 // ConvertSelection builds a ConvertSelection request.
359 func ConvertSelection(requestor, selection, target, property, time uint32) []byte {
360 b := make([]byte, 24)
361 reqHeader(b, opConvertSelection, 0)
362 le.PutUint32(b[4:], requestor)
363 le.PutUint32(b[8:], selection)
364 le.PutUint32(b[12:], target)
365 le.PutUint32(b[16:], property)
366 le.PutUint32(b[20:], time)
367 return b
368 }
369
370 // ChangeProperty builds a ChangeProperty (mode Replace) request. format is 8 or
371 // 32; data is the raw bytes, and the protocol length field is derived as the
372 // number of format units in data.
373 func ChangeProperty(window, property, typ uint32, format byte, data []byte) []byte {
374 b := make([]byte, 24+pad4(len(data)))
375 reqHeader(b, opChangeProperty, modeReplace)
376 le.PutUint32(b[4:], window)
377 le.PutUint32(b[8:], property)
378 le.PutUint32(b[12:], typ)
379 b[16] = format
380 le.PutUint32(b[20:], uint32(len(data)/(int(format)/8)))
381 copy(b[24:], data)
382 return b
383 }
384
385 // GetProperty builds a GetProperty request retrieving up to longLength 32-bit
386 // units starting at longOffset, optionally deleting the property afterwards.
387 func GetProperty(del bool, window, property, typ, longOffset, longLength uint32) []byte {
388 b := make([]byte, 24)
389 var d byte
390 if del {
391 d = 1
392 }
393 reqHeader(b, opGetProperty, d)
394 le.PutUint32(b[4:], window)
395 le.PutUint32(b[8:], property)
396 le.PutUint32(b[12:], typ)
397 le.PutUint32(b[16:], longOffset)
398 le.PutUint32(b[20:], longLength)
399 return b
400 }
401
402 // GetInputFocus builds a GetInputFocus request. It takes no arguments and
403 // always produces a reply, so it serves as a cheap sync barrier to flush the
404 // results (including any errors) of preceding fire-and-forget requests.
405 func GetInputFocus() []byte {
406 b := make([]byte, 4)
407 reqHeader(b, opGetInputFocus, 0)
408 return b
409 }
410
411 // DeleteProperty builds a DeleteProperty request.
412 func DeleteProperty(window, property uint32) []byte {
413 b := make([]byte, 12)
414 reqHeader(b, opDeleteProperty, 0)
415 le.PutUint32(b[4:], window)
416 le.PutUint32(b[8:], property)
417 return b
418 }
419
420 // SelectionNotify is the body of a SelectionNotify event.
421 type SelectionNotify struct {
422 Time uint32
423 Requestor uint32
424 Selection uint32
425 Target uint32
426 Property uint32 // None to refuse
427 }
428
429 // SendSelectionNotify builds a SendEvent request delivering a SelectionNotify
430 // (non-propagating, empty event mask) to the requestor window.
431 func SendSelectionNotify(ev SelectionNotify) []byte {
432 b := make([]byte, 44)
433 reqHeader(b, opSendEvent, 0) // propagate = false
434 le.PutUint32(b[4:], ev.Requestor)
435 // event-mask = 0 at b[8:12]
436 e := b[12:44] // the 32-byte event
437 e[0] = EventSelectionNotify
438 le.PutUint32(e[4:], ev.Time)
439 le.PutUint32(e[8:], ev.Requestor)
440 le.PutUint32(e[12:], ev.Selection)
441 le.PutUint32(e[16:], ev.Target)
442 le.PutUint32(e[20:], ev.Property)
443 return b
444 }
445
446 // ---------------------------------------------------------------------------
447 // Packet reading and decoding
448 // ---------------------------------------------------------------------------
449
450 // Packet is one server-to-client message: an error, a reply, or an event.
451 type Packet struct {
452 Raw []byte // 32 bytes for errors/events; 32+ for replies
453 }
454
455 // IsError reports whether the packet is an X11 protocol error.
456 func (p Packet) IsError() bool { return p.Raw[0] == 0 }
457
458 // IsReply reports whether the packet is a request reply.
459 func (p Packet) IsReply() bool { return p.Raw[0] == 1 }
460
461 // IsEvent reports whether the packet is an event.
462 func (p Packet) IsEvent() bool { return p.Raw[0] >= 2 }
463
464 // EventCode returns the event type, masking off the SendEvent-generated bit.
465 func (p Packet) EventCode() byte { return p.Raw[0] & 0x7f }
466
467 // Sequence returns the low 16 bits of the sequence number of the request a
468 // reply or error corresponds to. Meaningless for events.
469 func (p Packet) Sequence() uint16 { return le.Uint16(p.Raw[2:]) }
470
471 // ErrorCode returns the X11 error code of an error packet.
472 func (p Packet) ErrorCode() byte { return p.Raw[1] }
473
474 // ReadPacket reads one packet from r. Replies carry an extra reply-length*4
475 // bytes beyond the 32-byte header.
476 func ReadPacket(r io.Reader) (Packet, error) {
477 hdr := make([]byte, 32)
478 if _, err := io.ReadFull(r, hdr); err != nil {
479 return Packet{}, err
480 }
481 if hdr[0] == 1 { // reply
482 if extra := int(le.Uint32(hdr[4:])) * 4; extra > 0 {
483 buf := make([]byte, 32+extra)
484 copy(buf, hdr)
485 if _, err := io.ReadFull(r, buf[32:]); err != nil {
486 return Packet{}, err
487 }
488 return Packet{Raw: buf}, nil
489 }
490 }
491 return Packet{Raw: hdr}, nil
492 }
493
494 // NextEvent reads packets from r until it returns an event, discarding X11
495 // errors and stray replies. Discarding errors here is precisely what makes an
496 // asynchronous X11 protocol error unable to terminate the process (#61): there
497 // is no library default handler, so an Error is just decoded and dropped.
498 func NextEvent(r io.Reader) (Packet, error) {
499 for {
500 p, err := ReadPacket(r)
501 if err != nil {
502 return Packet{}, err
503 }
504 if p.IsEvent() {
505 return p, nil
506 }
507 }
508 }
509
510 // NextReply reads packets from r until it returns a reply. It returns an error
511 // if an X11 Error packet arrives first (the request failed).
512 func NextReply(r io.Reader) (Packet, error) {
513 for {
514 p, err := ReadPacket(r)
515 if err != nil {
516 return Packet{}, err
517 }
518 if p.IsReply() {
519 return p, nil
520 }
521 if p.IsError() {
522 return Packet{}, fmt.Errorf("x11: request failed (error code %d)", p.Raw[1])
523 }
524 }
525 }
526
527 // Atom decodes the atom from an InternAtom reply.
528 func (p Packet) Atom() uint32 { return le.Uint32(p.Raw[8:]) }
529
530 // AtomName decodes the name from a GetAtomName reply. The 2-byte name length is
531 // at offset 8 and the name bytes follow the 32-byte reply header. It returns ""
532 // for a malformed or empty reply.
533 func (p Packet) AtomName() string {
534 if len(p.Raw) < 32 {
535 return ""
536 }
537 n := int(le.Uint16(p.Raw[8:]))
538 if n <= 0 || 32+n > len(p.Raw) {
539 return ""
540 }
541 return string(p.Raw[32 : 32+n])
542 }
543
544 // SelectionOwner decodes the window from a GetSelectionOwner reply.
545 func (p Packet) SelectionOwner() uint32 { return le.Uint32(p.Raw[8:]) }
546
547 // PropertyValue decodes the value bytes from a GetProperty reply, using the
548 // format and item count to compute the exact (unpadded) length.
549 func (p Packet) PropertyValue() []byte {
550 format := p.Raw[1]
551 if format == 0 {
552 return nil // property does not exist / no data
553 }
554 nItems := le.Uint32(p.Raw[16:])
555 n := int(nItems) * (int(format) / 8)
556 if 32+n > len(p.Raw) {
557 n = len(p.Raw) - 32
558 }
559 return p.Raw[32 : 32+n]
560 }
561
562 // SelectionRequestEvent decodes a SelectionRequest event body.
563 type SelectionRequestEvent struct {
564 Time uint32
565 Owner uint32
566 Requestor uint32
567 Selection uint32
568 Target uint32
569 Property uint32
570 }
571
572 // SelectionRequest decodes a SelectionRequest event.
573 func (p Packet) SelectionRequest() SelectionRequestEvent {
574 return SelectionRequestEvent{
575 Time: le.Uint32(p.Raw[4:]),
576 Owner: le.Uint32(p.Raw[8:]),
577 Requestor: le.Uint32(p.Raw[12:]),
578 Selection: le.Uint32(p.Raw[16:]),
579 Target: le.Uint32(p.Raw[20:]),
580 Property: le.Uint32(p.Raw[24:]),
581 }
582 }
583
584 // SelectionNotifyEvent decodes a SelectionNotify event (read path).
585 type SelectionNotifyEvent struct {
586 Requestor uint32
587 Selection uint32
588 Target uint32
589 Property uint32
590 }
591
592 // SelectionNotify decodes a SelectionNotify event.
593 func (p Packet) SelectionNotify() SelectionNotifyEvent {
594 return SelectionNotifyEvent{
595 Requestor: le.Uint32(p.Raw[8:]),
596 Selection: le.Uint32(p.Raw[12:]),
597 Target: le.Uint32(p.Raw[16:]),
598 Property: le.Uint32(p.Raw[20:]),
599 }
600 }
601
602 // AtomList encodes a list of atoms as ChangeProperty data (format 32).
603 func AtomList(atoms ...uint32) []byte {
604 b := make([]byte, 4*len(atoms))
605 for i, a := range atoms {
606 le.PutUint32(b[4*i:], a)
607 }
608 return b
609 }