aboutsummaryrefslogtreecommitdiff
path: root/nexgb/xgb.go
blob: 0dd8163db8604b10751f6db48130cdc57523efc0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// Copyright 2009 The XGB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// The XGB package implements the X11 core protocol.
// It is based on XCB: http://xcb.freedesktop.org/
package xgb

import (
	"errors"
	"fmt"
	"io"
	"net"
	"os"
	"strconv"
	"strings"
	"sync"
)

const (
	readBuffer  = 100
	writeBuffer = 100
)

// A Conn represents a connection to an X server.
// Only one goroutine should use a Conn's methods at a time.
type Conn struct {
	host          string
	conn          net.Conn
	nextId        Id
	nextCookie    uint16
	cookies       map[uint16]*Cookie
	events        queue
	err           error
	display       string
	defaultScreen int
	scratch       [32]byte
	Setup         SetupInfo
	extensions    map[string]byte

	requestChan       chan *Request
	requestCookieChan chan *Cookie
	replyChan         chan bool
	eventChan         chan bool
	errorChan         chan bool

	newIdLock   sync.Mutex
	writeLock   sync.Mutex
	dequeueLock sync.Mutex
	cookieLock  sync.Mutex
	extLock     sync.Mutex
}

// Id is used for all X identifiers, such as windows, pixmaps, and GCs.
type Id uint32

// Request is used to abstract the difference between a request
// that expects a reply and a request that doesn't expect a reply.
type Request struct {
	buf        []byte
	cookieChan chan *Cookie
}

func newRequest(buf []byte, needsReply bool) *Request {
	req := &Request{
		buf:        buf,
		cookieChan: nil,
	}
	if needsReply {
		req.cookieChan = make(chan *Cookie)
	}
	return req
}

// Cookies are the sequence numbers used to pair replies up with their requests
type Cookie struct {
	id        uint16
	replyChan chan []byte
	errorChan chan error
}

func newCookie(id uint16) *Cookie {
	return &Cookie{
		id:        id,
		replyChan: make(chan []byte, 1),
		errorChan: make(chan error, 1),
	}
}

// Event is an interface that can contain any of the events returned by the
// server. Use a type assertion switch to extract the Event structs.
type Event interface {
	ImplementsEvent()
}

// newEventFuncs is a map from event numbers to functions that create
// the corresponding event.
var newEventFuncs = map[int]func(buf []byte) Event{}

// Error is an interface that can contain any of the errors returned by
// the server. Use a type assertion switch to extract the Error structs.
type Error interface {
	ImplementsError()
	SequenceId() uint16
	BadId() Id
	Error() string
}

// newErrorFuncs is a map from error numbers to functions that create
// the corresponding error.
var newErrorFuncs = map[int]func(buf []byte) Error{}

// NewID generates a new unused ID for use with requests like CreateWindow.
func (c *Conn) NewId() Id {
	c.newIdLock.Lock()
	defer c.newIdLock.Unlock()

	id := c.nextId
	// TODO: handle ID overflow
	c.nextId++
	return id
}

// RegisterExtension adds the respective extension's major op code to
// the extensions map.
func (c *Conn) RegisterExtension(name string) error {
	nameUpper := strings.ToUpper(name)
	reply, err := c.QueryExtension(uint16(len(nameUpper)), nameUpper)

	switch {
	case err != nil:
		return err
	case !reply.Present:
		return errors.New(fmt.Sprintf("No extension named '%s' is present.",
			nameUpper))
	}

	c.extLock.Lock()
	c.extensions[nameUpper] = reply.MajorOpcode
	c.extLock.Unlock()

	return nil
}

// A simple queue used to stow away events.
type queue struct {
	data [][]byte
	a, b int
}

func (q *queue) queue(item []byte) {
	if q.b == len(q.data) {
		if q.a > 0 {
			copy(q.data, q.data[q.a:q.b])
			q.a, q.b = 0, q.b-q.a
		} else {
			newData := make([][]byte, (len(q.data)*3)/2)
			copy(newData, q.data)
			q.data = newData
		}
	}
	q.data[q.b] = item
	q.b++
}

func (q *queue) dequeue(c *Conn) []byte {
	c.dequeueLock.Lock()
	defer c.dequeueLock.Unlock()

	if q.a < q.b {
		item := q.data[q.a]
		q.a++
		return item
	}
	return nil
}

// newWriteChan creates the channel required for writing to the net.Conn.
func (c *Conn) newRequestChannels() {
	c.requestChan = make(chan *Request, writeBuffer)
	c.requestCookieChan = make(chan *Cookie, 1)

	go func() {
		for request := range c.requestChan {
			cookieNum := c.nextCookie
			c.nextCookie++

			if request.cookieChan != nil {
				cookie := newCookie(cookieNum)
				c.cookies[cookieNum] = cookie
				request.cookieChan <- cookie
			}
			if _, err := c.conn.Write(request.buf); err != nil {
				fmt.Fprintf(os.Stderr, "x protocol write error: %s\n", err)
				close(c.requestChan)
				return
			}
		}
	}()
}

// request is a buffered write to net.Conn.
func (c *Conn) request(buf []byte, needsReply bool) *Cookie {
	req := newRequest(buf, needsReply)
	c.requestChan <- req

	if req.cookieChan != nil {
		cookie := <-req.cookieChan
		close(req.cookieChan)
		return cookie
	}
	return nil
}

func (c *Conn) sendRequest(needsReply bool, bufs ...[]byte) *Cookie {
	if len(bufs) == 1 {
		return c.request(bufs[0], needsReply)
	}

	total := make([]byte, 0)
	for _, buf := range bufs {
		total = append(total, buf...)
	}
	return c.request(total, needsReply)
}

func (c *Conn) newReadChannels() {
	c.eventChan = make(chan bool, readBuffer)

	onError := func() {
		panic("read error")
	}

	go func() {
		for {
			buf := make([]byte, 32)
			if _, err := io.ReadFull(c.conn, buf); err != nil {
				fmt.Fprintf(os.Stderr, "x protocol read error: %s\n", err)
				onError()
				return
			}

			switch buf[0] {
			case 0:
				// err := &Error{ 
					// Detail: buf[1], 
					// Cookie: uint16(get16(buf[2:])), 
					// Id:     Id(get32(buf[4:])), 
					// Minor:  get16(buf[8:]), 
					// Major:  buf[10], 
				// } 
				err := newErrorFuncs[int(buf[1])](buf)
				if cookie, ok := c.cookies[err.SequenceId()]; ok {
					cookie.errorChan <- err
				} else {
					fmt.Fprintf(os.Stderr, "x protocol error: %s\n", err)
				}
			case 1:
				seq := uint16(Get16(buf[2:]))
				if _, ok := c.cookies[seq]; !ok {
					continue
				}

				size := Get32(buf[4:])
				if size > 0 {
					bigbuf := make([]byte, 32+size*4, 32+size*4)
					copy(bigbuf[0:32], buf)
					if _, err := io.ReadFull(c.conn, bigbuf[32:]); err != nil {
						fmt.Fprintf(os.Stderr,
							"x protocol read error: %s\n", err)
						onError()
						return
					}
					c.cookies[seq].replyChan <- bigbuf
				} else {
					c.cookies[seq].replyChan <- buf
				}
			default:
				c.events.queue(buf)
				select {
				case c.eventChan <- true:
				default:
				}
			}
		}
	}()
}

func (c *Conn) waitForReply(cookie *Cookie) ([]byte, error) {
	if cookie == nil {
		panic("nil cookie")
	}
	if _, ok := c.cookies[cookie.id]; !ok {
		panic("waiting for a cookie that will never come")
	}
	select {
	case reply := <-cookie.replyChan:
		return reply, nil
	case err := <-cookie.errorChan:
		return nil, err
	}
	panic("unreachable")
}

// WaitForEvent returns the next event from the server.
// It will block until an event is available.
func (c *Conn) WaitForEvent() (Event, error) {
	for {
		if reply := c.events.dequeue(c); reply != nil {
			evCode := reply[0] & 0x7f
			return newEventFuncs[int(evCode)](reply), nil
		}
		if !<-c.eventChan {
			return nil, errors.New("Event channel has been closed.")
		}
	}
	panic("unreachable")
}

// PollForEvent returns the next event from the server if one is available in the internal queue.
// It will not read from the connection, so you must call WaitForEvent to receive new events.
// Only use this function to empty the queue without blocking.
func (c *Conn) PollForEvent() (Event, error) {
	if reply := c.events.dequeue(c); reply != nil {
		evCode := reply[0] & 0x7f
		return newEventFuncs[int(evCode)](reply), nil
	}
	return nil, nil
}

// Dial connects to the X server given in the 'display' string.
// If 'display' is empty it will be taken from os.Getenv("DISPLAY").
//
// Examples:
//	Dial(":1")                 // connect to net.Dial("unix", "", "/tmp/.X11-unix/X1")
//	Dial("/tmp/launch-123/:0") // connect to net.Dial("unix", "", "/tmp/launch-123/:0")
//	Dial("hostname:2.1")       // connect to net.Dial("tcp", "", "hostname:6002")
//	Dial("tcp/hostname:1.0")   // connect to net.Dial("tcp", "", "hostname:6001")
func Dial(display string) (*Conn, error) {
	c, err := connect(display)
	if err != nil {
		return nil, err
	}

	// Get authentication data
	authName, authData, err := readAuthority(c.host, c.display)
	noauth := false
	if err != nil {
		fmt.Fprintf(os.Stderr, "Could not get authority info: %v\n", err)
		fmt.Fprintf(os.Stderr, "Trying connection without authority info...\n")
		authName = ""
		authData = []byte{}
		noauth = true
	}

	// Assume that the authentication protocol is "MIT-MAGIC-COOKIE-1".
	if !noauth && (authName != "MIT-MAGIC-COOKIE-1" || len(authData) != 16) {
		return nil, errors.New("unsupported auth protocol " + authName)
	}

	buf := make([]byte, 12+pad(len(authName))+pad(len(authData)))
	buf[0] = 0x6c
	buf[1] = 0
	Put16(buf[2:], 11)
	Put16(buf[4:], 0)
	Put16(buf[6:], uint16(len(authName)))
	Put16(buf[8:], uint16(len(authData)))
	Put16(buf[10:], 0)
	copy(buf[12:], []byte(authName))
	copy(buf[12+pad(len(authName)):], authData)
	if _, err = c.conn.Write(buf); err != nil {
		return nil, err
	}

	head := make([]byte, 8)
	if _, err = io.ReadFull(c.conn, head[0:8]); err != nil {
		return nil, err
	}
	code := head[0]
	reasonLen := head[1]
	major := Get16(head[2:])
	minor := Get16(head[4:])
	dataLen := Get16(head[6:])

	if major != 11 || minor != 0 {
		return nil, errors.New(fmt.Sprintf("x protocol version mismatch: %d.%d", major, minor))
	}

	buf = make([]byte, int(dataLen)*4+8, int(dataLen)*4+8)
	copy(buf, head)
	if _, err = io.ReadFull(c.conn, buf[8:]); err != nil {
		return nil, err
	}

	if code == 0 {
		reason := buf[8 : 8+reasonLen]
		return nil, errors.New(fmt.Sprintf("x protocol authentication refused: %s", string(reason)))
	}

	ReadSetupInfo(buf, &c.Setup)

	if c.defaultScreen >= len(c.Setup.Roots) {
		c.defaultScreen = 0
	}

	c.nextId = Id(c.Setup.ResourceIdBase)
	c.nextCookie = 1
	c.cookies = make(map[uint16]*Cookie)
	c.events = queue{make([][]byte, 100), 0, 0}
	c.extensions = make(map[string]byte)

	c.newReadChannels()
	c.newRequestChannels()
	return c, nil
}

// Close closes the connection to the X server.
func (c *Conn) Close() { c.conn.Close() }

func connect(display string) (*Conn, error) {
	if len(display) == 0 {
		display = os.Getenv("DISPLAY")
	}

	display0 := display
	if len(display) == 0 {
		return nil, errors.New("empty display string")
	}

	colonIdx := strings.LastIndex(display, ":")
	if colonIdx < 0 {
		return nil, errors.New("bad display string: " + display0)
	}

	var protocol, socket string
	c := new(Conn)

	if display[0] == '/' {
		socket = display[0:colonIdx]
	} else {
		slashIdx := strings.LastIndex(display, "/")
		if slashIdx >= 0 {
			protocol = display[0:slashIdx]
			c.host = display[slashIdx+1 : colonIdx]
		} else {
			c.host = display[0:colonIdx]
		}
	}

	display = display[colonIdx+1 : len(display)]
	if len(display) == 0 {
		return nil, errors.New("bad display string: " + display0)
	}

	var scr string
	dotIdx := strings.LastIndex(display, ".")
	if dotIdx < 0 {
		c.display = display[0:]
	} else {
		c.display = display[0:dotIdx]
		scr = display[dotIdx+1:]
	}

	dispnum, err := strconv.Atoi(c.display)
	if err != nil || dispnum < 0 {
		return nil, errors.New("bad display string: " + display0)
	}

	if len(scr) != 0 {
		c.defaultScreen, err = strconv.Atoi(scr)
		if err != nil {
			return nil, errors.New("bad display string: " + display0)
		}
	}

	// Connect to server
	if len(socket) != 0 {
		c.conn, err = net.Dial("unix", socket+":"+c.display)
	} else if len(c.host) != 0 {
		if protocol == "" {
			protocol = "tcp"
		}
		c.conn, err = net.Dial(protocol, c.host+":"+strconv.Itoa(6000+dispnum))
	} else {
		c.conn, err = net.Dial("unix", "/tmp/.X11-unix/X"+c.display)
	}

	if err != nil {
		return nil, errors.New("cannot connect to " + display0 + ": " + err.Error())
	}
	return c, nil
}