File: dbusutil.go

package info (click to toggle)
go-dlib 5.6.0.9%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,212 kB
  • sloc: ansic: 4,664; xml: 1,456; makefile: 20; sh: 15
file content (730 lines) | stat: -rw-r--r-- 16,065 bytes parent folder | download | duplicates (3)
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
package dbusutil

import (
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"reflect"
	"strings"
	"sync"

	"github.com/godbus/dbus"
	"github.com/godbus/dbus/introspect"
)

var logger *log.Logger

func init() {
	// setup logger
	logOut := ioutil.Discard
	if os.Getenv("DEBUG_DBUSUTIL") == "1" {
		logOut = os.Stderr
	}
	logger = log.New(logOut, "[dbusutil]", log.Lshortfile)
}

const orgFreedesktopDBus = "org.freedesktop.DBus"

type accessType uint

const (
	accessRead      accessType = 1
	accessWrite                = 2
	accessReadWrite            = accessRead | accessWrite
)

func (a accessType) String() string {
	switch a {
	case accessRead:
		return "read"
	case accessWrite:
		return "write"
	case accessReadWrite:
		return "readwrite"
	default:
		return fmt.Sprintf("invalid(%d)", a)
	}
}

type emitType uint

const (
	emitFalse emitType = iota
	emitTrue
	emitInvalidates
)

func (e emitType) String() string {
	switch e {
	case emitFalse:
		return "false"
	case emitTrue:
		return "true"
	case emitInvalidates:
		return "invalidates"
	default:
		return fmt.Sprintf("invalid(%d)", e)
	}
}

// struct field prop
type fieldProp struct {
	rValue  reflect.Value
	valueMu *sync.RWMutex

	cbMu       sync.Mutex
	writeCb    PropertyWriteCallback
	readCb     PropertyReadCallback
	changedCbs []PropertyChangedCallback
}

type fieldPropStatic struct {
	name      string
	rType     reflect.Type
	valueType fieldPropValueType
	signature dbus.Signature
	hasStruct bool
	emit      emitType
	access    accessType
}

type fieldPropValueType uint

const (
	fieldPropValueNotProp fieldPropValueType = iota
	fieldPropValueImplProp
	fieldPropValuePtrImplProp
)

func (p *fieldProp) getValue(propRead *PropertyRead) (value interface{}, err *dbus.Error) {
	readCb := p.getReadCallback()
	if readCb != nil {
		err = readCb(propRead)
		if err != nil {
			return
		}
	}

	if p.valueMu != nil {
		p.valueMu.RLock()
	}

	value = p.rValue.Interface()
	if propValue, ok := value.(Property); ok {
		value, err = propValue.GetValue()
	}

	if p.valueMu != nil {
		p.valueMu.RUnlock()
	}
	return
}

func (p *fieldProp) GetValueVariant(propRead *PropertyRead,
	signature dbus.Signature) (dbus.Variant, *dbus.Error) {

	value, err := p.getValue(propRead)
	if err != nil {
		return dbus.Variant{}, err
	}
	return dbus.MakeVariantWithSignature(value, signature), nil
}

func (p *fieldProp) SetValue(propWrite *PropertyWrite) (changed bool, err *dbus.Error) {
	writeCb := p.getWriteCallback()
	if writeCb != nil {
		err = writeCb(propWrite)
		if err != nil {
			return
		}
	}

	if p.valueMu != nil {
		p.valueMu.Lock()
	}

	newVal := propWrite.Value

	value := p.rValue.Interface()
	propValue, ok := value.(Property)
	if ok {
		changed, err = propValue.SetValue(newVal)
	} else {
		newValRV := reflect.ValueOf(newVal)
		newValRT := reflect.TypeOf(newVal)
		valueRT := reflect.TypeOf(value)
		if valueRT != newValRT {
			// type not equal, try convert
			if newValRT.ConvertibleTo(valueRT) {
				newValRV = newValRV.Convert(valueRT)
			} else {
				err = dbus.MakeFailedError(errors.New("type not convertible"))
			}
		}

		if err == nil && !reflect.DeepEqual(value, newValRV.Interface()) {
			p.rValue.Set(newValRV)
			changed = true
		}
	}

	if p.valueMu != nil {
		p.valueMu.Unlock()
	}
	return
}

func (p *fieldProp) getWriteCallback() PropertyWriteCallback {
	p.cbMu.Lock()
	cb := p.writeCb
	p.cbMu.Unlock()
	return cb
}

func (p *fieldProp) getReadCallback() PropertyReadCallback {
	p.cbMu.Lock()
	cb := p.readCb
	p.cbMu.Unlock()
	return cb
}

func (p *fieldProp) setWriteCallback(cb PropertyWriteCallback) {
	p.cbMu.Lock()
	p.writeCb = cb
	p.cbMu.Unlock()
}

func (p *fieldProp) setReadCallback(cb PropertyReadCallback) {
	p.cbMu.Lock()
	p.readCb = cb
	p.cbMu.Unlock()
}

func (p *fieldProp) connectChanged(cb PropertyChangedCallback) {
	p.cbMu.Lock()

	// copy on write
	newCbs := make([]PropertyChangedCallback, len(p.changedCbs)+1)
	copy(newCbs, p.changedCbs)
	newCbs[len(newCbs)-1] = cb
	p.changedCbs = newCbs

	p.cbMu.Unlock()
}

// do changed callbacks
func (p *fieldProp) notifyChanged(change *PropertyChanged) {
	p.cbMu.Lock()
	callbacks := p.changedCbs
	p.cbMu.Unlock()
	for _, cb := range callbacks {
		cb(change)
	}
}

// emit DBus signal Properties.PropertiesChanged
func emitPropertiesChanged(conn *dbus.Conn, path dbus.ObjectPath, interfaceName string,
	propName string, value interface{}, emit emitType) (err error) {
	const signal = orgFreedesktopDBus + ".Properties.PropertiesChanged"
	var changedProps map[string]dbus.Variant
	switch emit {
	case emitFalse:
		// do nothing
	case emitInvalidates:
		err = conn.Emit(path, signal, interfaceName, changedProps, []string{propName})
	case emitTrue:
		changedProps = map[string]dbus.Variant{
			propName: dbus.MakeVariant(value),
		}
		err = conn.Emit(path, signal, interfaceName, changedProps, []string{})
	default:
		panic("invalid value for emitType")
	}
	return
}

func getPropsIntrospection(props map[string]*fieldPropStatic) []introspect.Property {
	var result = make([]introspect.Property, len(props))
	idx := 0
	for _, p := range props {

		var access string
		switch p.access {
		case accessWrite:
			access = "write"
		case accessRead:
			access = "read"
		case accessReadWrite:
			access = "readwrite"
		default:
			panic("invalid access")
		}

		result[idx] = introspect.Property{
			Name:   p.name,
			Type:   p.signature.String(),
			Access: access,
		}
		idx++
	}

	return result
}

func getSignals(structType reflect.Type) []introspect.Signal {
	signalsField, ok := structType.FieldByName("signals")
	if !ok {
		return nil
	}

	if signalsField.Type.Kind() != reflect.Ptr {
		return nil
	}

	signalsFieldElemType := signalsField.Type.Elem()
	if signalsFieldElemType.Kind() != reflect.Struct {
		return nil
	}

	var signals []introspect.Signal
	numField := signalsFieldElemType.NumField()
	for i := 0; i < numField; i++ {
		signalItem := signalsFieldElemType.Field(i)
		signalItemType := signalItem.Type

		if signalItemType.Kind() == reflect.Struct {
			var args []introspect.Arg
			numArg := signalItemType.NumField()
			for j := 0; j < numArg; j++ {
				signalArg := signalItemType.Field(j)
				args = append(args, introspect.Arg{
					Name: signalArg.Name,
					Type: dbus.SignatureOfType(signalArg.Type).String(),
				})
			}
			signals = append(signals, introspect.Signal{
				Name: signalItem.Name,
				Args: args,
			})
		}
	}
	return signals
}

const propsMuField = "PropsMu"

func getCorePropsMu(structValue reflect.Value) *sync.RWMutex {
	propsMasterRV := structValue.FieldByName(propsMuField)
	if !propsMasterRV.IsValid() {
		return nil
	}
	return propsMasterRV.Addr().Interface().(*sync.RWMutex)
}

func getStructValue(m interface{}) (reflect.Value, bool) {
	type0 := reflect.TypeOf(m)
	value0 := reflect.ValueOf(m)

	if type0.Kind() != reflect.Ptr {
		return reflect.Value{}, false
	}

	elemType := type0.Elem()
	elemValue := value0.Elem()

	if elemType.Kind() != reflect.Struct {
		return reflect.Value{}, false
	}
	if !elemValue.IsValid() {
		return reflect.Value{}, false
	}
	return elemValue, true
}

func getFieldPropStaticMap(structType reflect.Type,
	structValue reflect.Value) map[string]*fieldPropStatic {

	props := make(map[string]*fieldPropStatic)

	var prevField reflect.StructField
	numField := structType.NumField()
	for i := 0; i < numField; i++ {
		field := structType.Field(i)
		fieldValue := structValue.Field(i)

		if field.Name == propsMuField {
			prevField = field
			continue
		}

		if !fieldValue.CanSet() {
			prevField = field
			continue
		}

		tag := field.Tag.Get("prop")
		if tag == "-" {
			prevField = field
			continue
		}

		if prevField.Name+"Mu" == field.Name {
			prevField = field
			continue
		}

		prop0 := newFieldPropStatic(field, fieldValue, tag)
		props[field.Name] = prop0
		prevField = field
	}
	return props
}

func getFieldPropMap(impl *implementer, implStatic *implementerStatic,
	structValue reflect.Value, s *Service, path dbus.ObjectPath) map[string]*fieldProp {

	structType := structValue.Type()
	props := make(map[string]*fieldProp)

	corePropsMu := getCorePropsMu(structValue)

	numField := structType.NumField()
	var prevField reflect.StructField
	for i := 0; i < numField; i++ {
		field := structType.Field(i)
		fieldValue := structValue.Field(i)

		// ex:
		// prevField: Prop1
		// current Field: Prop1Mu
		if prevField.Name+"Mu" == field.Name &&
			props[prevField.Name] != nil {

			mu, ok := fieldValue.Addr().Interface().(*sync.RWMutex)
			if ok {
				// override prev fieldProp.ValueMu
				props[prevField.Name].valueMu = mu
			}

			prevField = field
			continue
		}

		propStatic, ok := implStatic.props[field.Name]
		if !ok {
			prevField = field
			continue
		}

		p := &fieldProp{
			rValue: fieldValue,
		}

		var propValue Property
		switch propStatic.valueType {
		case fieldPropValueNotProp:
			p.valueMu = corePropsMu

		case fieldPropValueImplProp:
			propValue = fieldValue.Interface().(Property)

		case fieldPropValuePtrImplProp:
			fieldValuePtr := fieldValue.Addr()
			propValue = fieldValuePtr.Interface().(Property)
			p.rValue = fieldValuePtr
		}

		if propValue != nil {
			propValue.SetNotifyChangedFunc(func(val interface{}) {
				impl.notifyChanged(s, path, p, propStatic, val)
			})
		}

		props[field.Name] = p
		prevField = field
	}
	return props
}

func parsePropTag(tag string) (accessType, emitType) {
	access := accessRead
	emit := emitTrue
	tagParts := strings.Split(tag, ",")
	for _, tagPart := range tagParts {
		if strings.HasPrefix(tagPart, "access:") {
			accessStr := tagPart[len("access:"):]
			switch accessStr {
			case "r", "read":
				access = accessRead
			case "w", "write":
				access = accessWrite
			case "rw", "readwrite":
				access = accessReadWrite
			default:
				panic(fmt.Errorf("invalid access %q", accessStr))
			}
			continue
		} else if strings.HasPrefix(tagPart, "emit:") {
			emitStr := tagPart[len("emit:"):]
			switch emitStr {
			case "true":
				emit = emitTrue
			case "false":
				emit = emitFalse
			case "invalidates":
				emit = emitInvalidates
			default:
				panic(fmt.Errorf("invalid emit %q", emitStr))
			}
			continue
		}
	}
	return access, emit
}

func toProperty(value reflect.Value) (Property, fieldPropValueType) {
	propValue, ok := value.Interface().(Property)
	if ok {
		return propValue, fieldPropValueImplProp
	}

	// try value.Addr
	if value.Kind() == reflect.Struct {
		propValue, ok = value.Addr().Interface().(Property)
		if ok {
			return propValue, fieldPropValuePtrImplProp
		}
	}
	return nil, fieldPropValueNotProp
}

func newFieldPropStatic(field reflect.StructField, fieldValue reflect.Value,
	tag string) *fieldPropStatic {

	access, emit := parsePropTag(tag)
	p := &fieldPropStatic{
		name:   field.Name,
		access: access,
		emit:   emit,
	}
	var rType reflect.Type

	propValue, valueType := toProperty(fieldValue)
	p.valueType = valueType
	if valueType == fieldPropValueNotProp {
		rType = field.Type
	} else {
		rType = propValue.GetType()
	}

	p.rType = rType
	p.signature = dbus.SignatureOfType(rType)
	if strings.Contains(p.signature.String(), "(") {
		p.hasStruct = true
	}
	return p
}

type methodDetail struct {
	In  []string
	Out []string
}

func (md methodDetail) getInArgName(index int, type0 reflect.Type, methodName string) string {
	if index >= len(md.In) {
		panic(fmt.Errorf("failed to get %s.%s in[%d] argument name",
			type0, methodName, index))
	}
	return md.In[index]
}

func (md methodDetail) getOutArgName(index int, type0 reflect.Type, methodName string) string {
	if index >= len(md.Out) {
		panic(fmt.Errorf("failed to get %s.%s out[%d] argument name",
			type0, methodName, index))
	}
	return md.Out[index]
}

func getMethodDetailMap(structType reflect.Type) map[string]methodDetail {
	result := make(map[string]methodDetail)
	methodsField, ok := structType.FieldByName("methods")
	if !ok {
		return nil
	}

	if methodsField.Type.Kind() != reflect.Ptr {
		return nil
	}

	methodsFieldElemType := methodsField.Type.Elem()
	if methodsFieldElemType.Kind() != reflect.Struct {
		return nil
	}

	numField := methodsFieldElemType.NumField()
	for i := 0; i < numField; i++ {
		methodItem := methodsFieldElemType.Field(i)
		tagIn := methodItem.Tag.Get("in")
		tagOut := methodItem.Tag.Get("out")

		result[methodItem.Name] = methodDetail{
			In:  splitArg(tagIn),
			Out: splitArg(tagOut),
		}
	}
	return result
}

func splitArg(str string) (result []string) {
	parts := strings.Split(str, ",")
	for _, part := range parts {
		part = strings.TrimSpace(part)
		if part != "" {
			result = append(result, part)
		}
	}
	return
}

// Methods returns the description of the methods of v. This can be used to
// create a Node which can be passed to NewIntrospectable.
func getMethods(v interface{}, methodDetailMap map[string]methodDetail) []introspect.Method {
	t := reflect.TypeOf(v)
	ms := make([]introspect.Method, 0, t.NumMethod())
	for i := 0; i < t.NumMethod(); i++ {
		if t.Method(i).PkgPath != "" {
			continue
		}
		mt := t.Method(i).Type
		if mt.NumOut() == 0 ||
			mt.Out(mt.NumOut()-1) != reflect.TypeOf(&dbus.Error{}) {

			continue
		}
		var m introspect.Method
		m.Name = t.Method(i).Name
		m.Args = make([]introspect.Arg, 0, mt.NumIn()+mt.NumOut()-2)

		methodDetail := methodDetailMap[m.Name]
		inArgIndex := 0
		for j := 1; j < mt.NumIn(); j++ {
			if mt.In(j) != reflect.TypeOf((*dbus.Sender)(nil)).Elem() &&
				mt.In(j) != reflect.TypeOf((*dbus.Message)(nil)).Elem() {

				argName := methodDetail.getInArgName(inArgIndex, t, m.Name)
				inArgIndex++
				arg := introspect.Arg{Name: argName,
					Type:      dbus.SignatureOfType(mt.In(j)).String(),
					Direction: "in",
				}
				m.Args = append(m.Args, arg)
			}
		}
		for j := 0; j < mt.NumOut()-1; j++ {
			argName := methodDetail.getOutArgName(j, t, m.Name)
			arg := introspect.Arg{
				Name:      argName,
				Type:      dbus.SignatureOfType(mt.Out(j)).String(),
				Direction: "out",
			}
			m.Args = append(m.Args, arg)
		}
		m.Annotations = make([]introspect.Annotation, 0)
		ms = append(ms, m)
	}
	return ms
}

type PropertyReadCallback func(read *PropertyRead) *dbus.Error

type PropertyWriteCallback func(write *PropertyWrite) *dbus.Error

type PropertyChangedCallback func(change *PropertyChanged)

type Property interface {
	SetValue(val interface{}) (changed bool, err *dbus.Error)
	GetValue() (val interface{}, err *dbus.Error)
	SetNotifyChangedFunc(func(val interface{}))
	GetType() reflect.Type
}

type PropertyInfo struct {
	Path      dbus.ObjectPath
	Interface string
	Name      string
}

type PropertyAccess struct {
	PropertyInfo
	Sender  dbus.Sender
	service *Service
}

func (pa *PropertyAccess) GetPID() (uint32, error) {
	return pa.service.GetConnPID(string(pa.Sender))
}

func (pa *PropertyAccess) GetUID() (uint32, error) {
	return pa.service.GetConnUID(string(pa.Sender))
}

type PropertyRead struct {
	PropertyAccess
}

func newPropertyRead(sender dbus.Sender, so *ServerObject,
	interfaceName, name string) *PropertyRead {

	pr := new(PropertyRead)
	pr.Sender = sender
	pr.service = so.service
	pr.Name = name
	pr.Interface = interfaceName
	pr.Path = so.path
	return pr
}

type PropertyWrite struct {
	PropertyAccess
	Value interface{} // new value
}

func newPropertyWrite(sender dbus.Sender, so *ServerObject,
	interfaceName, name string, value interface{}) *PropertyWrite {

	pw := new(PropertyWrite)
	pw.Sender = sender
	pw.service = so.service
	pw.Name = name
	pw.Interface = interfaceName
	pw.Path = so.path
	pw.Value = value
	return pw
}

type PropertyChanged struct {
	PropertyInfo
	Value interface{} // new value
}

func newPropertyChanged(path dbus.ObjectPath, interfaceName, name string,
	value interface{}) *PropertyChanged {
	pc := new(PropertyChanged)
	pc.Name = name
	pc.Interface = interfaceName
	pc.Path = path
	pc.Value = value
	return pc
}

func valueFromBus(src interface{}, valueRT reflect.Type) (reflect.Value, error) {
	newValueRV := reflect.New(valueRT)
	err := dbus.Store([]interface{}{src}, newValueRV.Interface())
	if err != nil {
		return reflect.Value{}, err
	}
	return newValueRV.Elem(), nil
}