This commit is contained in:
bluepython508 committed 2026-10-22 12:27:19 +01:00
1 parent 3530afb854
commit 6903fcff27
2146 files changed
+112256 -190703

No files matched your search

+4 -3
View File
@@ -1,10 +1,11 @@
# See https://cirrus-ci.org/guide/FreeBSD/
freebsd_instance:
image_family: freebsd-13-0
image_family: freebsd-14-3
task:
name: Test on FreeBSD
install_script: pkg install -y go119 dbus
install_script: pkg install -y go125 dbus
test_script: |
/usr/local/etc/rc.d/dbus onestart && \
eval `dbus-launch --sh-syntax` && \
go119 test -v ./...
go125 test -v ./...
+8 -2
View File
@@ -1,7 +1,13 @@
# For documentation, see https://golangci-lint.run/usage/configuration/
version: "2"
linters:
enable:
- gofumpt
- unconvert
- unparam
exclusions:
presets:
- std-error-handling
formatters:
enable:
- gofumpt
+1 -1
View File
@@ -14,7 +14,7 @@ D-Bus message bus system.
### Installation
This packages requires Go 1.12 or later. It can be installed by running the command below:
This packages requires Go 1.20 or later. It can be installed by running the command below:
```
go get github.com/godbus/dbus/v5
+2 -2
View File
@@ -54,10 +54,10 @@ type Auth interface {
func (conn *Conn) Auth(methods []Auth) error {
if methods == nil {
uid := strconv.Itoa(os.Geteuid())
methods = []Auth{AuthExternal(uid), AuthCookieSha1(uid, getHomeDir())}
methods = getDefaultAuthMethods(uid)
}
in := bufio.NewReader(conn.transport)
err := conn.transport.SendNullByte()
err := conn.SendNullByte()
if err != nil {
return err
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !windows
package dbus
func getDefaultAuthMethods(user string) []Auth {
return []Auth{AuthExternal(user)}
}
+5
View File
@@ -0,0 +1,5 @@
package dbus
func getDefaultAuthMethods(user string) []Auth {
return []Auth{AuthCookieSha1(user, getHomeDir())}
}
@@ -100,3 +100,10 @@ func (a authCookieSha1) generateChallenge() []byte {
hex.Encode(enc, b)
return enc
}
func getHomeDir() string {
if dir, err := os.UserHomeDir(); err == nil {
return dir
}
return "/"
}
+3 -3
View File
@@ -9,7 +9,7 @@ type Call struct {
Destination string
Path ObjectPath
Method string
Args []interface{}
Args []any
// Strobes when the call is complete.
Done chan *Call
@@ -19,7 +19,7 @@ type Call struct {
Err error
// Holds the response once the call is done.
Body []interface{}
Body []any
// ResponseSequence stores the sequence number of the DBus message containing
// the call response (or error). This can be compared to the sequence number
@@ -52,7 +52,7 @@ func (c *Call) ContextCancel() {
// Store stores the body of the reply into the provided pointers. It returns
// an error if the signatures of the body and retvalues don't match, or if
// the error status is not nil.
func (c *Call) Store(retvalues ...interface{}) error {
func (c *Call) Store(retvalues ...any) error {
if c.Err != nil {
return c.Err
}
+31 -17
View File
@@ -3,6 +3,7 @@ package dbus
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
@@ -96,7 +97,7 @@ func SessionBusPrivate(opts ...ConnOption) (*Conn, error) {
return Dial(address, opts...)
}
// SessionBusPrivate returns a new private connection to the session bus. If
// SessionBusPrivateNoAutoStartup returns a new private connection to the session bus. If
// the session bus is not already open, do not attempt to launch it.
func SessionBusPrivateNoAutoStartup(opts ...ConnOption) (*Conn, error) {
address, err := getSessionBusAddress(false)
@@ -107,7 +108,7 @@ func SessionBusPrivateNoAutoStartup(opts ...ConnOption) (*Conn, error) {
return Dial(address, opts...)
}
// SessionBusPrivate returns a new private connection to the session bus.
// SessionBusPrivateHandler returns a new private connection to the session bus.
//
// Deprecated: use SessionBusPrivate with options instead.
func SessionBusPrivateHandler(handler Handler, signalHandler SignalHandler) (*Conn, error) {
@@ -444,7 +445,8 @@ func (conn *Conn) handleSignal(sequence Sequence, msg *Message) {
// sender is optional for signals.
sender, _ := msg.Headers[FieldSender].value.(string)
if iface == "org.freedesktop.DBus" && sender == "org.freedesktop.DBus" {
if member == "NameLost" {
switch member {
case "NameLost":
// If we lost the name on the bus, remove it from our
// tracking list.
name, ok := msg.Body[0].(string)
@@ -452,7 +454,7 @@ func (conn *Conn) handleSignal(sequence Sequence, msg *Message) {
panic("Unable to read the lost name")
}
conn.names.loseName(name)
} else if member == "NameAcquired" {
case "NameAcquired":
// If we acquired the name on the bus, add it to our
// tracking list.
name, ok := msg.Body[0].(string)
@@ -500,15 +502,27 @@ func (conn *Conn) sendMessageAndIfClosed(msg *Message, ifClosed func()) error {
return err
}
func isEncodingError(err error) bool {
switch err.(type) {
case FormatError:
return true
case InvalidMessageError:
return true
}
return false
}
func (conn *Conn) handleSendError(msg *Message, err error) {
if msg.Type == TypeMethodCall {
switch msg.Type {
case TypeMethodCall:
conn.calls.handleSendError(msg, err)
} else if msg.Type == TypeMethodReply {
if _, ok := err.(FormatError); ok {
case TypeMethodReply:
if isEncodingError(err) {
// Make sure that the caller gets some kind of error response if
// the application code tried to respond, but the resulting message
// was malformed in the end
conn.sendError(err, msg.Headers[FieldDestination].value.(string), msg.Headers[FieldReplySerial].value.(uint32))
returnedErr := fmt.Errorf("destination tried to respond with invalid message (%w)", err)
conn.sendError(returnedErr, msg.Headers[FieldDestination].value.(string), msg.Headers[FieldReplySerial].value.(uint32))
}
}
conn.serialGen.RetireSerial(msg.serial)
@@ -613,7 +627,7 @@ func (conn *Conn) sendError(err error, dest string, serial uint32) {
// sendReply creates a method reply message corresponding to the parameters and
// sends it to conn.out.
func (conn *Conn) sendReply(dest string, serial uint32, values ...interface{}) {
func (conn *Conn) sendReply(dest string, serial uint32, values ...any) {
msg := new(Message)
msg.Type = TypeMethodReply
msg.Headers = make(map[HeaderField]Variant)
@@ -701,10 +715,10 @@ func (conn *Conn) SupportsUnixFDs() bool {
// Error represents a D-Bus message of type Error.
type Error struct {
Name string
Body []interface{}
Body []any
}
func NewError(name string, body []interface{}) *Error {
func NewError(name string, body []any) *Error {
return &Error{name, body}
}
@@ -724,7 +738,7 @@ type Signal struct {
Sender string
Path ObjectPath
Name string
Body []interface{}
Body []any
Sequence Sequence
}
@@ -775,10 +789,10 @@ func getTransport(address string) (transport, error) {
// getKey gets a key from a the list of keys. Returns "" on error / not found...
func getKey(s, key string) string {
for _, keyEqualsValue := range strings.Split(s, ",") {
keyValue := strings.SplitN(keyEqualsValue, "=", 2)
if len(keyValue) == 2 && keyValue[0] == key {
val, err := UnescapeBusAddressValue(keyValue[1])
keyEq := key + "="
for _, kv := range strings.Split(s, ",") {
if v, ok := strings.CutPrefix(kv, keyEq); ok {
val, err := UnescapeBusAddressValue(v)
if err != nil {
// No way to return an error.
return ""
@@ -951,7 +965,7 @@ func (tracker *callTracker) handleSendError(msg *Message, err error) {
}
}
func (tracker *callTracker) finalizeWithBody(sn uint32, sequence Sequence, body []interface{}) {
func (tracker *callTracker) finalizeWithBody(sn uint32, sequence Sequence, body []any) {
tracker.lck.Lock()
c, ok := tracker.calls[sn]
if ok {
+3 -10
View File
@@ -1,5 +1,4 @@
//go:build !darwin
// +build !darwin
package dbus
@@ -7,7 +6,6 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/user"
@@ -61,14 +59,9 @@ func tryDiscoverDbusSessionBusAddress() string {
// text file // containing the address of the socket, e.g.:
// DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-E1c73yNqrG
if f, err := ioutil.ReadFile(runUserSessionDbusFile); err == nil {
fileContent := string(f)
prefix := "DBUS_SESSION_BUS_ADDRESS="
if strings.HasPrefix(fileContent, prefix) {
address := strings.TrimRight(strings.TrimPrefix(fileContent, prefix), "\n\r")
return address
if f, err := os.ReadFile(runUserSessionDbusFile); err == nil {
if addr, ok := strings.CutPrefix(string(f), "DBUS_SESSION_BUS_ADDRESS="); ok {
return strings.TrimRight(addr, "\n\r")
}
}
}
+23 -1
View File
@@ -1,9 +1,9 @@
//go:build !windows && !solaris && !darwin
// +build !windows,!solaris,!darwin
package dbus
import (
"net"
"os"
)
@@ -16,3 +16,25 @@ func getSystemBusPlatformAddress() string {
}
return defaultSystemBusAddress
}
// DialUnix establishes a new private connection to the message bus specified by UnixConn.
func DialUnix(conn *net.UnixConn, opts ...ConnOption) (*Conn, error) {
tr := newUnixTransportFromConn(conn)
return newConn(tr, opts...)
}
func ConnectUnix(uconn *net.UnixConn, opts ...ConnOption) (*Conn, error) {
conn, err := DialUnix(uconn, opts...)
if err != nil {
return nil, err
}
if err = conn.Auth(conn.auth); err != nil {
_ = conn.Close()
return nil, err
}
if err = conn.Hello(); err != nil {
_ = conn.Close()
return nil, err
}
return conn, nil
}
+6 -6
View File
@@ -21,8 +21,8 @@ var (
signatureType = reflect.TypeOf(Signature{""})
objectPathType = reflect.TypeOf(ObjectPath(""))
variantType = reflect.TypeOf(Variant{Signature{""}, nil})
interfacesType = reflect.TypeOf([]interface{}{})
interfaceType = reflect.TypeOf((*interface{})(nil)).Elem()
interfacesType = reflect.TypeOf([]any{})
interfaceType = reflect.TypeOf((*any)(nil)).Elem()
unixFDType = reflect.TypeOf(UnixFD(0))
unixFDIndexType = reflect.TypeOf(UnixFDIndex(0))
errType = reflect.TypeOf((*error)(nil)).Elem()
@@ -42,7 +42,7 @@ func (e InvalidTypeError) Error() string {
// pointers. It converts slices of interfaces from src to corresponding structs
// in dest. An error is returned if the lengths of src and dest or the types of
// their elements don't match.
func Store(src []interface{}, dest ...interface{}) error {
func Store(src []any, dest ...any) error {
if len(src) != len(dest) {
return errors.New("dbus.Store: length mismatch")
}
@@ -55,7 +55,7 @@ func Store(src []interface{}, dest ...interface{}) error {
return nil
}
func storeInterfaces(src, dest interface{}) error {
func storeInterfaces(src, dest any) error {
return store(reflect.ValueOf(dest), reflect.ValueOf(src))
}
@@ -222,7 +222,7 @@ func storeStruct(dest, src reflect.Value) error {
if isVariant(dest.Type()) {
return storeBase(dest, src)
}
dval := make([]interface{}, 0, dest.NumField())
dval := make([]any, 0, dest.NumField())
dtype := dest.Type()
for i := 0; i < dest.NumField(); i++ {
field := dest.Field(i)
@@ -242,7 +242,7 @@ func storeStruct(dest, src reflect.Value) error {
"enough fields need: %d have: %d",
src.Len(), len(dval))
}
return Store(src.Interface().([]interface{}), dval...)
return Store(src.Interface().([]any), dval...)
}
func storeSliceIntoVariant(dest, src reflect.Value) error {
+9 -14
View File
@@ -53,13 +53,13 @@ func (dec *decoder) align(n int) {
}
// Calls binary.Read(dec.in, dec.order, v) and panics on read errors.
func (dec *decoder) binread(v interface{}) {
func (dec *decoder) binread(v any) {
if err := binary.Read(dec.in, dec.order, v); err != nil {
panic(err)
}
}
func (dec *decoder) Decode(sig Signature) (vs []interface{}, err error) {
func (dec *decoder) Decode(sig Signature) (vs []any, err error) {
defer func() {
var ok bool
v := recover()
@@ -69,7 +69,7 @@ func (dec *decoder) Decode(sig Signature) (vs []interface{}, err error) {
}
}
}()
vs = make([]interface{}, 0)
vs = make([]any, 0)
s := sig.str
for s != "" {
err, rem := validSingle(s, &depthCounter{})
@@ -106,7 +106,7 @@ func (dec *decoder) decodeU() uint32 {
return dec.order.Uint32(dec.buf)
}
func (dec *decoder) decode(s string, depth int) interface{} {
func (dec *decoder) decode(s string, depth int) any {
dec.align(alignment(typeFor(s)))
switch s[0] {
case 'y':
@@ -249,7 +249,7 @@ func (dec *decoder) decode(s string, depth int) interface{} {
panic(FormatError("input exceeds container depth limit"))
}
dec.align(8)
v := make([]interface{}, 0)
v := make([]any, 0)
s = s[1 : len(s)-1]
for s != "" {
err, rem := validSingle(s, &depthCounter{})
@@ -291,9 +291,10 @@ func sigByteSize(sig string) int {
i := 1
depth := 1
for i < len(sig[offset:]) && depth != 0 {
if sig[offset+i] == '(' {
switch sig[offset+i] {
case '(':
depth++
} else if sig[offset+i] == ')' {
case ')':
depth--
}
i++
@@ -370,12 +371,6 @@ func (c *stringConverter) String(b []byte) string {
}
// toString converts a byte slice to a string without allocating.
// Starting from Go 1.20 you should use unsafe.String.
func toString(b []byte) string {
var s string
h := (*reflect.StringHeader)(unsafe.Pointer(&s))
h.Data = uintptr(unsafe.Pointer(&b[0]))
h.Len = len(b)
return s
return unsafe.String(&b[0], len(b))
}
+7 -7
View File
@@ -52,9 +52,9 @@ func (h *defaultHandler) introspectPath(path ObjectPath) string {
if p != "/" {
p += "/"
}
if strings.HasPrefix(string(obj), p) {
node_name := strings.Split(string(obj[len(p):]), "/")[0]
subpath[node_name] = struct{}{}
if after, ok := strings.CutPrefix(string(obj), p); ok {
name, _, _ := strings.Cut(after, "/")
subpath[name] = struct{}{}
}
}
for s := range subpath {
@@ -117,7 +117,7 @@ type exportedMethod struct {
reflect.Value
}
func (m exportedMethod) Call(args ...interface{}) ([]interface{}, error) {
func (m exportedMethod) Call(args ...any) ([]any, error) {
t := m.Type()
params := make([]reflect.Value, len(args))
@@ -143,7 +143,7 @@ func (m exportedMethod) Call(args ...interface{}) ([]interface{}, error) {
ret = ret[:t.NumOut()-1]
}
}
out := make([]interface{}, len(ret))
out := make([]any, len(ret))
for i, val := range ret {
out[i] = val.Interface()
}
@@ -158,7 +158,7 @@ func (m exportedMethod) NumArguments() int {
return m.Value.Type().NumIn()
}
func (m exportedMethod) ArgumentValue(i int) interface{} {
func (m exportedMethod) ArgumentValue(i int) any {
return reflect.Zero(m.Type().In(i)).Interface()
}
@@ -166,7 +166,7 @@ func (m exportedMethod) NumReturns() int {
return m.Value.Type().NumOut()
}
func (m exportedMethod) ReturnValue(i int) interface{} {
func (m exportedMethod) ReturnValue(i int) any {
return reflect.Zero(m.Type().Out(i)).Interface()
}
+2 -2
View File
@@ -59,7 +59,7 @@ func (enc *encoder) padding(offset, algn int) int {
}
// Calls binary.Write(enc.out, enc.order, v) and panics on write errors.
func (enc *encoder) binwrite(v interface{}) {
func (enc *encoder) binwrite(v any) {
if err := binary.Write(enc.out, enc.order, v); err != nil {
panic(err)
}
@@ -67,7 +67,7 @@ func (enc *encoder) binwrite(v interface{}) {
// Encode encodes the given values to the underlying reader. All written values
// are aligned properly as required by the D-Bus spec.
func (enc *encoder) Encode(vs ...interface{}) (err error) {
func (enc *encoder) Encode(vs ...any) (err error) {
defer func() {
err, _ = recover().(error)
}()
+50 -24
View File
@@ -11,47 +11,47 @@ import (
var (
ErrMsgInvalidArg = Error{
"org.freedesktop.DBus.Error.InvalidArgs",
[]interface{}{"Invalid type / number of args"},
[]any{"Invalid type / number of args"},
}
ErrMsgNoObject = Error{
"org.freedesktop.DBus.Error.NoSuchObject",
[]interface{}{"No such object"},
[]any{"No such object"},
}
ErrMsgUnknownMethod = Error{
"org.freedesktop.DBus.Error.UnknownMethod",
[]interface{}{"Unknown / invalid method"},
[]any{"Unknown / invalid method"},
}
ErrMsgUnknownInterface = Error{
"org.freedesktop.DBus.Error.UnknownInterface",
[]interface{}{"Object does not implement the interface"},
[]any{"Object does not implement the interface"},
}
)
func MakeNoObjectError(path ObjectPath) Error {
return Error{
"org.freedesktop.DBus.Error.NoSuchObject",
[]interface{}{fmt.Sprintf("No such object '%s'", string(path))},
[]any{fmt.Sprintf("No such object '%s'", string(path))},
}
}
func MakeUnknownMethodError(methodName string) Error {
return Error{
"org.freedesktop.DBus.Error.UnknownMethod",
[]interface{}{fmt.Sprintf("Unknown / invalid method '%s'", methodName)},
[]any{fmt.Sprintf("Unknown / invalid method '%s'", methodName)},
}
}
func MakeUnknownInterfaceError(ifaceName string) Error {
return Error{
"org.freedesktop.DBus.Error.UnknownInterface",
[]interface{}{fmt.Sprintf("Object does not implement the interface '%s'", ifaceName)},
[]any{fmt.Sprintf("Object does not implement the interface '%s'", ifaceName)},
}
}
func MakeFailedError(err error) *Error {
return &Error{
"org.freedesktop.DBus.Error.Failed",
[]interface{}{err.Error()},
[]any{err.Error()},
}
}
@@ -67,7 +67,7 @@ func computeMethodName(name string, mapping map[string]string) string {
return name
}
func getMethods(in interface{}, mapping map[string]string) map[string]reflect.Value {
func getMethods(in any, mapping map[string]string) map[string]reflect.Value {
if in == nil {
return nil
}
@@ -91,7 +91,7 @@ func getMethods(in interface{}, mapping map[string]string) map[string]reflect.Va
return methods
}
func getAllMethods(in interface{}, mapping map[string]string) map[string]reflect.Value {
func getAllMethods(in any, mapping map[string]string) map[string]reflect.Value {
if in == nil {
return nil
}
@@ -107,9 +107,9 @@ func getAllMethods(in interface{}, mapping map[string]string) map[string]reflect
return methods
}
func standardMethodArgumentDecode(m Method, sender string, msg *Message, body []interface{}) ([]interface{}, error) {
pointers := make([]interface{}, m.NumArguments())
decode := make([]interface{}, 0, len(body))
func standardMethodArgumentDecode(m Method, sender string, msg *Message, body []any) ([]any, error) {
pointers := make([]any, m.NumArguments())
decode := make([]any, 0, len(body))
for i := 0; i < m.NumArguments(); i++ {
tp := reflect.TypeOf(m.ArgumentValue(i))
@@ -135,7 +135,7 @@ func standardMethodArgumentDecode(m Method, sender string, msg *Message, body []
return pointers, nil
}
func (conn *Conn) decodeArguments(m Method, sender string, msg *Message) ([]interface{}, error) {
func (conn *Conn) decodeArguments(m Method, sender string, msg *Message) ([]any, error) {
if decoder, ok := m.(ArgumentDecoder); ok {
return decoder.DecodeArguments(conn, sender, msg, msg.Body)
}
@@ -204,7 +204,7 @@ func (conn *Conn) handleCall(msg *Message) {
reply.Headers[FieldDestination] = msg.Headers[FieldSender]
}
reply.Headers[FieldReplySerial] = MakeVariant(msg.serial)
reply.Body = make([]interface{}, len(ret))
reply.Body = make([]any, len(ret))
copy(reply.Body, ret)
reply.Headers[FieldSignature] = MakeVariant(SignatureOf(reply.Body...))
@@ -218,7 +218,7 @@ func (conn *Conn) handleCall(msg *Message) {
// Emit emits the given signal on the message bus. The name parameter must be
// formatted as "interface.member", e.g., "org.freedesktop.DBus.NameLost".
func (conn *Conn) Emit(path ObjectPath, name string, values ...interface{}) error {
func (conn *Conn) Emit(path ObjectPath, name string, values ...any) error {
i := strings.LastIndex(name, ".")
if i == -1 {
return errors.New("dbus: invalid method name")
@@ -274,7 +274,7 @@ func (conn *Conn) Emit(path ObjectPath, name string, values ...interface{}) erro
// the given combination of path and interface.
//
// Export returns an error if path is not a valid path name.
func (conn *Conn) Export(v interface{}, path ObjectPath, iface string) error {
func (conn *Conn) Export(v any, path ObjectPath, iface string) error {
return conn.ExportWithMap(v, nil, path, iface)
}
@@ -286,7 +286,7 @@ func (conn *Conn) Export(v interface{}, path ObjectPath, iface string) error {
// type parameter to your method signature. If the error returned is not nil,
// it is sent back to the caller as an error. Otherwise, a method reply is
// sent with the other return values as its body.
func (conn *Conn) ExportAll(v interface{}, path ObjectPath, iface string) error {
func (conn *Conn) ExportAll(v any, path ObjectPath, iface string) error {
return conn.export(getAllMethods(v, nil), path, iface, false)
}
@@ -295,7 +295,7 @@ func (conn *Conn) ExportAll(v interface{}, path ObjectPath, iface string) error
//
// The keys in the map are the real method names (exported on the struct), and
// the values are the method names to be exported on DBus.
func (conn *Conn) ExportWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string) error {
func (conn *Conn) ExportWithMap(v any, mapping map[string]string, path ObjectPath, iface string) error {
return conn.export(getMethods(v, mapping), path, iface, false)
}
@@ -309,7 +309,7 @@ func (conn *Conn) ExportWithMap(v interface{}, mapping map[string]string, path O
// Note that more specific export paths take precedence over less specific. For
// example, a method call using the ObjectPath /foo/bar/baz will call a method
// exported on /foo/bar before a method exported on /foo.
func (conn *Conn) ExportSubtree(v interface{}, path ObjectPath, iface string) error {
func (conn *Conn) ExportSubtree(v any, path ObjectPath, iface string) error {
return conn.ExportSubtreeWithMap(v, nil, path, iface)
}
@@ -318,7 +318,7 @@ func (conn *Conn) ExportSubtree(v interface{}, path ObjectPath, iface string) er
//
// The keys in the map are the real method names (exported on the struct), and
// the values are the method names to be exported on DBus.
func (conn *Conn) ExportSubtreeWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string) error {
func (conn *Conn) ExportSubtreeWithMap(v any, mapping map[string]string, path ObjectPath, iface string) error {
return conn.export(getMethods(v, mapping), path, iface, true)
}
@@ -332,16 +332,16 @@ func (conn *Conn) ExportSubtreeWithMap(v interface{}, mapping map[string]string,
// methods on the fly.
//
// Any non-function objects in the method table are ignored.
func (conn *Conn) ExportMethodTable(methods map[string]interface{}, path ObjectPath, iface string) error {
func (conn *Conn) ExportMethodTable(methods map[string]any, path ObjectPath, iface string) error {
return conn.exportMethodTable(methods, path, iface, false)
}
// Like ExportSubtree, but with the same caveats as ExportMethodTable.
func (conn *Conn) ExportSubtreeMethodTable(methods map[string]interface{}, path ObjectPath, iface string) error {
func (conn *Conn) ExportSubtreeMethodTable(methods map[string]any, path ObjectPath, iface string) error {
return conn.exportMethodTable(methods, path, iface, true)
}
func (conn *Conn) exportMethodTable(methods map[string]interface{}, path ObjectPath, iface string, includeSubtree bool) error {
func (conn *Conn) exportMethodTable(methods map[string]any, path ObjectPath, iface string, includeSubtree bool) error {
var out map[string]reflect.Value
if methods != nil {
out = make(map[string]reflect.Value)
@@ -438,6 +438,18 @@ const (
ReleaseNameReplyNotOwner
)
func (rep ReleaseNameReply) String() string {
switch rep {
case ReleaseNameReplyReleased:
return "released"
case ReleaseNameReplyNonExistent:
return "non existent"
case ReleaseNameReplyNotOwner:
return "not owner"
}
return "unknown"
}
// RequestNameFlags represents the possible flags for a RequestName call.
type RequestNameFlags uint32
@@ -456,3 +468,17 @@ const (
RequestNameReplyExists
RequestNameReplyAlreadyOwner
)
func (rep RequestNameReply) String() string {
switch rep {
case RequestNameReplyPrimaryOwner:
return "primary owner"
case RequestNameReplyInQueue:
return "in queue"
case RequestNameReplyExists:
return "exists"
case RequestNameReplyAlreadyOwner:
return "already owner"
}
return "unknown"
}
-25
View File
@@ -1,25 +0,0 @@
package dbus
import (
"os"
"os/user"
)
// Get returns the home directory of the current user, which is usually the
// value of HOME environment variable. In case it is not set or empty, os/user
// package is used.
//
// If linking statically with cgo enabled against glibc, make sure the
// osusergo build tag is used.
//
// If needing to do nss lookups, do not disable cgo or set osusergo.
func getHomeDir() string {
homeDir := os.Getenv("HOME")
if homeDir != "" {
return homeDir
}
if u, err := user.Current(); err == nil {
return u.HomeDir
}
return "/"
}
+2 -2
View File
@@ -108,7 +108,7 @@ type Message struct {
Type
Flags
Headers map[HeaderField]Variant
Body []interface{}
Body []any
serial uint32
}
@@ -232,7 +232,7 @@ func (msg *Message) EncodeToWithFDs(out io.Writer, order binary.ByteOrder) (fds
if err := msg.validateHeader(); err != nil {
return nil, err
}
var vs [7]interface{}
var vs [7]any
switch order {
case binary.LittleEndian:
vs[0] = byte('l')
+13 -13
View File
@@ -9,15 +9,15 @@ import (
// BusObject is the interface of a remote object on which methods can be
// invoked.
type BusObject interface {
Call(method string, flags Flags, args ...interface{}) *Call
CallWithContext(ctx context.Context, method string, flags Flags, args ...interface{}) *Call
Go(method string, flags Flags, ch chan *Call, args ...interface{}) *Call
GoWithContext(ctx context.Context, method string, flags Flags, ch chan *Call, args ...interface{}) *Call
Call(method string, flags Flags, args ...any) *Call
CallWithContext(ctx context.Context, method string, flags Flags, args ...any) *Call
Go(method string, flags Flags, ch chan *Call, args ...any) *Call
GoWithContext(ctx context.Context, method string, flags Flags, ch chan *Call, args ...any) *Call
AddMatchSignal(iface, member string, options ...MatchOption) *Call
RemoveMatchSignal(iface, member string, options ...MatchOption) *Call
GetProperty(p string) (Variant, error)
StoreProperty(p string, value interface{}) error
SetProperty(p string, v interface{}) error
StoreProperty(p string, value any) error
SetProperty(p string, v any) error
Destination() string
Path() ObjectPath
}
@@ -30,12 +30,12 @@ type Object struct {
}
// Call calls a method with (*Object).Go and waits for its reply.
func (o *Object) Call(method string, flags Flags, args ...interface{}) *Call {
func (o *Object) Call(method string, flags Flags, args ...any) *Call {
return <-o.createCall(context.Background(), method, flags, make(chan *Call, 1), args...).Done
}
// CallWithContext acts like Call but takes a context
func (o *Object) CallWithContext(ctx context.Context, method string, flags Flags, args ...interface{}) *Call {
func (o *Object) CallWithContext(ctx context.Context, method string, flags Flags, args ...any) *Call {
return <-o.createCall(ctx, method, flags, make(chan *Call, 1), args...).Done
}
@@ -89,16 +89,16 @@ func (o *Object) RemoveMatchSignal(iface, member string, options ...MatchOption)
//
// If the method parameter contains a dot ('.'), the part before the last dot
// specifies the interface on which the method is called.
func (o *Object) Go(method string, flags Flags, ch chan *Call, args ...interface{}) *Call {
func (o *Object) Go(method string, flags Flags, ch chan *Call, args ...any) *Call {
return o.createCall(context.Background(), method, flags, ch, args...)
}
// GoWithContext acts like Go but takes a context
func (o *Object) GoWithContext(ctx context.Context, method string, flags Flags, ch chan *Call, args ...interface{}) *Call {
func (o *Object) GoWithContext(ctx context.Context, method string, flags Flags, ch chan *Call, args ...any) *Call {
return o.createCall(ctx, method, flags, ch, args...)
}
func (o *Object) createCall(ctx context.Context, method string, flags Flags, ch chan *Call, args ...interface{}) *Call {
func (o *Object) createCall(ctx context.Context, method string, flags Flags, ch chan *Call, args ...any) *Call {
if ctx == nil {
panic("nil context")
}
@@ -136,7 +136,7 @@ func (o *Object) GetProperty(p string) (Variant, error) {
// StoreProperty calls org.freedesktop.DBus.Properties.Get on the given
// object. The property name must be given in interface.member notation.
// It stores the returned property into the provided value.
func (o *Object) StoreProperty(p string, value interface{}) error {
func (o *Object) StoreProperty(p string, value any) error {
idx := strings.LastIndex(p, ".")
if idx == -1 || idx+1 == len(p) {
return errors.New("dbus: invalid property " + p)
@@ -152,7 +152,7 @@ func (o *Object) StoreProperty(p string, value interface{}) error {
// SetProperty calls org.freedesktop.DBus.Properties.Set on the given
// object. The property name must be given in interface.member notation.
// Panics if v is not a valid Variant type.
func (o *Object) SetProperty(p string, v interface{}) error {
func (o *Object) SetProperty(p string, v any) error {
// v might already be a variant...
variant, ok := v.(Variant)
if !ok {
+5 -5
View File
@@ -38,17 +38,17 @@ type Interface interface {
// A Method represents the exposed methods on D-Bus.
type Method interface {
// Call requires that all arguments are decoded before being passed to it.
Call(args ...interface{}) ([]interface{}, error)
Call(args ...any) ([]any, error)
NumArguments() int
NumReturns() int
// ArgumentValue returns a representative value for the argument at position
// it should be of the proper type. reflect.Zero would be a good mechanism
// to use for this Value.
ArgumentValue(position int) interface{}
ArgumentValue(position int) any
// ReturnValue returns a representative value for the return at position
// it should be of the proper type. reflect.Zero would be a good mechanism
// to use for this Value.
ReturnValue(position int) interface{}
ReturnValue(position int) any
}
// An Argument Decoder can decode arguments using the non-standard mechanism
@@ -65,7 +65,7 @@ type ArgumentDecoder interface {
// To decode the arguments of a method the sender and message are
// provided in case the semantics of the implementer provides access
// to these as part of the method invocation.
DecodeArguments(conn *Conn, sender string, msg *Message, args []interface{}) ([]interface{}, error)
DecodeArguments(conn *Conn, sender string, msg *Message, args []any) ([]any, error)
}
// A SignalHandler is responsible for delivering a signal.
@@ -93,7 +93,7 @@ type SignalRegistrar interface {
// "org.freedesktop.DBus.Error.Failed" error. By implementing this
// interface as well a custom encoding may be provided.
type DBusError interface {
DBusError() (string, []interface{})
DBusError() (string, []any)
}
// SerialGenerator is responsible for serials generation.
+14 -12
View File
@@ -31,7 +31,7 @@ type Signature struct {
// SignatureOf returns the concatenation of all the signatures of the given
// values. It panics if one of them is not representable in D-Bus.
func SignatureOf(vs ...interface{}) Signature {
func SignatureOf(vs ...any) Signature {
var s string
for _, v := range vs {
s += getSignature(reflect.TypeOf(v), &depthCounter{})
@@ -89,9 +89,10 @@ func getSignature(t reflect.Type, depth *depthCounter) (sig string) {
}
return "s"
case reflect.Struct:
if t == variantType {
switch t {
case variantType:
return "v"
} else if t == signatureType {
case signatureType:
return "g"
}
var s string
@@ -183,26 +184,26 @@ func (cnt *depthCounter) Valid() bool {
return cnt.arrayDepth <= 32 && cnt.structDepth <= 32 && cnt.dictEntryDepth <= 32
}
func (cnt *depthCounter) EnterArray() *depthCounter {
func (cnt depthCounter) EnterArray() *depthCounter {
cnt.arrayDepth++
return cnt
return &cnt
}
func (cnt *depthCounter) EnterStruct() *depthCounter {
func (cnt depthCounter) EnterStruct() *depthCounter {
cnt.structDepth++
return cnt
return &cnt
}
func (cnt *depthCounter) EnterDictEntry() *depthCounter {
func (cnt depthCounter) EnterDictEntry() *depthCounter {
cnt.dictEntryDepth++
return cnt
return &cnt
}
// Try to read a single type from this string. If it was successful, err is nil
// and rem is the remaining unparsed part. Otherwise, err is a non-nil
// SignatureError and rem is "". depth is the current recursion depth which may
// not be greater than 64 and should be given as 0 on the first call.
func validSingle(s string, depth *depthCounter) (err error, rem string) {
func validSingle(s string, depth *depthCounter) (err error, rem string) { //nolint:staticcheck // Ignore "ST1008: error should be returned as the last argument".
if s == "" {
return SignatureError{Sig: s, Reason: "empty signature"}, ""
}
@@ -258,9 +259,10 @@ func validSingle(s string, depth *depthCounter) (err error, rem string) {
func findMatching(s string, left, right rune) int {
n := 0
for i, v := range s {
if v == left {
switch v {
case left:
n++
} else if v == right {
case right:
n--
}
if n == 0 {
+4 -3
View File
@@ -1,12 +1,11 @@
//go:build !windows
// +build !windows
package dbus
import (
"errors"
"io/ioutil"
"net"
"os"
)
func init() {
@@ -28,12 +27,14 @@ func newNonceTcpTransport(keys string) (transport, error) {
if err != nil {
return nil, err
}
b, err := ioutil.ReadFile(noncefile)
b, err := os.ReadFile(noncefile)
if err != nil {
socket.Close()
return nil, err
}
_, err = socket.Write(b)
if err != nil {
socket.Close()
return nil, err
}
return NewConn(socket)
+15 -8
View File
@@ -1,5 +1,4 @@
//go:build !windows && !solaris
// +build !windows,!solaris
package dbus
@@ -55,6 +54,14 @@ type unixTransport struct {
hasUnixFDs bool
}
func newUnixTransportFromConn(conn *net.UnixConn) transport {
t := new(unixTransport)
t.UnixConn = conn
t.hasUnixFDs = true
return t
}
func newUnixTransport(keys string) (transport, error) {
var err error
@@ -134,16 +141,16 @@ func (t *unixTransport) ReadMessage() (*Message, error) {
}
msg := &Message{
Type: t.rdr.msghead.Type,
Flags: t.rdr.msghead.Flags,
serial: t.rdr.msghead.Serial,
Type: t.rdr.Type,
Flags: t.rdr.Flags,
serial: t.rdr.Serial,
}
// Length of header fields (without alignment).
hlen := t.rdr.msghead.HeaderLen
hlen := t.rdr.HeaderLen
if hlen%8 != 0 {
hlen += 8 - (hlen % 8)
}
if hlen+t.rdr.msghead.BodyLen+16 > 1<<27 {
if hlen+t.rdr.BodyLen+16 > 1<<27 {
return nil, InvalidMessageError("message is too long")
}
@@ -167,7 +174,7 @@ func (t *unixTransport) ReadMessage() (*Message, error) {
var unixfds uint32
for _, v := range t.rdr.headers {
if v.Field == byte(FieldUnixFDs) {
unixfds, _ = v.Variant.value.(uint32)
unixfds, _ = v.value.(uint32)
}
}
@@ -264,7 +271,7 @@ func (t *unixTransport) SendMessage(msg *Message) error {
return err
}
oob := syscall.UnixRights(fds...)
n, oobn, err := t.UnixConn.WriteMsgUnix(buf.Bytes(), oob, nil)
n, oobn, err := t.WriteMsgUnix(buf.Bytes(), oob, nil)
if err != nil {
return err
}
+1 -1
View File
@@ -14,7 +14,7 @@ import (
func (t *unixTransport) SendNullByte() error {
ucred := &syscall.Ucred{Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid())}
b := syscall.UnixCredentials(ucred)
_, oobn, err := t.UnixConn.WriteMsgUnix([]byte{0}, b, nil)
_, oobn, err := t.WriteMsgUnix([]byte{0}, b, nil)
if err != nil {
return err
}
+25 -6
View File
@@ -11,17 +11,17 @@ import (
// Variant represents the D-Bus variant type.
type Variant struct {
sig Signature
value interface{}
value any
}
// MakeVariant converts the given value to a Variant. It panics if v cannot be
// represented as a D-Bus type.
func MakeVariant(v interface{}) Variant {
func MakeVariant(v any) Variant {
return MakeVariantWithSignature(v, SignatureOf(v))
}
// MakeVariantWithSignature converts the given value to a Variant.
func MakeVariantWithSignature(v interface{}, s Signature) Variant {
func MakeVariantWithSignature(v any, s Signature) Variant {
return Variant{s, v}
}
@@ -73,7 +73,7 @@ func (v Variant) format() (string, bool) {
}
rv := reflect.ValueOf(v.value)
switch rv.Kind() {
case reflect.Slice:
case reflect.Slice, reflect.Array:
if rv.Len() == 0 {
return "[]", false
}
@@ -119,6 +119,25 @@ func (v Variant) format() (string, bool) {
}
buf.WriteByte('}')
return buf.String(), unamb
case reflect.Struct:
if rv.NumField() == 0 {
return "()", false
}
unamb := true
var buf bytes.Buffer
buf.WriteByte('(')
for i := 0; i < rv.NumField(); i++ {
s, b := MakeVariant(rv.Field(i).Interface()).format()
unamb = unamb && b
buf.WriteString(s)
buf.WriteString(",")
if i != rv.NumField()-1 {
buf.WriteString(" ")
}
}
buf.WriteByte(')')
return buf.String(), unamb
}
return `"INVALID"`, true
}
@@ -139,12 +158,12 @@ func (v Variant) String() string {
}
// Value returns the underlying value of v.
func (v Variant) Value() interface{} {
func (v Variant) Value() any {
return v.value
}
// Store converts the variant into a native go type using the same
// mechanism as the "Store" function.
func (v Variant) Store(value interface{}) error {
func (v Variant) Store(value any) error {
return storeInterfaces(v.value, value)
}
+1 -1
View File
@@ -67,7 +67,7 @@ func (l *varLexer) emit(t varTokenType) {
l.start = l.pos
}
func (l *varLexer) errorf(format string, v ...interface{}) lexState {
func (l *varLexer) errorf(format string, v ...any) lexState {
l.tokens = append(l.tokens, varToken{
tokError,
fmt.Sprintf(format, v...),
+22 -22
View File
@@ -33,7 +33,7 @@ type varNode interface {
Infer() (Signature, error)
String() string
Sigs() sigSet
Value(Signature) (interface{}, error)
Value(Signature) (any, error)
}
func varMakeNode(p *varParser) (varNode, error) {
@@ -134,7 +134,7 @@ func (s sigSet) ToArray() sigSet {
type numNode struct {
sig Signature
str string
val interface{}
val any
}
var numSigSet = sigSet{
@@ -169,7 +169,7 @@ func (n numNode) Sigs() sigSet {
return numSigSet
}
func (n numNode) Value(sig Signature) (interface{}, error) {
func (n numNode) Value(sig Signature) (any, error) {
if n.sig.str != "" && n.sig != sig {
return nil, varTypeError{n.str, sig}
}
@@ -190,7 +190,7 @@ func varMakeNumNode(tok varToken, sig Signature) (varNode, error) {
return numNode{sig: sig, val: num}, nil
}
func varNumAs(s string, sig Signature) (interface{}, error) {
func varNumAs(s string, sig Signature) (any, error) {
isUnsigned := false
size := 32
switch sig.str {
@@ -220,20 +220,20 @@ func varNumAs(s string, sig Signature) (interface{}, error) {
return nil, varTypeError{s, sig}
}
base := 10
if strings.HasPrefix(s, "0x") {
if after, ok := strings.CutPrefix(s, "0x"); ok {
base = 16
s = s[2:]
s = after
}
if strings.HasPrefix(s, "0") && len(s) != 1 {
if after, ok := strings.CutPrefix(s, "0"); ok && len(s) != 1 {
base = 8
s = s[1:]
s = after
}
if isUnsigned {
i, err := strconv.ParseUint(s, base, size)
if err != nil {
return nil, err
}
var v interface{} = i
var v any = i
switch sig.str {
case "y":
v = byte(i)
@@ -248,7 +248,7 @@ func varNumAs(s string, sig Signature) (interface{}, error) {
if err != nil {
return nil, err
}
var v interface{} = i
var v any = i
switch sig.str {
case "n":
v = int16(i)
@@ -260,8 +260,8 @@ func varNumAs(s string, sig Signature) (interface{}, error) {
type stringNode struct {
sig Signature
str string // parsed
val interface{} // has correct type
str string // parsed
val any // has correct type
}
var stringSigSet = sigSet{
@@ -285,19 +285,19 @@ func (n stringNode) Sigs() sigSet {
return stringSigSet
}
func (n stringNode) Value(sig Signature) (interface{}, error) {
func (n stringNode) Value(sig Signature) (any, error) {
if n.sig.str != "" && n.sig != sig {
return nil, varTypeError{n.str, sig}
}
if n.val != nil {
return n.val, nil
}
switch {
case sig.str == "g":
switch sig.str {
case "g":
return Signature{n.str}, nil
case sig.str == "o":
case "o":
return ObjectPath(n.str), nil
case sig.str == "s":
case "s":
return n.str, nil
default:
return nil, varTypeError{n.str, sig}
@@ -407,7 +407,7 @@ func (boolNode) Sigs() sigSet {
return boolSigSet
}
func (b boolNode) Value(sig Signature) (interface{}, error) {
func (b boolNode) Value(sig Signature) (any, error) {
if sig.str != "b" {
return nil, varTypeError{b.String(), sig}
}
@@ -445,7 +445,7 @@ func (n arrayNode) Sigs() sigSet {
return n.set
}
func (n arrayNode) Value(sig Signature) (interface{}, error) {
func (n arrayNode) Value(sig Signature) (any, error) {
if n.set.Empty() {
// no type information whatsoever, so this must be an empty slice
return reflect.MakeSlice(typeFor(sig.str), 0, 0).Interface(), nil
@@ -536,7 +536,7 @@ func (variantNode) Sigs() sigSet {
return variantSet
}
func (n variantNode) Value(sig Signature) (interface{}, error) {
func (n variantNode) Value(sig Signature) (any, error) {
if sig.str != "v" {
return nil, varTypeError{n.String(), sig}
}
@@ -612,7 +612,7 @@ func (n dictNode) Sigs() sigSet {
return r
}
func (n dictNode) Value(sig Signature) (interface{}, error) {
func (n dictNode) Value(sig Signature) (any, error) {
set := n.Sigs()
if set.Empty() {
// no type information -> empty dict
@@ -747,7 +747,7 @@ func (b byteStringNode) Sigs() sigSet {
return byteStringSet
}
func (b byteStringNode) Value(sig Signature) (interface{}, error) {
func (b byteStringNode) Value(sig Signature) (any, error) {
if sig.str != "ay" {
return nil, varTypeError{b.String(), sig}
}