summaryrefslogtreecommitdiff
path: root/xgob.go
blob: fc76de7c6b28008f2d67153e8ad22d605f839cbd (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
package xgob

import (
		"bufio"
		"bytes"
		"io"
		"net"
		"os"
		"strconv"
		"strings"
		"sync"
	   )

const X_TCP_PORT = 6000

type ConnectionBlock struct {
	Major, Minor uint16
	todo []byte
}

type Event struct {
	EventType	uint8
	Sent		bool
	Remainder	[31]byte
}

type Error struct {
	Sequence	uint64
	BadValue	uint32
	Minor		uint16
	Major		uint8
	Error		uint8
}

type Reply struct {
	Sequence	uint64
	Length		uint32
	Remainder	[]byte
	Aux			byte
}

type Connection struct {
	Setup				ConnectionBlock
	Event				chan Event
	conn				io.ReadWriteCloser
	reply				map[uint64]chan interface {}
	replyMutex			sync.Mutex
	lastRequestWritten	uint64
	lastSequenceRead	uint64
}

const events_before_readblock = 10000

func parse_display (name string) (host string, protocol string, display int, screen int) {
    if len(name) == 0 {
		name = os.Getenv("DISPLAY")
	}
    if len(name) == 0 {
        return
	}

    if !strings.HasPrefix(name, "/tmp/launch") {
		slash := strings.LastIndex(name, "/")
		if slash >= 0 {
			protocol = name[:slash]
			name = name[slash+1:]
		}
	}

	var err os.Error
	
    dot := strings.LastIndex(name, ".");
	if dot >= 0 {
		screen,err = strconv.Atoi(name[dot+1:])
		if err == nil {
			name = name[:dot]
		}
	}
    colon := strings.LastIndex(name, ":");
    if colon < 0 {
		return
	}
	display, err = strconv.Atoi(name[colon+1:])
	if err != nil {
		return
	}
	host = name[:colon]
	return
}

func open(host string, protocol string, display int) io.ReadWriteCloser {
	unix_base := "/tmp/.X11-unix/X";
	base := unix_base

	if strings.HasPrefix(host, "/tmp/launch") {
		base = host
		host = ""
		protocol = ""
	}

	if(len(host) > 0 || len(protocol) > 0) {
		if len(protocol) > 0 || "unix" == host { /* follow the old unix: rule */
			/* display specifies TCP */
			port := X_TCP_PORT + display;
			return open_tcp(host, protocol, port);
		}
	}

	var file string
	/* display specifies Unix socket */
	if strings.HasPrefix(base, "/tmp/launch") {
		file = base + ":" + strconv.Itoa(display)
	} else {
		file = base + strconv.Itoa(display)
	}

    return open_unix(protocol, file)
}

func open_tcp(host string, protocol string, port int) io.ReadWriteCloser {
	if len(protocol) > 0 && "tcp" != protocol && "inet" != protocol && "inet6" != protocol {
		return nil;
	}
	proto := "tcp"
	if protocol == "inet6" {
		proto = "tcp6"
	}

	if len(host) == 0 {
		host = "localhost"
	}

	conn, err := net.Dial(proto, "", host + ":" + strconv.Itoa(port))
	// TODO - remove
	if err != nil {
		println("TCP error ", err.String())
	}
	return conn
}

func open_unix(protocol string, file string) io.ReadWriteCloser {
	if len(protocol) > 0 && "unix" != protocol {
		return nil
	}

	conn, err := net.Dial(protocol, "", file)
	// TODO - remove
	if err != nil {
		println("Unix socket error ", err.String())
	}
	return conn
}

func Pad (i int) int {
	return (-i) & 3
}

func (c *Connection) write_setup (name string, data string) {
	buf := make([]byte, 0, 100)

	buf = append(buf, 'B')		// Big endian.
	buf = append(buf, 'l')
	buf = append(buf, 0, 11)	// X11
	buf = append(buf, 0, 0)		// .0
	buf = append(buf, byte((len(name) & 0xFF00) >> 8), byte(len(name) & 0xFF))
	buf = append(buf, byte((len(data) & 0xFF00) >> 8), byte(len(data) & 0xFF))
	buf = append(buf, 0, 0)		// pad

	if len(name) > 0 && len(data) > 0 {
		n := bytes.NewBufferString(name)
		buf = append(buf, n.Bytes()...)
		for i := 0; i < Pad(len(name)); i++ {
			buf = append(buf, 0)
		}
		n = bytes.NewBufferString(data)
		buf = append(buf, n.Bytes()...)
		for i := 0; i < Pad(len(data)); i++ {
			buf = append(buf, 0)
		}
	}

	c.conn.Write(buf)
}

func getUint16(in *bufio.Reader) uint16 {
	var rv uint16
	i, _ := in.ReadByte()
	rv = uint16(i) << 8
	i, _ = in.ReadByte()
	rv |= uint16(i)
	return rv
}

func getUint32(in *bufio.Reader) uint32 {
	var rv uint32
	i, _ := in.ReadByte()
	rv = uint32(i) << 24
	i, _ = in.ReadByte()
	rv |= uint32(i) << 16
	i, _ = in.ReadByte()
	rv |= uint32(i) << 8
	i, _ = in.ReadByte()
	rv |= uint32(i)
	return rv
}

func skipBytes (in *bufio.Reader, skip uint) {
	for i := uint(0); i < skip; i++ {
		_, _ = in.ReadByte()
	}
}

func readAll(in *bufio.Reader, buf []byte) {
	var read int
	len := len(buf)
	for read < len {
		input, err := in.Read(buf[read:])
		if err != nil {
			return
		}
		read += input
	}
}

func (c *Connection) read_setup(in *bufio.Reader) bool {
	status, _ := in.ReadByte()
	reason_len, _ := in.ReadByte()
	c.Setup.Major = getUint16(in)
	c.Setup.Minor = getUint16(in)
	len := getUint16(in)

	c.Setup.todo = make([]byte, len * 4)
	readAll(in, c.Setup.todo)

	switch status {
	case 0:
		println("Server refused connection because")
		println(bytes.NewBuffer(c.Setup.todo[:reason_len]).String())
	case 1:
		/* Success */
		return true
	case 2:
		println("Server requires authentication")
		println(bytes.NewBuffer(c.Setup.todo).String())
	default:
		panic("Unexpected return value from server " + strconv.Uitoa(uint(status)))
	}
	return false
}

func (c *Connection) fullSeq(seq uint16) uint64 {
	var fs uint64
	fs = (c.lastSequenceRead &^ 0xFFFF) | uint64(seq)
	if fs < c.lastSequenceRead {
		fs += 0x10000
	}
	return fs
}

func (c *Connection) postReply (seq uint64, reply interface{}) {
	c.replyMutex.Lock()
	defer c.replyMutex.Unlock()

	if c.reply[seq] == nil {
		println("Error: Unexpected sequence", seq)
		return
	}

	for i := c.lastSequenceRead; i < seq; i++ {
		c.reply[i] <- nil
		c.reply[i] = nil, false
	}
	c.reply[seq] <- reply
	c.lastSequenceRead = seq
}

func (c *Connection) read (in *bufio.Reader) {
	for {
		t, err := in.ReadByte()
		if err != nil {
			c.conn = nil
			return
		}

		switch t {
		case 0:
			var e Error
			e.Error, _ = in.ReadByte()
			e.Sequence = c.fullSeq(getUint16(in))
			e.BadValue = getUint32(in)
			e.Minor = getUint16(in)
			e.Major, _ = in.ReadByte()
			skipBytes(in, 20)
			c.postReply(e.Sequence, e)
		case 1:
			var r Reply
			r.Aux, _ = in.ReadByte()
			r.Sequence = c.fullSeq(getUint16(in))
			r.Length = getUint32(in)
			r.Remainder = make([]byte, r.Length * 4 + 24)
			readAll(in, r.Remainder)
			c.postReply(r.Sequence, r)
		default:
			var e Event
			e.EventType = t
			if t & 0x80 != 0 {
				e.EventType = t & 0x7F
				e.Sent = true
			}
			readAll(in, e.Remainder[:])
			c.Event <- e
		// TODO GenericEvent
		}
	}
}

func (c *Connection)connect_auth(name string, data string) {
	c.write_setup(name, data)
	in := bufio.NewReader(c.conn)
	if !c.read_setup(in) {
		c.Disconnect()
		return
	}
	c.Event = make (chan Event, events_before_readblock)
	c.reply = make (map [uint64]chan interface{})
	c.lastSequenceRead = 1			// Not really, but this prevents writing to a nil channel
	go c.read(in)
}

func Connect (dpy string) (conn *Connection, screen int) {
	host, proto, display, screen := parse_display(dpy)

	var c Connection
	c.conn = open(host, proto, display);

    if c.conn == nil {
		return
	}

	// TODO: name, data := c.get_auth_info()
	name, data := "", ""
	c.connect_auth(name, data);
	conn = &c
	return
}

func (c *Connection) Disconnect () {
	c.conn.Close()
	c.conn = nil
}

func (c *Connection) WriteMultiRequest (req []byte, expected int) chan interface{} {
	rv := make(chan interface {}, expected)

	if c == nil || c.conn == nil {
		return rv
	}

	c.replyMutex.Lock()
	defer c.replyMutex.Unlock()

	c.lastRequestWritten++
	c.reply[c.lastRequestWritten] = rv

	c.conn.Write(req)
	return rv
}

func (c *Connection) WriteRequest (req []byte) chan interface{} {
	return c.WriteMultiRequest(req, 1)
}

func (c *Connection) Flush () {
	// TODO buffer WriteRequest
}

func (c *Connection) HasError () bool {
	if c == nil || c.conn == nil {
		return true
	}
	return false
}