File: dbus.go

package info (click to toggle)
golang-go-dbus 1~bzr20150122-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 328 kB
  • sloc: makefile: 13
file content (329 lines) | stat: -rw-r--r-- 8,214 bytes parent folder | download
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
// Package dbus provides a client interface to the D-Bus IPC system.
// It can be used to talk to system services (via the "system bus") or
// services within the user's session (via the "session bus").
package dbus

import (
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"strings"
	"sync"
	"sync/atomic"
)

type StandardBus int

const (
	SessionBus StandardBus = iota
	SystemBus
)

const (
	BUS_DAEMON_NAME  = "org.freedesktop.DBus"
	BUS_DAEMON_PATH  = ObjectPath("/org/freedesktop/DBus")
	BUS_DAEMON_IFACE = "org.freedesktop.DBus"
)

type MessageFilter struct {
	filter func(*Message) *Message
}

// Connection represents a connection to a message bus.
type Connection struct {
	// The unique name of this connection on the message bus.
	UniqueName string
	conn       net.Conn
	writeLock  sync.Mutex
	busProxy   BusDaemon
	lastSerial uint32

	handlerMutex       sync.Mutex // covers the next three
	messageFilters     []*MessageFilter
	methodCallReplies  map[uint32]chan<- *Message
	objectPathHandlers map[ObjectPath]chan<- *Message
	signalMatchRules   signalWatchSet

	nameInfoMutex sync.Mutex
	nameInfo      map[string]*nameInfo
}

// ObjectProxy represents a remote object on the bus.  It can be used
// to simplify constructing method calls, and acts as a basis for
// D-Bus interface client stubs.
type ObjectProxy struct {
	bus         *Connection
	destination string
	path        ObjectPath
}

func (o *ObjectProxy) ObjectPath() ObjectPath {
	return o.path
}

// Call the given method on the remote object.
//
// On success, the reply message will be returned, whose arguments can
// be unpacked with its Args() method.
//
// On failure (both network failures and D-Bus level errors), an error
// will be returned.
func (o *ObjectProxy) Call(iface, method string, args ...interface{}) (*Message, error) {
	msg := NewMethodCallMessage(o.destination, o.path, iface, method)
	if err := msg.AppendArgs(args...); err != nil {
		return nil, err
	}
	reply, err := o.bus.SendWithReply(msg)
	if err != nil {
		return nil, err
	}
	if reply.Type == TypeError {
		return nil, reply.AsError()
	}
	return reply, nil
}

func (o *ObjectProxy) WatchSignal(iface, member string) (*SignalWatch, error) {
	return o.bus.WatchSignal(&MatchRule{
		Type:      TypeSignal,
		Sender:    o.destination,
		Path:      o.path,
		Interface: iface,
		Member:    member})
}

// Connect returns a connection to the message bus identified by busType.
func Connect(busType StandardBus) (*Connection, error) {
	var address string

	switch busType {
	case SessionBus:
		address = os.Getenv("DBUS_SESSION_BUS_ADDRESS")

	case SystemBus:
		if address = os.Getenv("DBUS_SYSTEM_BUS_ADDRESS"); len(address) == 0 {
			address = "unix:path=/var/run/dbus/system_bus_socket"
		}

	default:
		return nil, errors.New("Unknown bus")
	}

	trans, err := newTransport(address)
	if err != nil {
		return nil, err
	}
	bus := new(Connection)
	if bus.conn, err = trans.Dial(); err != nil {
		return nil, err
	}

	if err = authenticate(bus.conn, nil); err != nil {
		bus.conn.Close()
		return nil, err
	}

	bus.busProxy = BusDaemon{bus.Object(BUS_DAEMON_NAME, BUS_DAEMON_PATH)}
	bus.messageFilters = []*MessageFilter{}
	bus.methodCallReplies = make(map[uint32]chan<- *Message)
	bus.objectPathHandlers = make(map[ObjectPath]chan<- *Message)
	bus.signalMatchRules = make(signalWatchSet)
	bus.nameInfo = make(map[string]*nameInfo)

	go bus.receiveLoop()
	if bus.UniqueName, err = bus.busProxy.Hello(); err != nil {
		bus.Close()
		return nil, err
	}

	return bus, nil
}

func (p *Connection) Authenticate() error {
	log.Println("dbus.Connection.Authenticate() is deprecated.  This call can be removed")
	return nil
}

func (p *Connection) receiveLoop() {
	for {
		msg, err := readMessage(p.conn)
		if err != nil {
			if err != io.EOF {
				log.Println("Failed to read message:", err)
			}
			break
		}
		if err = p.dispatchMessage(msg); err != nil {
			log.Println("Error dispatching message:", err)
			break
		}
	}
}

func (p *Connection) handlerForPath(objpath ObjectPath) (chan<- *Message, bool) {
	p.handlerMutex.Lock()
	defer p.handlerMutex.Unlock()

	path := string(objpath)
	idx := strings.LastIndex(path, "/") + 1

	for {
		h, ok := p.objectPathHandlers[ObjectPath(path)]
		if ok {
			return h, true
		}
		if idx < 1 {
			return nil, false
		}
		idx = strings.LastIndex(path[:idx], "/")
		path = path[:idx+1] + "*"
	}
}

func (p *Connection) dispatchMessage(msg *Message) error {
	// Run the message through the registered filters, stopping
	// processing if a filter returns nil.
	for _, filter := range p.messageFilters {
		msg := filter.filter(msg)
		if msg == nil {
			return nil
		}
	}

	switch msg.Type {
	case TypeMethodCall:
		switch {
		case msg.Interface == "org.freedesktop.DBus.Peer" && msg.Member == "Ping":
			reply := NewMethodReturnMessage(msg)
			if err := p.Send(reply); err != nil {
				return err
			}
		case msg.Interface == "org.freedesktop.DBus.Peer" && msg.Member == "GetMachineId":
			// Should be returning the UUID found in /var/lib/dbus/machine-id
			fmt.Println("XXX: handle GetMachineId")
			reply := NewMethodReturnMessage(msg)
			if err := reply.AppendArgs("machine-id"); err != nil {
				return err
			}
			if err := p.Send(reply); err != nil {
				return err
			}
		default:
			handler, ok := p.handlerForPath(msg.Path)
			if ok {
				handler <- msg
			} else {
				reply := NewErrorMessage(msg, "org.freedesktop.DBus.Error.UnknownObject", "Unknown object path "+string(msg.Path))
				if err := p.Send(reply); err != nil {
					return err
				}
			}
		}
	case TypeMethodReturn, TypeError:
		p.handlerMutex.Lock()
		rs := msg.replySerial
		replyChan, ok := p.methodCallReplies[rs]
		if ok {
			delete(p.methodCallReplies, rs)
		}
		p.handlerMutex.Unlock()
		if ok {
			replyChan <- msg
		}
	case TypeSignal:
		p.handlerMutex.Lock()
		watches := p.signalMatchRules.FindMatches(msg)
		p.handlerMutex.Unlock()
		for _, watch := range watches {
			watch.cb(msg)
		}
	}
	return nil
}

func (p *Connection) Close() error {
	return p.conn.Close()
}

func (p *Connection) nextSerial() uint32 {
	return atomic.AddUint32(&p.lastSerial, 1)
}

func (p *Connection) atomicWriteMessage(msg *Message) error {
	p.writeLock.Lock()
	defer p.writeLock.Unlock()
	_, err := msg.WriteTo(p.conn)
	return err
}

func (p *Connection) Send(msg *Message) error {
	msg.setSerial(p.nextSerial())
	return p.atomicWriteMessage(msg)
}

func (p *Connection) SendWithReply(msg *Message) (*Message, error) {
	// XXX: also check for "no reply" flag.
	if msg.Type != TypeMethodCall {
		panic("Only method calls have replies")
	}
	serial := p.nextSerial()
	msg.setSerial(serial)

	replyChan := make(chan *Message, 1)
	p.handlerMutex.Lock()
	p.methodCallReplies[serial] = replyChan
	p.handlerMutex.Unlock()

	if err := p.atomicWriteMessage(msg); err != nil {
		p.handlerMutex.Lock()
		delete(p.methodCallReplies, serial)
		p.handlerMutex.Unlock()
		return nil, err
	}

	reply := <-replyChan
	return reply, nil
}

func (p *Connection) RegisterMessageFilter(filter func(*Message) *Message) *MessageFilter {
	msgFilter := &MessageFilter{filter}
	p.messageFilters = append(p.messageFilters, msgFilter)
	return msgFilter
}

func (p *Connection) UnregisterMessageFilter(filter *MessageFilter) {
	for i, other := range p.messageFilters {
		if other == filter {
			p.messageFilters = append(p.messageFilters[:i], p.messageFilters[i+1:]...)
			return
		}
	}
	panic("Message filter not registered to this bus")
}

func (p *Connection) RegisterObjectPath(path ObjectPath, handler chan<- *Message) {
	p.handlerMutex.Lock()
	defer p.handlerMutex.Unlock()
	if _, ok := p.objectPathHandlers[path]; ok {
		panic("A handler has already been registered for " + string(path))
	}
	p.objectPathHandlers[path] = handler
}

func (p *Connection) UnregisterObjectPath(path ObjectPath) {
	p.handlerMutex.Lock()
	defer p.handlerMutex.Unlock()
	if _, ok := p.objectPathHandlers[path]; !ok {
		panic("No handler registered for " + string(path))
	}
	delete(p.objectPathHandlers, path)
}

// Object returns a proxy for the object identified by the given
// destination address and path
func (p *Connection) Object(dest string, path ObjectPath) *ObjectProxy {
	return &ObjectProxy{p, dest, path}
}