| 1 |
/* |
| 2 |
Copyright 2013-2014 Canonical Ltd. |
| 3 |
|
| 4 |
This program is free software: you can redistribute it and/or modify it |
| 5 |
under the terms of the GNU General Public License version 3, as published |
| 6 |
by the Free Software Foundation. |
| 7 |
|
| 8 |
This program is distributed in the hope that it will be useful, but |
| 9 |
WITHOUT ANY WARRANTY; without even the implied warranties of |
| 10 |
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR |
| 11 |
PURPOSE. See the GNU General Public License for more details. |
| 12 |
|
| 13 |
You should have received a copy of the GNU General Public License along |
| 14 |
with this program. If not, see <http://www.gnu.org/licenses/>. |
| 15 |
*/ |
| 16 |
|
| 17 |
package bus |
| 18 |
|
| 19 |
// Here we define the Endpoint, which represents the DBus connection itself. |
| 20 |
|
| 21 |
import ( |
| 22 |
"errors" |
| 23 |
"fmt" |
| 24 |
"slices" |
| 25 |
"strings" |
| 26 |
|
| 27 |
"github.com/godbus/dbus/v5" |
| 28 |
|
| 29 |
"gitlab.com/ubports/development/core/lomiri-push-service/logger" |
| 30 |
) |
| 31 |
|
| 32 |
/***************************************************************** |
| 33 |
* Endpoint (and its implementation) |
| 34 |
*/ |
| 35 |
|
| 36 |
type DispatchMap map[string]interface{} |
| 37 |
|
| 38 |
// Cancellable can be canceled. |
| 39 |
type Cancellable interface { |
| 40 |
Cancel() |
| 41 |
} |
| 42 |
|
| 43 |
type signalSubscription struct { |
| 44 |
interface_ string |
| 45 |
member string |
| 46 |
signals chan *dbus.Signal |
| 47 |
unsubscribe chan<- *signalSubscription |
| 48 |
} |
| 49 |
|
| 50 |
func (s *signalSubscription) key() string { |
| 51 |
return s.interface_ + "." + s.member |
| 52 |
} |
| 53 |
|
| 54 |
func (s *signalSubscription) Cancel() { |
| 55 |
s.unsubscribe <- s |
| 56 |
} |
| 57 |
|
| 58 |
// bus.Endpoint represents the DBus connection itself. |
| 59 |
type Endpoint interface { |
| 60 |
GrabName(allowReplacement bool) <-chan error |
| 61 |
WatchSignal(member string, f func(...interface{}), d func()) (Cancellable, error) |
| 62 |
WatchMethod(DispatchMap, string) error |
| 63 |
Signal(string, string, []interface{}) error |
| 64 |
Call(member string, args []interface{}, rvs ...interface{}) error |
| 65 |
GetProperty(property string) (interface{}, error) |
| 66 |
SetProperty(property string, suffix string, value interface{}) error |
| 67 |
WatchProperties(f func(map[string]dbus.Variant, []string), d func()) (Cancellable, error) |
| 68 |
Dial() error |
| 69 |
Close() |
| 70 |
String() string |
| 71 |
} |
| 72 |
|
| 73 |
type endpoint struct { |
| 74 |
bus Bus |
| 75 |
conn *dbus.Conn |
| 76 |
obj dbus.BusObject |
| 77 |
signals chan *dbus.Signal |
| 78 |
subscribeSignals chan *signalSubscription |
| 79 |
unsubscribeSignals chan *signalSubscription |
| 80 |
done chan struct{} |
| 81 |
addr Address |
| 82 |
log logger.Logger |
| 83 |
} |
| 84 |
|
| 85 |
// constructor |
| 86 |
func newEndpoint(bus Bus, addr Address, log logger.Logger) *endpoint { |
| 87 |
return &endpoint{bus: bus, addr: addr, log: log} |
| 88 |
} |
| 89 |
|
| 90 |
// ensure endpoint implements Endpoint |
| 91 |
var _ Endpoint = (*endpoint)(nil) |
| 92 |
|
| 93 |
/* |
| 94 |
public methods |
| 95 |
|
| 96 |
XXX: these are almost entirely untested, as that would need |
| 97 |
XXX: integration tests we are currently missing. |
| 98 |
*/ |
| 99 |
|
| 100 |
// Dial() (re)establishes the connection with dbus |
| 101 |
// |
| 102 |
// XXX: mostly untested |
| 103 |
func (endp *endpoint) Dial() error { |
| 104 |
var conn *dbus.Conn |
| 105 |
var err error |
| 106 |
if endp.bus == SystemBus { |
| 107 |
conn, err = dbus.ConnectSystemBus() |
| 108 |
} else { |
| 109 |
conn, err = dbus.ConnectSessionBus() |
| 110 |
} |
| 111 |
if err != nil { |
| 112 |
return err |
| 113 |
} |
| 114 |
|
| 115 |
name := endp.addr.Name |
| 116 |
var hasOwner bool |
| 117 |
if err := conn.BusObject().Call("org.freedesktop.DBus.NameHasOwner", 0, name).Store(&hasOwner); err != nil { |
| 118 |
endp.log.Debugf("unable to determine ownership of %#v: %v", name, err) |
| 119 |
conn.Close() |
| 120 |
return err |
| 121 |
} |
| 122 |
if !hasOwner { |
| 123 |
var names []string |
| 124 |
if err := conn.BusObject().Call("org.freedesktop.DBus.ListActivatableNames", 0).Store(&names); err != nil { |
| 125 |
endp.log.Debugf("%#v has no owner, and when listing activatable: %v", name, err) |
| 126 |
conn.Close() |
| 127 |
return err |
| 128 |
} |
| 129 |
if !slices.Contains(names, name) { |
| 130 |
err = fmt.Errorf("%#v has no owner, and not in activatables", name) |
| 131 |
endp.log.Debugf("%s", err) |
| 132 |
conn.Close() |
| 133 |
return err |
| 134 |
} |
| 135 |
} |
| 136 |
endp.log.Debugf("%#v dialed in.", name) |
| 137 |
endp.conn = conn |
| 138 |
endp.obj = conn.Object(name, dbus.ObjectPath(endp.addr.Path)) |
| 139 |
endp.signals = make(chan *dbus.Signal) |
| 140 |
conn.Signal(endp.signals) |
| 141 |
endp.subscribeSignals = make(chan *signalSubscription) |
| 142 |
endp.unsubscribeSignals = make(chan *signalSubscription) |
| 143 |
endp.done = make(chan struct{}) |
| 144 |
go endp.handleSignals() |
| 145 |
return nil |
| 146 |
} |
| 147 |
|
| 148 |
// WatchSignal() takes a member name, sets up a watch for it (on the name, |
| 149 |
// path and interface provided when creating the endpoint), and then calls f() |
| 150 |
// with the unpacked value. If it's unable to set up the watch it returns an |
| 151 |
// error. If the watch fails once established, d() is called. Typically f() |
| 152 |
// sends the values over a channel, and d() would close the channel. |
| 153 |
// |
| 154 |
// XXX: untested |
| 155 |
func (endp *endpoint) WatchSignal(member string, f func(...interface{}), d func()) (Cancellable, error) { |
| 156 |
ch := make(chan *dbus.Signal) |
| 157 |
sub := &signalSubscription{ |
| 158 |
interface_: endp.addr.Interface, |
| 159 |
member: member, |
| 160 |
signals: ch, |
| 161 |
unsubscribe: endp.unsubscribeSignals, |
| 162 |
} |
| 163 |
endp.subscribeSignals <- sub |
| 164 |
|
| 165 |
go func() { |
| 166 |
for { |
| 167 |
sig, ok := <-ch |
| 168 |
if !ok { |
| 169 |
break |
| 170 |
} |
| 171 |
f(sig.Body...) |
| 172 |
} |
| 173 |
d() |
| 174 |
}() |
| 175 |
return sub, nil |
| 176 |
} |
| 177 |
|
| 178 |
// Call() invokes the provided member method (on the name, path and |
| 179 |
// interface provided when creating the endpoint). args can be built |
| 180 |
// using bus.Args(...). The return value is unpacked into rvs before being |
| 181 |
// returned. |
| 182 |
// |
| 183 |
// XXX: untested |
| 184 |
func (endp *endpoint) Call(member string, args []interface{}, rvs ...interface{}) (err error) { |
| 185 |
err = endp.obj.Call(endp.addr.Interface + "." + member, 0, args...).Store(rvs...) |
| 186 |
return |
| 187 |
} |
| 188 |
|
| 189 |
// GetProperty uses the org.freedesktop.DBus.Properties interface's Get method |
| 190 |
// to read a given property on the name, path and interface provided when |
| 191 |
// creating the endpoint. The return value is unpacked into a dbus.Variant, |
| 192 |
// and its value returned. |
| 193 |
// |
| 194 |
// XXX: untested |
| 195 |
func (endp *endpoint) GetProperty(property string) (interface{}, error) { |
| 196 |
variant, err := endp.obj.GetProperty(endp.addr.Interface + "." + property) |
| 197 |
if err != nil { |
| 198 |
return nil, err |
| 199 |
} |
| 200 |
return variant.Value(), nil |
| 201 |
} |
| 202 |
|
| 203 |
// SetProperty calls org.freedesktop.DBus.Properties's Set method |
| 204 |
// |
| 205 |
// XXX: untested |
| 206 |
func (endp *endpoint) SetProperty(property string, suffix string, value interface{}) error { |
| 207 |
// can't use the pre-existing ObjectProxy for this one |
| 208 |
obj := endp.conn.Object(endp.addr.Name, dbus.ObjectPath(endp.addr.Path+suffix)) |
| 209 |
return obj.SetProperty(endp.addr.Interface + "." + property, value) |
| 210 |
} |
| 211 |
|
| 212 |
// WatchProperties() sets up a watch for |
| 213 |
// org.freedesktop.DBus.Properties PropertiesChanged signal for the |
| 214 |
// path and interface provided when creating the endpoint, and then |
| 215 |
// calls f() with the unpacked value. If it's unable to set up the |
| 216 |
// watch it returns an error. If the watch fails once established, d() |
| 217 |
// is called. Typically f() sends the values over a channel, and d() |
| 218 |
// would close the channel. |
| 219 |
// |
| 220 |
// XXX: untested |
| 221 |
func (endp *endpoint) WatchProperties(f func(map[string]dbus.Variant, []string), d func()) (Cancellable, error) { |
| 222 |
ch := make(chan *dbus.Signal) |
| 223 |
sub := &signalSubscription{ |
| 224 |
interface_: "org.freedesktop.DBus.Properties", |
| 225 |
member: "PropertiesChanged", |
| 226 |
signals: ch, |
| 227 |
unsubscribe: endp.unsubscribeSignals, |
| 228 |
} |
| 229 |
endp.subscribeSignals <- sub |
| 230 |
|
| 231 |
go func() { |
| 232 |
for { |
| 233 |
sig, ok := <-ch |
| 234 |
if !ok { |
| 235 |
break |
| 236 |
} |
| 237 |
var intfName string |
| 238 |
var changed map[string]dbus.Variant |
| 239 |
var invalidated []string |
| 240 |
if err := dbus.Store(sig.Body, &intfName, &changed, &invalidated); err != nil { |
| 241 |
endp.log.Errorf("unexpected values from Properties watch: %v", err) |
| 242 |
break |
| 243 |
} |
| 244 |
if intfName != endp.addr.Interface { |
| 245 |
// ignore |
| 246 |
continue |
| 247 |
} |
| 248 |
f(changed, invalidated) |
| 249 |
} |
| 250 |
d() |
| 251 |
}() |
| 252 |
return sub, nil |
| 253 |
} |
| 254 |
|
| 255 |
// Close the connection to dbus. |
| 256 |
// |
| 257 |
// XXX: untested |
| 258 |
func (endp *endpoint) Close() { |
| 259 |
if endp.conn != nil { |
| 260 |
close(endp.done) |
| 261 |
close(endp.subscribeSignals) |
| 262 |
close(endp.unsubscribeSignals) |
| 263 |
endp.conn.Close() |
| 264 |
endp.conn = nil |
| 265 |
endp.obj = nil |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
// String() performs advanced endpoint stringification |
| 270 |
// |
| 271 |
// XXX: untested |
| 272 |
func (endp *endpoint) String() string { |
| 273 |
return fmt.Sprintf("<Connection to %s %#v>", endp.conn.Names()[0], endp.addr) |
| 274 |
} |
| 275 |
|
| 276 |
// GrabName() takes over the name on the bus, reporting errors over the |
| 277 |
// returned channel. |
| 278 |
// |
| 279 |
// While the first result will be nil on success, successive results would |
| 280 |
// typically indicate another process trying to take over the name. |
| 281 |
// |
| 282 |
// XXX: untested |
| 283 |
func (endp *endpoint) GrabName(allowReplacement bool) <-chan error { |
| 284 |
errs := make(chan error, 2) |
| 285 |
flags := dbus.NameFlagAllowReplacement | dbus.NameFlagReplaceExisting |
| 286 |
if !allowReplacement { |
| 287 |
flags = 0 |
| 288 |
} |
| 289 |
reply, err := endp.conn.RequestName(endp.addr.Name, flags) |
| 290 |
if err == nil && reply != dbus.RequestNameReplyPrimaryOwner { |
| 291 |
switch reply { |
| 292 |
case dbus.RequestNameReplyInQueue: |
| 293 |
err = errors.New("failed to grab DBus name: in waiting queue") |
| 294 |
case dbus.RequestNameReplyExists: |
| 295 |
err = errors.New("failed to grab DBus name: already exists") |
| 296 |
case dbus.RequestNameReplyAlreadyOwner: |
| 297 |
err = errors.New("failed to grab DBus name: already owned") |
| 298 |
default: |
| 299 |
err = errors.New("failed to grab DBus name: unknown error") |
| 300 |
} |
| 301 |
} |
| 302 |
if err != nil { |
| 303 |
errs <-err |
| 304 |
return errs |
| 305 |
} |
| 306 |
|
| 307 |
nameLost := make(chan *dbus.Signal) |
| 308 |
sub := &signalSubscription{ |
| 309 |
interface_: "org.freedesktop.DBus", |
| 310 |
member: "NameLost", |
| 311 |
signals: nameLost, |
| 312 |
unsubscribe: endp.unsubscribeSignals, |
| 313 |
} |
| 314 |
endp.subscribeSignals <- sub |
| 315 |
|
| 316 |
go func() { |
| 317 |
for { |
| 318 |
sig := <-nameLost |
| 319 |
var name string |
| 320 |
if err := dbus.Store(sig.Body, &name); err != nil { |
| 321 |
errs <- fmt.Errorf("failed to parse org.freedesktop.DBus.NameLost: %w", err) |
| 322 |
break |
| 323 |
} |
| 324 |
if name == endp.addr.Name { |
| 325 |
errs <-fmt.Errorf("DBus ownership of name %s was lost", name) |
| 326 |
break |
| 327 |
} |
| 328 |
} |
| 329 |
sub.Cancel() |
| 330 |
close(errs) |
| 331 |
}() |
| 332 |
|
| 333 |
return errs |
| 334 |
} |
| 335 |
|
| 336 |
// Signal() sends out a signal called <member> containing <args>. |
| 337 |
// |
| 338 |
// XXX: untested |
| 339 |
func (endp *endpoint) Signal(member string, suffix string, args []interface{}) error { |
| 340 |
path := dbus.ObjectPath(endp.addr.Path + suffix) |
| 341 |
iface := endp.addr.Interface + "." + member |
| 342 |
err := endp.conn.Emit(path, iface, args...) |
| 343 |
if err != nil { |
| 344 |
endp.log.Errorf("unable to send dbus signal: %v", err) |
| 345 |
} else { |
| 346 |
endp.log.Debugf("sent dbus signal %s(%#v)", member, args) |
| 347 |
} |
| 348 |
return err |
| 349 |
} |
| 350 |
|
| 351 |
// WatchMethod() uses the given DispatchMap to answer incoming method |
| 352 |
// calls. |
| 353 |
// |
| 354 |
// XXX: untested |
| 355 |
func (endp *endpoint) WatchMethod(dispatch DispatchMap, suffix string) error { |
| 356 |
fullPath := endp.addr.Path + suffix |
| 357 |
subTreePath, isSubTree := strings.CutSuffix(fullPath, "/*") |
| 358 |
|
| 359 |
var err error |
| 360 |
if isSubTree { |
| 361 |
err = endp.conn.ExportSubtreeMethodTable( |
| 362 |
dispatch, |
| 363 |
dbus.ObjectPath(subTreePath), |
| 364 |
endp.addr.Interface) |
| 365 |
} else { |
| 366 |
err = endp.conn.ExportMethodTable( |
| 367 |
dispatch, |
| 368 |
dbus.ObjectPath(fullPath), |
| 369 |
endp.addr.Interface) |
| 370 |
} |
| 371 |
|
| 372 |
if err != nil { |
| 373 |
endp.log.Errorf("Failed to export methods: %v", err) |
| 374 |
} |
| 375 |
return err |
| 376 |
} |
| 377 |
|
| 378 |
/* |
| 379 |
private methods |
| 380 |
*/ |
| 381 |
|
| 382 |
func (endp *endpoint) matchRuleForSignal(sub *signalSubscription) string { |
| 383 |
return fmt.Sprintf( |
| 384 |
"type='signal',sender='%s',path='%s',interface='%s',member='%s'", |
| 385 |
endp.addr.Name, |
| 386 |
endp.addr.Path, |
| 387 |
sub.interface_, |
| 388 |
sub.member, |
| 389 |
) |
| 390 |
|
| 391 |
} |
| 392 |
|
| 393 |
// signal handling multiplexer |
| 394 |
func (endp *endpoint) handleSignals() { |
| 395 |
subs := make(map[string]map[chan *dbus.Signal]bool) |
| 396 |
|
| 397 |
loop: |
| 398 |
for { |
| 399 |
select { |
| 400 |
case sub := <-endp.subscribeSignals: |
| 401 |
key := sub.key() |
| 402 |
if subs[key] == nil { |
| 403 |
subs[key] = make(map[chan *dbus.Signal]bool) |
| 404 |
endp.conn.BusObject().Call( |
| 405 |
"org.freedesktop.DBus.AddMatch", |
| 406 |
0, |
| 407 |
endp.matchRuleForSignal(sub)) |
| 408 |
} |
| 409 |
subs[key][sub.signals] = true |
| 410 |
case sub := <-endp.unsubscribeSignals: |
| 411 |
key := sub.key() |
| 412 |
if subs[key][sub.signals] { |
| 413 |
delete(subs[key], sub.signals) |
| 414 |
close(sub.signals) |
| 415 |
} |
| 416 |
|
| 417 |
if len(subs[key]) == 0 { |
| 418 |
endp.conn.BusObject().Call( |
| 419 |
"org.freedesktop.DBus.RemoveMatch", |
| 420 |
0, |
| 421 |
endp.matchRuleForSignal(sub)) |
| 422 |
delete(subs, key) |
| 423 |
} |
| 424 |
case sig := <-endp.signals: |
| 425 |
for ch, _ := range subs[sig.Name] { |
| 426 |
ch <- sig |
| 427 |
} |
| 428 |
case <-endp.done: |
| 429 |
break loop |
| 430 |
} |
| 431 |
} |
| 432 |
|
| 433 |
for _, chans := range subs { |
| 434 |
for c, _ := range chans { |
| 435 |
close(c) |
| 436 |
} |
| 437 |
} |
| 438 |
clear(subs) |
| 439 |
} |