initial commit

This commit is contained in:
NeilClack
2026-08-07 14:51:41 -05:00
commit 9251b3a196
604 changed files with 464448 additions and 0 deletions
@@ -0,0 +1,23 @@
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
.idea/
+179
View File
@@ -0,0 +1,179 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
AccessPointInterface = NetworkManagerInterface + ".AccessPoint"
/* Properties */
AccessPointPropertyFlags = AccessPointInterface + ".Flags" // readable u
AccessPointPropertyWpaFlags = AccessPointInterface + ".WpaFlags" // readable u
AccessPointPropertyRsnFlags = AccessPointInterface + ".RsnFlags" // readable u
AccessPointPropertySsid = AccessPointInterface + ".Ssid" // readable ay
AccessPointPropertyFrequency = AccessPointInterface + ".Frequency" // readable u
AccessPointPropertyHwAddress = AccessPointInterface + ".HwAddress" // readable s
AccessPointPropertyMode = AccessPointInterface + ".Mode" // readable u
AccessPointPropertyMaxBitrate = AccessPointInterface + ".MaxBitrate" // readable u
AccessPointPropertyStrength = AccessPointInterface + ".Strength" // readable y
AccessPointPropertyLastSeen = AccessPointInterface + ".LastSeen" // readable i
)
type AccessPoint interface {
GetPath() dbus.ObjectPath
// GetPropertyFlags gets flags describing the capabilities of the access point.
GetPropertyFlags() (uint32, error)
// GetPropertyWPAFlags gets flags describing the access point's capabilities
// according to WPA (Wi-Fi Protected Access).
GetPropertyWPAFlags() (uint32, error)
// GetPropertyRSNFlags gets flags describing the access point's capabilities
// according to the RSN (Robust Secure Network) protocol.
GetPropertyRSNFlags() (uint32, error)
// GetPropertySSID returns the Service Set Identifier identifying the access point.
GetPropertySSID() (string, error)
// GetPropertyFrequency gets the radio channel frequency in use by the access point, in MHz.
GetPropertyFrequency() (uint32, error)
// GetPropertyHWAddress gets the hardware address (BSSID) of the access point.
GetPropertyHWAddress() (string, error)
// GetPropertyMode describes the operating mode of the access point.
GetPropertyMode() (Nm80211Mode, error)
// GetPropertyMaxBitrate gets the maximum bitrate this access point is capable of, in kilobits/second (Kb/s).
GetPropertyMaxBitrate() (uint32, error)
// GetPropertyStrength gets the current signal quality of the access point, in percent.
GetPropertyStrength() (uint8, error)
// GetPropertyLastSeen The timestamp (in CLOCK_BOOTTIME seconds) for the last time the access point was found in scan results.
// A value of -1 means the access point has never been found in scan results.
GetPropertyLastSeen() (int32, error)
MarshalJSON() ([]byte, error)
}
func NewAccessPoint(objectPath dbus.ObjectPath) (AccessPoint, error) {
var a accessPoint
return &a, a.init(NetworkManagerInterface, objectPath)
}
type accessPoint struct {
dbusBase
}
func (a *accessPoint) GetPath() dbus.ObjectPath {
return a.obj.Path()
}
func (a *accessPoint) GetPropertyFlags() (uint32, error) {
return a.getUint32Property(AccessPointPropertyFlags)
}
func (a *accessPoint) GetPropertyWPAFlags() (uint32, error) {
return a.getUint32Property(AccessPointPropertyWpaFlags)
}
func (a *accessPoint) GetPropertyRSNFlags() (uint32, error) {
return a.getUint32Property(AccessPointPropertyRsnFlags)
}
func (a *accessPoint) GetPropertySSID() (string, error) {
r, err := a.getSliceByteProperty(AccessPointPropertySsid)
if err != nil {
return "", err
}
return string(r), nil
}
func (a *accessPoint) GetPropertyFrequency() (uint32, error) {
return a.getUint32Property(AccessPointPropertyFrequency)
}
func (a *accessPoint) GetPropertyHWAddress() (string, error) {
return a.getStringProperty(AccessPointPropertyHwAddress)
}
func (a *accessPoint) GetPropertyMode() (Nm80211Mode, error) {
r, err := a.getUint32Property(AccessPointPropertyMode)
if err != nil {
return Nm80211ModeUnknown, err
}
return Nm80211Mode(r), nil
}
func (a *accessPoint) GetPropertyMaxBitrate() (uint32, error) {
return a.getUint32Property(AccessPointPropertyMaxBitrate)
}
func (a *accessPoint) GetPropertyStrength() (uint8, error) {
return a.getUint8Property(AccessPointPropertyStrength)
}
func (a *accessPoint) GetPropertyLastSeen() (int32, error) {
return a.getInt32Property(AccessPointPropertyLastSeen)
}
func (a *accessPoint) MarshalJSON() ([]byte, error) {
Flags, err := a.GetPropertyFlags()
if err != nil {
return nil, err
}
WPAFlags, err := a.GetPropertyWPAFlags()
if err != nil {
return nil, err
}
RSNFlags, err := a.GetPropertyRSNFlags()
if err != nil {
return nil, err
}
SSID, err := a.GetPropertySSID()
if err != nil {
return nil, err
}
Frequency, err := a.GetPropertyFrequency()
if err != nil {
return nil, err
}
HWAddress, err := a.GetPropertyHWAddress()
if err != nil {
return nil, err
}
Mode, err := a.GetPropertyMode()
if err != nil {
return nil, err
}
MaxBitrate, err := a.GetPropertyMaxBitrate()
if err != nil {
return nil, err
}
Strength, err := a.GetPropertyStrength()
if err != nil {
return nil, err
}
LastSeen, err := a.GetPropertyLastSeen()
if err != nil {
return nil, err
}
return json.Marshal(map[string]interface{}{
"Flags": Flags,
"WPAFlags": WPAFlags,
"RSNFlags": RSNFlags,
"SSID": SSID,
"Frequency": Frequency,
"HWAddress": HWAddress,
"Mode": Mode.String(),
"MaxBitrate": MaxBitrate,
"Strength": Strength,
"LastSeen": LastSeen,
})
}
+274
View File
@@ -0,0 +1,274 @@
package gonetworkmanager
import (
"fmt"
"github.com/godbus/dbus/v5"
)
const (
ActiveConnectionInterface = NetworkManagerInterface + ".Connection.Active"
/* Properties */
ActiveConnectionPropertyConnection = ActiveConnectionInterface + ".Connection" // readable o
ActiveConnectionPropertySpecificObject = ActiveConnectionInterface + ".SpecificObject" // readable o
ActiveConnectionPropertyId = ActiveConnectionInterface + ".Id" // readable s
ActiveConnectionPropertyUuid = ActiveConnectionInterface + ".Uuid" // readable s
ActiveConnectionPropertyType = ActiveConnectionInterface + ".Type" // readable s
ActiveConnectionPropertyDevices = ActiveConnectionInterface + ".Devices" // readable ao
ActiveConnectionPropertyState = ActiveConnectionInterface + ".State" // readable u
ActiveConnectionPropertyStateFlags = ActiveConnectionInterface + ".StateFlags" // readable u
ActiveConnectionPropertyDefault = ActiveConnectionInterface + ".Default" // readable b
ActiveConnectionPropertyIp4Config = ActiveConnectionInterface + ".Ip4Config" // readable o
ActiveConnectionPropertyDhcp4Config = ActiveConnectionInterface + ".Dhcp4Config" // readable o
ActiveConnectionPropertyDefault6 = ActiveConnectionInterface + ".Default6" // readable b
ActiveConnectionPropertyIp6Config = ActiveConnectionInterface + ".Ip6Config" // readable o
ActiveConnectionPropertyDhcp6Config = ActiveConnectionInterface + ".Dhcp6Config" // readable o
ActiveConnectionPropertyVpn = ActiveConnectionInterface + ".Vpn" // readable b
ActiveConnectionPropertyMaster = ActiveConnectionInterface + ".Master" // readable o
/* Signals */
ActiveConnectionSignalStateChanged = "StateChanged" // u state, u reason
)
type ActiveConnection interface {
GetPath() dbus.ObjectPath
// GetPropertyConnection gets connection object of the connection.
GetPropertyConnection() (Connection, error)
// GetPropertySpecificObject gets a specific object associated with the active connection.
GetPropertySpecificObject() (AccessPoint, error)
// GetPropertyID gets the ID of the connection.
GetPropertyID() (string, error)
// GetPropertyUUID gets the UUID of the connection.
GetPropertyUUID() (string, error)
// GetPropertyType gets the type of the connection.
GetPropertyType() (string, error)
// GetPropertyDevices gets array of device objects which are part of this active connection.
GetPropertyDevices() ([]Device, error)
// GetPropertyState gets the state of the connection.
GetPropertyState() (NmActiveConnectionState, error)
// GetPropertyStateFlags gets the state flags of the connection.
GetPropertyStateFlags() (uint32, error)
// GetPropertyDefault gets the default IPv4 flag of the connection.
GetPropertyDefault() (bool, error)
// GetPropertyIP4Config gets the IP4Config of the connection.
GetPropertyIP4Config() (IP4Config, error)
// GetPropertyDHCP4Config gets the DHCP6Config of the connection.
GetPropertyDHCP4Config() (DHCP4Config, error)
// GetPropertyDefault6 gets the default IPv6 flag of the connection.
GetPropertyDefault6() (bool, error)
// GetPropertyIP6Config gets the IP6Config of the connection.
GetPropertyIP6Config() (IP6Config, error)
// GetPropertyDHCP6Config gets the DHCP4Config of the connection.
GetPropertyDHCP6Config() (DHCP6Config, error)
// GetPropertyVPN gets the VPN flag of the connection.
GetPropertyVPN() (bool, error)
// GetPropertyMaster gets the master device of the connection.
GetPropertyMaster() (Device, error)
SubscribeState(receiver chan StateChange, exit chan struct{}) (err error)
}
func NewActiveConnection(objectPath dbus.ObjectPath) (ActiveConnection, error) {
var a activeConnection
return &a, a.init(NetworkManagerInterface, objectPath)
}
type activeConnection struct {
dbusBase
}
func (a *activeConnection) GetPath() dbus.ObjectPath {
return a.obj.Path()
}
func (a *activeConnection) GetPropertyConnection() (Connection, error) {
path, err := a.getObjectProperty(ActiveConnectionPropertyConnection)
if err != nil {
return nil, err
}
con, err := NewConnection(path)
if err != nil {
return nil, err
}
return con, nil
}
func (a *activeConnection) GetPropertySpecificObject() (AccessPoint, error) {
path, err := a.getObjectProperty(ActiveConnectionPropertySpecificObject)
if err != nil {
return nil, err
}
ap, err := NewAccessPoint(path)
if err != nil {
return nil, err
}
return ap, nil
}
func (a *activeConnection) GetPropertyID() (string, error) {
return a.getStringProperty(ActiveConnectionPropertyId)
}
func (a *activeConnection) GetPropertyUUID() (string, error) {
return a.getStringProperty(ActiveConnectionPropertyUuid)
}
func (a *activeConnection) GetPropertyType() (string, error) {
return a.getStringProperty(ActiveConnectionPropertyType)
}
func (a *activeConnection) GetPropertyDevices() ([]Device, error) {
paths, err := a.getSliceObjectProperty(ActiveConnectionPropertyDevices)
if err != nil {
return nil, err
}
devices := make([]Device, len(paths))
for i, path := range paths {
devices[i], err = DeviceFactory(path)
if err != nil {
return nil, err
}
}
return devices, nil
}
func (a *activeConnection) GetPropertyState() (NmActiveConnectionState, error) {
v, err := a.getUint32Property(ActiveConnectionPropertyState)
return NmActiveConnectionState(v), err
}
func (a *activeConnection) GetPropertyStateFlags() (uint32, error) {
return a.getUint32Property(ActiveConnectionPropertyStateFlags)
}
func (a *activeConnection) GetPropertyDefault() (bool, error) {
b, err := a.getProperty(ActiveConnectionPropertyDefault)
if err != nil {
return false, err
}
return b.(bool), nil
}
func (a *activeConnection) GetPropertyIP4Config() (IP4Config, error) {
path, err := a.getObjectProperty(ActiveConnectionPropertyIp4Config)
if err != nil || path == "/" {
return nil, err
}
return NewIP4Config(path)
}
func (a *activeConnection) GetPropertyDHCP4Config() (DHCP4Config, error) {
path, err := a.getObjectProperty(ActiveConnectionPropertyDhcp4Config)
if err != nil || path == "/" {
return nil, err
}
return NewDHCP4Config(path)
}
func (a *activeConnection) GetPropertyDefault6() (bool, error) {
return a.getBoolProperty(ActiveConnectionPropertyDefault6)
}
func (a *activeConnection) GetPropertyIP6Config() (IP6Config, error) {
path, err := a.getObjectProperty(ActiveConnectionPropertyIp6Config)
if err != nil || path == "/" {
return nil, err
}
return NewIP6Config(path)
}
func (a *activeConnection) GetPropertyDHCP6Config() (DHCP6Config, error) {
path, err := a.getObjectProperty(ActiveConnectionPropertyDhcp6Config)
if err != nil || path == "/" {
return nil, err
}
return NewDHCP6Config(path)
}
func (a *activeConnection) GetPropertyVPN() (bool, error) {
ret, err := a.getProperty(ActiveConnectionPropertyVpn)
if err != nil {
return false, err
}
return ret.(bool), nil
}
func (a *activeConnection) GetPropertyMaster() (Device, error) {
path, err := a.getObjectProperty(ActiveConnectionPropertyMaster)
if err != nil || path == "/" {
return nil, err
}
return DeviceFactory(path)
}
type StateChange struct {
Path dbus.ObjectPath
State NmActiveConnectionState
Reason NmActiveConnectionStateReason
}
func (a *activeConnection) SubscribeState(receiver chan StateChange, exit chan struct{}) (err error) {
channel := make(chan *dbus.Signal, 1)
a.conn.Signal(channel)
err = a.conn.AddMatchSignal(
dbus.WithMatchInterface(ActiveConnectionInterface),
dbus.WithMatchMember(ActiveConnectionSignalStateChanged),
dbus.WithMatchObjectPath(a.GetPath()),
)
if err != nil {
return err
}
go func() {
for {
select {
case signal, ok := <-channel:
if !ok {
err = fmt.Errorf("connection closed for %s", ActiveConnectionSignalStateChanged)
return
}
if signal.Name != ActiveConnectionInterface+"."+ActiveConnectionSignalStateChanged {
continue
}
stateChange := StateChange{
Path: signal.Path,
State: NmActiveConnectionState(signal.Body[0].(uint32)),
Reason: NmActiveConnectionStateReason(signal.Body[1].(uint32)),
}
receiver <- stateChange
case <-exit:
a.conn.RemoveSignal(channel)
close(channel)
return
}
}
}()
return
}
+85
View File
@@ -0,0 +1,85 @@
# Changelog
All notable changes to this project since will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2.1.0] - 2023-01-19
### Added
- Add device auto-connect setter
### Fixed
- Connection settings route and address data types
## [2.0.0] - 2022-11-22
### Changes
- Update go-dbus to v5.1.0
- **BREAKING CHANGE** : Generic recursive settings map dbus variants decoding
## [0.5.0] - 2022-11-22
### Added
- Godoc standard comment prefix
- DnsManager
- Device: GetIp4Connectivity
- Constants for Nm80211APSec
- Add gitignore
### Fixed
- CheckpointCreate: fix devicePaths variable scope
## [0.4.0] - 2022-01-17
### Added
- AccessPoint: add LastSeen property
### Changed
- Examples: move examples to their own subfolders
### Fixed
- DeviceWireless: remove duplicated fields
- PrimaryConnection: use ActiveConnection type
- SubscribeState: add the path to the recieved chan type, catch connect event for ActiveConnection
## [0.3.0] - 2020-03-26
### Added
- SetPropertyManaged (@joseffilzmaier)
- GetConnectionByUUID (@paulburlumi)
- VpnConnection
- ActiveConnectionSignalStateChanged
- CheckpointRollback
- SetPropertyWirelessEnabled (@Raqbit)
- Settings.ReloadConnections (@appnostic-io)
Static connection example (@everactivemilligan)
### Fixed
- GetPropertyRouteData panic (@zhengdelun)
## [0.2.0] - 2020-03-06
### Fixed
- added missing flag for Reload
- added parameter specific_object for AddAndActivateConnection
- Fix CheckpointCreateand GetPropertyCheckpoints
### Added
- Add property setter helper
- Add Device.SetPropertyRefreshRateMs
- Add Device.Reapply
+79
View File
@@ -0,0 +1,79 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
CheckpointInterface = NetworkManagerInterface + ".Checkpoint"
/* Properties */
CheckpointPropertyDevices = CheckpointInterface + ".Devices" // readable ao
CheckpointPropertyCreated = CheckpointInterface + ".Created" // readable x
CheckpointPropertyRollbackTimeout = CheckpointInterface + ".RollbackTimeout" // readable u
)
type Checkpoint interface {
GetPath() dbus.ObjectPath
// GetPropertyDevices Array of object paths for devices which are part of this checkpoint.
GetPropertyDevices() ([]Device, error)
// GetPropertyCreated The timestamp (in CLOCK_BOOTTIME milliseconds) of checkpoint creation.
GetPropertyCreated() (int64, error)
// GetPropertyRollbackTimeout Timeout in seconds for automatic rollback, or zero.
GetPropertyRollbackTimeout() (uint32, error)
MarshalJSON() ([]byte, error)
}
func NewCheckpoint(objectPath dbus.ObjectPath) (Checkpoint, error) {
var c checkpoint
return &c, c.init(NetworkManagerInterface, objectPath)
}
type checkpoint struct {
dbusBase
}
func (c *checkpoint) GetPropertyDevices() ([]Device, error) {
devicesPaths, err := c.getSliceObjectProperty(CheckpointPropertyDevices)
if err != nil {
return nil, err
}
devices := make([]Device, len(devicesPaths))
for i, path := range devicesPaths {
devices[i], err = NewDevice(path)
if err != nil {
return devices, err
}
}
return devices, nil
}
func (c *checkpoint) GetPropertyCreated() (int64, error) {
return c.getInt64Property(CheckpointPropertyCreated)
}
func (c *checkpoint) GetPropertyRollbackTimeout() (uint32, error) {
return c.getUint32Property(CheckpointPropertyRollbackTimeout)
}
func (c *checkpoint) GetPath() dbus.ObjectPath {
return c.obj.Path()
}
func (c *checkpoint) MarshalJSON() ([]byte, error) {
m := make(map[string]interface{})
m["Devices"], _ = c.GetPropertyDevices()
m["Created"], _ = c.GetPropertyCreated()
m["RollbackTimeout"], _ = c.GetPropertyRollbackTimeout()
return json.Marshal(m)
}
+184
View File
@@ -0,0 +1,184 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
ConnectionInterface = SettingsInterface + ".Connection"
/* Methods */
ConnectionUpdate = ConnectionInterface + ".Update"
ConnectionUpdateUnsaved = ConnectionInterface + ".UpdateUnsaved"
ConnectionDelete = ConnectionInterface + ".Delete"
ConnectionGetSettings = ConnectionInterface + ".GetSettings"
ConnectionGetSecrets = ConnectionInterface + ".GetSecrets"
ConnectionClearSecrets = ConnectionInterface + ".ClearSecrets"
ConnectionSave = ConnectionInterface + ".Save"
ConnectionUpdate2 = ConnectionInterface + ".Update2"
/* Properties */
ConnectionPropertyUnsaved = ConnectionInterface + ".Unsaved" // readable b
ConnectionPropertyFlags = ConnectionInterface + ".Flags" // readable u
ConnectionPropertyFilename = ConnectionInterface + ".Filename" // readable s
)
//type ConnectionSettings map[string]map[string]interface{}
type ConnectionSettings map[string]map[string]interface{}
type Connection interface {
GetPath() dbus.ObjectPath
// Update the connection with new settings and properties (replacing all previous settings and properties) and save the connection to disk. Secrets may be part of the update request, and will be either stored in persistent storage or sent to a Secret Agent for storage, depending on the flags associated with each secret.
Update(settings ConnectionSettings) error
// UpdateUnsaved Update the connection with new settings and properties (replacing all previous settings and properties) but do not immediately save the connection to disk. Secrets may be part of the update request and may sent to a Secret Agent for storage, depending on the flags associated with each secret. Use the 'Save' method to save these changes to disk. Note that unsaved changes will be lost if the connection is reloaded from disk (either automatically on file change or due to an explicit ReloadConnections call).
UpdateUnsaved(settings ConnectionSettings) error
// Delete the connection.
Delete() error
// GetSettings gets the settings maps describing this network configuration.
// This will never include any secrets required for connection to the
// network, as those are often protected. Secrets must be requested
// separately using the GetSecrets() method.
GetSettings() (ConnectionSettings, error)
// GetSecrets Get the secrets belonging to this network configuration. Only secrets from
// persistent storage or a Secret Agent running in the requestor's session
// will be returned. The user will never be prompted for secrets as a result
// of this request.
GetSecrets(settingName string) (ConnectionSettings, error)
// ClearSecrets Clear the secrets belonging to this network connection profile.
ClearSecrets() error
// Save a "dirty" connection (that had previously been updated with UpdateUnsaved) to persistent storage.
Save() error
// GetPropertyUnsaved If set, indicates that the in-memory state of the connection does not match the on-disk state. This flag will be set when UpdateUnsaved() is called or when any connection details change, and cleared when the connection is saved to disk via Save() or from internal operations.
GetPropertyUnsaved() (bool, error)
// GetPropertyFlags Additional flags of the connection profile.
GetPropertyFlags() (uint32, error)
// GetPropertyFilename File that stores the connection in case the connection is file-backed.
GetPropertyFilename() (string, error)
MarshalJSON() ([]byte, error)
}
func NewConnection(objectPath dbus.ObjectPath) (Connection, error) {
var c connection
return &c, c.init(NetworkManagerInterface, objectPath)
}
type connection struct {
dbusBase
}
func (c *connection) GetPath() dbus.ObjectPath {
return c.obj.Path()
}
func (c *connection) Update(settings ConnectionSettings) error {
return c.call(ConnectionUpdate, settings)
}
func (c *connection) UpdateUnsaved(settings ConnectionSettings) error {
return c.call(ConnectionUpdateUnsaved, settings)
}
func (c *connection) Delete() error {
return c.call(ConnectionDelete)
}
func (c *connection) GetSettings() (ConnectionSettings, error) {
var settings map[string]map[string]dbus.Variant
if err := c.callWithReturn(&settings, ConnectionGetSettings); err != nil {
return nil, err
}
return decodeSettings(settings), nil
}
func (c *connection) GetSecrets(settingName string) (ConnectionSettings, error) {
var settings map[string]map[string]dbus.Variant
if err := c.callWithReturn(&settings, ConnectionGetSecrets, settingName); err != nil {
return nil, err
}
return decodeSettings(settings), nil
}
func decodeSettings(input map[string]map[string]dbus.Variant) (settings ConnectionSettings) {
valueMap := ConnectionSettings{}
for key, data := range input {
valueMap[key] = decode(data).(map[string]interface{})
}
return valueMap
}
func decode(input interface{}) (value interface{}) {
if variant, isVariant := input.(dbus.Variant); isVariant {
return decode(variant.Value())
} else if inputMap, isMap := input.(map[string]dbus.Variant); isMap {
return decodeMap(inputMap)
} else if inputArray, isArray := input.([]dbus.Variant); isArray {
return decodeArray(inputArray)
} else if inputArray, isArray := input.([]map[string]dbus.Variant); isArray {
return decodeMapArray(inputArray)
} else {
return input
}
}
func decodeArray(input []dbus.Variant) (value []interface{}) {
for _, data := range input {
value = append(value, decode(data))
}
return
}
func decodeMapArray(input []map[string]dbus.Variant) (value []map[string]interface{}) {
for _, data := range input {
value = append(value, decodeMap(data))
}
return
}
func decodeMap(input map[string]dbus.Variant) (value map[string]interface{}) {
value = map[string]interface{}{}
for key, data := range input {
value[key] = decode(data)
}
return
}
func (c *connection) ClearSecrets() error {
return c.call(ConnectionClearSecrets)
}
func (c *connection) Save() error {
return c.call(ConnectionSave)
}
func (c *connection) GetPropertyUnsaved() (bool, error) {
return c.getBoolProperty(ConnectionPropertyUnsaved)
}
func (c *connection) GetPropertyFlags() (uint32, error) {
return c.getUint32Property(ConnectionPropertyFlags)
}
func (c *connection) GetPropertyFilename() (string, error) {
return c.getStringProperty(ConnectionPropertyFilename)
}
func (c *connection) MarshalJSON() ([]byte, error) {
s, _ := c.GetSettings()
return json.Marshal(s)
}
+56
View File
@@ -0,0 +1,56 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
DHCP4ConfigInterface = NetworkManagerInterface + ".DHCP4Config"
// Properties
DHCP4ConfigPropertyOptions = DHCP4ConfigInterface + ".Options"
)
type DHCP4Options map[string]interface{}
type DHCP4Config interface {
// GetPropertyOptions GetOptions gets options map of configuration returned by the IPv4 DHCP server.
GetPropertyOptions() (DHCP4Options, error)
MarshalJSON() ([]byte, error)
}
func NewDHCP4Config(objectPath dbus.ObjectPath) (DHCP4Config, error) {
var c dhcp4Config
return &c, c.init(NetworkManagerInterface, objectPath)
}
type dhcp4Config struct {
dbusBase
}
func (c *dhcp4Config) GetPropertyOptions() (DHCP4Options, error) {
options, err := c.getMapStringVariantProperty(DHCP4ConfigPropertyOptions)
rv := make(DHCP4Options)
if err != nil {
return rv, err
}
for k, v := range options {
rv[k] = v.Value()
}
return rv, nil
}
func (c *dhcp4Config) MarshalJSON() ([]byte, error) {
Options, err := c.GetPropertyOptions()
if err != nil {
return nil, err
}
return json.Marshal(map[string]interface{}{
"Options": Options,
})
}
+54
View File
@@ -0,0 +1,54 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
DHCP6ConfigInterface = NetworkManagerInterface + ".DHCP6Config"
// Properties
DHCP6ConfigPropertyOptions = DHCP6ConfigInterface + ".Options"
)
type DHCP6Options map[string]interface{}
type DHCP6Config interface {
// GetPropertyOptions GetOptions gets options map of configuration returned by the IPv4 DHCP server.
GetPropertyOptions() (DHCP6Options, error)
MarshalJSON() ([]byte, error)
}
func NewDHCP6Config(objectPath dbus.ObjectPath) (DHCP6Config, error) {
var c dhcp6Config
return &c, c.init(NetworkManagerInterface, objectPath)
}
type dhcp6Config struct {
dbusBase
}
func (c *dhcp6Config) GetPropertyOptions() (DHCP6Options, error) {
options, err := c.getMapStringVariantProperty(DHCP6ConfigPropertyOptions)
rv := make(DHCP6Options)
if err != nil {
return rv, err
}
for k, v := range options {
rv[k] = v.Value()
}
return rv, nil
}
func (c *dhcp6Config) MarshalJSON() ([]byte, error) {
m := make(map[string]interface{})
m["Options"], _ = c.GetPropertyOptions()
return json.Marshal(m)
}
+434
View File
@@ -0,0 +1,434 @@
package gonetworkmanager
import (
"encoding/json"
"fmt"
"github.com/godbus/dbus/v5"
)
const (
DeviceInterface = NetworkManagerInterface + ".Device"
/* Methods */
DeviceReapply = DeviceInterface + ".Reapply"
DeviceGetAppliedConnection = DeviceInterface + ".GetAppliedConnection"
DeviceDisconnect = DeviceInterface + ".Disconnect"
DeviceDelete = DeviceInterface + ".Delete"
/* Properties */
DevicePropertyUdi = DeviceInterface + ".Udi" // readable s
DevicePropertyInterface = DeviceInterface + ".Interface" // readable s
DevicePropertyIpInterface = DeviceInterface + ".IpInterface" // readable s
DevicePropertyDriver = DeviceInterface + ".Driver" // readable s
DevicePropertyDriverVersion = DeviceInterface + ".DriverVersion" // readable s
DevicePropertyFirmwareVersion = DeviceInterface + ".FirmwareVersion" // readable s
DevicePropertyCapabilities = DeviceInterface + ".Capabilities" // readable u
DevicePropertyState = DeviceInterface + ".State" // readable u
DevicePropertyStateReason = DeviceInterface + ".StateReason" // readable (uu)
DevicePropertyActiveConnection = DeviceInterface + ".ActiveConnection" // readable o
DevicePropertyIp4Config = DeviceInterface + ".Ip4Config" // readable o
DevicePropertyDhcp4Config = DeviceInterface + ".Dhcp4Config" // readable o
DevicePropertyIp6Config = DeviceInterface + ".Ip6Config" // readable o
DevicePropertyDhcp6Config = DeviceInterface + ".Dhcp6Config" // readable o
DevicePropertyManaged = DeviceInterface + ".Managed" // readwrite b
DevicePropertyAutoconnect = DeviceInterface + ".Autoconnect" // readwrite b
DevicePropertyFirmwareMissing = DeviceInterface + ".FirmwareMissing" // readable b
DevicePropertyNmPluginMissing = DeviceInterface + ".NmPluginMissing" // readable b
DevicePropertyDeviceType = DeviceInterface + ".DeviceType" // readable u
DevicePropertyAvailableConnections = DeviceInterface + ".AvailableConnections" // readable ao
DevicePropertyPhysicalPortId = DeviceInterface + ".PhysicalPortId" // readable s
DevicePropertyMtu = DeviceInterface + ".Mtu" // readable u
DevicePropertyMetered = DeviceInterface + ".Metered" // readable u
DevicePropertyLldpNeighbors = DeviceInterface + ".LldpNeighbors" // readable aa{sv}
DevicePropertyReal = DeviceInterface + ".Real" // readable b
DevicePropertyIp4Connectivity = DeviceInterface + ".Ip4Connectivity" // readable u
/* Signals */
DeviceSignalStateChanged = "StateChanged" // u state, u reason
)
func DeviceFactory(objectPath dbus.ObjectPath) (Device, error) {
d, err := NewDevice(objectPath)
if err != nil {
return nil, err
}
deviceType, err := d.GetPropertyDeviceType()
if err != nil {
return nil, err
}
switch deviceType {
case NmDeviceTypeDummy:
return NewDeviceDummy(objectPath)
case NmDeviceTypeGeneric:
return NewDeviceGeneric(objectPath)
case NmDeviceTypeIpTunnel:
return NewDeviceIpTunnel(objectPath)
case NmDeviceTypeBridge:
return NewDeviceBridge(objectPath)
case NmDeviceTypeEthernet:
return NewDeviceWired(objectPath)
case NmDeviceTypeWifi:
return NewDeviceWireless(objectPath)
}
return d, nil
}
type Device interface {
GetPath() dbus.ObjectPath
// Reapply Attempts to update the configuration of a device without deactivating it. NetworkManager has the concept of connections, which are profiles that contain the configuration for a networking device. Those connections are exposed via D-Bus as individual objects that can be created, modified and deleted. When activating such a settings-connection on a device, the settings-connection is cloned to become an applied-connection and used to configure the device (see GetAppliedConnection). Subsequent modification of the settings-connection don't propagate automatically to the device's applied-connection (with exception of the firewall-zone and the metered property). For the changes to take effect, you can either re-activate the settings-connection, or call Reapply. The Reapply call allows you to directly update the applied-connection and reconfigure the device. Reapply can also be useful if the currently applied-connection is equal to the connection that is about to be reapplied. This allows to reconfigure the device and revert external changes like removing or adding an IP address (which NetworkManager doesn't revert automatically because it is assumed that the user made these changes intentionally outside of NetworkManager). Reapply can make the applied-connection different from the settings-connection, just like updating the settings-connection can make them different.
// connection: The optional connection settings that will be reapplied on the device. If empty, the currently active settings-connection will be used. The connection cannot arbitrarly differ from the current applied-connection otherwise the call will fail. Only certain changes are supported, like adding or removing IP addresses.
// versionId: If non-zero, the current version id of the applied-connection must match. The current version id can be retrieved via GetAppliedConnection. This optional argument allows to catch concurrent modifications between the GetAppliedConnection call and Reapply.
// flags: Flags which would modify the behavior of the Reapply call. There are no flags defined currently and the users should use the value of 0.
Reapply(connection Connection, versionId uint64, flags uint32) error
// Disconnect a device and prevents the device from automatically activating further connections without user intervention.
Disconnect() error
// Delete a software device from NetworkManager and removes the interface from the system. The method returns an error when called for a hardware device.
Delete() error
// GetPropertyUdi Operating-system specific transient device hardware identifier. This is an opaque string representing the underlying hardware for the device, and shouldn't be used to keep track of individual devices. For some device types (Bluetooth, Modems) it is an identifier used by the hardware service (ie bluez or ModemManager) to refer to that device, and client programs use it get additional information from those services which NM does not provide. The Udi is not guaranteed to be consistent across reboots or hotplugs of the hardware. If you're looking for a way to uniquely track each device in your application, use the object path. If you're looking for a way to track a specific piece of hardware across reboot or hotplug, use a MAC address or USB serial number.
GetPropertyUdi() (string, error)
// GetPropertyInterface The name of the device's control (and often data) interface. Note that non UTF-8 characters are backslash escaped, so the resulting name may be longer then 15 characters. Use g_strcompress() to revert the escaping.
GetPropertyInterface() (string, error)
// GetPropertyIpInterface The name of the device's data interface when available. This property may not refer to the actual data interface until the device has successfully established a data connection, indicated by the device's State becoming ACTIVATED. Note that non UTF-8 characters are backslash escaped, so the resulting name may be longer then 15 characters. Use g_strcompress() to revert the escaping.
GetPropertyIpInterface() (string, error)
// GetPropertyDriver The driver handling the device. Non-UTF-8 sequences are backslash escaped. Use g_strcompress() to revert.
GetPropertyDriver() (string, error)
// GetPropertyDriverVersion The version of the driver handling the device. Non-UTF-8 sequences are backslash escaped. Use g_strcompress() to revert.
GetPropertyDriverVersion() (string, error)
// GetPropertyFirmwareVersion The firmware version for the device. Non-UTF-8 sequences are backslash escaped. Use g_strcompress() to revert.
GetPropertyFirmwareVersion() (string, error)
// GetPropertyState The current state of the device.
GetPropertyState() (NmDeviceState, error)
// GetPropertyActiveConnection Object path of an ActiveConnection object that "owns" this device during activation. The ActiveConnection object tracks the life-cycle of a connection to a specific network and implements the org.freedesktop.NetworkManager.Connection.Active D-Bus interface.
GetPropertyActiveConnection() (ActiveConnection, error)
// GetPropertyIP4Config Object path of the Ip4Config object describing the configuration of the device. Only valid when the device is in the NM_DEVICE_STATE_ACTIVATED state.
GetPropertyIP4Config() (IP4Config, error)
// GetPropertyDHCP4Config Object path of the Dhcp4Config object describing the DHCP options returned by the DHCP server. Only valid when the device is in the NM_DEVICE_STATE_ACTIVATED state.
GetPropertyDHCP4Config() (DHCP4Config, error)
// GetPropertyIP6Config Object path of the Ip6Config object describing the configuration of the device. Only valid when the device is in the NM_DEVICE_STATE_ACTIVATED state.
GetPropertyIP6Config() (IP6Config, error)
// GetPropertyDHCP6Config Object path of the Dhcp6Config object describing the DHCP options returned by the DHCP server. Only valid when the device is in the NM_DEVICE_STATE_ACTIVATED state.
GetPropertyDHCP6Config() (DHCP6Config, error)
// GetPropertyManaged Whether this device is managed by NetworkManager. Setting this property has a similar effect to configuring the device as unmanaged via the keyfile.unmanaged-devices setting in NetworkManager.conf. Changes to this value are not persistent and lost after NetworkManager restart.
GetPropertyManaged() (bool, error)
SetPropertyManaged(bool) error
// GetPropertyAutoConnect If TRUE, indicates the device is allowed to autoconnect. If FALSE, manual intervention is required before the device will automatically connect to a known network, such as activating a connection using the device, or setting this property to TRUE. This property cannot be set to TRUE for default-unmanaged devices, since they never autoconnect.
GetPropertyAutoConnect() (bool, error)
SetPropertyAutoConnect(bool) error
// GetPropertyFirmwareMissing If TRUE, indicates the device is likely missing firmware necessary for its operation.
GetPropertyFirmwareMissing() (bool, error)
// GetPropertyNmPluginMissing If TRUE, indicates the NetworkManager plugin for the device is likely missing or misconfigured.
GetPropertyNmPluginMissing() (bool, error)
// GetPropertyDeviceType The general type of the network device; ie Ethernet, Wi-Fi, etc.
GetPropertyDeviceType() (NmDeviceType, error)
// GetPropertyAvailableConnections An array of object paths of every configured connection that is currently 'available' through this device.
GetPropertyAvailableConnections() ([]Connection, error)
// GetPropertyPhysicalPortId If non-empty, an (opaque) indicator of the physical network port associated with the device. This can be used to recognize when two seemingly-separate hardware devices are actually just different virtual interfaces to the same physical port.
GetPropertyPhysicalPortId() (string, error)
// GetPropertyMtu The device MTU (maximum transmission unit).
GetPropertyMtu() (uint32, error)
// GetPropertyReal True if the device exists, or False for placeholder devices that do not yet exist but could be automatically created by NetworkManager if one of their AvailableConnections was activated.
GetPropertyReal() (bool, error)
// The result of the last IPv4 connectivity check.
GetPropertyIp4Connectivity() (NmConnectivity, error)
SubscribeState(receiver chan DeviceStateChange, exit chan struct{}) (err error)
MarshalJSON() ([]byte, error)
}
func NewDevice(objectPath dbus.ObjectPath) (Device, error) {
var d device
return &d, d.init(NetworkManagerInterface, objectPath)
}
type device struct {
dbusBase
}
func (d *device) GetPath() dbus.ObjectPath {
return d.obj.Path()
}
func (d *device) Reapply(connection Connection, versionId uint64, flags uint32) error {
return d.call(DeviceReapply, connection, versionId, flags)
}
func (d *device) Disconnect() error {
return d.call(DeviceDisconnect)
}
func (d *device) Delete() error {
return d.call(DeviceDelete)
}
func (d *device) GetPropertyUdi() (string, error) {
return d.getStringProperty(DevicePropertyUdi)
}
func (d *device) GetPropertyInterface() (string, error) {
return d.getStringProperty(DevicePropertyInterface)
}
func (d *device) GetPropertyIpInterface() (string, error) {
return d.getStringProperty(DevicePropertyIpInterface)
}
func (d *device) GetPropertyDriver() (string, error) {
return d.getStringProperty(DevicePropertyDriver)
}
func (d *device) GetPropertyDriverVersion() (string, error) {
return d.getStringProperty(DevicePropertyDriverVersion)
}
func (d *device) GetPropertyFirmwareVersion() (string, error) {
return d.getStringProperty(DevicePropertyFirmwareVersion)
}
func (d *device) GetPropertyState() (NmDeviceState, error) {
r, err := d.getUint32Property(DevicePropertyState)
if err != nil {
return NmDeviceStateFailed, err
}
return NmDeviceState(r), nil
}
func (d *device) GetPropertyActiveConnection() (ActiveConnection, error) {
path, err := d.getObjectProperty(DevicePropertyActiveConnection)
if err != nil || path == "/" {
return nil, err
}
return NewActiveConnection(path)
}
func (d *device) GetPropertyIP4Config() (IP4Config, error) {
path, err := d.getObjectProperty(DevicePropertyIp4Config)
if err != nil || path == "/" {
return nil, err
}
return NewIP4Config(path)
}
func (d *device) GetPropertyDHCP4Config() (DHCP4Config, error) {
path, err := d.getObjectProperty(DevicePropertyDhcp4Config)
if err != nil || path == "/" {
return nil, err
}
return NewDHCP4Config(path)
}
func (d *device) GetPropertyIP6Config() (IP6Config, error) {
path, err := d.getObjectProperty(DevicePropertyIp6Config)
if err != nil || path == "/" {
return nil, err
}
return NewIP6Config(path)
}
func (d *device) GetPropertyDHCP6Config() (DHCP6Config, error) {
path, err := d.getObjectProperty(DevicePropertyDhcp6Config)
if err != nil || path == "/" {
return nil, err
}
return NewDHCP6Config(path)
}
func (d *device) GetPropertyManaged() (bool, error) {
return d.getBoolProperty(DevicePropertyManaged)
}
func (d *device) SetPropertyManaged(managed bool) error {
return d.setProperty(DevicePropertyManaged, managed)
}
func (d *device) GetPropertyAutoConnect() (bool, error) {
return d.getBoolProperty(DevicePropertyAutoconnect)
}
func (d *device) SetPropertyAutoConnect(managed bool) error {
return d.setProperty(DevicePropertyAutoconnect, managed)
}
func (d *device) GetPropertyFirmwareMissing() (bool, error) {
return d.getBoolProperty(DevicePropertyFirmwareMissing)
}
func (d *device) GetPropertyNmPluginMissing() (bool, error) {
return d.getBoolProperty(DevicePropertyNmPluginMissing)
}
func (d *device) GetPropertyDeviceType() (NmDeviceType, error) {
v, err := d.getUint32Property(DevicePropertyDeviceType)
return NmDeviceType(v), err
}
func (d *device) GetPropertyAvailableConnections() ([]Connection, error) {
connPaths, err := d.getSliceObjectProperty(DevicePropertyAvailableConnections)
if err != nil {
return nil, err
}
conns := make([]Connection, len(connPaths))
for i, path := range connPaths {
conns[i], err = NewConnection(path)
if err != nil {
return conns, err
}
}
return conns, nil
}
func (d *device) GetPropertyPhysicalPortId() (string, error) {
return d.getStringProperty(DevicePropertyPhysicalPortId)
}
func (d *device) GetPropertyMtu() (uint32, error) {
return d.getUint32Property(DevicePropertyMtu)
}
func (d *device) GetPropertyReal() (bool, error) {
return d.getBoolProperty(DevicePropertyReal)
}
func (d *device) GetPropertyIp4Connectivity() (NmConnectivity, error) {
u, err := d.getUint32Property(DevicePropertyIp4Connectivity)
return NmConnectivity(u), err
}
func (d *device) marshalMap() (map[string]interface{}, error) {
Interface, err := d.GetPropertyInterface()
if err != nil {
return nil, err
}
IpInterface, err := d.GetPropertyIpInterface()
if err != nil {
return nil, err
}
State, err := d.GetPropertyState()
if err != nil {
return nil, err
}
IP4Config, err := d.GetPropertyIP4Config()
if err != nil {
return nil, err
}
DHCP4Config, err := d.GetPropertyDHCP4Config()
if err != nil {
return nil, err
}
DeviceType, err := d.GetPropertyDeviceType()
if err != nil {
return nil, err
}
AvailableConnections, err := d.GetPropertyAvailableConnections()
if err != nil {
return nil, err
}
return map[string]interface{}{
"Interface": Interface,
"IP interface": IpInterface,
"State": State.String(),
"IP4Config": IP4Config,
"DHCP4Config": DHCP4Config,
"DeviceType": DeviceType.String(),
"AvailableConnections": AvailableConnections,
}, nil
}
type DeviceStateChange struct {
Path dbus.ObjectPath
State NmDeviceState
Reason NmDeviceStateReason
}
func (d *device) SubscribeState(receiver chan DeviceStateChange, exit chan struct{}) (err error) {
channel := make(chan *dbus.Signal, 1)
d.conn.Signal(channel)
err = d.conn.AddMatchSignal(
dbus.WithMatchInterface(DeviceInterface),
dbus.WithMatchMember(DeviceSignalStateChanged),
dbus.WithMatchObjectPath(d.GetPath()),
)
if err != nil {
return err
}
go func() {
for {
select {
case signal, ok := <-channel:
if !ok {
err = fmt.Errorf("connection closed for %s", DeviceSignalStateChanged)
return
}
if signal.Name != DeviceInterface+"."+DeviceSignalStateChanged {
continue
}
stateChange := DeviceStateChange{
Path: signal.Path,
State: NmDeviceState(signal.Body[0].(uint32)),
Reason: NmDeviceStateReason(signal.Body[1].(uint32)),
}
receiver <- stateChange
case <-exit:
d.conn.RemoveSignal(channel)
close(channel)
return
}
}
}()
return
}
func (d *device) MarshalJSON() ([]byte, error) {
m, err := d.marshalMap()
if err != nil {
return nil, err
}
return json.Marshal(m)
}
+75
View File
@@ -0,0 +1,75 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
DeviceBridgeInterface = DeviceInterface + ".Bridge"
// Properties
DeviceBridgePropertyHwAddress = DeviceBridgeInterface + ".HwAddress" // readable s
DeviceBridgePropertySlaves = DeviceBridgeInterface + ".Slaves" // readable as
DeviceBridgePropertyCarrier = DeviceBridgeInterface + ".Carrier" // readable b
)
type DeviceBridge interface {
Device
// GetPropertyHwAddress Active hardware address of the device.
GetPropertyHwAddress() (string, error)
// GetPropertySlaves Array of paths of enslaved and active devices.
// DEPRECATED. Use the "Ports" property in "org.freedesktop.NetworkManager.Device" instead which exists since version NetworkManager 1.34.0.
GetPropertySlaves() ([]Device, error)
// GetPropertyCarrier Indicates whether the physical carrier is found (e.g. whether a cable is plugged in or not).
// DEPRECATED: check for the "carrier" flag in the "InterfaceFlags" property on the "org.freedesktop.NetworkManager.Device" interface.
GetPropertyCarrier() (bool, error)
}
func NewDeviceBridge(objectPath dbus.ObjectPath) (DeviceBridge, error) {
var d deviceBridge
return &d, d.init(NetworkManagerInterface, objectPath)
}
type deviceBridge struct {
device
}
func (d *deviceBridge) GetPropertyHwAddress() (string, error) {
return d.getStringProperty(DeviceBridgePropertyHwAddress)
}
func (d *deviceBridge) GetPropertySlaves() ([]Device, error) {
paths, err := d.getSliceObjectProperty(DeviceBridgePropertySlaves)
if err != nil {
return nil, err
}
devices := make([]Device, len(paths))
for i, path := range paths {
devices[i], err = DeviceFactory(path)
if err != nil {
return nil, err
}
}
return devices, nil
}
func (d *deviceBridge) GetPropertyCarrier() (bool, error) {
return d.getBoolProperty(DeviceBridgePropertyCarrier)
}
func (d *deviceBridge) MarshalJSON() ([]byte, error) {
m, err := d.device.marshalMap()
if err != nil {
return nil, err
}
m["HwAddress"], _ = d.GetPropertyHwAddress()
m["Slaves"], _ = d.GetPropertySlaves()
m["Carrier"], _ = d.GetPropertyCarrier()
return json.Marshal(m)
}
+44
View File
@@ -0,0 +1,44 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
DeviceDummyInterface = DeviceInterface + ".Dummy"
/* Properties */
DeviceDummyPropertyHwAddress = DeviceDummyInterface + ".HwAddress" // readable s
)
type DeviceDummy interface {
Device
// Hardware address of the device.
GetPropertyHwAddress() (string, error)
}
func NewDeviceDummy(objectPath dbus.ObjectPath) (DeviceDummy, error) {
var d deviceDummy
return &d, d.init(NetworkManagerInterface, objectPath)
}
type deviceDummy struct {
device
}
func (d *deviceDummy) GetPropertyHwAddress() (string, error) {
return d.getStringProperty(DeviceDummyPropertyHwAddress)
}
func (d *deviceDummy) MarshalJSON() ([]byte, error) {
m, err := d.device.marshalMap()
if err != nil {
return nil, err
}
m["HwAddress"], _ = d.GetPropertyHwAddress()
return json.Marshal(m)
}
+53
View File
@@ -0,0 +1,53 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
DeviceGenericInterface = DeviceInterface + ".Generic"
// Properties
DeviceGenericPropertyHwAddress = DeviceGenericInterface + ".HwAddress" // readable s
DeviceGenericPropertyTypeDescription = DeviceGenericInterface + ".TypeDescription" // readable s
)
type DeviceGeneric interface {
Device
// GetPropertyHwAddress Active hardware address of the device.
GetPropertyHwAddress() (string, error)
// GetPropertyTypeDescription A (non-localized) description of the interface type, if known.
GetPropertyTypeDescription() (string, error)
}
func NewDeviceGeneric(objectPath dbus.ObjectPath) (DeviceGeneric, error) {
var d deviceGeneric
return &d, d.init(NetworkManagerInterface, objectPath)
}
type deviceGeneric struct {
device
}
func (d *deviceGeneric) GetPropertyHwAddress() (string, error) {
return d.getStringProperty(DeviceGenericPropertyHwAddress)
}
func (d *deviceGeneric) GetPropertyTypeDescription() (string, error) {
return d.getStringProperty(DeviceGenericPropertyTypeDescription)
}
func (d *deviceGeneric) MarshalJSON() ([]byte, error) {
m, err := d.device.marshalMap()
if err != nil {
return nil, err
}
m["HwAddress"], _ = d.GetPropertyHwAddress()
m["TypeDescription"], _ = d.GetPropertyTypeDescription()
return json.Marshal(m)
}
+150
View File
@@ -0,0 +1,150 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
DeviceIpTunnelInterface = DeviceInterface + ".IPTunnel"
// Properties
DeviceIpTunnelPropertyHwAddress = DeviceIpTunnelInterface + "HwAddress" // readable s
DeviceIpTunnelPropertyMode = DeviceIpTunnelInterface + ".Mode" // readable u
DeviceIpTunnelPropertyParent = DeviceIpTunnelInterface + ".Parent" // readable o
DeviceIpTunnelPropertyLocal = DeviceIpTunnelInterface + ".Local" // readable s
DeviceIpTunnelPropertyRemote = DeviceIpTunnelInterface + ".Remote" // readable s
DeviceIpTunnelPropertyTtl = DeviceIpTunnelInterface + ".Ttl" // readable y
DeviceIpTunnelPropertyTos = DeviceIpTunnelInterface + ".Tos" // readable y
DeviceIpTunnelPropertyPathMtuDiscovery = DeviceIpTunnelInterface + ".PathMtuDiscovery" // readable b
DeviceIpTunnelPropertyInputKey = DeviceIpTunnelInterface + ".InputKey" // readable s
DeviceIpTunnelPropertyOutputKey = DeviceIpTunnelInterface + ".OutputKey" // readable s
DeviceIpTunnelPropertyEncapsulationLimit = DeviceIpTunnelInterface + ".EncapsulationLimit" // readable y
DeviceIpTunnelPropertyFlowLabel = DeviceIpTunnelInterface + ".FlowLabel" // readable u
DeviceIpTunnelPropertyFlags = DeviceIpTunnelInterface + ".Flags" // readable u
)
type DeviceIpTunnel interface {
Device
// GetPropertyMode The tunneling mode
GetPropertyMode() (uint32, error)
// GetPropertyParent The object path of the parent device.
GetPropertyParent() (Device, error)
// GetPropertyLocal The local endpoint of the tunnel.
GetPropertyLocal() (string, error)
// GetPropertyRemote The remote endpoint of the tunnel.
GetPropertyRemote() (string, error)
// GetPropertyTtl The TTL assigned to tunneled packets. 0 is a special value meaning that packets inherit the TTL value
GetPropertyTtl() (uint8, error)
// GetPropertyTos The type of service (IPv4) or traffic class (IPv6) assigned to tunneled packets.
GetPropertyTos() (uint8, error)
// GetPropertyPathMtuDiscovery Whether path MTU discovery is enabled on this tunnel.
GetPropertyPathMtuDiscovery() (bool, error)
// GetPropertyInputKey The key used for incoming packets.
GetPropertyInputKey() (string, error)
// GetPropertyOutputKey The key used for outgoing packets.
GetPropertyOutputKey() (string, error)
// GetPropertyEncapsulationLimit How many additional levels of encapsulation are permitted to be prepended to packets. This property applies only to IPv6 tunnels.
GetPropertyEncapsulationLimit() (uint8, error)
// GetPropertyFlowLabel The flow label to assign to tunnel packets. This property applies only to IPv6 tunnels.
GetPropertyFlowLabel() (uint32, error)
// GetPropertyFlags Tunnel flags.
GetPropertyFlags() (uint32, error)
}
func NewDeviceIpTunnel(objectPath dbus.ObjectPath) (DeviceIpTunnel, error) {
var d deviceIpTunnel
return &d, d.init(NetworkManagerInterface, objectPath)
}
type deviceIpTunnel struct {
device
}
func (d *deviceIpTunnel) GetPropertyMode() (uint32, error) {
return d.getUint32Property(DeviceIpTunnelPropertyMode)
}
func (d *deviceIpTunnel) GetPropertyParent() (Device, error) {
path, err := d.getObjectProperty(DeviceIpTunnelPropertyParent)
if err != nil || path == "/" {
return nil, err
}
return DeviceFactory(path)
}
func (d *deviceIpTunnel) GetPropertyLocal() (string, error) {
return d.getStringProperty(DeviceIpTunnelPropertyLocal)
}
func (d *deviceIpTunnel) GetPropertyRemote() (string, error) {
return d.getStringProperty(DeviceIpTunnelPropertyRemote)
}
func (d *deviceIpTunnel) GetPropertyTtl() (uint8, error) {
return d.getUint8Property(DeviceIpTunnelPropertyTtl)
}
func (d *deviceIpTunnel) GetPropertyTos() (uint8, error) {
return d.getUint8Property(DeviceIpTunnelPropertyTos)
}
func (d *deviceIpTunnel) GetPropertyPathMtuDiscovery() (bool, error) {
return d.getBoolProperty(DeviceIpTunnelPropertyPathMtuDiscovery)
}
func (d *deviceIpTunnel) GetPropertyInputKey() (string, error) {
return d.getStringProperty(DeviceIpTunnelPropertyInputKey)
}
func (d *deviceIpTunnel) GetPropertyOutputKey() (string, error) {
return d.getStringProperty(DeviceIpTunnelPropertyOutputKey)
}
func (d *deviceIpTunnel) GetPropertyEncapsulationLimit() (uint8, error) {
return d.getUint8Property(DeviceIpTunnelPropertyEncapsulationLimit)
}
func (d *deviceIpTunnel) GetPropertyFlowLabel() (uint32, error) {
return d.getUint32Property(DeviceIpTunnelPropertyFlowLabel)
}
func (d *deviceIpTunnel) GetPropertyFlags() (uint32, error) {
return d.getUint32Property(DeviceIpTunnelPropertyFlags)
}
func (d *deviceIpTunnel) MarshalJSON() ([]uint8, error) {
m, err := d.device.marshalMap()
if err != nil {
return nil, err
}
m["Mode"], _ = d.GetPropertyMode()
m["Parent"], _ = d.GetPropertyParent()
m["Local"], _ = d.GetPropertyLocal()
m["Remote"], _ = d.GetPropertyRemote()
m["Ttl"], _ = d.GetPropertyTtl()
m["Tos"], _ = d.GetPropertyTos()
m["PathMtuDiscovery"], _ = d.GetPropertyPathMtuDiscovery()
m["InputKey"], _ = d.GetPropertyInputKey()
m["OutputKey"], _ = d.GetPropertyOutputKey()
m["EncapsulationLimit"], _ = d.GetPropertyEncapsulationLimit()
m["FlowLabel"], _ = d.GetPropertyFlowLabel()
m["Flags"], _ = d.GetPropertyFlags()
return json.Marshal(m)
}
+74
View File
@@ -0,0 +1,74 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
DeviceStatisticsInterface = DeviceInterface + ".Statistics"
// Properties
DeviceStatisticsPropertyRefreshRateMs = DeviceStatisticsInterface + ".RefreshRateMs" // readwrite u
DeviceStatisticsPropertyTxBytes = DeviceStatisticsInterface + ".TxBytes" // readable t
DeviceStatisticsPropertyRxBytes = DeviceStatisticsInterface + ".RxBytes" // readable t
)
type DeviceStatistics interface {
GetPath() dbus.ObjectPath
// GetPropertyRefreshRateMs Refresh rate of the rest of properties of this interface. The properties are guaranteed to be refreshed each RefreshRateMs milliseconds in case the underlying counter has changed too. If zero, there is no guaranteed refresh rate of the properties.
GetPropertyRefreshRateMs() (uint32, error)
SetPropertyRefreshRateMs(uint32) error
// GetPropertyTxBytes Number of transmitted bytes
GetPropertyTxBytes() (uint64, error)
// GetPropertyRxBytes Number of received bytes
GetPropertyRxBytes() (uint64, error)
}
func NewDeviceStatistics(objectPath dbus.ObjectPath) (DeviceStatistics, error) {
var d deviceStatistics
return &d, d.init(NetworkManagerInterface, objectPath)
}
type deviceStatistics struct {
dbusBase
}
func (d *deviceStatistics) GetPath() dbus.ObjectPath {
return d.obj.Path()
}
func (d *deviceStatistics) GetPropertyRefreshRateMs() (uint32, error) {
return d.getUint32Property(DeviceStatisticsPropertyRefreshRateMs)
}
func (d *deviceStatistics) SetPropertyRefreshRateMs(rate uint32) error {
return d.setProperty(DeviceStatisticsPropertyRefreshRateMs, rate)
}
func (d *deviceStatistics) GetPropertyTxBytes() (uint64, error) {
return d.getUint64Property(DeviceStatisticsPropertyTxBytes)
}
func (d *deviceStatistics) GetPropertyRxBytes() (uint64, error) {
return d.getUint64Property(DeviceStatisticsPropertyRxBytes)
}
func (d *deviceStatistics) marshalMap() map[string]interface{} {
return map[string]interface{}{}
}
func (d *deviceStatistics) MarshalJSON() ([]byte, error) {
m := make(map[string]interface{})
m["RefreshRateMs"], _ = d.GetPropertyRefreshRateMs()
m["TxBytes"], _ = d.GetPropertyTxBytes()
m["RxBytes"], _ = d.GetPropertyRxBytes()
return json.Marshal(m)
}
+80
View File
@@ -0,0 +1,80 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
DeviceWiredInterface = DeviceInterface + ".Wired"
// Properties
DeviceWiredPropertyHwAddress = DeviceWiredInterface + ".HwAddress" // readable s
DeviceWiredPropertyPermHwAddress = DeviceWiredInterface + ".PermHwAddress" // readable s
DeviceWiredPropertySpeed = DeviceWiredInterface + ".Speed" // readable u
DeviceWiredPropertyS390Subchannels = DeviceWiredInterface + ".S390Subchannels" // readable as
DeviceWiredPropertyCarrier = DeviceWiredInterface + ".Carrier" // readable b
)
type DeviceWired interface {
Device
// GetPropertyHwAddress Active hardware address of the device.
GetPropertyHwAddress() (string, error)
// GetPropertyPermHwAddress Permanent hardware address of the device.
GetPropertyPermHwAddress() (string, error)
// GetPropertySpeed Design speed of the device, in megabits/second (Mb/s).
GetPropertySpeed() (uint32, error)
// GetPropertyS390Subchannels Array of S/390 subchannels for S/390 or z/Architecture devices.
GetPropertyS390Subchannels() ([]string, error)
// GetPropertyCarrier Indicates whether the physical carrier is found (e.g. whether a cable is plugged in or not).
GetPropertyCarrier() (bool, error)
}
func NewDeviceWired(objectPath dbus.ObjectPath) (DeviceWired, error) {
var d deviceWired
return &d, d.init(NetworkManagerInterface, objectPath)
}
type deviceWired struct {
device
}
func (d *deviceWired) GetPropertyHwAddress() (string, error) {
return d.getStringProperty(DeviceWiredPropertyHwAddress)
}
func (d *deviceWired) GetPropertyPermHwAddress() (string, error) {
return d.getStringProperty(DeviceWiredPropertyPermHwAddress)
}
func (d *deviceWired) GetPropertySpeed() (uint32, error) {
return d.getUint32Property(DeviceWiredPropertySpeed)
}
func (d *deviceWired) GetPropertyS390Subchannels() ([]string, error) {
return d.getSliceStringProperty(DeviceWiredPropertyS390Subchannels)
}
func (d *deviceWired) GetPropertyCarrier() (bool, error) {
return d.getBoolProperty(DeviceWiredPropertyCarrier)
}
func (d *deviceWired) MarshalJSON() ([]byte, error) {
m, err := d.device.marshalMap()
if err != nil {
return nil, err
}
m["HwAddress"], _ = d.GetPropertyHwAddress()
m["PermHwAddress"], _ = d.GetPropertyPermHwAddress()
m["Speed"], _ = d.GetPropertySpeed()
m["S390Subchannels"], _ = d.GetPropertyS390Subchannels()
m["Carrier"], _ = d.GetPropertyCarrier()
return json.Marshal(m)
}
+193
View File
@@ -0,0 +1,193 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
DeviceWirelessInterface = DeviceInterface + ".Wireless"
// Methods
DeviceWirelessGetAccessPoints = DeviceWirelessInterface + ".GetAccessPoints"
DeviceWirelessGetAllAccessPoints = DeviceWirelessInterface + ".GetAllAccessPoints"
DeviceWirelessRequestScan = DeviceWirelessInterface + ".RequestScan"
// Properties
DeviceWirelessPropertyHwAddress = DeviceWirelessInterface + ".HwAddress" // readable s
DeviceWirelessPropertyPermHwAddress = DeviceWirelessInterface + ".PermHwAddress" // readable s
DeviceWirelessPropertyMode = DeviceWirelessInterface + ".Mode" // readable u
DeviceWirelessPropertyBitrate = DeviceWirelessInterface + ".Bitrate" // readable u
DeviceWirelessPropertyAccessPoints = DeviceWirelessInterface + ".AccessPoints" // readable ao
DeviceWirelessPropertyActiveAccessPoint = DeviceWirelessInterface + ".ActiveAccessPoint" // readable o
DeviceWirelessPropertyWirelessCapabilities = DeviceWirelessInterface + ".WirelessCapabilities" // readable u
DeviceWirelessPropertyLastScan = DeviceWirelessInterface + ".LastScan" // readable x
)
type DeviceWireless interface {
Device
// GetAccessPoints gets the list of access points visible to this device.
// Note that this list does not include access points which hide their SSID.
// To retrieve a list of all access points (including hidden ones) use the
// GetAllAccessPoints() method.
GetAccessPoints() ([]AccessPoint, error)
// GetAllAccessPoints gets the list of all access points visible to this
// device, including hidden ones for which the SSID is not yet known.
GetAllAccessPoints() ([]AccessPoint, error)
// RequestScan Request the device to scan. To know when the scan is finished, use the
// "PropertiesChanged" signal from "org.freedesktop.DBus.Properties" to listen
// to changes to the "LastScan" property.
RequestScan() error
// GetPropertyHwAddress The active hardware address of the device.
GetPropertyHwAddress() (string, error)
// GetPropertyPermHwAddress The permanent hardware address of the device.
GetPropertyPermHwAddress() (string, error)
// GetPropertyMode The operating mode of the wireless device.
GetPropertyMode() (Nm80211Mode, error)
// GetPropertyBitrate The bit rate currently used by the wireless device, in kilobits/second (Kb/s).
GetPropertyBitrate() (uint32, error)
// GetPropertyAccessPoints List of object paths of access point visible to this wireless device.
GetPropertyAccessPoints() ([]AccessPoint, error)
// GetPropertyActiveAccessPoint Object path of the access point currently used by the wireless device.
GetPropertyActiveAccessPoint() (AccessPoint, error)
// GetPropertyWirelessCapabilities The capabilities of the wireless device.
GetPropertyWirelessCapabilities() (uint32, error)
// GetPropertyLastScan The timestamp (in CLOCK_BOOTTIME milliseconds) for the last finished
// network scan. A value of -1 means the device never scanned for access
// points.
GetPropertyLastScan() (int64, error)
}
func NewDeviceWireless(objectPath dbus.ObjectPath) (DeviceWireless, error) {
var d deviceWireless
return &d, d.init(NetworkManagerInterface, objectPath)
}
type deviceWireless struct {
device
}
func (d *deviceWireless) GetAccessPoints() ([]AccessPoint, error) {
var apPaths []dbus.ObjectPath
err := d.callWithReturn(&apPaths, DeviceWirelessGetAccessPoints)
if err != nil {
return nil, err
}
aps := make([]AccessPoint, len(apPaths))
for i, path := range apPaths {
aps[i], err = NewAccessPoint(path)
if err != nil {
return aps, err
}
}
return aps, nil
}
func (d *deviceWireless) GetAllAccessPoints() ([]AccessPoint, error) {
var apPaths []dbus.ObjectPath
err := d.callWithReturn(&apPaths, DeviceWirelessGetAllAccessPoints)
if err != nil {
return nil, err
}
aps := make([]AccessPoint, len(apPaths))
for i, path := range apPaths {
aps[i], err = NewAccessPoint(path)
if err != nil {
return aps, err
}
}
return aps, nil
}
func (d *deviceWireless) RequestScan() error {
var options map[string]interface{}
return d.obj.Call(DeviceWirelessRequestScan, 0, options).Store()
}
func (d *deviceWireless) GetPropertyHwAddress() (string, error) {
return d.getStringProperty(DeviceWirelessPropertyHwAddress)
}
func (d *deviceWireless) GetPropertyPermHwAddress() (string, error) {
return d.getStringProperty(DeviceWirelessPropertyPermHwAddress)
}
func (d *deviceWireless) GetPropertyMode() (Nm80211Mode, error) {
v, err := d.getUint32Property(DeviceWirelessPropertyMode)
return Nm80211Mode(v), err
}
func (d *deviceWireless) GetPropertyBitrate() (uint32, error) {
return d.getUint32Property(DeviceWirelessPropertyBitrate)
}
func (d *deviceWireless) GetPropertyAccessPoints() ([]AccessPoint, error) {
apPaths, err := d.getSliceObjectProperty(DeviceWirelessPropertyAccessPoints)
if err != nil {
return nil, err
}
ap := make([]AccessPoint, len(apPaths))
for i, path := range apPaths {
ap[i], err = NewAccessPoint(path)
if err != nil {
return ap, err
}
}
return ap, nil
}
func (d *deviceWireless) GetPropertyActiveAccessPoint() (AccessPoint, error) {
path, err := d.getObjectProperty(DeviceWirelessPropertyActiveAccessPoint)
if err != nil || path == "/" {
return nil, err
}
return NewAccessPoint(path)
}
func (d *deviceWireless) GetPropertyWirelessCapabilities() (uint32, error) {
return d.getUint32Property(DeviceWirelessPropertyWirelessCapabilities)
}
func (d *deviceWireless) GetPropertyLastScan() (int64, error) {
return d.getInt64Property(DeviceWirelessPropertyLastScan)
}
func (d *deviceWireless) MarshalJSON() ([]byte, error) {
m, err := d.device.marshalMap()
if err != nil {
return nil, err
}
m["AccessPoints"], _ = d.GetPropertyAccessPoints()
m["HwAddress"], _ = d.GetPropertyHwAddress()
m["PermHwAddress"], _ = d.GetPropertyPermHwAddress()
m["Mode"], _ = d.GetPropertyMode()
m["Bitrate"], _ = d.GetPropertyBitrate()
m["ActiveAccessPoint"], _ = d.GetPropertyActiveAccessPoint()
m["WirelessCapabilities"], _ = d.GetPropertyWirelessCapabilities()
m["LastScan"], _ = d.GetPropertyLastScan()
return json.Marshal(m)
}
+96
View File
@@ -0,0 +1,96 @@
package gonetworkmanager
import (
"errors"
"github.com/godbus/dbus/v5"
)
const (
DnsManagerInterface = NetworkManagerInterface + ".DnsManager"
DnsManagerObjectPath = "/org/freedesktop/NetworkManager/DnsManager"
/* Property */
DnsManagerPropertyMode = DnsManagerInterface + ".Mode" // readable s
DnsManagerPropertyRcManager = DnsManagerInterface + ".RcManager" // readable s
DnsManagerPropertyConfiguration = DnsManagerInterface + ".Configuration" // readable aa{sv}
)
type DnsConfigurationData struct {
Nameservers []string
Priority int32
Interface string
Vpn bool
}
type DnsManager interface {
GetPath() dbus.ObjectPath
GetPropertyMode() (string, error)
GetPropertyRcManager() (string, error)
GetPropertyConfiguration() ([]DnsConfigurationData, error)
}
type dnsManager struct {
dbusBase
}
func NewDnsManager() (DnsManager, error) {
var d dnsManager
return &d, d.init(NetworkManagerInterface, DnsManagerObjectPath)
}
func (d *dnsManager) GetPath() dbus.ObjectPath {
return d.obj.Path()
}
func (d *dnsManager) GetPropertyMode() (string, error) {
return d.getStringProperty(DnsManagerPropertyMode)
}
func (d *dnsManager) GetPropertyRcManager() (string, error) {
return d.getStringProperty(DnsManagerPropertyRcManager)
}
func (d *dnsManager) GetPropertyConfiguration() ([]DnsConfigurationData, error) {
configurations, err := d.getSliceMapStringVariantProperty(DnsManagerPropertyConfiguration)
if err != nil {
return nil, err
}
ret := make([]DnsConfigurationData, len(configurations))
for i, conf := range configurations {
if serversVar, exist := conf["nameservers"]; exist {
servers, ok := serversVar.Value().([]string)
if !ok {
return nil, errors.New("unexpected variant type for nameservers")
}
ret[i].Nameservers = servers
}
if priorityVar, exist := conf["priority"]; exist {
priority, ok := priorityVar.Value().(int32)
if !ok {
return nil, errors.New("unexpected variant type for priority")
}
ret[i].Priority = priority
}
if interfaceVar, exist := conf["interface"]; exist {
iface, ok := interfaceVar.Value().(string)
if !ok {
return nil, errors.New("unexpected variant type for interface")
}
ret[i].Interface = iface
}
if vpnVar, exist := conf["vpn"]; exist {
vpn, ok := vpnVar.Value().(bool)
if !ok {
return nil, errors.New("unexpected variant type for vpn")
}
ret[i].Vpn = vpn
}
}
return ret, nil
}
+321
View File
@@ -0,0 +1,321 @@
package gonetworkmanager
import (
"encoding/json"
"errors"
"github.com/godbus/dbus/v5"
)
const (
IP4ConfigInterface = NetworkManagerInterface + ".IP4Config"
/* Properties */
IP4ConfigPropertyAddresses = IP4ConfigInterface + ".Addresses" // readable aau
IP4ConfigPropertyAddressData = IP4ConfigInterface + ".AddressData" // readable aa{sv}
IP4ConfigPropertyGateway = IP4ConfigInterface + ".Gateway" // readable s
IP4ConfigPropertyRoutes = IP4ConfigInterface + ".Routes" // readable aau
IP4ConfigPropertyRouteData = IP4ConfigInterface + ".RouteData" // readable aa{sv}
IP4ConfigPropertyNameservers = IP4ConfigInterface + ".Nameservers" // readable au
IP4ConfigPropertyNameserverData = IP4ConfigInterface + ".NameserverData" // readable aa{sv}
IP4ConfigPropertyDomains = IP4ConfigInterface + ".Domains" // readable as
IP4ConfigPropertySearches = IP4ConfigInterface + ".Searches" // readable as
IP4ConfigPropertyDnsOptions = IP4ConfigInterface + ".DnsOptions" // readable as
IP4ConfigPropertyDnsPriority = IP4ConfigInterface + ".DnsPriority" // readable i
IP4ConfigPropertyWinsServers = IP4ConfigInterface + ".WinsServers" // readable au
IP4ConfigPropertyWinsServerData = IP4ConfigInterface + ".WinsServerData" // readable as
)
// Deprecated: use IP4AddressData instead
type IP4Address struct {
Address string
Prefix uint8
Gateway string
}
type IP4AddressData struct {
Address string
Prefix uint8
}
// Deprecated: use IP4RouteData instead
type IP4Route struct {
Route string
Prefix uint8
NextHop string
Metric uint8
}
type IP4RouteData struct {
Destination string
Prefix uint8
NextHop string
Metric uint8
AdditionalAttributes map[string]string
}
type IP4NameserverData struct {
Address string
}
type IP4Config interface {
// GetPropertyAddresses Array of arrays of IPv4 address/prefix/gateway. All 3 elements of each array are in network byte order. Essentially: [(addr, prefix, gateway), (addr, prefix, gateway), ...]
// Deprecated: use AddressData and Gateway
GetPropertyAddresses() ([]IP4Address, error)
// GetPropertyAddressData Array of IP address data objects. All addresses will include "address" (an IP address string), and "prefix" (a uint). Some addresses may include additional attributes.
GetPropertyAddressData() ([]IP4AddressData, error)
// GetPropertyGateway The gateway in use.
GetPropertyGateway() (string, error)
// GetPropertyRoutes Arrays of IPv4 route/prefix/next-hop/metric. All 4 elements of each tuple are in network byte order. 'route' and 'next hop' are IPv4 addresses, while prefix and metric are simple unsigned integers. Essentially: [(route, prefix, next-hop, metric), (route, prefix, next-hop, metric), ...]
// Deprecated: use RouteData
GetPropertyRoutes() ([]IP4Route, error)
// GetPropertyRouteData Array of IP route data objects. All routes will include "dest" (an IP address string) and "prefix" (a uint). Some routes may include "next-hop" (an IP address string), "metric" (a uint), and additional attributes.
GetPropertyRouteData() ([]IP4RouteData, error)
// GetPropertyNameservers The nameservers in use.
// Deprecated: use NameserverData
GetPropertyNameservers() ([]string, error)
// GetPropertyNameserverData The nameservers in use. Currently only the value "address" is recognized (with an IP address string).
GetPropertyNameserverData() ([]IP4NameserverData, error)
// GetPropertyDomains A list of domains this address belongs to.
GetPropertyDomains() ([]string, error)
// GetPropertySearches A list of dns searches.
GetPropertySearches() ([]string, error)
// GetPropertyDnsOptions A list of DNS options that modify the behavior of the DNS resolver. See resolv.conf(5) manual page for the list of supported options.
GetPropertyDnsOptions() ([]string, error)
// GetPropertyDnsPriority The relative priority of DNS servers.
GetPropertyDnsPriority() (uint32, error)
// GetPropertyWinsServerData The Windows Internet Name Service servers associated with the connection.
GetPropertyWinsServerData() ([]string, error)
MarshalJSON() ([]byte, error)
}
func NewIP4Config(objectPath dbus.ObjectPath) (IP4Config, error) {
var c ip4Config
return &c, c.init(NetworkManagerInterface, objectPath)
}
type ip4Config struct {
dbusBase
}
// Deprecated: use GetPropertyAddressData
func (c *ip4Config) GetPropertyAddresses() ([]IP4Address, error) {
addresses, err := c.getSliceSliceUint32Property(IP4ConfigPropertyAddresses)
ret := make([]IP4Address, len(addresses))
if err != nil {
return ret, err
}
for i, parts := range addresses {
ret[i] = IP4Address{
Address: ip4ToString(parts[0]),
Prefix: uint8(parts[1]),
Gateway: ip4ToString(parts[2]),
}
}
return ret, nil
}
func (c *ip4Config) GetPropertyAddressData() ([]IP4AddressData, error) {
addresses, err := c.getSliceMapStringVariantProperty(IP4ConfigPropertyAddressData)
ret := make([]IP4AddressData, len(addresses))
if err != nil {
return ret, err
}
for i, address := range addresses {
prefix, ok := address["prefix"].Value().(uint32)
if !ok {
return ret, errors.New("unexpected variant type for address prefix")
}
address, ok := address["address"].Value().(string)
if !ok {
return ret, errors.New("unexpected variant type for address")
}
ret[i] = IP4AddressData{
Address: address,
Prefix: uint8(prefix),
}
}
return ret, nil
}
func (c *ip4Config) GetPropertyGateway() (string, error) {
return c.getStringProperty(IP4ConfigPropertyGateway)
}
// Deprecated: use GetPropertyRouteData
func (c *ip4Config) GetPropertyRoutes() ([]IP4Route, error) {
routes, err := c.getSliceSliceUint32Property(IP4ConfigPropertyRoutes)
ret := make([]IP4Route, len(routes))
if err != nil {
return ret, err
}
for i, parts := range routes {
ret[i] = IP4Route{
Route: ip4ToString(parts[0]),
Prefix: uint8(parts[1]),
NextHop: ip4ToString(parts[2]),
Metric: uint8(parts[3]),
}
}
return ret, nil
}
func (c *ip4Config) GetPropertyRouteData() ([]IP4RouteData, error) {
routesData, err := c.getSliceMapStringVariantProperty(IP4ConfigPropertyRouteData)
routes := make([]IP4RouteData, len(routesData))
if err != nil {
return routes, err
}
for index, routeData := range routesData {
route := IP4RouteData{}
for routeDataAttributeName, routeDataAttribute := range routeData {
switch routeDataAttributeName {
case "dest":
destination, ok := routeDataAttribute.Value().(string)
if !ok {
return routes, errors.New("unexpected variant type for dest")
}
route.Destination = destination
case "prefix":
prefix, ok := routeDataAttribute.Value().(uint32)
if !ok {
return routes, errors.New("unexpected variant type for prefix")
}
route.Prefix = uint8(prefix)
case "next-hop":
nextHop, ok := routeDataAttribute.Value().(string)
if !ok {
return routes, errors.New("unexpected variant type for next-hop")
}
route.NextHop = nextHop
case "metric":
metric, ok := routeDataAttribute.Value().(uint32)
if !ok {
return routes, errors.New("unexpected variant type for metric")
}
route.Metric = uint8(metric)
default:
if route.AdditionalAttributes == nil {
route.AdditionalAttributes = make(map[string]string)
}
route.AdditionalAttributes[routeDataAttributeName] = routeDataAttribute.String()
}
}
routes[index] = route
}
return routes, nil
}
// Deprecated: use GetPropertyNameserverData
func (c *ip4Config) GetPropertyNameservers() ([]string, error) {
nameservers, err := c.getSliceUint32Property(IP4ConfigPropertyNameservers)
ret := make([]string, len(nameservers))
if err != nil {
return ret, err
}
for i, ns := range nameservers {
ret[i] = ip4ToString(ns)
}
return ret, nil
}
func (c *ip4Config) GetPropertyNameserverData() ([]IP4NameserverData, error) {
nameserversData, err := c.getSliceMapStringVariantProperty(IP4ConfigPropertyNameserverData)
nameservers := make([]IP4NameserverData, 0, len(nameserversData))
if err != nil {
return nameservers, err
}
for _, nameserverData := range nameserversData {
address, ok := nameserverData["address"].Value().(string)
if !ok {
return nameservers, errors.New("unexpected variant type for address")
}
nameserver := IP4NameserverData{
Address: address,
}
nameservers = append(nameservers, nameserver)
}
return nameservers, nil
}
func (c *ip4Config) GetPropertyDomains() ([]string, error) {
return c.getSliceStringProperty(IP4ConfigPropertyDomains)
}
func (c *ip4Config) GetPropertySearches() ([]string, error) {
return c.getSliceStringProperty(IP4ConfigPropertySearches)
}
func (c *ip4Config) GetPropertyDnsOptions() ([]string, error) {
return c.getSliceStringProperty(IP4ConfigPropertyDnsOptions)
}
func (c *ip4Config) GetPropertyDnsPriority() (uint32, error) {
return c.getUint32Property(IP4ConfigPropertyDnsPriority)
}
func (c *ip4Config) GetPropertyWinsServerData() ([]string, error) {
return c.getSliceStringProperty(IP4ConfigPropertyWinsServerData)
}
func (c *ip4Config) MarshalJSON() ([]byte, error) {
Addresses, err := c.GetPropertyAddressData()
if err != nil {
return nil, err
}
Routes, err := c.GetPropertyRouteData()
if err != nil {
return nil, err
}
Nameservers, err := c.GetPropertyNameserverData()
if err != nil {
return nil, err
}
Domains, err := c.GetPropertyDomains()
if err != nil {
return nil, err
}
return json.Marshal(map[string]interface{}{
"Addresses": Addresses,
"Routes": Routes,
"Nameservers": Nameservers,
"Domains": Domains,
})
}
+215
View File
@@ -0,0 +1,215 @@
package gonetworkmanager
import (
"encoding/json"
"errors"
"github.com/godbus/dbus/v5"
)
const (
IP6ConfigInterface = NetworkManagerInterface + ".IP6Config"
/* Properties */
IP6ConfigPropertyAddresses = IP6ConfigInterface + ".Addresses" // readable a(ayuay)
IP6ConfigPropertyAddressData = IP6ConfigInterface + ".AddressData" // readable aa{sv}
IP6ConfigPropertyGateway = IP6ConfigInterface + ".Gateway" // readable s
IP6ConfigPropertyRoutes = IP6ConfigInterface + ".Routes" // readable a(ayuayu)
IP6ConfigPropertyRouteData = IP6ConfigInterface + ".RouteData" // readable aa{sv}
IP6ConfigPropertyNameservers = IP6ConfigInterface + ".Nameservers" // readable aay
IP6ConfigPropertyDomains = IP6ConfigInterface + ".Domains" // readable as
IP6ConfigPropertySearches = IP6ConfigInterface + ".Searches" // readable as
IP6ConfigPropertyDnsOptions = IP6ConfigInterface + ".DnsOptions" // readable as
IP6ConfigPropertyDnsPriority = IP6ConfigInterface + ".DnsPriority" // readable i
)
// Deprecated: use IP6AddressData instead
type IP6Address struct {
Address string
Prefix uint8
Gateway string
}
type IP6AddressData struct {
Address string
Prefix uint8
}
// Deprecated: use IP6RouteData instead
type IP6Route struct {
Route string
Prefix uint8
NextHop string
Metric uint8
}
type IP6RouteData struct {
Destination string
Prefix uint8
NextHop string
Metric uint8
AdditionalAttributes map[string]string
}
type IP6Config interface {
// GetPropertyAddressData Array of IP address data objects. All addresses will include "address" (an IP address string), and "prefix" (a uint). Some addresses may include additional attributes.
GetPropertyAddressData() ([]IP6AddressData, error)
// GetPropertyGateway The gateway in use.
GetPropertyGateway() (string, error)
// GetPropertyRouteData Array of IP route data objects. All routes will include "dest" (an IP address string) and "prefix" (a uint). Some routes may include "next-hop" (an IP address string), "metric" (a uint), and additional attributes.
GetPropertyRouteData() ([]IP6RouteData, error)
// GetPropertyNameservers GetNameservers gets the nameservers in use.
GetPropertyNameservers() ([][]byte, error)
// GetPropertyDomains A list of domains this address belongs to.
GetPropertyDomains() ([]string, error)
// GetPropertySearches A list of dns searches.
GetPropertySearches() ([]string, error)
// GetPropertyDnsOptions A list of DNS options that modify the behavior of the DNS resolver. See resolv.conf(5) manual page for the list of supported options.
GetPropertyDnsOptions() ([]string, error)
// GetPropertyDnsPriority The relative priority of DNS servers.
GetPropertyDnsPriority() (uint32, error)
MarshalJSON() ([]byte, error)
}
func NewIP6Config(objectPath dbus.ObjectPath) (IP6Config, error) {
var c ip6Config
return &c, c.init(NetworkManagerInterface, objectPath)
}
type ip6Config struct {
dbusBase
}
func (c *ip6Config) GetPropertyAddressData() ([]IP6AddressData, error) {
addresses, err := c.getSliceMapStringVariantProperty(IP6ConfigPropertyAddressData)
ret := make([]IP6AddressData, len(addresses))
if err != nil {
return ret, err
}
for i, address := range addresses {
prefix, ok := address["prefix"].Value().(uint32)
if !ok {
return ret, errors.New("unexpected variant type for prefix")
}
address, ok := address["address"].Value().(string)
if !ok {
return ret, errors.New("unexpected variant type for address")
}
ret[i] = IP6AddressData{
Address: address,
Prefix: uint8(prefix),
}
}
return ret, nil
}
func (c *ip6Config) GetPropertyGateway() (string, error) {
return c.getStringProperty(IP6ConfigPropertyGateway)
}
func (c *ip6Config) GetPropertyRouteData() ([]IP6RouteData, error) {
routesData, err := c.getSliceMapStringVariantProperty(IP6ConfigPropertyRouteData)
routes := make([]IP6RouteData, len(routesData))
if err != nil {
return routes, err
}
for index, routeData := range routesData {
route := IP6RouteData{}
for routeDataAttributeName, routeDataAttribute := range routeData {
switch routeDataAttributeName {
case "dest":
destination, ok := routeDataAttribute.Value().(string)
if !ok {
return routes, errors.New("unexpected variant type for dest")
}
route.Destination = destination
case "prefix":
prefix, ok := routeDataAttribute.Value().(uint32)
if !ok {
return routes, errors.New("unexpected variant type for prefix")
}
route.Prefix = uint8(prefix)
case "next-hop":
nextHop, ok := routeDataAttribute.Value().(string)
if !ok {
return routes, errors.New("unexpected variant type for next-hop")
}
route.NextHop = nextHop
case "metric":
metric, ok := routeDataAttribute.Value().(uint32)
if !ok {
return routes, errors.New("unexpected variant type for metric")
}
route.Metric = uint8(metric)
default:
if route.AdditionalAttributes == nil {
route.AdditionalAttributes = make(map[string]string)
}
route.AdditionalAttributes[routeDataAttributeName] = routeDataAttribute.String()
}
}
routes[index] = route
}
return routes, nil
}
func (c *ip6Config) GetPropertyNameservers() ([][]byte, error) {
nameservers, err := c.getSliceSliceByteProperty(IP6ConfigPropertyNameservers)
ret := make([][]byte, len(nameservers))
if err != nil {
return ret, err
}
for i, nameserver := range nameservers {
ret[i] = nameserver
}
return ret, nil
}
func (c *ip6Config) GetPropertyDomains() ([]string, error) {
return c.getSliceStringProperty(IP6ConfigPropertyDomains)
}
func (c *ip6Config) GetPropertySearches() ([]string, error) {
return c.getSliceStringProperty(IP6ConfigPropertySearches)
}
func (c *ip6Config) GetPropertyDnsOptions() ([]string, error) {
return c.getSliceStringProperty(IP6ConfigPropertyDnsOptions)
}
func (c *ip6Config) GetPropertyDnsPriority() (uint32, error) {
return c.getUint32Property(IP6ConfigPropertyDnsPriority)
}
func (c *ip6Config) MarshalJSON() ([]byte, error) {
m := make(map[string]interface{})
m["Addresses"], _ = c.GetPropertyAddressData()
m["Routes"], _ = c.GetPropertyRouteData()
m["Nameservers"], _ = c.GetPropertyNameservers()
m["Domains"], _ = c.GetPropertyDomains()
return json.Marshal(m)
}
+45
View File
@@ -0,0 +1,45 @@
The MIT License (MIT)
Copyright (c) 2019 Wifx Sàrl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2016 Bellerophon Mobile
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+751
View File
@@ -0,0 +1,751 @@
package gonetworkmanager
import (
"encoding/json"
"github.com/godbus/dbus/v5"
)
const (
NetworkManagerInterface = "org.freedesktop.NetworkManager"
NetworkManagerObjectPath = "/org/freedesktop/NetworkManager"
/* Methods */
NetworkManagerReload = NetworkManagerInterface + ".Reload"
NetworkManagerGetDevices = NetworkManagerInterface + ".GetDevices"
NetworkManagerGetAllDevices = NetworkManagerInterface + ".GetAllDevices"
NetworkManagerGetDeviceByIpIface = NetworkManagerInterface + ".GetDeviceByIpIface"
NetworkManagerActivateConnection = NetworkManagerInterface + ".ActivateConnection"
NetworkManagerAddAndActivateConnection = NetworkManagerInterface + ".AddAndActivateConnection"
NetworkManagerAddAndActivateConnection2 = NetworkManagerInterface + ".AddAndActivateConnection2"
NetworkManagerDeactivateConnection = NetworkManagerInterface + ".DeactivateConnection"
NetworkManagerSleep = NetworkManagerInterface + ".Sleep"
NetworkManagerEnable = NetworkManagerInterface + ".Enable"
NetworkManagerGetPermissions = NetworkManagerInterface + ".GetPermissions"
NetworkManagerSetLogging = NetworkManagerInterface + ".SetLogging"
NetworkManagerGetLogging = NetworkManagerInterface + ".GetLogging"
NetworkManagerCheckConnectivity = NetworkManagerInterface + ".CheckConnectivity"
NetworkManagerState = NetworkManagerInterface + ".state"
NetworkManagerCheckpointCreate = NetworkManagerInterface + ".CheckpointCreate"
NetworkManagerCheckpointDestroy = NetworkManagerInterface + ".CheckpointDestroy"
NetworkManagerCheckpointRollback = NetworkManagerInterface + ".CheckpointRollback"
NetworkManagerCheckpointAdjustRollbackTimeout = NetworkManagerInterface + ".CheckpointAdjustRollbackTimeout"
/* Property */
NetworkManagerPropertyDevices = NetworkManagerInterface + ".Devices" // readable ao
NetworkManagerPropertyAllDevices = NetworkManagerInterface + ".AllDevices" // readable ao
NetworkManagerPropertyCheckpoints = NetworkManagerInterface + ".Checkpoints" // readable ao
NetworkManagerPropertyNetworkingEnabled = NetworkManagerInterface + ".NetworkingEnabled" // readable b
NetworkManagerPropertyWirelessEnabled = NetworkManagerInterface + ".WirelessEnabled" // readwrite b
NetworkManagerPropertyWirelessHardwareEnabled = NetworkManagerInterface + ".WirelessHardwareEnabled" // readable b
NetworkManagerPropertyWwanEnabled = NetworkManagerInterface + ".WwanEnabled" // readwrite b
NetworkManagerPropertyWwanHardwareEnabled = NetworkManagerInterface + ".WwanHardwareEnabled" // readable b
NetworkManagerPropertyWimaxEnabled = NetworkManagerInterface + ".WimaxEnabled" // readwrite b
NetworkManagerPropertyWimaxHardwareEnabled = NetworkManagerInterface + ".WimaxHardwareEnabled" // readable b
NetworkManagerPropertyActiveConnections = NetworkManagerInterface + ".ActiveConnections" // readable ao
NetworkManagerPropertyPrimaryConnection = NetworkManagerInterface + ".PrimaryConnection" // readable o
NetworkManagerPropertyPrimaryConnectionType = NetworkManagerInterface + ".PrimaryConnectionType" // readable s
NetworkManagerPropertyMetered = NetworkManagerInterface + ".Metered" // readable u
NetworkManagerPropertyActivatingConnection = NetworkManagerInterface + ".ActivatingConnection" // readable o
NetworkManagerPropertyStartup = NetworkManagerInterface + ".Startup" // readable b
NetworkManagerPropertyVersion = NetworkManagerInterface + ".Version" // readable s
NetworkManagerPropertyCapabilities = NetworkManagerInterface + ".Capabilities" // readable au
NetworkManagerPropertyState = NetworkManagerInterface + ".State" // readable u
NetworkManagerPropertyConnectivity = NetworkManagerInterface + ".Connectivity" // readable u
NetworkManagerPropertyConnectivityCheckAvailable = NetworkManagerInterface + ".ConnectivityCheckAvailable" // readable b
NetworkManagerPropertyConnectivityCheckEnabled = NetworkManagerInterface + ".ConnectivityCheckEnabled" // readwrite b
NetworkManagerPropertyGlobalDnsConfiguration = NetworkManagerInterface + ".GlobalDnsConfiguration" // readwrite a{sv}
)
type NetworkManager interface {
/* METHODS */
// Reload NetworkManager's configuration and perform certain updates, like flushing a cache or rewriting external state to disk. This is similar to sending SIGHUP to NetworkManager but it allows for more fine-grained control over what to reload (see flags). It also allows non-root access via PolicyKit and contrary to signals it is synchronous.
// No flags (0x00) means to reload everything that is supported which is identical to sending a SIGHUP.
// (0x01) means to reload the NetworkManager.conf configuration from disk. Note that this does not include connections, which can be reloaded via Setting's ReloadConnections.
// (0x02) means to update DNS configuration, which usually involves writing /etc/resolv.conf anew.
// (0x04) means to restart the DNS plugin. This is for example useful when using dnsmasq plugin, which uses additional configuration in /etc/NetworkManager/dnsmasq.d. If you edit those files, you can restart the DNS plugin. This action shortly interrupts name resolution. Note that flags may affect each other. For example, restarting the DNS plugin (0x04) implicitly updates DNS too (0x02). Or when reloading the configuration (0x01), changes to DNS setting also cause a DNS update (0x02). However, (0x01) does not involve restarting the DNS plugin (0x04) or update resolv.conf (0x02), unless the DNS related configuration changes in NetworkManager.conf.
Reload(flags uint32) error
// GetDevices Get the list of realized network devices.
GetDevices() ([]Device, error)
// GetAllDevices Get the list of all network devices.
GetAllDevices() ([]Device, error)
// GetDeviceByIpIface Return the object path of the network device referenced by its IP interface name. Note that some devices (usually modems) only have an IP interface name when they are connected.
GetDeviceByIpIface(interfaceId string) (Device, error)
// ActivateConnection Activate a connection using the supplied device.
ActivateConnection(connection Connection, device Device, specificObject *dbus.Object) (ActiveConnection, error)
// AddAndActivateConnection Adds a new connection using the given details (if any) as a template (automatically filling in missing settings with the capabilities of the given device), then activate the new connection. Cannot be used for VPN connections at this time.
AddAndActivateConnection(connection map[string]map[string]interface{}, device Device) (ActiveConnection, error)
// ActivateWirelessConnection requests activating access point to network device
ActivateWirelessConnection(connection Connection, device Device, accessPoint AccessPoint) (ActiveConnection, error)
// AddAndActivateWirelessConnection adds a new connection profile to the network device it has been
// passed. It then activates the connection to the passed access point. The first parameter contains
// additional information for the connection (most probably the credentials).
// Example contents for connection are:
// connection := make(map[string]map[string]interface{})
// connection["802-11-wireless"] = make(map[string]interface{})
// connection["802-11-wireless"]["security"] = "802-11-wireless-security"
// connection["802-11-wireless-security"] = make(map[string]interface{})
// connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"
// connection["802-11-wireless-security"]["psk"] = password
AddAndActivateWirelessConnection(connection map[string]map[string]interface{}, device Device, accessPoint AccessPoint) (ActiveConnection, error)
// DeactivateConnection Deactivate an active connection.
DeactivateConnection(connection ActiveConnection) error
// Sleep Control the NetworkManager daemon's sleep state. When asleep, all interfaces that it manages are deactivated. When awake, devices are available to be activated. This command should not be called directly by users or clients; it is intended for system suspend/resume tracking.
// sleepnWake: Indicates whether the NetworkManager daemon should sleep or wake.
Sleep(sleepNWake bool) error
// Enable Control whether overall networking is enabled or disabled. When disabled, all interfaces that NM manages are deactivated. When enabled, all managed interfaces are re-enabled and available to be activated. This command should be used by clients that provide to users the ability to enable/disable all networking.
// enableNDisable: If FALSE, indicates that all networking should be disabled. If TRUE, indicates that NetworkManager should begin managing network devices.
Enable(enableNDisable bool) error
// CheckConnectivity Re-check the network connectivity state.
CheckConnectivity() error
// State The overall networking state as determined by the NetworkManager daemon, based on the state of network devices under its management.
State() (NmState, error)
// CheckpointCreate Create a checkpoint of the current networking configuration for given interfaces. If rollback_timeout is not zero, a rollback is automatically performed after the given timeout.
// devices: A list of device paths for which a checkpoint should be created. An empty list means all devices.
// rollbackTimeout: The time in seconds until NetworkManager will automatically rollback to the checkpoint. Set to zero for infinite.
// flags: Flags for the creation.
// returns: On success, the new checkpoint.
CheckpointCreate(devices []Device, rollbackTimeout uint32, flags uint32) (Checkpoint, error)
// CheckpointDestroy Destroy a previously created checkpoint.
// checkpoint: The checkpoint to be destroyed. Set to empty to cancel all pending checkpoints.
CheckpointDestroy(checkpoint Checkpoint) error
// CheckpointRollback Rollback a checkpoint before the timeout is reached.
// checkpoint: The checkpoint to be rolled back.
// result: On return, a dictionary of devices and results. Devices are represented by their original D-Bus path; each result is a RollbackResult.
CheckpointRollback(checkpoint Checkpoint) (result map[dbus.ObjectPath]NmRollbackResult, err error)
// CheckpointAdjustRollbackTimeout Reset the timeout for rollback for the checkpoint.
// Since: 1.12
// addTimeout: number of seconds from ~now~ in which the timeout will expire. Set to 0 to disable the timeout. Note that the added seconds start counting from now, not "Created" timestamp or the previous expiration time. Note that the "Created" property of the checkpoint will stay unchanged by this call. However, the "RollbackTimeout" will be recalculated to give the approximate new expiration time. The new "RollbackTimeout" property will be approximate up to one second precision, which is the accuracy of the property.
CheckpointAdjustRollbackTimeout(checkpoint Checkpoint, addTimeout uint32) error
/* PROPERTIES */
// GetPropertyDevices The list of realized network devices. Realized devices are those which have backing resources (eg from the kernel or a management daemon like ModemManager, teamd, etc).
GetPropertyDevices() ([]Device, error)
// GetPropertyAllDevices The list of both realized and un-realized network devices. Un-realized devices are software devices which do not yet have backing resources, but for which backing resources can be created if the device is activated.
GetPropertyAllDevices() ([]Device, error)
// GetPropertyCheckpoints The list of active checkpoints.
GetPropertyCheckpoints() ([]Checkpoint, error)
// GetPropertyNetworkingEnabled Indicates if overall networking is currently enabled or not. See the Enable() method.
GetPropertyNetworkingEnabled() (bool, error)
// GetPropertyWirelessEnabled Indicates if wireless is currently enabled or not.
GetPropertyWirelessEnabled() (bool, error)
SetPropertyWirelessEnabled(bool) error
// GetPropertyWirelessHardwareEnabled Indicates if the wireless hardware is currently enabled, i.e. the state of the RF kill switch.
GetPropertyWirelessHardwareEnabled() (bool, error)
// GetPropertyWwanEnabled Indicates if mobile broadband devices are currently enabled or not.
GetPropertyWwanEnabled() (bool, error)
// GetPropertyWwanHardwareEnabled Indicates if the mobile broadband hardware is currently enabled, i.e. the state of the RF kill switch.
GetPropertyWwanHardwareEnabled() (bool, error)
// GetPropertyWimaxEnabled Indicates if WiMAX devices are currently enabled or not.
GetPropertyWimaxEnabled() (bool, error)
// GetPropertyWimaxHardwareEnabled Indicates if the WiMAX hardware is currently enabled, i.e. the state of the RF kill switch.
GetPropertyWimaxHardwareEnabled() (bool, error)
// GetPropertyActiveConnections List of active connection object paths.
GetPropertyActiveConnections() ([]ActiveConnection, error)
// GetPropertyPrimaryConnection The object path of the "primary" active connection being used to access the network. In particular, if there is no VPN active, or the VPN does not have the default route, then this indicates the connection that has the default route. If there is a VPN active with the default route, then this indicates the connection that contains the route to the VPN endpoint.
GetPropertyPrimaryConnection() (ActiveConnection, error)
// GetPropertyPrimaryConnectionType The connection type of the "primary" active connection being used to access the network. This is the same as the Type property on the object indicated by PrimaryConnection.
GetPropertyPrimaryConnectionType() (string, error)
// GetPropertyMetered Indicates whether the connectivity is metered. This is equivalent to the metered property of the device associated with the primary connection.
GetPropertyMetered() (NmMetered, error)
// GetPropertyActivatingConnection The object path of an active connection that is currently being activated and which is expected to become the new PrimaryConnection when it finishes activating.
GetPropertyActivatingConnection() (ActiveConnection, error)
// GetPropertyStartup Indicates whether NM is still starting up; this becomes FALSE when NM has finished attempting to activate every connection that it might be able to activate at startup.
GetPropertyStartup() (bool, error)
// GetPropertyVersion NetworkManager version.
GetPropertyVersion() (string, error)
// GetPropertyCapabilities The current set of capabilities. See NMCapability for currently defined capability numbers. The array is guaranteed to be sorted in ascending order without duplicates.
GetPropertyCapabilities() ([]NmCapability, error)
// GetPropertyState The overall state of the NetworkManager daemon.
// This takes state of all active connections and the connectivity state into account to produce a single indicator of the network accessibility status.
// The graphical shells may use this property to provide network connection status indication and applications may use this to check if Internet connection is accessible. Shell that is able to cope with captive portals should use the "Connectivity" property to decide whether to present a captive portal authentication dialog.
GetPropertyState() (NmState, error)
// GetPropertyConnectivity The result of the last connectivity check. The connectivity check is triggered automatically when a default connection becomes available, periodically and by calling a CheckConnectivity() method.
// This property is in general useful for the graphical shell to determine whether the Internet access is being hijacked by an authentication gateway (a "captive portal"). In such case it would typically present a web browser window to give the user a chance to authenticate and call CheckConnectivity() when the user submits a form or dismisses the window.
// To determine the whether the user is able to access the Internet without dealing with captive portals (e.g. to provide a network connection indicator or disable controls that require Internet access), the "State" property is more suitable.
GetPropertyConnectivity() (NmConnectivity, error)
// GetPropertyConnectivityCheckAvailable Indicates whether connectivity checking service has been configured. This may return true even if the service is not currently enabled.
// This is primarily intended for use in a privacy control panel, as a way to determine whether to show an option to enable/disable the feature.
GetPropertyConnectivityCheckAvailable() (bool, error)
// GetPropertyConnectivityCheckEnabled Indicates whether connectivity checking is enabled. This property can also be written to to disable connectivity checking (as a privacy control panel might want to do).
GetPropertyConnectivityCheckEnabled() (bool, error)
// Dictionary of global DNS settings where the key is one of "searches", "options" and "domains". The values for the "searches" and "options" keys are string arrays describing the list of search domains and resolver options, respectively. The value of the "domains" key is a second-level dictionary, where each key is a domain name, and each key's value is a third-level dictionary with the keys "servers" and "options". "servers" is a string array of DNS servers, "options" is a string array of domain-specific options.
//GetPropertyGlobalDnsConfiguration() []interface{}
Subscribe() <-chan *dbus.Signal
Unsubscribe()
MarshalJSON() ([]byte, error)
}
func NewNetworkManager() (NetworkManager, error) {
var nm networkManager
return &nm, nm.init(NetworkManagerInterface, NetworkManagerObjectPath)
}
type networkManager struct {
dbusBase
sigChan chan *dbus.Signal
}
func (nm *networkManager) Reload(flags uint32) error {
return nm.call(NetworkManagerReload, flags)
}
func (nm *networkManager) GetDevices() (devices []Device, err error) {
var devicePaths []dbus.ObjectPath
err = nm.callWithReturn(&devicePaths, NetworkManagerGetDevices)
if err != nil {
return
}
devices = make([]Device, len(devicePaths))
for i, path := range devicePaths {
devices[i], err = DeviceFactory(path)
if err != nil {
return
}
}
return
}
func (nm *networkManager) GetAllDevices() (devices []Device, err error) {
var devicePaths []dbus.ObjectPath
err = nm.callWithReturn(&devicePaths, NetworkManagerGetAllDevices)
if err != nil {
return
}
devices = make([]Device, len(devicePaths))
for i, path := range devicePaths {
devices[i], err = DeviceFactory(path)
if err != nil {
return
}
}
return
}
func (nm *networkManager) GetDeviceByIpIface(interfaceId string) (device Device, err error) {
var devicePath dbus.ObjectPath
err = nm.callWithReturn(&devicePath, NetworkManagerGetDeviceByIpIface, interfaceId)
if err != nil {
return
}
device, err = DeviceFactory(devicePath)
if err != nil {
return
}
return
}
func (nm *networkManager) ActivateConnection(connection Connection, device Device, specificObject *dbus.Object) (ac ActiveConnection, err error) {
var connectionPath dbus.ObjectPath
var devicePath dbus.ObjectPath
if device != nil {
devicePath = device.GetPath()
} else {
devicePath = "/"
}
var specificObjectPath dbus.ObjectPath
if specificObject != nil {
specificObjectPath = specificObject.Path()
} else {
specificObjectPath = "/"
}
err = nm.callWithReturn(&connectionPath, NetworkManagerActivateConnection, connection.GetPath(), devicePath, specificObjectPath)
if err != nil {
return
}
ac, err = NewActiveConnection(connectionPath)
if err != nil {
return
}
return
}
func (nm *networkManager) AddAndActivateConnection(connection map[string]map[string]interface{}, d Device) (ac ActiveConnection, err error) {
var opath1 dbus.ObjectPath
var opath2 dbus.ObjectPath
var devicePath dbus.ObjectPath
if d != nil {
devicePath = d.GetPath()
}
err = nm.callWithReturn2(&opath1, &opath2, NetworkManagerAddAndActivateConnection, connection, devicePath, dbus.ObjectPath("/"))
if err != nil {
return
}
ac, err = NewActiveConnection(opath2)
if err != nil {
return
}
return
}
func (nm *networkManager) ActivateWirelessConnection(c Connection, d Device, ap AccessPoint) (ac ActiveConnection, err error) {
var opath dbus.ObjectPath
err = nm.callWithReturn(&opath, NetworkManagerActivateConnection, c.GetPath(), d.GetPath(), ap.GetPath())
if err != nil {
return nil, err
}
ac, err = NewActiveConnection(opath)
if err != nil {
return nil, err
}
return
}
func (nm *networkManager) AddAndActivateWirelessConnection(connection map[string]map[string]interface{}, d Device, ap AccessPoint) (ac ActiveConnection, err error) {
var opath1 dbus.ObjectPath
var opath2 dbus.ObjectPath
err = nm.callWithReturn2(&opath1, &opath2, NetworkManagerAddAndActivateConnection, connection, d.GetPath(), ap.GetPath())
if err != nil {
return
}
ac, err = NewActiveConnection(opath2)
if err != nil {
return
}
return
}
func (nm *networkManager) DeactivateConnection(c ActiveConnection) error {
return nm.call(NetworkManagerDeactivateConnection, c.GetPath())
}
func (nm *networkManager) Sleep(sleepNWake bool) error {
return nm.call(NetworkManagerSleep, sleepNWake)
}
func (nm *networkManager) Enable(enableNDisable bool) error {
return nm.call(NetworkManagerEnable, enableNDisable)
}
func (nm *networkManager) CheckConnectivity() error {
return nm.call(NetworkManagerCheckConnectivity)
}
func (nm *networkManager) State() (state NmState, err error) {
err = nm.callWithReturn(&state, NetworkManagerState)
return
}
func (nm *networkManager) CheckpointCreate(devices []Device, rollbackTimeout uint32, flags uint32) (cp Checkpoint, err error) {
var devicePaths []dbus.ObjectPath
if len(devices) > 0 {
for _, device := range devices {
devicePaths = append(devicePaths, device.GetPath())
}
}
var checkpointPath dbus.ObjectPath
err = nm.callWithReturn(&checkpointPath, NetworkManagerCheckpointCreate, devicePaths, rollbackTimeout, flags)
if err != nil {
return
}
cp, err = NewCheckpoint(checkpointPath)
return
}
func (nm *networkManager) CheckpointDestroy(checkpoint Checkpoint) error {
if checkpoint == nil {
return nm.call(NetworkManagerCheckpointDestroy)
} else {
return nm.call(NetworkManagerCheckpointDestroy, checkpoint.GetPath())
}
}
func (nm *networkManager) CheckpointRollback(checkpoint Checkpoint) (results map[dbus.ObjectPath]NmRollbackResult, err error) {
var ret map[dbus.ObjectPath]NmRollbackResult
err = nm.callWithReturn(&ret, NetworkManagerCheckpointRollback, checkpoint.GetPath())
if err != nil {
return
}
results = map[dbus.ObjectPath]NmRollbackResult{}
for devicePath, result := range ret {
results[devicePath] = result
}
return
}
func (nm *networkManager) CheckpointAdjustRollbackTimeout(checkpoint Checkpoint, addTimeout uint32) error {
return nm.call(NetworkManagerCheckpointAdjustRollbackTimeout, checkpoint, addTimeout)
}
/* PROPERTIES */
func (nm *networkManager) GetPropertyDevices() ([]Device, error) {
devicesPaths, err := nm.getSliceObjectProperty(NetworkManagerPropertyDevices)
if err != nil {
return nil, err
}
devices := make([]Device, len(devicesPaths))
for i, path := range devicesPaths {
devices[i], err = NewDevice(path)
if err != nil {
return devices, err
}
}
return devices, nil
}
func (nm *networkManager) GetPropertyAllDevices() ([]Device, error) {
devicesPaths, err := nm.getSliceObjectProperty(NetworkManagerPropertyAllDevices)
if err != nil {
return nil, err
}
devices := make([]Device, len(devicesPaths))
for i, path := range devicesPaths {
devices[i], err = NewDevice(path)
if err != nil {
return devices, err
}
}
return devices, nil
}
func (nm *networkManager) GetPropertyCheckpoints() ([]Checkpoint, error) {
checkpointsPaths, err := nm.getSliceObjectProperty(NetworkManagerPropertyCheckpoints)
if err != nil {
return nil, err
}
checkpoints := make([]Checkpoint, len(checkpointsPaths))
for i, path := range checkpointsPaths {
checkpoints[i], err = NewCheckpoint(path)
if err != nil {
return checkpoints, err
}
}
return checkpoints, nil
}
func (nm *networkManager) GetPropertyNetworkingEnabled() (bool, error) {
return nm.getBoolProperty(NetworkManagerPropertyNetworkingEnabled)
}
func (nm *networkManager) GetPropertyWirelessEnabled() (bool, error) {
return nm.getBoolProperty(NetworkManagerPropertyWirelessEnabled)
}
func (nm *networkManager) SetPropertyWirelessEnabled(enabled bool) error {
return nm.setProperty(NetworkManagerPropertyWirelessEnabled, enabled)
}
func (nm *networkManager) GetPropertyWirelessHardwareEnabled() (bool, error) {
return nm.getBoolProperty(NetworkManagerPropertyWirelessHardwareEnabled)
}
func (nm *networkManager) GetPropertyWwanEnabled() (bool, error) {
return nm.getBoolProperty(NetworkManagerPropertyWwanEnabled)
}
func (nm *networkManager) GetPropertyWwanHardwareEnabled() (bool, error) {
return nm.getBoolProperty(NetworkManagerPropertyWwanHardwareEnabled)
}
func (nm *networkManager) GetPropertyWimaxEnabled() (bool, error) {
return nm.getBoolProperty(NetworkManagerPropertyWimaxEnabled)
}
func (nm *networkManager) GetPropertyWimaxHardwareEnabled() (bool, error) {
return nm.getBoolProperty(NetworkManagerPropertyWimaxHardwareEnabled)
}
func (nm *networkManager) GetPropertyActiveConnections() ([]ActiveConnection, error) {
acPaths, err := nm.getSliceObjectProperty(NetworkManagerPropertyActiveConnections)
if err != nil {
return nil, err
}
ac := make([]ActiveConnection, len(acPaths))
for i, path := range acPaths {
ac[i], err = NewActiveConnection(path)
if err != nil {
return ac, err
}
}
return ac, nil
}
func (nm *networkManager) GetPropertyPrimaryConnection() (ActiveConnection, error) {
activeConnectionPath, err := nm.getObjectProperty(NetworkManagerPropertyPrimaryConnection)
if err != nil {
return nil, err
}
return NewActiveConnection(activeConnectionPath)
}
func (nm *networkManager) GetPropertyPrimaryConnectionType() (string, error) {
return nm.getStringProperty(NetworkManagerPropertyPrimaryConnectionType)
}
func (nm *networkManager) GetPropertyMetered() (NmMetered, error) {
v, err := nm.getUint32Property(NetworkManagerPropertyMetered)
return NmMetered(v), err
}
func (nm *networkManager) GetPropertyActivatingConnection() (ActiveConnection, error) {
panic("implement me")
}
func (nm *networkManager) GetPropertyStartup() (bool, error) {
return nm.getBoolProperty(NetworkManagerPropertyStartup)
}
func (nm *networkManager) GetPropertyVersion() (string, error) {
return nm.getStringProperty(NetworkManagerPropertyVersion)
}
func (nm *networkManager) GetPropertyCapabilities() ([]NmCapability, error) {
panic("implement me")
}
func (nm *networkManager) GetPropertyState() (NmState, error) {
v, err := nm.getUint32Property(NetworkManagerPropertyState)
return NmState(v), err
}
func (nm *networkManager) GetPropertyConnectivity() (NmConnectivity, error) {
v, err := nm.getUint32Property(NetworkManagerPropertyConnectivity)
return NmConnectivity(v), err
}
func (nm *networkManager) GetPropertyConnectivityCheckAvailable() (bool, error) {
return nm.getBoolProperty(NetworkManagerPropertyConnectivityCheckAvailable)
}
func (nm *networkManager) GetPropertyConnectivityCheckEnabled() (bool, error) {
return nm.getBoolProperty(NetworkManagerPropertyConnectivityCheckEnabled)
}
func (nm *networkManager) Subscribe() <-chan *dbus.Signal {
if nm.sigChan != nil {
return nm.sigChan
}
nm.subscribeNamespace(NetworkManagerObjectPath)
nm.sigChan = make(chan *dbus.Signal, 10)
nm.conn.Signal(nm.sigChan)
return nm.sigChan
}
func (nm *networkManager) Unsubscribe() {
nm.conn.RemoveSignal(nm.sigChan)
nm.sigChan = nil
}
func (nm *networkManager) MarshalJSON() ([]byte, error) {
Devices, err := nm.GetPropertyDevices()
if err != nil {
return nil, err
}
AllDevices, err := nm.GetPropertyAllDevices()
if err != nil {
return nil, err
}
Checkpoints, err := nm.GetPropertyCheckpoints()
if err != nil {
return nil, err
}
NetworkingEnabled, err := nm.GetPropertyNetworkingEnabled()
if err != nil {
return nil, err
}
WirelessEnabled, err := nm.GetPropertyWirelessEnabled()
if err != nil {
return nil, err
}
WirelessHardwareEnabled, err := nm.GetPropertyWirelessHardwareEnabled()
if err != nil {
return nil, err
}
WwanEnabled, err := nm.GetPropertyWwanEnabled()
if err != nil {
return nil, err
}
WwanHardwareEnabled, err := nm.GetPropertyWwanHardwareEnabled()
if err != nil {
return nil, err
}
WimaxEnabled, err := nm.GetPropertyWimaxEnabled()
if err != nil {
return nil, err
}
WimaxHardwareEnabled, err := nm.GetPropertyWimaxHardwareEnabled()
if err != nil {
return nil, err
}
ActiveConnections, err := nm.GetPropertyActiveConnections()
if err != nil {
return nil, err
}
PrimaryConnection, err := nm.GetPropertyPrimaryConnection()
if err != nil {
return nil, err
}
PrimaryConnectionType, err := nm.GetPropertyPrimaryConnectionType()
if err != nil {
return nil, err
}
Metered, err := nm.GetPropertyMetered()
if err != nil {
return nil, err
}
ActivatingConnection, err := nm.GetPropertyActivatingConnection()
if err != nil {
return nil, err
}
Startup, err := nm.GetPropertyStartup()
if err != nil {
return nil, err
}
Version, err := nm.GetPropertyVersion()
if err != nil {
return nil, err
}
Capabilities, err := nm.GetPropertyCapabilities()
if err != nil {
return nil, err
}
State, err := nm.GetPropertyState()
if err != nil {
return nil, err
}
Connectivity, err := nm.GetPropertyConnectivity()
if err != nil {
return nil, err
}
ConnectivityCheckAvailable, err := nm.GetPropertyConnectivityCheckAvailable()
if err != nil {
return nil, err
}
ConnectivityCheckEnabled, err := nm.GetPropertyConnectivityCheckEnabled()
if err != nil {
return nil, err
}
return json.Marshal(map[string]interface{}{
"Devices": Devices,
"AllDevices": AllDevices,
"Checkpoints": Checkpoints,
"NetworkingEnabled": NetworkingEnabled,
"WirelessEnabled": WirelessEnabled,
"WirelessHardwareEnabled": WirelessHardwareEnabled,
"WwanEnabled": WwanEnabled,
"WwanHardwareEnabled": WwanHardwareEnabled,
"WimaxEnabled": WimaxEnabled,
"WimaxHardwareEnabled": WimaxHardwareEnabled,
"ActiveConnections": ActiveConnections,
"PrimaryConnection": PrimaryConnection,
"PrimaryConnectionType": PrimaryConnectionType,
"Metered": Metered,
"ActivatingConnection": ActivatingConnection,
"Startup": Startup,
"Version": Version,
"Capabilities": Capabilities,
"State": State,
"Connectivity": Connectivity,
"ConnectivityCheckAvailable": ConnectivityCheckAvailable,
"ConnectivityCheckEnabled": ConnectivityCheckEnabled,
})
}
+35
View File
@@ -0,0 +1,35 @@
[![GoDoc](https://godoc.org/github.com/Wifx/gonetworkmanager?status.svg)](https://pkg.go.dev/github.com/Wifx/gonetworkmanager)
[![Go build](https://github.com/Wifx/gonetworkmanager/workflows/Go/badge.svg)](https://github.com/Wifx/gonetworkmanager/actions?query=workflow%3AGo)
gonetworkmanager
================
Go D-Bus bindings for [NetworkManager](https://networkmanager.dev/).
## Usage
You can find some examples in the [examples](examples) directory.
## External documentations
- [NetworkManager D-Bus Spec](https://networkmanager.dev/docs/api/latest/spec.html)
- [nm-settings-dbus](https://networkmanager.dev/docs/api/latest/nm-settings-dbus.html)
## Backward compatibility
The library is most likely compatible with NetworkManager 0.9 to 1.40.
## Tests
Tested with NetworkManager 1.40.0.
There are no automated tests for this library. Tests are made manually on a best-effort basis. Unit tests PRs are welcome.
## Development and contributions
There is no active development workforce from the maintainer. PRs are welcome.
## Issues
Before reporting an issue, please test the scenario with nmcli (if possible) to ensure the problem comes from the library.
+129
View File
@@ -0,0 +1,129 @@
package gonetworkmanager
import (
"github.com/godbus/dbus/v5"
)
const (
SettingsInterface = NetworkManagerInterface + ".Settings"
SettingsObjectPath = NetworkManagerObjectPath + "/Settings"
/* Methods */
SettingsListConnections = SettingsInterface + ".ListConnections"
SettingsGetConnectionByUUID = SettingsInterface + ".GetConnectionByUuid"
SettingsAddConnection = SettingsInterface + ".AddConnection"
SettingsAddConnectionUnsaved = SettingsInterface + ".AddConnectionUnsaved"
SettingsLoadConnections = SettingsInterface + ".LoadConnections"
SettingsReloadConnections = SettingsInterface + ".ReloadConnections"
SettingsSaveHostname = SettingsInterface + ".SaveHostname"
/* Properties */
SettingsPropertyConnections = SettingsInterface + ".Connections" // readable ao
SettingsPropertyHostname = SettingsInterface + ".Hostname" // readable s
SettingsPropertyCanModify = SettingsInterface + ".CanModify" // readable b
)
type Settings interface {
// ListConnections gets list the saved network connections known to NetworkManager
ListConnections() ([]Connection, error)
// ReloadConnections tells NetworkManager to reload all connection files from disk, including noticing any added or deleted connection files.
ReloadConnections() error
// GetConnectionByUUID gets the connection, given that connection's UUID.
GetConnectionByUUID(uuid string) (Connection, error)
// AddConnection adds new connection and save it to disk.
AddConnection(settings ConnectionSettings) (Connection, error)
// AddConnectionUnsaved Add new connection but do not save it to disk immediately. This operation does not start the network connection unless (1) device is idle and able to connect to the network described by the new connection, and (2) the connection is allowed to be started automatically. Use the 'Save' method on the connection to save these changes to disk. Note that unsaved changes will be lost if the connection is reloaded from disk (either automatically on file change or due to an explicit ReloadConnections call).
AddConnectionUnsaved(settings ConnectionSettings) (Connection, error)
// SaveHostname Save the hostname to persistent configuration.
SaveHostname(hostname string) error
// GetPropertyCanModify If true, adding and modifying connections is supported.
GetPropertyCanModify() (bool, error)
// GetPropertyHostname The machine hostname stored in persistent configuration.
GetPropertyHostname() (string, error)
}
func NewSettings() (Settings, error) {
var s settings
return &s, s.init(NetworkManagerInterface, SettingsObjectPath)
}
type settings struct {
dbusBase
}
func (s *settings) ListConnections() ([]Connection, error) {
var connectionPaths []dbus.ObjectPath
err := s.callWithReturn(&connectionPaths, SettingsListConnections)
if err != nil {
return nil, err
}
connections := make([]Connection, len(connectionPaths))
for i, path := range connectionPaths {
connections[i], err = NewConnection(path)
if err != nil {
return connections, err
}
}
return connections, nil
}
// ReloadConnections tells NetworkManager to reload (and apply) configuration files
// from disk taking notice of any added or removed connections.
func (s *settings) ReloadConnections() error {
return s.call(SettingsReloadConnections)
}
// GetConnectionByUUID gets the connection, given that connection's UUID.
func (s *settings) GetConnectionByUUID(uuid string) (Connection, error) {
var path dbus.ObjectPath
err := s.callWithReturn(&path, SettingsGetConnectionByUUID, uuid)
if err != nil {
return nil, err
}
return NewConnection(path)
}
func (s *settings) AddConnection(settings ConnectionSettings) (Connection, error) {
var path dbus.ObjectPath
err := s.callWithReturn(&path, SettingsAddConnection, settings)
if err != nil {
return nil, err
}
return NewConnection(path)
}
func (s *settings) AddConnectionUnsaved(settings ConnectionSettings) (Connection, error) {
var path dbus.ObjectPath
err := s.callWithReturn(&path, SettingsAddConnectionUnsaved, settings)
if err != nil {
return nil, err
}
return NewConnection(path)
}
func (s *settings) SaveHostname(hostname string) error {
return s.call(SettingsSaveHostname, hostname)
}
func (s *settings) GetPropertyHostname() (string, error) {
return s.getStringProperty(SettingsPropertyHostname)
}
func (s *settings) GetPropertyCanModify() (bool, error) {
return s.getBoolProperty(SettingsPropertyCanModify)
}
+45
View File
@@ -0,0 +1,45 @@
package gonetworkmanager
import (
"github.com/godbus/dbus/v5"
)
const (
VpnConnectionInterface = NetworkManagerInterface + ".VPN.Connection"
/* Properties */
VpnConnectionPropertyVpnState = VpnConnectionInterface + ".VpnState" // readable u
VpnConnectionPropertyBanner = VpnConnectionInterface + ".Banner" // readable s
)
type VpnConnection interface {
GetPath() dbus.ObjectPath
// GetPropertyVpnState The VPN-specific state of the connection.
GetPropertyVpnState() (NmVpnConnectionState, error)
// GetPropertyBanner The banner string of the VPN connection.
GetPropertyBanner() (string, error)
}
func NewVpnConnection(objectPath dbus.ObjectPath) (VpnConnection, error) {
var a vpnConnection
return &a, a.init(NetworkManagerInterface, objectPath)
}
type vpnConnection struct {
dbusBase
}
func (a *vpnConnection) GetPath() dbus.ObjectPath {
return a.obj.Path()
}
func (a *vpnConnection) GetPropertyVpnState() (NmVpnConnectionState, error) {
v, err := a.getUint32Property(VpnConnectionPropertyVpnState)
return NmVpnConnectionState(v), err
}
func (a *vpnConnection) GetPropertyBanner() (string, error) {
return a.getStringProperty(VpnConnectionPropertyBanner)
}
+293
View File
@@ -0,0 +1,293 @@
package gonetworkmanager
//go:generate stringer -type=NmConnectivity
type NmConnectivity uint32
const (
NmConnectivityUnknown NmConnectivity = 0 // Network connectivity is unknown. This means the connectivity checks are disabled (e.g. on server installations) or has not run yet. The graphical shell should assume the Internet connection might be available and not present a captive portal window.
NmConnectivityNone NmConnectivity = 1 // The host is not connected to any network. There's no active connection that contains a default route to the internet and thus it makes no sense to even attempt a connectivity check. The graphical shell should use this state to indicate the network connection is unavailable.
NmConnectivityPortal NmConnectivity = 2 // The Internet connection is hijacked by a captive portal gateway. The graphical shell may open a sandboxed web browser window (because the captive portals typically attempt a man-in-the-middle attacks against the https connections) for the purpose of authenticating to a gateway and retrigger the connectivity check with CheckConnectivity() when the browser window is dismissed.
NmConnectivityLimited NmConnectivity = 3 // The host is connected to a network, does not appear to be able to reach the full Internet, but a captive portal has not been detected.
NmConnectivityFull NmConnectivity = 4 // The host is connected to a network, and appears to be able to reach the full Internet.
)
//go:generate stringer -type=NmState
type NmState uint32
const (
NmStateUnknown NmState = 0 // Networking state is unknown. This indicates a daemon error that makes it unable to reasonably assess the state. In such event the applications are expected to assume Internet connectivity might be present and not disable controls that require network access. The graphical shells may hide the network accessibility indicator altogether since no meaningful status indication can be provided.
NmStateAsleep NmState = 10 // Networking is not enabled, the system is being suspended or resumed from suspend.
NmStateDisconnected NmState = 20 // There is no active network connection. The graphical shell should indicate no network connectivity and the applications should not attempt to access the network.
NmStateDisconnecting NmState = 30 // Network connections are being cleaned up. The applications should tear down their network sessions.
NmStateConnecting NmState = 40 // A network connection is being started The graphical shell should indicate the network is being connected while the applications should still make no attempts to connect the network.
NmStateConnectedLocal NmState = 50 // There is only local IPv4 and/or IPv6 connectivity, but no default route to access the Internet. The graphical shell should indicate no network connectivity.
NmStateConnectedSite NmState = 60 // There is only site-wide IPv4 and/or IPv6 connectivity. This means a default route is available, but the Internet connectivity check (see "Connectivity" property) did not succeed. The graphical shell should indicate limited network connectivity.
NmStateConnectedGlobal NmState = 70 // There is global IPv4 and/or IPv6 Internet connectivity This means the Internet connectivity check succeeded, the graphical shell should indicate full network connectivity.
)
//go:generate stringer -type=NmCheckpointCreateFlags
type NmCheckpointCreateFlags uint32
const (
NmCheckpointCreateFlagsNone NmCheckpointCreateFlags = 0 // no flags
NmCheckpointCreateFlagsDestroyAll NmCheckpointCreateFlags = 0x01 // when creating a new checkpoint, destroy all existing ones.
NmCheckpointCreateFlagsDeleteNewConnections NmCheckpointCreateFlags = 0x02 // upon rollback, delete any new connection added after the checkpoint (Since: 1.6)
NmCheckpointCreateFlagsDisconnectNewDevices NmCheckpointCreateFlags = 0x04 // upon rollback, disconnect any new device appeared after the checkpoint (Since: 1.6)
NmCheckpointCreateFlagsAllowOverlapping NmCheckpointCreateFlags = 0x08 // by default, creating a checkpoint fails if there are already existing checkoints that reference the same devices. With this flag, creation of such checkpoints is allowed, however, if an older checkpoint that references overlapping devices gets rolled back, it will automatically destroy this checkpoint during rollback. This allows to create several overlapping checkpoints in parallel, and rollback to them at will. With the special case that rolling back to an older checkpoint will invalidate all overlapping younger checkpoints. This opts-in that the checkpoint can be automatically destroyed by the rollback of an older checkpoint. (Since: 1.12)
)
//go:generate stringer -type=NmCapability
type NmCapability uint32
const (
NmCapabilityTeam NmCapability = 1 // Teams can be managed
)
//go:generate stringer -type=NmMetered
type NmMetered uint32
const (
NmMeteredUnknown NmMetered = 0 // The metered status is unknown
NmMeteredYes NmMetered = 1 // Metered, the value was statically set
NmMeteredNo NmMetered = 2 // Not metered, the value was statically set
NmMeteredGuessYes NmMetered = 3 // Metered, the value was guessed
NmMeteredGuessNo NmMetered = 4 // Not metered, the value was guessed
)
//go:generate stringer -type=NmDeviceState
type NmDeviceState uint32
const (
NmDeviceStateUnknown NmDeviceState = 0 // the device's state is unknown
NmDeviceStateUnmanaged NmDeviceState = 10 // the device is recognized, but not managed by NetworkManager
NmDeviceStateUnavailable NmDeviceState = 20 // the device is managed by NetworkManager, but is not available for use. Reasons may include the wireless switched off, missing firmware, no ethernet carrier, missing supplicant or modem manager, etc.
NmDeviceStateDisconnected NmDeviceState = 30 // the device can be activated, but is currently idle and not connected to a network.
NmDeviceStatePrepare NmDeviceState = 40 // the device is preparing the connection to the network. This may include operations like changing the MAC address, setting physical link properties, and anything else required to connect to the requested network.
NmDeviceStateConfig NmDeviceState = 50 // the device is connecting to the requested network. This may include operations like associating with the Wi-Fi AP, dialing the modem, connecting to the remote Bluetooth device, etc.
NmDeviceStateNeedAuth NmDeviceState = 60 // the device requires more information to continue connecting to the requested network. This includes secrets like WiFi passphrases, login passwords, PIN codes, etc.
NmDeviceStateIpConfig NmDeviceState = 70 // the device is requesting IPv4 and/or IPv6 addresses and routing information from the network.
NmDeviceStateIpCheck NmDeviceState = 80 // the device is checking whether further action is required for the requested network connection. This may include checking whether only local network access is available, whether a captive portal is blocking access to the Internet, etc.
NmDeviceStateSecondaries NmDeviceState = 90 // the device is waiting for a secondary connection (like a VPN) which must activated before the device can be activated
NmDeviceStateActivated NmDeviceState = 100 // the device has a network connection, either local or global.
NmDeviceStateDeactivating NmDeviceState = 110 // a disconnection from the current network connection was requested, and the device is cleaning up resources used for that connection. The network connection may still be valid.
NmDeviceStateFailed NmDeviceState = 120 // the device failed to connect to the requested network and is cleaning up the connection request
)
//go:generate stringer -type=NmActiveConnectionState
type NmActiveConnectionState uint32
const (
NmActiveConnectionStateUnknown NmActiveConnectionState = 0 // The state of the connection is unknown
NmActiveConnectionStateActivating NmActiveConnectionState = 1 // A network connection is being prepared
NmActiveConnectionStateActivated NmActiveConnectionState = 2 // There is a connection to the network
NmActiveConnectionStateDeactivating NmActiveConnectionState = 3 // The network connection is being torn down and cleaned up
NmActiveConnectionStateDeactivated NmActiveConnectionState = 4 // The network connection is disconnected and will be removed
)
//go:generate stringer -type=NmActivationStateFlag
type NmActivationStateFlag uint32
const (
NmActivationStateFlagNone NmActivationStateFlag = 0x00 // an alias for numeric zero, no flags set.
NmActivationStateFlagIsMaster NmActivationStateFlag = 0x01 // the device is a master.
NmActivationStateFlagIsSlave NmActivationStateFlag = 0x02 // the device is a slave.
NmActivationStateFlagLayer2Ready NmActivationStateFlag = 0x04 // layer2 is activated and ready.
NmActivationStateFlagIp4Ready NmActivationStateFlag = 0x08 // IPv4 setting is completed.
NmActivationStateFlagIp6Ready NmActivationStateFlag = 0x10 // IPv6 setting is completed.
NmActivationStateFlagMasterHasSlaves NmActivationStateFlag = 0x20 // The master has any slave devices attached. This only makes sense if the device is a master.
NmActivationStateFlagLifetimeBoundToProfileVisibility NmActivationStateFlag = 0x40 // the lifetime of the activation is bound to the visilibity of the connection profile, which in turn depends on "connection.permissions" and whether a session for the user exists. Since: 1.16
)
//go:generate stringer -type=NmDeviceType
type NmDeviceType uint32
const (
NmDeviceTypeUnknown NmDeviceType = 0 // unknown device
NmDeviceTypeGeneric NmDeviceType = 14 // generic support for unrecognized device types
NmDeviceTypeEthernet NmDeviceType = 1 // a wired ethernet device
NmDeviceTypeWifi NmDeviceType = 2 // an 802.11 Wi-Fi device
NmDeviceTypeUnused1 NmDeviceType = 3 // not used
NmDeviceTypeUnused2 NmDeviceType = 4 // not used
NmDeviceTypeBt NmDeviceType = 5 // a Bluetooth device supporting PAN or DUN access protocols
NmDeviceTypeOlpcMesh NmDeviceType = 6 // an OLPC XO mesh networking device
NmDeviceTypeWimax NmDeviceType = 7 // an 802.16e Mobile WiMAX broadband device
NmDeviceTypeModem NmDeviceType = 8 // a modem supporting analog telephone, CDMA/EVDO, GSM/UMTS, or LTE network access protocols
NmDeviceTypeInfiniband NmDeviceType = 9 // an IP-over-InfiniBand device
NmDeviceTypeBond NmDeviceType = 10 // a bond master interface
NmDeviceTypeVlan NmDeviceType = 11 // an 802.1Q VLAN interface
NmDeviceTypeAdsl NmDeviceType = 12 // ADSL modem
NmDeviceTypeBridge NmDeviceType = 13 // a bridge master interface
NmDeviceTypeTeam NmDeviceType = 15 // a team master interface
NmDeviceTypeTun NmDeviceType = 16 // a TUN or TAP interface
NmDeviceTypeIpTunnel NmDeviceType = 17 // a IP tunnel interface
NmDeviceTypeMacvlan NmDeviceType = 18 // a MACVLAN interface
NmDeviceTypeVxlan NmDeviceType = 19 // a VXLAN interface
NmDeviceTypeVeth NmDeviceType = 20 // a VETH interface
NmDeviceTypeMacsec NmDeviceType = 21 // a MACsec interface
NmDeviceTypeDummy NmDeviceType = 22 // a dummy interface
NmDeviceTypePpp NmDeviceType = 23 // a PPP interface
NmDeviceTypeOvsInterface NmDeviceType = 24 // a Open vSwitch interface
NmDeviceTypeOvsPort NmDeviceType = 25 // a Open vSwitch port
NmDeviceTypeOvsBridge NmDeviceType = 26 // a Open vSwitch bridge
NmDeviceTypeWpan NmDeviceType = 27 // a IEEE 802.15.4 (WPAN) MAC Layer Device
NmDeviceType6lowpan NmDeviceType = 28 // 6LoWPAN interface
NmDeviceTypeWireguard NmDeviceType = 29 // a WireGuard interface
NmDeviceTypeWifiP2p NmDeviceType = 30 // an 802.11 Wi-Fi P2P device (Since: 1.16)
)
//go:generate stringer -type=Nm80211APFlags
type Nm80211APFlags uint32
const (
Nm80211APFlagsNone Nm80211APFlags = 0x0
Nm80211APFlagsPrivacy Nm80211APFlags = 0x1
)
//go:generate stringer -type=Nm80211APSec
type Nm80211APSec uint32
const (
Nm80211APSecNone Nm80211APSec = 0x0
Nm80211APSecPairWEP40 Nm80211APSec = 0x1
Nm80211APSecPairWEP104 Nm80211APSec = 0x2
Nm80211APSecPairTKIP Nm80211APSec = 0x4
Nm80211APSecPairCCMP Nm80211APSec = 0x8
Nm80211APSecGroupWEP40 Nm80211APSec = 0x10
Nm80211APSecGroupWEP104 Nm80211APSec = 0x20
Nm80211APSecGroupTKIP Nm80211APSec = 0x40
Nm80211APSecGroupCCMP Nm80211APSec = 0x80
Nm80211APSecKeyMgmtPSK Nm80211APSec = 0x100
Nm80211APSecKeyMgmt8021X Nm80211APSec = 0x200
Nm80211APSecKeyMgmtSAE Nm80211APSec = 0x400
Nm80211APSecKeyMgmtOWE Nm80211APSec = 0x800
Nm80211APSecKeyMgmtOWETM Nm80211APSec = 0x1000
)
//go:generate stringer -type=Nm80211Mode
type Nm80211Mode uint32
const (
Nm80211ModeUnknown Nm80211Mode = 0
Nm80211ModeAdhoc Nm80211Mode = 1
Nm80211ModeInfra Nm80211Mode = 2
Nm80211ModeAp Nm80211Mode = 3
)
//go:generate stringer -type=NmActiveConnectionState
type NmVpnConnectionState uint32
const (
NmVpnConnectionUnknown = 0 //The state of the VPN connection is unknown.
NmVpnConnectionPrepare = 1 //The VPN connection is preparing to connect.
NmVpnConnectionNeedAuth = 2 //The VPN connection needs authorization credentials.
NmVpnConnectionConnect = 3 //The VPN connection is being established.
NmVpnConnectionIpConfigGet = 4 //The VPN connection is getting an IP address.
NmVpnConnectionActivated = 5 //The VPN connection is active.
NmVpnConnectionFailed = 6 //The VPN connection failed.
NmVpnConnectionDisconnected = 7 //The VPN connection is disconnected.
)
//go:generate stringer -type=NmDeviceStateReason
type NmDeviceStateReason uint32
const (
NmDeviceStateReasonNone = 0 // No reason given
NmDeviceStateReasonUnknown = 1 // Unknown error
NmDeviceStateReasonNowManaged = 2 // Device is now managed
NmDeviceStateReasonNowUnmanaged = 3 // Device is now unmanaged
NmDeviceStateReasonConfigFailed = 4 // The device could not be readied for configuration
NmDeviceStateReasonIpConfigUnavailable = 5 // IP configuration could not be reserved (no available address, timeout, etc)
NmDeviceStateReasonIpConfigExpired = 6 // The IP config is no longer valid
NmDeviceStateReasonNoSecrets = 7 // Secrets were required, but not provided
NmDeviceStateReasonSupplicantDisconnect = 8 // 802.1x supplicant disconnected
NmDeviceStateReasonSupplicantConfigFailed = 9 // 802.1x supplicant configuration failed
NmDeviceStateReasonSupplicantFailed = 10 // 802.1x supplicant failed
NmDeviceStateReasonSupplicantTimeout = 11 // 802.1x supplicant took too long to authenticate
NmDeviceStateReasonPppStartFailed = 12 // PPP service failed to start
NmDeviceStateReasonPppDisconnect = 13 // PPP service disconnected
NmDeviceStateReasonPppFailed = 14 // PPP failed
NmDeviceStateReasonDhcpStartFailed = 15 // DHCP client failed to start
NmDeviceStateReasonDhcpError = 16 // DHCP client error
NmDeviceStateReasonDhcpFailed = 17 // DHCP client failed
NmDeviceStateReasonSharedStartFailed = 18 // Shared connection service failed to start
NmDeviceStateReasonSharedFailed = 19 // Shared connection service failed
NmDeviceStateReasonAutoipStartFailed = 20 // AutoIP service failed to start
NmDeviceStateReasonAutoipError = 21 // AutoIP service error
NmDeviceStateReasonAutoipFailed = 22 // AutoIP service failed
NmDeviceStateReasonModemBusy = 23 // The line is busy
NmDeviceStateReasonModemNoDialTone = 24 // No dial tone
NmDeviceStateReasonModemNoCarrier = 25 // No carrier could be established
NmDeviceStateReasonModemDialTimeout = 26 // The dialing request timed out
NmDeviceStateReasonModemDialFailed = 27 // The dialing attempt failed
NmDeviceStateReasonModemInitFailed = 28 // Modem initialization failed
NmDeviceStateReasonGsmApnFailed = 29 // Failed to select the specified APN
NmDeviceStateReasonGsmRegistrationNotSearching = 30 // Not searching for networks
NmDeviceStateReasonGsmRegistrationDenied = 31 // Network registration denied
NmDeviceStateReasonGsmRegistrationTimeout = 32 // Network registration timed out
NmDeviceStateReasonGsmRegistrationFailed = 33 // Failed to register with the requested network
NmDeviceStateReasonGsmPinCheckFailed = 34 // PIN check failed
NmDeviceStateReasonFirmwareMissing = 35 // Necessary firmware for the device may be missing
NmDeviceStateReasonRemoved = 36 // The device was removed
NmDeviceStateReasonSleeping = 37 // NetworkManager went to sleep
NmDeviceStateReasonConnectionRemoved = 38 // The device's active connection disappeared
NmDeviceStateReasonUserRequested = 39 // Device disconnected by user or client
NmDeviceStateReasonCarrier = 40 // Carrier/link changed
NmDeviceStateReasonConnectionAssumed = 41 // The device's existing connection was assumed
NmDeviceStateReasonSupplicantAvailable = 42 // The supplicant is now available
NmDeviceStateReasonModemNotFound = 43 // The modem could not be found
NmDeviceStateReasonBtFailed = 44 // The Bluetooth connection failed or timed out
NmDeviceStateReasonGsmSimNotInserted = 45 // GSM Modem's SIM Card not inserted
NmDeviceStateReasonGsmSimPinRequired = 46 // GSM Modem's SIM Pin required
NmDeviceStateReasonGsmSimPukRequired = 47 // GSM Modem's SIM Puk required
NmDeviceStateReasonGsmSimWrong = 48 // GSM Modem's SIM wrong
NmDeviceStateReasonInfinibandMode = 49 // InfiniBand device does not support connected mode
NmDeviceStateReasonDependencyFailed = 50 // A dependency of the connection failed
NmDeviceStateReasonBr2684Failed = 51 // Problem with the RFC 2684 Ethernet over ADSL bridge
NmDeviceStateReasonModemManagerUnavailable = 52 // ModemManager not running
NmDeviceStateReasonSsidNotFound = 53 // The Wi-Fi network could not be found
NmDeviceStateReasonSecondaryConnectionFailed = 54 // A secondary connection of the base connection failed
NmDeviceStateReasonDcbFcoeFailed = 55 // DCB or FCoE setup failed
NmDeviceStateReasonTeamdControlFailed = 56 // teamd control failed
NmDeviceStateReasonModemFailed = 57 // Modem failed or no longer available
NmDeviceStateReasonModemAvailable = 58 // Modem now ready and available
NmDeviceStateReasonSimPinIncorrect = 59 // SIM PIN was incorrect
NmDeviceStateReasonNewActivation = 60 // New connection activation was enqueued
NmDeviceStateReasonParentChanged = 61 // the device's parent changed
NmDeviceStateReasonParentManagedChanged = 62 // the device parent's management changed
NmDeviceStateReasonOvsdbFailed = 63 // problem communicating with Open vSwitch database
NmDeviceStateReasonIpAddressDuplicate = 64 // a duplicate IP address was detected
NmDeviceStateReasonIpMethodUnsupported = 65 // The selected IP method is not supported
NmDeviceStateReasonSriovConfigurationFailed = 66 // configuration of SR-IOV parameters failed
NmDeviceStateReasonPeerNotFound = 67 // The Wi-Fi P2P peer could not be found
)
//go:generate stringer -type=NmActiveConnectionStateReason
type NmActiveConnectionStateReason uint32
const (
NmActiveConnectionStateReasonUnknown = 0 // The reason for the active connection state change is unknown.
NmActiveConnectionStateReasonNone = 1 // No reason was given for the active connection state change.
NmActiveConnectionStateReasonUserDisconnected = 2 // The active connection changed state because the user disconnected it.
NmActiveConnectionStateReasonDeviceDisconnected = 3 // The active connection changed state because the device it was using was disconnected.
NmActiveConnectionStateReasonServiceStopped = 4 // The service providing the VPN connection was stopped.
NmActiveConnectionStateReasonIpConfigInvalid = 5 // The IP config of the active connection was invalid.
NmActiveConnectionStateReasonConnectTimeout = 6 // The connection attempt to the VPN service timed out.
NmActiveConnectionStateReasonServiceStartTimeout = 7 // A timeout occurred while starting the service providing the VPN connection.
NmActiveConnectionStateReasonServiceStartFailed = 8 // Starting the service providing the VPN connection failed.
NmActiveConnectionStateReasonNoSecrets = 9 // Necessary secrets for the connection were not provided.
NmActiveConnectionStateReasonLoginFailed = 10 // Authentication to the server failed.
NmActiveConnectionStateReasonConnectionRemoved = 11 // The connection was deleted from settings.
NmActiveConnectionStateReasonDependencyFailed = 12 // Master connection of this connection failed to activate.
NmActiveConnectionStateReasonDeviceRealizeFailed = 13 // Could not create the software device link.
NmActiveConnectionStateReasonDeviceRemoved = 14 // The device this connection depended on disappeared.
)
//go:generate stringer -type=NmRollbackResult
type NmRollbackResult uint32
const (
NmRollbackResultOk = 0 // the rollback succeeded.
NmRollbackResultErrNoDevice = 1 // the device no longer exists.
NmRollbackResultErrDeviceUnmanaged = 2 // the device is now unmanaged.
NmRollbackResultErrFailed = 3 // other errors during rollback.
)
@@ -0,0 +1,24 @@
// Code generated by "stringer -type=Nm80211APFlags"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Nm80211APFlagsNone-0]
_ = x[Nm80211APFlagsPrivacy-1]
}
const _Nm80211APFlags_name = "Nm80211APFlagsNoneNm80211APFlagsPrivacy"
var _Nm80211APFlags_index = [...]uint8{0, 18, 39}
func (i Nm80211APFlags) String() string {
if i >= Nm80211APFlags(len(_Nm80211APFlags_index)-1) {
return "Nm80211APFlags(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Nm80211APFlags_name[_Nm80211APFlags_index[i]:_Nm80211APFlags_index[i+1]]
}
@@ -0,0 +1,51 @@
// Code generated by "stringer -type=Nm80211APSec"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Nm80211APSecNone-0]
_ = x[Nm80211APSecPairWEP40-1]
_ = x[Nm80211APSecPairWEP104-2]
_ = x[Nm80211APSecPairTKIP-4]
_ = x[Nm80211APSecPairCCMP-8]
_ = x[Nm80211APSecGroupWEP40-16]
_ = x[Nm80211APSecGroupWEP104-32]
_ = x[Nm80211APSecGroupTKIP-64]
_ = x[Nm80211APSecGroupCCMP-128]
_ = x[Nm80211APSecKeyMgmtPSK-256]
_ = x[Nm80211APSecKeyMgmt8021X-512]
_ = x[Nm80211APSecKeyMgmtSAE-1024]
_ = x[Nm80211APSecKeyMgmtOWE-2048]
_ = x[Nm80211APSecKeyMgmtOWETM-4096]
}
const _Nm80211APSec_name = "Nm80211APSecNoneNm80211APSecPairWEP40Nm80211APSecPairWEP104Nm80211APSecPairTKIPNm80211APSecPairCCMPNm80211APSecGroupWEP40Nm80211APSecGroupWEP104Nm80211APSecGroupTKIPNm80211APSecGroupCCMPNm80211APSecKeyMgmtPSKNm80211APSecKeyMgmt8021XNm80211APSecKeyMgmtSAENm80211APSecKeyMgmtOWENm80211APSecKeyMgmtOWETM"
var _Nm80211APSec_map = map[Nm80211APSec]string{
0: _Nm80211APSec_name[0:16],
1: _Nm80211APSec_name[16:37],
2: _Nm80211APSec_name[37:59],
4: _Nm80211APSec_name[59:79],
8: _Nm80211APSec_name[79:99],
16: _Nm80211APSec_name[99:121],
32: _Nm80211APSec_name[121:144],
64: _Nm80211APSec_name[144:165],
128: _Nm80211APSec_name[165:186],
256: _Nm80211APSec_name[186:208],
512: _Nm80211APSec_name[208:232],
1024: _Nm80211APSec_name[232:254],
2048: _Nm80211APSec_name[254:276],
4096: _Nm80211APSec_name[276:300],
}
func (i Nm80211APSec) String() string {
if str, ok := _Nm80211APSec_map[i]; ok {
return str
}
return "Nm80211APSec(" + strconv.FormatInt(int64(i), 10) + ")"
}
@@ -0,0 +1,26 @@
// Code generated by "stringer -type=Nm80211Mode"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Nm80211ModeUnknown-0]
_ = x[Nm80211ModeAdhoc-1]
_ = x[Nm80211ModeInfra-2]
_ = x[Nm80211ModeAp-3]
}
const _Nm80211Mode_name = "Nm80211ModeUnknownNm80211ModeAdhocNm80211ModeInfraNm80211ModeAp"
var _Nm80211Mode_index = [...]uint8{0, 18, 34, 50, 63}
func (i Nm80211Mode) String() string {
if i >= Nm80211Mode(len(_Nm80211Mode_index)-1) {
return "Nm80211Mode(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Nm80211Mode_name[_Nm80211Mode_index[i]:_Nm80211Mode_index[i+1]]
}
@@ -0,0 +1,51 @@
// Code generated by "stringer -type=NmActivationStateFlag"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[NmActivationStateFlagNone-0]
_ = x[NmActivationStateFlagIsMaster-1]
_ = x[NmActivationStateFlagIsSlave-2]
_ = x[NmActivationStateFlagLayer2Ready-4]
_ = x[NmActivationStateFlagIp4Ready-8]
_ = x[NmActivationStateFlagIp6Ready-16]
_ = x[NmActivationStateFlagMasterHasSlaves-32]
_ = x[NmActivationStateFlagLifetimeBoundToProfileVisibility-64]
}
const (
_NmActivationStateFlag_name_0 = "NmActivationStateFlagNoneNmActivationStateFlagIsMasterNmActivationStateFlagIsSlave"
_NmActivationStateFlag_name_1 = "NmActivationStateFlagLayer2Ready"
_NmActivationStateFlag_name_2 = "NmActivationStateFlagIp4Ready"
_NmActivationStateFlag_name_3 = "NmActivationStateFlagIp6Ready"
_NmActivationStateFlag_name_4 = "NmActivationStateFlagMasterHasSlaves"
_NmActivationStateFlag_name_5 = "NmActivationStateFlagLifetimeBoundToProfileVisibility"
)
var (
_NmActivationStateFlag_index_0 = [...]uint8{0, 25, 54, 82}
)
func (i NmActivationStateFlag) String() string {
switch {
case 0 <= i && i <= 2:
return _NmActivationStateFlag_name_0[_NmActivationStateFlag_index_0[i]:_NmActivationStateFlag_index_0[i+1]]
case i == 4:
return _NmActivationStateFlag_name_1
case i == 8:
return _NmActivationStateFlag_name_2
case i == 16:
return _NmActivationStateFlag_name_3
case i == 32:
return _NmActivationStateFlag_name_4
case i == 64:
return _NmActivationStateFlag_name_5
default:
return "NmActivationStateFlag(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
@@ -0,0 +1,27 @@
// Code generated by "stringer -type=NmActiveConnectionState"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[NmActiveConnectionStateUnknown-0]
_ = x[NmActiveConnectionStateActivating-1]
_ = x[NmActiveConnectionStateActivated-2]
_ = x[NmActiveConnectionStateDeactivating-3]
_ = x[NmActiveConnectionStateDeactivated-4]
}
const _NmActiveConnectionState_name = "NmActiveConnectionStateUnknownNmActiveConnectionStateActivatingNmActiveConnectionStateActivatedNmActiveConnectionStateDeactivatingNmActiveConnectionStateDeactivated"
var _NmActiveConnectionState_index = [...]uint8{0, 30, 63, 95, 130, 164}
func (i NmActiveConnectionState) String() string {
if i >= NmActiveConnectionState(len(_NmActiveConnectionState_index)-1) {
return "NmActiveConnectionState(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _NmActiveConnectionState_name[_NmActiveConnectionState_index[i]:_NmActiveConnectionState_index[i+1]]
}
@@ -0,0 +1,24 @@
// Code generated by "stringer -type=NmCapability"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[NmCapabilityTeam-1]
}
const _NmCapability_name = "NmCapabilityTeam"
var _NmCapability_index = [...]uint8{0, 16}
func (i NmCapability) String() string {
i -= 1
if i >= NmCapability(len(_NmCapability_index)-1) {
return "NmCapability(" + strconv.FormatInt(int64(i+1), 10) + ")"
}
return _NmCapability_name[_NmCapability_index[i]:_NmCapability_index[i+1]]
}
@@ -0,0 +1,39 @@
// Code generated by "stringer -type=NmCheckpointCreateFlags"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[NmCheckpointCreateFlagsNone-0]
_ = x[NmCheckpointCreateFlagsDestroyAll-1]
_ = x[NmCheckpointCreateFlagsDeleteNewConnections-2]
_ = x[NmCheckpointCreateFlagsDisconnectNewDevices-4]
_ = x[NmCheckpointCreateFlagsAllowOverlapping-8]
}
const (
_NmCheckpointCreateFlags_name_0 = "NmCheckpointCreateFlagsNoneNmCheckpointCreateFlagsDestroyAllNmCheckpointCreateFlagsDeleteNewConnections"
_NmCheckpointCreateFlags_name_1 = "NmCheckpointCreateFlagsDisconnectNewDevices"
_NmCheckpointCreateFlags_name_2 = "NmCheckpointCreateFlagsAllowOverlapping"
)
var (
_NmCheckpointCreateFlags_index_0 = [...]uint8{0, 27, 60, 103}
)
func (i NmCheckpointCreateFlags) String() string {
switch {
case 0 <= i && i <= 2:
return _NmCheckpointCreateFlags_name_0[_NmCheckpointCreateFlags_index_0[i]:_NmCheckpointCreateFlags_index_0[i+1]]
case i == 4:
return _NmCheckpointCreateFlags_name_1
case i == 8:
return _NmCheckpointCreateFlags_name_2
default:
return "NmCheckpointCreateFlags(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
@@ -0,0 +1,27 @@
// Code generated by "stringer -type=NmConnectivity"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[NmConnectivityUnknown-0]
_ = x[NmConnectivityNone-1]
_ = x[NmConnectivityPortal-2]
_ = x[NmConnectivityLimited-3]
_ = x[NmConnectivityFull-4]
}
const _NmConnectivity_name = "NmConnectivityUnknownNmConnectivityNoneNmConnectivityPortalNmConnectivityLimitedNmConnectivityFull"
var _NmConnectivity_index = [...]uint8{0, 21, 39, 59, 80, 98}
func (i NmConnectivity) String() string {
if i >= NmConnectivity(len(_NmConnectivity_index)-1) {
return "NmConnectivity(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _NmConnectivity_name[_NmConnectivity_index[i]:_NmConnectivity_index[i+1]]
}
@@ -0,0 +1,49 @@
// Code generated by "stringer -type=NmDeviceState"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[NmDeviceStateUnknown-0]
_ = x[NmDeviceStateUnmanaged-10]
_ = x[NmDeviceStateUnavailable-20]
_ = x[NmDeviceStateDisconnected-30]
_ = x[NmDeviceStatePrepare-40]
_ = x[NmDeviceStateConfig-50]
_ = x[NmDeviceStateNeedAuth-60]
_ = x[NmDeviceStateIpConfig-70]
_ = x[NmDeviceStateIpCheck-80]
_ = x[NmDeviceStateSecondaries-90]
_ = x[NmDeviceStateActivated-100]
_ = x[NmDeviceStateDeactivating-110]
_ = x[NmDeviceStateFailed-120]
}
const _NmDeviceState_name = "NmDeviceStateUnknownNmDeviceStateUnmanagedNmDeviceStateUnavailableNmDeviceStateDisconnectedNmDeviceStatePrepareNmDeviceStateConfigNmDeviceStateNeedAuthNmDeviceStateIpConfigNmDeviceStateIpCheckNmDeviceStateSecondariesNmDeviceStateActivatedNmDeviceStateDeactivatingNmDeviceStateFailed"
var _NmDeviceState_map = map[NmDeviceState]string{
0: _NmDeviceState_name[0:20],
10: _NmDeviceState_name[20:42],
20: _NmDeviceState_name[42:66],
30: _NmDeviceState_name[66:91],
40: _NmDeviceState_name[91:111],
50: _NmDeviceState_name[111:130],
60: _NmDeviceState_name[130:151],
70: _NmDeviceState_name[151:172],
80: _NmDeviceState_name[172:192],
90: _NmDeviceState_name[192:216],
100: _NmDeviceState_name[216:238],
110: _NmDeviceState_name[238:263],
120: _NmDeviceState_name[263:282],
}
func (i NmDeviceState) String() string {
if str, ok := _NmDeviceState_map[i]; ok {
return str
}
return "NmDeviceState(" + strconv.FormatInt(int64(i), 10) + ")"
}
@@ -0,0 +1,53 @@
// Code generated by "stringer -type=NmDeviceType"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[NmDeviceTypeUnknown-0]
_ = x[NmDeviceTypeGeneric-14]
_ = x[NmDeviceTypeEthernet-1]
_ = x[NmDeviceTypeWifi-2]
_ = x[NmDeviceTypeUnused1-3]
_ = x[NmDeviceTypeUnused2-4]
_ = x[NmDeviceTypeBt-5]
_ = x[NmDeviceTypeOlpcMesh-6]
_ = x[NmDeviceTypeWimax-7]
_ = x[NmDeviceTypeModem-8]
_ = x[NmDeviceTypeInfiniband-9]
_ = x[NmDeviceTypeBond-10]
_ = x[NmDeviceTypeVlan-11]
_ = x[NmDeviceTypeAdsl-12]
_ = x[NmDeviceTypeBridge-13]
_ = x[NmDeviceTypeTeam-15]
_ = x[NmDeviceTypeTun-16]
_ = x[NmDeviceTypeIpTunnel-17]
_ = x[NmDeviceTypeMacvlan-18]
_ = x[NmDeviceTypeVxlan-19]
_ = x[NmDeviceTypeVeth-20]
_ = x[NmDeviceTypeMacsec-21]
_ = x[NmDeviceTypeDummy-22]
_ = x[NmDeviceTypePpp-23]
_ = x[NmDeviceTypeOvsInterface-24]
_ = x[NmDeviceTypeOvsPort-25]
_ = x[NmDeviceTypeOvsBridge-26]
_ = x[NmDeviceTypeWpan-27]
_ = x[NmDeviceType6lowpan-28]
_ = x[NmDeviceTypeWireguard-29]
_ = x[NmDeviceTypeWifiP2p-30]
}
const _NmDeviceType_name = "NmDeviceTypeUnknownNmDeviceTypeEthernetNmDeviceTypeWifiNmDeviceTypeUnused1NmDeviceTypeUnused2NmDeviceTypeBtNmDeviceTypeOlpcMeshNmDeviceTypeWimaxNmDeviceTypeModemNmDeviceTypeInfinibandNmDeviceTypeBondNmDeviceTypeVlanNmDeviceTypeAdslNmDeviceTypeBridgeNmDeviceTypeGenericNmDeviceTypeTeamNmDeviceTypeTunNmDeviceTypeIpTunnelNmDeviceTypeMacvlanNmDeviceTypeVxlanNmDeviceTypeVethNmDeviceTypeMacsecNmDeviceTypeDummyNmDeviceTypePppNmDeviceTypeOvsInterfaceNmDeviceTypeOvsPortNmDeviceTypeOvsBridgeNmDeviceTypeWpanNmDeviceType6lowpanNmDeviceTypeWireguardNmDeviceTypeWifiP2p"
var _NmDeviceType_index = [...]uint16{0, 19, 39, 55, 74, 93, 107, 127, 144, 161, 183, 199, 215, 231, 249, 268, 284, 299, 319, 338, 355, 371, 389, 406, 421, 445, 464, 485, 501, 520, 541, 560}
func (i NmDeviceType) String() string {
if i >= NmDeviceType(len(_NmDeviceType_index)-1) {
return "NmDeviceType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _NmDeviceType_name[_NmDeviceType_index[i]:_NmDeviceType_index[i+1]]
}
+27
View File
@@ -0,0 +1,27 @@
// Code generated by "stringer -type=NmMetered"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[NmMeteredUnknown-0]
_ = x[NmMeteredYes-1]
_ = x[NmMeteredNo-2]
_ = x[NmMeteredGuessYes-3]
_ = x[NmMeteredGuessNo-4]
}
const _NmMetered_name = "NmMeteredUnknownNmMeteredYesNmMeteredNoNmMeteredGuessYesNmMeteredGuessNo"
var _NmMetered_index = [...]uint8{0, 16, 28, 39, 56, 72}
func (i NmMetered) String() string {
if i >= NmMetered(len(_NmMetered_index)-1) {
return "NmMetered(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _NmMetered_name[_NmMetered_index[i]:_NmMetered_index[i+1]]
}
+53
View File
@@ -0,0 +1,53 @@
// Code generated by "stringer -type=NmState"; DO NOT EDIT.
package gonetworkmanager
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[NmStateUnknown-0]
_ = x[NmStateAsleep-10]
_ = x[NmStateDisconnected-20]
_ = x[NmStateDisconnecting-30]
_ = x[NmStateConnecting-40]
_ = x[NmStateConnectedLocal-50]
_ = x[NmStateConnectedSite-60]
_ = x[NmStateConnectedGlobal-70]
}
const (
_NmState_name_0 = "NmStateUnknown"
_NmState_name_1 = "NmStateAsleep"
_NmState_name_2 = "NmStateDisconnected"
_NmState_name_3 = "NmStateDisconnecting"
_NmState_name_4 = "NmStateConnecting"
_NmState_name_5 = "NmStateConnectedLocal"
_NmState_name_6 = "NmStateConnectedSite"
_NmState_name_7 = "NmStateConnectedGlobal"
)
func (i NmState) String() string {
switch {
case i == 0:
return _NmState_name_0
case i == 10:
return _NmState_name_1
case i == 20:
return _NmState_name_2
case i == 30:
return _NmState_name_3
case i == 40:
return _NmState_name_4
case i == 50:
return _NmState_name_5
case i == 60:
return _NmState_name_6
case i == 70:
return _NmState_name_7
default:
return "NmState(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
+282
View File
@@ -0,0 +1,282 @@
package gonetworkmanager
import (
"encoding/binary"
"fmt"
"net"
"github.com/godbus/dbus/v5"
)
const (
dbusMethodAddMatch = "org.freedesktop.DBus.AddMatch"
)
type dbusBase struct {
conn *dbus.Conn
obj dbus.BusObject
}
func (d *dbusBase) init(iface string, objectPath dbus.ObjectPath) error {
var err error
d.conn, err = dbus.SystemBus()
if err != nil {
return err
}
d.obj = d.conn.Object(iface, objectPath)
return nil
}
func (d *dbusBase) call(method string, args ...interface{}) error {
return d.obj.Call(method, 0, args...).Err
}
func (d *dbusBase) callWithReturn(ret interface{}, method string, args ...interface{}) error {
return d.obj.Call(method, 0, args...).Store(ret)
}
func (d *dbusBase) callWithReturn2(ret1 interface{}, ret2 interface{}, method string, args ...interface{}) error {
return d.obj.Call(method, 0, args...).Store(ret1, ret2)
}
func (d *dbusBase) subscribe(iface, member string) {
rule := fmt.Sprintf("type='signal',interface='%s',path='%s',member='%s'",
iface, d.obj.Path(), NetworkManagerInterface)
d.conn.BusObject().Call(dbusMethodAddMatch, 0, rule)
}
func (d *dbusBase) subscribeNamespace(namespace string) {
rule := fmt.Sprintf("type='signal',path_namespace='%s'", namespace)
d.conn.BusObject().Call(dbusMethodAddMatch, 0, rule)
}
func (d *dbusBase) getProperty(iface string) (interface{}, error) {
variant, err := d.obj.GetProperty(iface)
return variant.Value(), err
}
func (d *dbusBase) setProperty(iface string, value interface{}) error {
err := d.obj.SetProperty(iface, dbus.MakeVariant(value))
return err
}
func (d *dbusBase) getObjectProperty(iface string) (value dbus.ObjectPath, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.(dbus.ObjectPath)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getSliceObjectProperty(iface string) (value []dbus.ObjectPath, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.([]dbus.ObjectPath)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getBoolProperty(iface string) (value bool, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.(bool)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getStringProperty(iface string) (value string, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.(string)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getSliceStringProperty(iface string) (value []string, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.([]string)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getSliceSliceByteProperty(iface string) (value [][]byte, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.([][]byte)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getMapStringVariantProperty(iface string) (value map[string]dbus.Variant, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.(map[string]dbus.Variant)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getUint8Property(iface string) (value uint8, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.(uint8)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getUint32Property(iface string) (value uint32, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.(uint32)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getInt32Property(iface string) (value int32, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.(int32)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getInt64Property(iface string) (value int64, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.(int64)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getUint64Property(iface string) (value uint64, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.(uint64)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getSliceUint32Property(iface string) (value []uint32, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.([]uint32)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getSliceSliceUint32Property(iface string) (value [][]uint32, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.([][]uint32)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getSliceMapStringVariantProperty(iface string) (value []map[string]dbus.Variant, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.([]map[string]dbus.Variant)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func (d *dbusBase) getSliceByteProperty(iface string) (value []byte, err error) {
prop, err := d.getProperty(iface)
if err != nil {
return
}
value, ok := prop.([]byte)
if !ok {
err = makeErrVariantType(iface)
return
}
return
}
func makeErrVariantType(iface string) error {
return fmt.Errorf("unexpected variant type for '%s'", iface)
}
func ip4ToString(ip uint32) string {
bs := []byte{0, 0, 0, 0}
binary.LittleEndian.PutUint32(bs, ip)
return net.IP(bs).String()
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Eric Woroshow
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+5
View File
@@ -0,0 +1,5 @@
//go:build required
// +build required
// Package dummy prevents go tooling from stripping the c dependencies.
package dummy
+290
View File
@@ -0,0 +1,290 @@
#ifndef __khrplatform_h_
#define __khrplatform_h_
/*
** Copyright (c) 2008-2018 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Khronos platform-specific types and definitions.
*
* The master copy of khrplatform.h is maintained in the Khronos EGL
* Registry repository at https://github.com/KhronosGroup/EGL-Registry
* The last semantic modification to khrplatform.h was at commit ID:
* 67a3e0864c2d75ea5287b9f3d2eb74a745936692
*
* Adopters may modify this file to suit their platform. Adopters are
* encouraged to submit platform specific modifications to the Khronos
* group so that they can be included in future versions of this file.
* Please submit changes by filing pull requests or issues on
* the EGL Registry repository linked above.
*
*
* See the Implementer's Guidelines for information about where this file
* should be located on your system and for more details of its use:
* http://www.khronos.org/registry/implementers_guide.pdf
*
* This file should be included as
* #include <KHR/khrplatform.h>
* by Khronos client API header files that use its types and defines.
*
* The types in khrplatform.h should only be used to define API-specific types.
*
* Types defined in khrplatform.h:
* khronos_int8_t signed 8 bit
* khronos_uint8_t unsigned 8 bit
* khronos_int16_t signed 16 bit
* khronos_uint16_t unsigned 16 bit
* khronos_int32_t signed 32 bit
* khronos_uint32_t unsigned 32 bit
* khronos_int64_t signed 64 bit
* khronos_uint64_t unsigned 64 bit
* khronos_intptr_t signed same number of bits as a pointer
* khronos_uintptr_t unsigned same number of bits as a pointer
* khronos_ssize_t signed size
* khronos_usize_t unsigned size
* khronos_float_t signed 32 bit floating point
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
* nanoseconds
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
* khronos_boolean_enum_t enumerated boolean type. This should
* only be used as a base type when a client API's boolean type is
* an enum. Client APIs which use an integer or other type for
* booleans cannot use this as the base type for their boolean.
*
* Tokens defined in khrplatform.h:
*
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
*
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
*
* Calling convention macros defined in this file:
* KHRONOS_APICALL
* KHRONOS_APIENTRY
* KHRONOS_APIATTRIBUTES
*
* These may be used in function prototypes as:
*
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
* int arg1,
* int arg2) KHRONOS_APIATTRIBUTES;
*/
#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC)
# define KHRONOS_STATIC 1
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APICALL
*-------------------------------------------------------------------------
* This precedes the return type of the function in the function prototype.
*/
#if defined(KHRONOS_STATIC)
/* If the preprocessor constant KHRONOS_STATIC is defined, make the
* header compatible with static linking. */
# define KHRONOS_APICALL
#elif defined(_WIN32)
# define KHRONOS_APICALL __declspec(dllimport)
#elif defined (__SYMBIAN32__)
# define KHRONOS_APICALL IMPORT_C
#elif defined(__ANDROID__)
# define KHRONOS_APICALL __attribute__((visibility("default")))
#else
# define KHRONOS_APICALL
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIENTRY
*-------------------------------------------------------------------------
* This follows the return type of the function and precedes the function
* name in the function prototype.
*/
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
/* Win32 but not WinCE */
# define KHRONOS_APIENTRY __stdcall
#else
# define KHRONOS_APIENTRY
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIATTRIBUTES
*-------------------------------------------------------------------------
* This follows the closing parenthesis of the function prototype arguments.
*/
#if defined (__ARMCC_2__)
#define KHRONOS_APIATTRIBUTES __softfp
#else
#define KHRONOS_APIATTRIBUTES
#endif
/*-------------------------------------------------------------------------
* basic type definitions
*-----------------------------------------------------------------------*/
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
/*
* Using <stdint.h>
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__VMS ) || defined(__sgi)
/*
* Using <inttypes.h>
*/
#include <inttypes.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
/*
* Win32
*/
typedef __int32 khronos_int32_t;
typedef unsigned __int32 khronos_uint32_t;
typedef __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__sun__) || defined(__digital__)
/*
* Sun or Digital
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#if defined(__arch64__) || defined(_LP64)
typedef long int khronos_int64_t;
typedef unsigned long int khronos_uint64_t;
#else
typedef long long int khronos_int64_t;
typedef unsigned long long int khronos_uint64_t;
#endif /* __arch64__ */
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif 0
/*
* Hypothetical platform with no float or int64 support
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#define KHRONOS_SUPPORT_INT64 0
#define KHRONOS_SUPPORT_FLOAT 0
#else
/*
* Generic fallback
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#endif
/*
* Types that are (so far) the same on all platforms
*/
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
/*
* Types that differ between LLP64 and LP64 architectures - in LLP64,
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
* to be the only LLP64 architecture in current use.
*/
#ifdef _WIN64
typedef signed long long int khronos_intptr_t;
typedef unsigned long long int khronos_uintptr_t;
typedef signed long long int khronos_ssize_t;
typedef unsigned long long int khronos_usize_t;
#else
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#endif
#if KHRONOS_SUPPORT_FLOAT
/*
* Float type
*/
typedef float khronos_float_t;
#endif
#if KHRONOS_SUPPORT_INT64
/* Time types
*
* These types can be used to represent a time interval in nanoseconds or
* an absolute Unadjusted System Time. Unadjusted System Time is the number
* of nanoseconds since some arbitrary system event (e.g. since the last
* time the system booted). The Unadjusted System Time is an unsigned
* 64 bit value that wraps back to 0 every 584 years. Time intervals
* may be either signed or unsigned.
*/
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
typedef khronos_int64_t khronos_stime_nanoseconds_t;
#endif
/*
* Dummy value used to pad enum types to 32 bits.
*/
#ifndef KHRONOS_MAX_ENUM
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
#endif
/*
* Enumerated boolean type
*
* Values other than zero should be considered to be true. Therefore
* comparisons should not be made against KHRONOS_TRUE.
*/
typedef enum {
KHRONOS_FALSE = 0,
KHRONOS_TRUE = 1,
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
} khronos_boolean_enum_t;
#endif /* __khrplatform_h_ */
+17
View File
@@ -0,0 +1,17 @@
//go:build required
// +build required
package gl
// This file exists purely to prevent the golang toolchain from stripping
// away the c source directories and files when `go mod vendor` is used
// to populate a `vendor/` directory of a project depending on `go-gl/go`.
//
// How it works:
// - every directory which only includes c source files receives a dummy.go file.
// - every directory we want to preserve is included here as a _ import.
// - this file is given a build tag to exclude it from the regular build.
import (
// Prevent go tooling from stripping out the c source files.
_ "github.com/go-gl/gl/v3.3-core/gl/KHR"
)
+116
View File
@@ -0,0 +1,116 @@
// Code generated by glow (https://github.com/go-gl/glow). DO NOT EDIT.
package gl
import (
"fmt"
"reflect"
"strings"
"unsafe"
)
// #include <stdlib.h>
import "C"
// Ptr takes a slice or pointer (to a singular scalar value or the first
// element of an array or slice) and returns its GL-compatible address.
//
// For example:
//
// var data []uint8
// ...
// gl.TexImage2D(gl.TEXTURE_2D, ..., gl.UNSIGNED_BYTE, gl.Ptr(&data[0]))
func Ptr(data interface{}) unsafe.Pointer {
if data == nil {
return unsafe.Pointer(nil)
}
var addr unsafe.Pointer
v := reflect.ValueOf(data)
switch v.Type().Kind() {
case reflect.Ptr:
e := v.Elem()
switch e.Kind() {
case
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
addr = unsafe.Pointer(e.UnsafeAddr())
default:
panic(fmt.Errorf("unsupported pointer to type %s; must be a slice or pointer to a singular scalar value or the first element of an array or slice", e.Kind()))
}
case reflect.Uintptr:
addr = unsafe.Pointer(data.(uintptr))
case reflect.Slice:
addr = unsafe.Pointer(v.Index(0).UnsafeAddr())
default:
panic(fmt.Errorf("unsupported type %s; must be a slice or pointer to a singular scalar value or the first element of an array or slice", v.Type()))
}
return addr
}
// PtrOffset takes a pointer offset and returns a GL-compatible pointer.
// Originally intended for functions such as glVertexAttribPointer that take pointer
// parameters also for offsets, since Go 1.14 this is no longer recommended.
//
// Use a corresponding offset-compatible variant of the function instead.
// For example, for gl.VertexAttribPointer() there is gl.VertexAttribPointerWithOffset().
//
// See https://github.com/go-gl/gl#go-114-and-checkptr for more details on the checkptr detector.
// See https://github.com/go-gl/glow#overloads, about adding new overloads.
//
// Deprecated: Use more appropriate overload function instead
func PtrOffset(offset int) unsafe.Pointer {
return unsafe.Pointer(uintptr(offset))
}
// Str takes a null-terminated Go string and returns its GL-compatible address.
// This function reaches into Go string storage in an unsafe way so the caller
// must ensure the string is not garbage collected.
func Str(str string) *uint8 {
if !strings.HasSuffix(str, "\x00") {
panic("str argument missing null terminator: " + str)
}
header := (*reflect.StringHeader)(unsafe.Pointer(&str))
return (*uint8)(unsafe.Pointer(header.Data))
}
// GoStr takes a null-terminated string returned by OpenGL and constructs a
// corresponding Go string.
func GoStr(cstr *uint8) string {
return C.GoString((*C.char)(unsafe.Pointer(cstr)))
}
// Strs takes a list of Go strings (with or without null-termination) and
// returns their C counterpart.
//
// The returned free function must be called once you are done using the strings
// in order to free the memory.
//
// If no strings are provided as a parameter this function will panic.
func Strs(strs ...string) (cstrs **uint8, free func()) {
if len(strs) == 0 {
panic("Strs: expected at least 1 string")
}
// Allocate a contiguous array large enough to hold all the strings' contents.
n := 0
for i := range strs {
n += len(strs[i])
}
if n == 0 {
n = 1 // avoid allocating zero bytes in case all strings are empty.
}
data := C.malloc(C.size_t(n))
// Copy all the strings into data.
dataSlice := (*[1 << 30]byte)(data)[:n]
css := make([]*uint8, len(strs)) // Populated with pointers to each string.
offset := 0
for i := range strs {
copy(dataSlice[offset:offset+len(strs[i])], strs[i][:]) // Copy strs[i] into proper data location.
css[i] = (*uint8)(unsafe.Pointer(&dataSlice[offset])) // Set a pointer to it.
offset += len(strs[i])
}
return (**uint8)(&css[0]), func() { C.free(data) }
}
+31
View File
@@ -0,0 +1,31 @@
// Code generated by glow (https://github.com/go-gl/glow). DO NOT EDIT.
package gl
import "C"
import "unsafe"
type DebugProc func(
source uint32,
gltype uint32,
id uint32,
severity uint32,
length int32,
message string,
userParam unsafe.Pointer)
var userDebugCallback DebugProc
//export glowDebugCallback_glcore33
func glowDebugCallback_glcore33(
source uint32,
gltype uint32,
id uint32,
severity uint32,
length int32,
message *uint8,
userParam unsafe.Pointer) {
if userDebugCallback != nil {
userDebugCallback(source, gltype, id, severity, length, GoStr(message), userParam)
}
}
File diff suppressed because it is too large Load Diff
+75
View File
@@ -0,0 +1,75 @@
// Code generated by glow (https://github.com/go-gl/glow). DO NOT EDIT.
// This file implements GlowGetProcAddress for every supported platform. The
// correct version is chosen automatically based on build tags:
//
// windows: WGL
// darwin: CGL
// linux freebsd netbsd openbsd: GLX
//
// Use of EGL instead of the platform's default (listed above) is made possible
// via the "egl" build tag.
//
// It is also possible to install your own function outside this package for
// retrieving OpenGL function pointers, to do this see InitWithProcAddrFunc.
package gl
/*
#cgo windows CFLAGS: -DTAG_WINDOWS
#cgo !gles2,windows LDFLAGS: -lopengl32
#cgo gles2,windows LDFLAGS: -lGLESv2
#cgo darwin CFLAGS: -DTAG_DARWIN
#cgo !gles2,darwin LDFLAGS: -framework OpenGL
#cgo gles2,darwin LDFLAGS: -framework OpenGLES
#cgo linux freebsd netbsd openbsd CFLAGS: -DTAG_POSIX
#cgo !egl,linux !egl,freebsd !egl,netbsd !egl,openbsd pkg-config: gl
#cgo egl,linux egl,freebsd egl,netbsd egl,openbsd egl,windows CFLAGS: -DTAG_EGL
#cgo egl,linux egl,freebsd egl,netbsd egl,openbsd pkg-config: egl
#cgo egl,windows LDFLAGS: -lEGL
#cgo egl,darwin LDFLAGS: -lEGL
// Check the EGL tag first as it takes priority over the platform's default
// configuration of WGL/GLX/CGL.
#if defined(TAG_EGL)
#include <stdlib.h>
#include <EGL/egl.h>
static void* GlowGetProcAddress(const char* name) {
return eglGetProcAddress(name);
}
#elif defined(TAG_WINDOWS)
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#include <stdlib.h>
static HMODULE ogl32dll = NULL;
static void* GlowGetProcAddress(const char* name) {
void* pf = wglGetProcAddress((LPCSTR) name);
if (pf) {
return pf;
}
if (ogl32dll == NULL) {
ogl32dll = LoadLibraryA("opengl32.dll");
}
return GetProcAddress(ogl32dll, (LPCSTR) name);
}
#elif defined(TAG_DARWIN)
#include <stdlib.h>
#include <dlfcn.h>
static void* GlowGetProcAddress(const char* name) {
return dlsym(RTLD_DEFAULT, name);
}
#elif defined(TAG_POSIX)
#include <stdlib.h>
#include <GL/glx.h>
static void* GlowGetProcAddress(const char* name) {
return glXGetProcAddress((const GLubyte *) name);
}
#endif
*/
import "C"
import "unsafe"
func getProcAddress(namea string) unsafe.Pointer {
cname := C.CString(namea)
defer C.free(unsafe.Pointer(cname))
return C.GlowGetProcAddress(cname)
}
+14
View File
@@ -0,0 +1,14 @@
# This is the official list of go-gl/mathgl authors for copyright purposes.
# This file is distinct from the CONTRIBUTORS files.
# See the latter for an explanation.
# Names should be added to this file as
# Name or Organization <email address>
# The email address is not required for organizations.
# Please keep the list sorted.
Alex Vasi <eee@someuser.com>
Dmitri Shuralyov <shurcooL@gmail.com>
GlenKelley <???>
Zoe Juozapaitis <jragonmiris@gmail.com>
+21
View File
@@ -0,0 +1,21 @@
# This is the official list of people who can contribute
# (and typically have contributed) code to the mathgl
# repository.
#
# The AUTHORS file lists the copyright holders; this file
# lists people. For example, Google employees would be listed here
# but not in AUTHORS, because Google would hold the copyright.
#
# When adding J Random Contributor's name to this file,
# either J's name or J's organization's name should be
# added to the AUTHORS file.
#
# Names should be added to this file like so:
# Name <email address>
#
# Please keep the list sorted.
Alex Vasi <eee@someuser.com>
Dmitri Shuralyov <shurcooL@gmail.com>
GlenKelley <???>
Zoe Juozapaitis <jragonmiris@gmail.com>
+23
View File
@@ -0,0 +1,23 @@
Copyright ©2013 The go-gl Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the gonum project nor the names of its authors and
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+94
View File
@@ -0,0 +1,94 @@
// Copyright 2014 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mgl32
import (
"math"
)
// CartesianToSpherical converts 3-dimensional cartesian coordinates (x,y,z) to spherical
// coordinates with radius r, inclination theta, and azimuth phi.
//
// All angles are in radians.
func CartesianToSpherical(coord Vec3) (r, theta, phi float32) {
r = coord.Len()
theta = float32(math.Acos(float64(coord[2] / r)))
phi = float32(math.Atan2(float64(coord[1]), float64(coord[0])))
return
}
// CartesianToCylindical converts 3-dimensional cartesian coordinates (x,y,z) to
// cylindrical coordinates with radial distance r, azimuth phi, and height z.
//
// All angles are in radians.
func CartesianToCylindical(coord Vec3) (rho, phi, z float32) {
rho = float32(math.Hypot(float64(coord[0]), float64(coord[1])))
phi = float32(math.Atan2(float64(coord[1]), float64(coord[0])))
z = coord[2]
return
}
// SphericalToCartesian converts spherical coordinates with radius r, inclination theta,
// and azimuth phi to cartesian coordinates (x,y,z).
//
// Angles are in radians.
func SphericalToCartesian(r, theta, phi float32) Vec3 {
st, ct := math.Sincos(float64(theta))
sp, cp := math.Sincos(float64(phi))
return Vec3{r * float32(st*cp), r * float32(st*sp), r * float32(ct)}
}
// SphericalToCylindrical converts spherical coordinates with radius r,
// inclination theta, and azimuth phi to cylindrical coordinates with radial
// distance r, azimuth phi, and height z.
//
// Angles are in radians
func SphericalToCylindrical(r, theta, phi float32) (rho, phi2, z float32) {
s, c := math.Sincos(float64(theta))
rho = r * float32(s)
z = r * float32(c)
phi2 = phi
return
}
// CylindircalToSpherical converts cylindrical coordinates with radial distance
// r, azimuth phi, and height z to spherical coordinates with radius r,
// inclination theta, and azimuth phi.
//
// Angles are in radians
func CylindircalToSpherical(rho, phi, z float32) (r, theta, phi2 float32) {
r = float32(math.Hypot(float64(rho), float64(z)))
phi2 = phi
theta = float32(math.Atan2(float64(rho), float64(z)))
return
}
// CylindricalToCartesian converts cylindrical coordinates with radial distance
// r, azimuth phi, and height z to cartesian coordinates (x,y,z)
//
// Angles are in radians.
func CylindricalToCartesian(rho, phi, z float32) Vec3 {
s, c := math.Sincos(float64(phi))
return Vec3{rho * float32(c), rho * float32(s), z}
}
// DegToRad converts degrees to radians
func DegToRad(angle float32) float32 {
return angle * float32(math.Pi) / 180
}
// RadToDeg converts radians to degrees
func RadToDeg(angle float32) float32 {
return angle * 180 / float32(math.Pi)
}
+22
View File
@@ -0,0 +1,22 @@
// Copyright 2014 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package mgl[32|64] (an abbreviation of mathgl since the packages were split between 32 and 64-bit versions)
is a pure Go math package specialized for 3D math, with inspiration from GLM. It provides statically-sized vectors and matrices with
compile-time generated calculations for most basic math operations. It also provides several basic graphics utilities such as bezier curves and surfaces,
generation of basic primitives like circles, easy creation of common matrices such as perspective or rotation, and common operations like converting
to/from screen/OpenGL coordinates or Projecting/Unprojecting from an MVP matrix. Quaternions are also supported.
The basic vectors and matrices are written with code generation, so looking directly at the source will probably be a bit confusing. I recommend looking at the Godoc
instead, as all basic functions are documented.
This package is written in Column Major Order to make it easier with OpenGL. This means for uniform blocks you can use the default ordering, and when you call
pass-in functions you can leave the "transpose" argument as false.
The package now contains variable sized vectors and matrices. Using these is discouraged. They exist for corner cases where you need "small" matrices that are still
bigger than 4x4. An example may be a Jacobean used for inverse kinematics. Things like computer vision or general linear algebra are best left to packages
more directly suited for that task -- OpenCV, BLAS, LAPACK, numpy, gonum (if you want to stay in Go), and so on.
*/
package mgl32
+511
View File
@@ -0,0 +1,511 @@
// Copyright 2014 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mgl32
import (
"math"
)
// MatMxN is an arbitrary mxn matrix backed by a slice of floats.
//
// This is emphatically not recommended for hardcore n-dimensional
// linear algebra. For that purpose I recommend github.com/gonum/matrix or
// well-tested C libraries such as BLAS or LAPACK.
//
// This is meant to complement future algorithms that may require matrices larger than
// 4x4, but still relatively small (e.g. Jacobeans for inverse kinematics).
//
// It makes use of the same memory sync.Pool set that VecN does, with the same sizing rules.
//
// MatMN will always check if the receiver is nil on any method. Meaning MathMN(nil).Add(dst,m2)
// should always work. Except for the Reshape function, the semantics of this is to "propogate" nils
// forward, so if an invalid operation occurs in a long chain of matrix operations, the overall result will be nil.
type MatMxN struct {
m, n int
dat []float32
}
// NewMatrix creates a matrix backed by a new slice of size m*n
func NewMatrix(m, n int) (mat *MatMxN) {
if shouldPool {
return &MatMxN{m: m, n: n, dat: grabFromPool(m * n)}
} else {
return &MatMxN{m: m, n: n, dat: make([]float32, m*n)}
}
}
// NewMatrixFromData returns a matrix with data specified by the data in src
//
// For instance, to create a 3x3 MatMN from a Mat3
//
// m1 := mgl32.Rotate3DX(3.14159)
// mat := mgl32.NewBackedMatrix(m1[:],3,3)
//
// will create an MN matrix matching the data in the original rotation matrix.
// This matrix is NOT backed by the initial slice; it's a copy of the data
//
// If m*n > cap(src), this function will panic.
func NewMatrixFromData(src []float32, m, n int) *MatMxN {
var internal []float32
if shouldPool {
internal = grabFromPool(m * n)
} else {
internal = make([]float32, m*n)
}
copy(internal, src[:m*n])
return &MatMxN{m: m, n: n, dat: internal}
}
// CopyMatMN copies src into dst. This Reshapes dst
// to the same size as src.
//
// If dst or src is nil, this is a no-op
func CopyMatMN(dst, src *MatMxN) {
if dst == nil || src == nil {
return
}
dst.Reshape(src.m, src.n)
copy(dst.dat, src.dat)
}
// IdentN stores the NxN identity matrix in dst, reallocating as necessary.
func IdentN(dst *MatMxN, n int) *MatMxN {
dst = dst.Reshape(n, n)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i == j {
dst.Set(i, j, 1)
} else {
dst.Set(i, j, 0)
}
}
}
return dst
}
// DiagN creates an NxN diagonal matrix seeded by the diagonal vector diag.
// Meaning: for all entries, where i==j, dst.At(i,j) = diag[i]. Otherwise
// dst.At(i,j) = 0
//
// This reshapes dst to the correct size, returning/grabbing from the memory
// pool as necessary.
func DiagN(dst *MatMxN, diag *VecN) *MatMxN {
dst = dst.Reshape(len(diag.vec), len(diag.vec))
n := len(diag.vec)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i == j {
dst.Set(i, j, diag.vec[i])
} else {
dst.Set(i, j, 0)
}
}
}
return dst
}
// Zero reshapes the matrix to m by n and zeroes out all
// elements.
func (mat *MatMxN) Zero(m, n int) {
if mat == nil {
return
}
mat.Reshape(m, n)
for i := range mat.dat {
mat.dat[i] = 0
}
}
// destroy returns the underlying matrix slice to the memory pool
func (mat *MatMxN) destroy() {
if mat == nil {
return
}
if shouldPool && mat.dat != nil {
returnToPool(mat.dat)
}
mat.m, mat.n = 0, 0
mat.dat = nil
}
// Reshape reshapes the matrix to the desired dimensions.
// If the overall size of the new matrix (m*n) is bigger
// than the current size, the underlying slice will
// be grown, sending the current slice to the memory pool
// and grabbing a bigger one if necessary
//
// If the caller is a nil pointer, the return value will be a new
// matrix, as if NewMatrix(m,n) had been called. Otherwise it's
// simply the caller.
func (mat *MatMxN) Reshape(m, n int) *MatMxN {
if mat == nil {
return NewMatrix(m, n)
}
if m*n <= cap(mat.dat) {
if mat.dat != nil {
mat.dat = mat.dat[:m*n]
} else {
mat.dat = []float32{}
}
mat.m, mat.n = m, n
return mat
}
if shouldPool && mat.dat != nil {
returnToPool(mat.dat)
}
(*mat) = (*NewMatrix(m, n))
return mat
}
// InferMatrix infers an MxN matrix from a constant matrix from this package.
// For instance, a Mat2x3 inferred with this function will work just like
// NewMatrixFromData(m[:],2,3) where m is the Mat2x3. This uses a type switch.
//
// I personally recommend using NewMatrixFromData, because it avoids a
// potentially costly type switch. However, this is also more robust and less
// error prone if you change the size of your matrix somewhere.
//
// If the value passed in is not recognized, it returns an InferMatrixError.
func (mat *MatMxN) InferMatrix(m interface{}) (*MatMxN, error) {
switch raw := m.(type) {
case Mat2:
return NewMatrixFromData(raw[:], 2, 2), nil
case Mat2x3:
return NewMatrixFromData(raw[:], 2, 3), nil
case Mat2x4:
return NewMatrixFromData(raw[:], 2, 4), nil
case Mat3:
return NewMatrixFromData(raw[:], 3, 3), nil
case Mat3x2:
return NewMatrixFromData(raw[:], 3, 2), nil
case Mat3x4:
return NewMatrixFromData(raw[:], 3, 4), nil
case Mat4:
return NewMatrixFromData(raw[:], 4, 4), nil
case Mat4x2:
return NewMatrixFromData(raw[:], 4, 2), nil
case Mat4x3:
return NewMatrixFromData(raw[:], 4, 3), nil
default:
return nil, InferMatrixError{}
}
}
// Trace returns the trace of a square matrix (sum of all diagonal elements). If
// the matrix is nil, or not square, the result will be NaN.
func (mat *MatMxN) Trace() float32 {
if mat == nil || mat.m != mat.n {
return float32(math.NaN())
}
var out float32
for i := 0; i < mat.m; i++ {
out += mat.At(i, i)
}
return out
}
// Transpose takes the transpose of mat and puts it in dst.
//
// If dst is not of the correct dimensions, it will be Reshaped,
// if dst and mat are the same, a temporary matrix of the correct size will
// be allocated; these resources will be released via the memory pool.
//
// This should be improved in the future.
func (mat *MatMxN) Transpose(dst *MatMxN) (t *MatMxN) {
if mat == nil {
return nil
}
if dst == mat {
dst = NewMatrix(mat.n, mat.m)
// Copy data to correct matrix,
// delete temporary buffer,
// and set the return value to the
// correct one
defer func() {
copy(mat.dat, dst.dat)
mat.m, mat.n = mat.n, mat.m
dst.destroy()
t = mat
}()
return mat
} else {
dst = dst.Reshape(mat.n, mat.m)
}
for r := 0; r < mat.m; r++ {
for c := 0; c < mat.n; c++ {
dst.dat[r*dst.m+c] = mat.dat[c*mat.m+r]
}
}
return dst
}
// Raw returns the raw slice backing this matrix
func (mat *MatMxN) Raw() []float32 {
if mat == nil {
return nil
}
return mat.dat
}
// NumRows returns the number of rows in this matrix
func (mat *MatMxN) NumRows() int {
return mat.m
}
// NumCols returns the number of columns in this matrix
func (mat *MatMxN) NumCols() int {
return mat.n
}
// NumRowCols returns the number of rows and columns in this matrix
// as a single operation
func (mat *MatMxN) NumRowCols() (rows, cols int) {
return mat.m, mat.n
}
// At returns the element at the given row and column.
// This is garbage in/garbage out and does no bounds
// checking. If the computation happens to lead to an invalid
// element, it will be returned; or it may panic.
func (mat *MatMxN) At(row, col int) float32 {
return mat.dat[col*mat.m+row]
}
// Set sets the element at the given row and column.
// This is garbage in/garbage out and does no bounds
// checking. If the computation happens to lead to an invalid
// element, it will be set; or it may panic.
func (mat *MatMxN) Set(row, col int, val float32) {
mat.dat[col*mat.m+row] = val
}
// Add is the arithemtic + operator defined on a MatMxN.
func (mat *MatMxN) Add(dst *MatMxN, addend *MatMxN) *MatMxN {
if mat == nil || addend == nil || mat.m != addend.m || mat.n != addend.n {
return nil
}
dst = dst.Reshape(mat.m, mat.n)
// No need to care about rows and columns
// since it's element-wise anyway
for i, el := range mat.dat {
dst.dat[i] = el + addend.dat[i]
}
return dst
}
// Sub is the arithemtic - operator defined on a MatMxN.
func (mat *MatMxN) Sub(dst *MatMxN, subtrahend *MatMxN) *MatMxN {
if mat == nil || subtrahend == nil || mat.m != subtrahend.m || mat.n != subtrahend.n {
return nil
}
dst = dst.Reshape(mat.m, mat.n)
// No need to care about rows and columns
// since it's element-wise anyway
for i, el := range mat.dat {
dst.dat[i] = el - subtrahend.dat[i]
}
return dst
}
// MulMxN performs matrix multiplication on MxN matrix mat and NxO matrix mul,
// storing the result in dst. This returns dst, or nil if the operation is not
// able to be performed.
//
// If mat == dst, or mul == dst a temporary matrix will be used.
//
// This uses the naive algorithm (though on smaller matrices, this can actually
// be faster; about len(mat)+len(mul) < ~100)
func (mat *MatMxN) MulMxN(dst *MatMxN, mul *MatMxN) *MatMxN {
if mat == nil || mul == nil || mat.n != mul.m {
return nil
}
if dst == mul {
mul = NewMatrix(mul.m, mul.n)
copy(mul.dat, dst.dat)
// If mat==dst==mul, we need to change
// mat too or we have a bug
if mat == dst {
mat = mul
}
defer mul.destroy()
} else if dst == mat {
mat = NewMatrix(mat.m, mat.n)
copy(mat.dat, dst.dat)
defer mat.destroy()
}
dst = dst.Reshape(mat.m, mul.n)
for r1 := 0; r1 < mat.m; r1++ {
for c2 := 0; c2 < mul.n; c2++ {
dst.dat[c2*mat.m+r1] = 0
for i := 0; i < mat.n; i++ {
dst.dat[c2*mat.m+r1] += mat.dat[i*mat.m+r1] * mul.dat[c2*mul.m+i]
}
}
}
return dst
}
// Mul performs a scalar multiplication between mat and some constant c,
// storing the result in dst. Mat and dst can be equal. If dst is not the
// correct size, a Reshape will occur.
func (mat *MatMxN) Mul(dst *MatMxN, c float32) *MatMxN {
if mat == nil {
return nil
}
dst = dst.Reshape(mat.m, mat.n)
for i, el := range mat.dat {
dst.dat[i] = el * c
}
return dst
}
// MulNx1 multiplies the matrix by a vector of size n. If mat or v is nil, this
// returns nil. If the number of columns in mat does not match the Size of v,
// this also returns nil.
//
// Dst will be resized if it's not big enough. If dst == v; a temporary vector
// will be allocated and returned via the realloc callback when complete.
func (mat *MatMxN) MulNx1(dst, v *VecN) *VecN {
if mat == nil || v == nil || mat.n != len(v.vec) {
return nil
}
if dst == v {
v = NewVecN(len(v.vec))
copy(v.vec, dst.vec)
defer v.destroy()
}
dst = dst.Resize(mat.m)
for r := 0; r < mat.m; r++ {
dst.vec[r] = 0
for c := 0; c < mat.n; c++ {
dst.vec[r] += mat.At(r, c) * v.vec[c]
}
}
return dst
}
// ApproxEqual returns whether the two vectors are approximately equal (See
// FloatEqual).
func (mat *MatMxN) ApproxEqual(m2 *MatMxN) bool {
if mat == m2 {
return true
}
if mat.m != m2.m || mat.n != m2.n {
return false
}
for i, el := range mat.dat {
if !FloatEqual(el, m2.dat[i]) {
return false
}
}
return true
}
// ApproxEqualThreshold returns whether the two vectors are approximately equal
// to within the given threshold given by "epsilon" (See ApproxEqualThreshold).
func (mat *MatMxN) ApproxEqualThreshold(m2 *MatMxN, epsilon float32) bool {
if mat == m2 {
return true
}
if mat.m != m2.m || mat.n != m2.n {
return false
}
for i, el := range mat.dat {
if !FloatEqualThreshold(el, m2.dat[i], epsilon) {
return false
}
}
return true
}
// ApproxEqualFunc returns whether the two vectors are approximately equal,
// given a function which compares two scalar elements.
func (mat *MatMxN) ApproxEqualFunc(m2 *MatMxN, comp func(float32, float32) bool) bool {
if mat == m2 {
return true
}
if mat.m != m2.m || mat.n != m2.n {
return false
}
for i, el := range mat.dat {
if !comp(el, m2.dat[i]) {
return false
}
}
return true
}
// InferMatrixError may be returned by InferMatrix.
//
// Make sure you're using a constant matrix such as Mat3 from within the same
// package (meaning: mgl32.MatMxN can't handle a mgl64.Mat2x3).
type InferMatrixError struct{}
func (me InferMatrixError) Error() string {
return "could not infer matrix. Make sure you're using a constant matrix such as Mat3 from within the same package (meaning: mgl32.MatMxN can't handle a mgl64.Mat2x3)."
}
// RectangularMatrixError is returned when a rectangular matrix was expected but
// not given.
type RectangularMatrixError struct{}
func (mse RectangularMatrixError) Error() string {
return "the matrix was the wrong shape, needed a square matrix."
}
// NilMatrixError is returned when an operand to a function was unexpectedly 'nil'.
type NilMatrixError struct{}
func (me NilMatrixError) Error() string {
return "the matrix is nil"
}
File diff suppressed because it is too large Load Diff
+379
View File
@@ -0,0 +1,379 @@
// Copyright 2014 The go-gl/mathgl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// <<.Comment>>
// Edit <<.TemplateName>> and run "go generate" to make changes.
package mgl32
import (
"bytes"
"fmt"
"text/tabwriter"
)
type Mat2 [2*2]float32
type Mat2x3 [2*3]float32
type Mat2x4 [2*4]float32
type Mat3x2 [3*2]float32
type Mat3 [3*3]float32
type Mat3x4 [3*4]float32
type Mat4x2 [4*2]float32
type Mat4x3 [4*3]float32
type Mat4 [4*4]float32
func (m Mat2) Mat3() Mat3 {
col0, col1 := m.Cols()
return Mat3FromCols(
col0.Vec3(0),
col1.Vec3(0),
Vec3{0, 0, 1},
)
}
func (m Mat2) Mat4() Mat4 {
col0, col1 := m.Cols()
return Mat4FromCols(
col0.Vec4(0, 0),
col1.Vec4(0, 0),
Vec4{0, 0, 1, 0},
Vec4{0, 0, 0, 1},
)
}
func (m Mat3) Mat2() Mat2 {
col0, col1, _ := m.Cols()
return Mat2FromCols(
col0.Vec2(),
col1.Vec2(),
)
}
func (m Mat3) Mat4() Mat4 {
col0, col1, col2 := m.Cols()
return Mat4FromCols(
col0.Vec4(0),
col1.Vec4(0),
col2.Vec4(0),
Vec4{0, 0, 0, 1},
)
}
func (m Mat4) Mat2() Mat2 {
col0, col1, _, _ := m.Cols()
return Mat2FromCols(
col0.Vec2(),
col1.Vec2(),
)
}
func (m Mat4) Mat3() Mat3 {
col0, col1, col2, _ := m.Cols()
return Mat3FromCols(
col0.Vec3(),
col1.Vec3(),
col2.Vec3(),
)
}
<</* Common functions for all matrices */>>
<<range $m := enum 2 3 4>><<range $n := enum 2 3 4>>
<<$type := typename $m $n>>
// SetCol sets a Column within the Matrix, so it mutates the calling matrix.
func (m *<<$type>>) SetCol(col int, v <<typename $m 1>>) {
<<range $i := iter 0 $m>><<sep "," $i>>m[col*<<$m>>+<<$i>>]<<end>> = <<repeat $m "v[%d]" ",">>
}
// SetRow sets a Row within the Matrix, so it mutates the calling matrix.
func (m *<<$type>>) SetRow(row int, v <<typename $n 1>>) {
<<range $i := iter 0 $n>><<sep "," $i>>m[row+<<mul $m $i>>]<<end>> = <<repeat $n "v[%d]" ",">>
}
<<if eq $m $n>>
// Diag is a basic operation on a square matrix that simply
// returns main diagonal (meaning all elements such that row==col).
func (m <<$type>>) Diag() <<typename $m 1>> {
return <<typename $m 1>>{<<range $i := iter 0 $m>>m[<<mul $i $m | add $i>>],<<end>>}
}
<<end>>
<<if eq $m $n>>
// Ident<<$m>> returns the <<$m>>x<<$n>> identity matrix.
// The identity matrix is a square matrix with the value 1 on its
// diagonals. The characteristic property of the identity matrix is that
// any matrix multiplied by it is itself. (MI = M; IN = N)
func Ident<<$m>>() <<$type>> {
return <<$type>>{<<range $i := matiter $m $n>><<if eq $i.M $i.N>>1<<else>>0<<end>>,<<end>>}
}
<<end>>
<<if eq $m $n>>
// Diag<<$m>> creates a diagonal matrix from the entries of the input vector.
// That is, for each pointer for row==col, vector[row] is the entry. Otherwise it's 0.
//
// Another way to think about it is that the identity is this function where the every vector element is 1.
func Diag<<$m>>(v <<typename $m 1>>) <<$type>> {
var m <<$type>>
<<range $i := iter 0 $m>><<sep "," $i>>m[<<mul $i $m | add $i>>]<<end>> = <<repeat $m "v[%d]" ",">>
return m
}
<<end>>
// <<$type>>FromRows builds a new matrix from row vectors.
// The resulting matrix will still be in column major order, but this can be
// good for hand-building matrices.
func <<$type>>FromRows(<<range $i := iter 0 $m>><<sep "," $i>>row<<$i>><<end>> <<typename $n 1>>) <<$type>> {
return <<$type>>{<<range $i := matiter $m $n>>row<<$i.M>>[<<$i.N>>],<<end>>}
}
// <<$type>>FromCols builds a new matrix from column vectors.
func <<$type>>FromCols(<<repeat $n "col%d" ",">> <<typename $m 1>>) <<$type>> {
return <<$type>>{<<range $i := matiter $m $n>>col<<$i.N>>[<<$i.M>>], <<end>>}
}
// Add performs an element-wise addition of two matrices, this is
// equivalent to iterating over every element of m1 and adding the corresponding value of m2.
func (m1 <<$type>>) Add(m2 <<$type>>) <<$type>> {
return <<$type>>{<< range $i := matiter $m $n>>m1[<<$i>>] + m2[<<$i>>], <<end>>}
}
// Sub performs an element-wise subtraction of two matrices, this is
// equivalent to iterating over every element of m1 and subtracting the corresponding value of m2.
func (m1 <<$type>>) Sub(m2 <<$type>>) <<$type>> {
return <<$type>>{<< range $i := matiter $m $n>>m1[<<$i>>] - m2[<<$i>>], <<end>>}
}
// Mul performs a scalar multiplcation of the matrix. This is equivalent to iterating
// over every element of the matrix and multiply it by c.
func (m1 <<$type>>) Mul(c float32) <<$type>> {
return <<$type>>{<< range $i := matiter $m $n>>m1[<<$i>>] * c, <<end>>}
}
<<range $o := enum 1 2 3 4>>
// Mul<<$n>><<if ne $n $o>>x<<$o>><<end>> performs a "matrix product" between this matrix
// and another of the given dimension. For any two matrices of dimensionality
// MxN and NxO, the result will be MxO. For instance, Mat4 multiplied using
// Mul4x2 will result in a Mat4x2.
func (m1 <<$type>>) Mul<<$n>><<if ne $n $o>>x<<$o>><<end>>(m2 <<typename $n $o>>) <<typename $m $o>> {
return <<typename $m $o>>{<<range $i := matiter $m $o>>
<<range $k := iter 0 $n>><<sep "+" $k>>m1[<<mul $k $m | add $i.M>>]*m2[<<mul $i.N $n| add $k>>]<<end>>,<<end>>
}
}
<<end>>
// Transpose produces the transpose of this matrix. For any MxN matrix
// the transpose is an NxM matrix with the rows swapped with the columns. For instance
// the transpose of the Mat3x2 is a Mat2x3 like so:
//
// [[a b]] [[a c e]]
// [[c d]] = [[b d f]]
// [[e f]]
func (m1 <<$type>>) Transpose() <<typename $n $m>> {
return <<typename $n $m>>{<<range $i := matiter $n $m>>m1[<<mul $m $i.M | add $i.N>>], <<end>>}
}
<<if eq $m $n>>
// Det returns the determinant of a matrix. It is a measure of a square matrix's
// singularity and invertability, among other things. In this library, the
// determinant is hard coded based on pre-computed cofactor expansion, and uses
// no loops. Of course, the addition and multiplication must still be done.
func (m <<$type>>) Det() float32 {
<<if eq $m 2 ->>
return m[0]*m[3] - m[1]*m[2]
<<else if eq $m 3 ->>
return m[0]*m[4]*m[8] + m[3]*m[7]*m[2] + m[6]*m[1]*m[5] - m[6]*m[4]*m[2] - m[3]*m[1]*m[8] - m[0]*m[7]*m[5]
<<else if eq $m 4 ->>
return m[0]*m[5]*m[10]*m[15] - m[0]*m[5]*m[11]*m[14] - m[0]*m[6]*m[9]*m[15] + m[0]*m[6]*m[11]*m[13] + m[0]*m[7]*m[9]*m[14] - m[0]*m[7]*m[10]*m[13] - m[1]*m[4]*m[10]*m[15] + m[1]*m[4]*m[11]*m[14] + m[1]*m[6]*m[8]*m[15] - m[1]*m[6]*m[11]*m[12] - m[1]*m[7]*m[8]*m[14] + m[1]*m[7]*m[10]*m[12] + m[2]*m[4]*m[9]*m[15] - m[2]*m[4]*m[11]*m[13] - m[2]*m[5]*m[8]*m[15] + m[2]*m[5]*m[11]*m[12] + m[2]*m[7]*m[8]*m[13] - m[2]*m[7]*m[9]*m[12] - m[3]*m[4]*m[9]*m[14] + m[3]*m[4]*m[10]*m[13] + m[3]*m[5]*m[8]*m[14] - m[3]*m[5]*m[10]*m[12] - m[3]*m[6]*m[8]*m[13] + m[3]*m[6]*m[9]*m[12]
<<end ->>
}
<<end>>
<<if eq $m $n>>
// Inv computes the inverse of a square matrix. An inverse is a square matrix such that when multiplied by the
// original, yields the identity.
//
// M_inv * M = M * M_inv = I
//
// In this library, the math is precomputed, and uses no loops, though the multiplications, additions, determinant calculation, and scaling
// are still done. This can still be (relatively) expensive for a 4x4.
//
// This function checks the determinant to see if the matrix is invertible.
// If the determinant is 0.0, this function returns the zero matrix. However, due to floating point errors, it is
// entirely plausible to get a false positive or negative.
// In the future, an alternate function may be written which takes in a pre-computed determinant.
func (m <<$type>>) Inv() <<$type>> {
det := m.Det()
if FloatEqual(det, float32(0.0)) {
return <<$type>>{}
}
<<if eq $m 2>>
retMat := Mat2{m[3], -m[1], -m[2], m[0]}
<<else if eq $m 3>>
retMat := Mat3{
m[4]*m[8] - m[5]*m[7],
m[2]*m[7] - m[1]*m[8],
m[1]*m[5] - m[2]*m[4],
m[5]*m[6] - m[3]*m[8],
m[0]*m[8] - m[2]*m[6],
m[2]*m[3] - m[0]*m[5],
m[3]*m[7] - m[4]*m[6],
m[1]*m[6] - m[0]*m[7],
m[0]*m[4] - m[1]*m[3],
}
<<else if eq $m 4>>
retMat := Mat4{
-m[7]*m[10]*m[13] + m[6]*m[11]*m[13] + m[7]*m[9]*m[14] - m[5]*m[11]*m[14] - m[6]*m[9]*m[15] + m[5]*m[10]*m[15],
m[3]*m[10]*m[13] - m[2]*m[11]*m[13] - m[3]*m[9]*m[14] + m[1]*m[11]*m[14] + m[2]*m[9]*m[15] - m[1]*m[10]*m[15],
-m[3]*m[6]*m[13] + m[2]*m[7]*m[13] + m[3]*m[5]*m[14] - m[1]*m[7]*m[14] - m[2]*m[5]*m[15] + m[1]*m[6]*m[15],
m[3]*m[6]*m[9] - m[2]*m[7]*m[9] - m[3]*m[5]*m[10] + m[1]*m[7]*m[10] + m[2]*m[5]*m[11] - m[1]*m[6]*m[11],
m[7]*m[10]*m[12] - m[6]*m[11]*m[12] - m[7]*m[8]*m[14] + m[4]*m[11]*m[14] + m[6]*m[8]*m[15] - m[4]*m[10]*m[15],
-m[3]*m[10]*m[12] + m[2]*m[11]*m[12] + m[3]*m[8]*m[14] - m[0]*m[11]*m[14] - m[2]*m[8]*m[15] + m[0]*m[10]*m[15],
m[3]*m[6]*m[12] - m[2]*m[7]*m[12] - m[3]*m[4]*m[14] + m[0]*m[7]*m[14] + m[2]*m[4]*m[15] - m[0]*m[6]*m[15],
-m[3]*m[6]*m[8] + m[2]*m[7]*m[8] + m[3]*m[4]*m[10] - m[0]*m[7]*m[10] - m[2]*m[4]*m[11] + m[0]*m[6]*m[11],
-m[7]*m[9]*m[12] + m[5]*m[11]*m[12] + m[7]*m[8]*m[13] - m[4]*m[11]*m[13] - m[5]*m[8]*m[15] + m[4]*m[9]*m[15],
m[3]*m[9]*m[12] - m[1]*m[11]*m[12] - m[3]*m[8]*m[13] + m[0]*m[11]*m[13] + m[1]*m[8]*m[15] - m[0]*m[9]*m[15],
-m[3]*m[5]*m[12] + m[1]*m[7]*m[12] + m[3]*m[4]*m[13] - m[0]*m[7]*m[13] - m[1]*m[4]*m[15] + m[0]*m[5]*m[15],
m[3]*m[5]*m[8] - m[1]*m[7]*m[8] - m[3]*m[4]*m[9] + m[0]*m[7]*m[9] + m[1]*m[4]*m[11] - m[0]*m[5]*m[11],
m[6]*m[9]*m[12] - m[5]*m[10]*m[12] - m[6]*m[8]*m[13] + m[4]*m[10]*m[13] + m[5]*m[8]*m[14] - m[4]*m[9]*m[14],
-m[2]*m[9]*m[12] + m[1]*m[10]*m[12] + m[2]*m[8]*m[13] - m[0]*m[10]*m[13] - m[1]*m[8]*m[14] + m[0]*m[9]*m[14],
m[2]*m[5]*m[12] - m[1]*m[6]*m[12] - m[2]*m[4]*m[13] + m[0]*m[6]*m[13] + m[1]*m[4]*m[14] - m[0]*m[5]*m[14],
-m[2]*m[5]*m[8] + m[1]*m[6]*m[8] + m[2]*m[4]*m[9] - m[0]*m[6]*m[9] - m[1]*m[4]*m[10] + m[0]*m[5]*m[10],
}
<<end>>
return retMat.Mul(1 / det)
}
<<end>>
// ApproxEqual performs an element-wise approximate equality test between two matrices,
// as if FloatEqual had been used.
func (m1 <<$type>>) ApproxEqual(m2 <<$type>>) bool {
for i := range m1 {
if !FloatEqual(m1[i], m2[i]) {
return false
}
}
return true
}
// ApproxEqualThreshold performs an element-wise approximate equality test between two matrices
// with a given epsilon threshold, as if FloatEqualThreshold had been used.
func (m1 <<$type>>) ApproxEqualThreshold(m2 <<$type>>, threshold float32) bool {
for i := range m1 {
if !FloatEqualThreshold(m1[i], m2[i], threshold) {
return false
}
}
return true
}
// ApproxFuncEqual performs an element-wise approximate equality test between two matrices
// with a given equality functions, intended to be used with FloatEqualFunc; although and comparison
// function may be used in practice.
func (m1 <<$type>>) ApproxFuncEqual(m2 <<$type>>, eq func(float32, float32) bool) bool {
for i := range m1 {
if !eq(m1[i], m2[i]) {
return false
}
}
return true
}
// NumRows returns the number of rows in this matrix
func (m <<$type>>) NumRows() int {
return <<$m>>
}
// NumCols returns the number of columns in this matrix
func (m <<$type>>) NumCols() int {
return <<$n>>
}
// At returns the matrix element at the given row and column.
// This is equivalent to mat[col * numRow + row] where numRow is constant
// (E.G. for a Mat3x2 it's equal to 3)
//
// This method is garbage-in garbage-out. For instance, on a Mat4 asking for
// At(5,0) will work just like At(1,1). Or it may panic if it's out of bounds.
func (m <<$type>>) At(row, col int) float32 {
return m[col*<<$m>>+row]
}
// Set sets the corresponding matrix element at the given row and column.
// This has a pointer receiver because it mutates the matrix.
//
// This method is garbage-in garbage-out. For instance, on a Mat4 asking for
// Set(5,0,val) will work just like Set(1,1,val). Or it may panic if it's out of bounds.
func (m *<<$type>>) Set(row, col int, value float32) {
m[col*<<$m>>+row] = value
}
// Index returns the index of the given row and column, to be used with direct
// access. E.G. Index(0,0) = 0.
//
// This is a garbage-in garbage-out method. For instance, on a Mat4 asking for the index of
// (5,0) will work the same as asking for (1,1). Or it may give you a value that will cause
// a panic if you try to access the array with it if it's truly out of bounds.
func (m <<$type>>) Index(row, col int) int {
return col*<<$m>> + row
}
// Row returns a vector representing the corresponding row (starting at row 0).
// This package makes no distinction between row and column vectors, so it
// will be a normal VecM for a MxN matrix.
func (m <<$type>>) Row(row int) <<typename $n 1>> {
return <<typename $n 1>>{<<range $i := iter 0 $n>>m[row+<<mul $m $i>>],<<end>>}
}
// Rows decomposes a matrix into its corresponding row vectors.
// This is equivalent to calling mat.Row for each row.
func (m <<$type>>) Rows() (<<repeat $m "row%d" ",">> <<typename $n 1>>) {
return <<repeat $m "m.Row(%d)" ",">>
}
// Col returns a vector representing the corresponding column (starting at col 0).
// This package makes no distinction between row and column vectors, so it
// will be a normal VecN for a MxN matrix.
func (m <<$type>>) Col(col int) <<typename $m 1>> {
return <<typename $m 1>>{<<range $i := iter 0 $m>>m[col*<<$m>>+<<$i>>],<<end>>}
}
// Cols decomposes a matrix into its corresponding column vectors.
// This is equivalent to calling mat.Col for each column.
func (m <<$type>>) Cols() (<<repeat $n "col%d" ",">> <<typename $m 1>>) {
return <<repeat $n "m.Col(%d)" ",">>
}
<<if eq $m $n>>
// Trace is a basic operation on a square matrix that simply
// sums up all elements on the main diagonal (meaning all elements such that row==col).
func (m <<$type>>) Trace() float32 {
return <<range $i := iter 0 $m>><<sep "+" $i>> m[<<mul $i $m | add $i>>]<<end>>
}
<<end>>
// Abs returns the element-wise absolute value of this matrix
func (m <<$type>>) Abs() <<$type>> {
return <<$type>>{<<repeat (mul $m $n) "Abs(m[%d])" ",">>}
}
// Pretty prints the matrix
func (m <<$type>>) String() string {
buf := new(bytes.Buffer)
w := tabwriter.NewWriter(buf, 4, 4, 1, ' ', tabwriter.AlignRight)
for i := 0; i < <<$m>>; i++ {
for _, col := range m.Row(i) {
fmt.Fprintf(w, "%f\t", col)
}
fmt.Fprintln(w, "")
}
w.Flush()
return buf.String()
}
<<end>><<end>> <</* range $m range $n */>>
+121
View File
@@ -0,0 +1,121 @@
// Copyright 2014 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mgl32
import (
"sync"
)
var (
slicePools []*sync.Pool
listLock sync.RWMutex
)
var shouldPool = true
func DisableMemoryPooling() {
shouldPool = false
}
// Returns the given memory pool. If the pool doesn't exist, it will
// create all pools up to element i. The number "i" corresponds to "p"
// in most other comments. That is, it's Ceil(log_2(whatever)). So i=0
// means you'll get the pool for slices of size 1, i=1 for size 2, i=2 for size 4,
// and so on.
//
// This is concurrency safe and uses an RWMutex to protect the list expansion.
func getPool(i int) *sync.Pool {
listLock.RLock()
if i >= len(slicePools) {
// Promote to a write lock because we now
// need to mutate the pool
listLock.RUnlock()
listLock.Lock()
defer listLock.Unlock()
for n := i - len(slicePools); n >= 0; n-- {
newFunc := genPoolNew(1 << uint(len(slicePools)))
slicePools = append(slicePools, &sync.Pool{New: newFunc})
}
} else {
defer listLock.RUnlock()
}
return slicePools[i]
}
func genPoolNew(i int) func() interface{} {
return func() interface{} {
return make([]float32, 0, i)
}
}
// Grabs a slice from the memory pool, such that its cap
// is 2^p where p is Ceil(log_2(size)). It will be downsliced
// such that the len is size.
func grabFromPool(size int) []float32 {
pool, exact := binLog(size)
// Tried to grab something of size
// zero or less
if pool == -1 {
return nil
}
// If the log is not exact, we
// need to "overallocate" so we have
// log+1
if !exact {
pool++
}
slice := getPool(pool).Get().([]float32)
slice = slice[:size]
return slice
}
// Returns a slice to the appropriate pool. If the slice does not have a cap that's precisely
// a power of 2, this will panic.
func returnToPool(slice []float32) {
if cap(slice) == 0 {
return
}
pool, exact := binLog(cap(slice))
if !exact {
panic("attempt to pool slice with non-exact cap. If you're a user, please file an issue with github.com/go-gl/mathgl about this bug. This should never happen.")
}
getPool(pool).Put(slice)
}
// This returns the integer base 2 log of the value
// and whether the log is exact or rounded down.
//
// This is only for positive integers.
//
// There are faster ways to do this, I'm open to suggestions. Most rely on knowing system endianness
// which Go makes hard to do. I'm hesistant to use float conversions and the math package because of off-by-one errors.
func binLog(val int) (int, bool) {
if val <= 0 {
return -1, false
}
exact := true
l := 0
for ; val > 1; val = val >> 1 {
// If the current lsb is 1 and the number
// is not equal to 1, this is not an exact
// log, but rather a rounding of it
if val&1 != 0 {
exact = false
}
l++
}
return l, exact
}
+109
View File
@@ -0,0 +1,109 @@
// Copyright 2014 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mgl32
import (
"errors"
"math"
)
// Ortho generates an Ortho Matrix.
func Ortho(left, right, bottom, top, near, far float32) Mat4 {
rml, tmb, fmn := (right - left), (top - bottom), (far - near)
return Mat4{float32(2. / rml), 0, 0, 0, 0, float32(2. / tmb), 0, 0, 0, 0, float32(-2. / fmn), 0, float32(-(right + left) / rml), float32(-(top + bottom) / tmb), float32(-(far + near) / fmn), 1}
}
// Ortho2D is equivalent to Ortho with the near and far planes being -1 and 1,
// respectively.
func Ortho2D(left, right, bottom, top float32) Mat4 {
return Ortho(left, right, bottom, top, -1, 1)
}
// Perspective generates a Perspective Matrix.
func Perspective(fovy, aspect, near, far float32) Mat4 {
// fovy = (fovy * math.Pi) / 180.0 // convert from degrees to radians
nmf, f := near-far, float32(1./math.Tan(float64(fovy)/2.0))
return Mat4{float32(f / aspect), 0, 0, 0, 0, float32(f), 0, 0, 0, 0, float32((near + far) / nmf), -1, 0, 0, float32((2. * far * near) / nmf), 0}
}
// Frustum generates a Frustum Matrix.
func Frustum(left, right, bottom, top, near, far float32) Mat4 {
rml, tmb, fmn := (right - left), (top - bottom), (far - near)
A, B, C, D := (right+left)/rml, (top+bottom)/tmb, -(far+near)/fmn, -(2*far*near)/fmn
return Mat4{float32((2. * near) / rml), 0, 0, 0, 0, float32((2. * near) / tmb), 0, 0, float32(A), float32(B), float32(C), -1, 0, 0, float32(D), 0}
}
// LookAt generates a transform matrix from world space to the given eye space.
func LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float32) Mat4 {
return LookAtV(Vec3{eyeX, eyeY, eyeZ}, Vec3{centerX, centerY, centerZ}, Vec3{upX, upY, upZ})
}
// LookAtV generates a transform matrix from world space into the specific eye
// space.
func LookAtV(eye, center, up Vec3) Mat4 {
f := center.Sub(eye).Normalize()
s := f.Cross(up).Normalize()
u := s.Cross(f)
M := Mat4{
s[0], u[0], -f[0], 0,
s[1], u[1], -f[1], 0,
s[2], u[2], -f[2], 0,
0, 0, 0, 1,
}
return M.Mul4(Translate3D(float32(-eye[0]), float32(-eye[1]), float32(-eye[2])))
}
// Project transforms a set of coordinates from object space (in obj) to window
// coordinates (with depth).
//
// Window coordinates are continuous, not discrete (well, as continuous as an
// IEEE Floating Point can be), so you won't get exact pixel locations without
// rounding or similar
func Project(obj Vec3, modelview, projection Mat4, initialX, initialY, width, height int) (win Vec3) {
obj4 := obj.Vec4(1)
vpp := projection.Mul4(modelview).Mul4x1(obj4)
vpp = vpp.Mul(1 / vpp.W())
win[0] = float32(initialX) + (float32(width)*(vpp[0]+1))/2
win[1] = float32(initialY) + (float32(height)*(vpp[1]+1))/2
win[2] = (vpp[2] + 1) / 2
return win
}
// UnProject transforms a set of window coordinates to object space. If your MVP
// (projection.Mul(modelview) matrix is not invertible, this will return an
// error.
//
// Note that the projection may not be perfect if you use strict pixel locations
// rather than the exact values given by Projectf. (It's still unlikely to be
// perfect due to precision errors, but it will be closer)
func UnProject(win Vec3, modelview, projection Mat4, initialX, initialY, width, height int) (obj Vec3, err error) {
inv := projection.Mul4(modelview).Inv()
var blank Mat4
if inv == blank {
return Vec3{}, errors.New("Could not find matrix inverse (projection times modelview is probably non-singular)")
}
obj4 := inv.Mul4x1(Vec4{
(2 * (win[0] - float32(initialX)) / float32(width)) - 1,
(2 * (win[1] - float32(initialY)) / float32(height)) - 1,
2*win[2] - 1,
1.0,
})
obj = obj4.Vec3()
//if obj4[3] > MinValue {}
obj[0] /= obj4[3]
obj[1] /= obj4[3]
obj[2] /= obj4[3]
return obj, nil
}
+469
View File
@@ -0,0 +1,469 @@
// Copyright 2014 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mgl32
import (
"math"
)
// RotationOrder is the order in which rotations will be transformed for the
// purposes of AnglesToQuat.
type RotationOrder int
// The RotationOrder constants represent a series of rotations along the given
// axes for the use of AnglesToQuat.
const (
XYX RotationOrder = iota
XYZ
XZX
XZY
YXY
YXZ
YZY
YZX
ZYZ
ZYX
ZXZ
ZXY
)
// Quat represents a Quaternion, which is an extension of the imaginary numbers;
// there's all sorts of interesting theory behind it. In 3D graphics we mostly
// use it as a cheap way of representing rotation since quaternions are cheaper
// to multiply by, and easier to interpolate than matrices.
//
// A Quaternion has two parts: W, the so-called scalar component, and "V", the
// vector component. The vector component is considered to be the part in 3D
// space, while W (loosely interpreted) is its 4D coordinate.
type Quat struct {
W float32
V Vec3
}
// QuatIdent returns the quaternion identity: W=1; V=(0,0,0).
//
// As with all identities, multiplying any quaternion by this will yield the same
// quaternion you started with.
func QuatIdent() Quat {
return Quat{1., Vec3{0, 0, 0}}
}
// QuatRotate creates an angle from an axis and an angle relative to that axis.
//
// This is cheaper than HomogRotate3D.
func QuatRotate(angle float32, axis Vec3) Quat {
// angle = (float32(math.Pi) * angle) / 180.0
sn, cs := math.Sincos(float64(angle / 2))
s, c := float32(sn), float32(cs)
return Quat{c, axis.Mul(s)}
}
// X is a convenient alias for q.V[0]
func (q Quat) X() float32 {
return q.V[0]
}
// Y is a convenient alias for q.V[1]
func (q Quat) Y() float32 {
return q.V[1]
}
// Z is a convenient alias for q.V[2]
func (q Quat) Z() float32 {
return q.V[2]
}
// Add adds two quaternions. It's no more complicated than
// adding their W and V components.
func (q1 Quat) Add(q2 Quat) Quat {
return Quat{q1.W + q2.W, q1.V.Add(q2.V)}
}
// Sub subtracts two quaternions. It's no more complicated than
// subtracting their W and V components.
func (q1 Quat) Sub(q2 Quat) Quat {
return Quat{q1.W - q2.W, q1.V.Sub(q2.V)}
}
// Mul multiplies two quaternions. This can be seen as a rotation. Note that
// Multiplication is NOT commutative, meaning q1.Mul(q2) does not necessarily
// equal q2.Mul(q1).
func (q1 Quat) Mul(q2 Quat) Quat {
return Quat{q1.W*q2.W - q1.V.Dot(q2.V), q1.V.Cross(q2.V).Add(q2.V.Mul(q1.W)).Add(q1.V.Mul(q2.W))}
}
// Scale every element of the quaternion by some constant factor.
func (q1 Quat) Scale(c float32) Quat {
return Quat{q1.W * c, Vec3{q1.V[0] * c, q1.V[1] * c, q1.V[2] * c}}
}
// Conjugate returns the conjugate of a quaternion. Equivalent to
// Quat{q1.W, q1.V.Mul(-1)}.
func (q1 Quat) Conjugate() Quat {
return Quat{q1.W, q1.V.Mul(-1)}
}
// Len gives the Length of the quaternion, also known as its Norm. This is the
// same thing as the Len of a Vec4.
func (q1 Quat) Len() float32 {
return float32(math.Sqrt(float64(q1.W*q1.W + q1.V[0]*q1.V[0] + q1.V[1]*q1.V[1] + q1.V[2]*q1.V[2])))
}
// Norm is an alias for Len() since both are very common terms.
func (q1 Quat) Norm() float32 {
return q1.Len()
}
// Normalize the quaternion, returning its versor (unit quaternion).
//
// This is the same as normalizing it as a Vec4.
func (q1 Quat) Normalize() Quat {
length := q1.Len()
if FloatEqual(1, length) {
return q1
}
if length == 0 {
return QuatIdent()
}
if length == InfPos {
length = MaxValue
}
return Quat{q1.W * 1 / length, q1.V.Mul(1 / length)}
}
// Inverse of a quaternion. The inverse is equivalent
// to the conjugate divided by the square of the length.
//
// This method computes the square norm by directly adding the sum
// of the squares of all terms instead of actually squaring q1.Len(),
// both for performance and precision.
func (q1 Quat) Inverse() Quat {
return q1.Conjugate().Scale(1 / q1.Dot(q1))
}
// Rotate a vector by the rotation this quaternion represents.
// This will result in a 3D vector. Strictly speaking, this is
// equivalent to q1.v.q* where the "."" is quaternion multiplication and v is interpreted
// as a quaternion with W 0 and V v. In code:
// q1.Mul(Quat{0,v}).Mul(q1.Conjugate()), and
// then retrieving the imaginary (vector) part.
//
// In practice, we hand-compute this in the general case and simplify
// to save a few operations.
func (q1 Quat) Rotate(v Vec3) Vec3 {
cross := q1.V.Cross(v)
// v + 2q_w * (q_v x v) + 2q_v x (q_v x v)
return v.Add(cross.Mul(2 * q1.W)).Add(q1.V.Mul(2).Cross(cross))
}
// Mat4 returns the homogeneous 3D rotation matrix corresponding to the
// quaternion.
func (q1 Quat) Mat4() Mat4 {
w, x, y, z := q1.W, q1.V[0], q1.V[1], q1.V[2]
return Mat4{
1 - 2*y*y - 2*z*z, 2*x*y + 2*w*z, 2*x*z - 2*w*y, 0,
2*x*y - 2*w*z, 1 - 2*x*x - 2*z*z, 2*y*z + 2*w*x, 0,
2*x*z + 2*w*y, 2*y*z - 2*w*x, 1 - 2*x*x - 2*y*y, 0,
0, 0, 0, 1,
}
}
// Dot product between two quaternions, equivalent to if this was a Vec4.
func (q1 Quat) Dot(q2 Quat) float32 {
return q1.W*q2.W + q1.V[0]*q2.V[0] + q1.V[1]*q2.V[1] + q1.V[2]*q2.V[2]
}
// ApproxEqual returns whether the quaternions are approximately equal, as if
// FloatEqual was called on each matching element
func (q1 Quat) ApproxEqual(q2 Quat) bool {
return FloatEqual(q1.W, q2.W) && q1.V.ApproxEqual(q2.V)
}
// ApproxEqualThreshold returns whether the quaternions are approximately equal with a given tolerence, as if
// FloatEqualThreshold was called on each matching element with the given epsilon
func (q1 Quat) ApproxEqualThreshold(q2 Quat, epsilon float32) bool {
return FloatEqualThreshold(q1.W, q2.W, epsilon) && q1.V.ApproxEqualThreshold(q2.V, epsilon)
}
// ApproxEqualFunc returns whether the quaternions are approximately equal using the given comparison function, as if
// the function had been called on each individual element
func (q1 Quat) ApproxEqualFunc(q2 Quat, f func(float32, float32) bool) bool {
return f(q1.W, q2.W) && q1.V.ApproxFuncEqual(q2.V, f)
}
// OrientationEqual returns whether the quaternions represents the same orientation
//
// Different values can represent the same orientation (q == -q) because quaternions avoid singularities
// and discontinuities involved with rotation in 3 dimensions by adding extra dimensions
func (q1 Quat) OrientationEqual(q2 Quat) bool {
return q1.OrientationEqualThreshold(q2, Epsilon)
}
// OrientationEqualThreshold returns whether the quaternions represents the same orientation with a given tolerence
func (q1 Quat) OrientationEqualThreshold(q2 Quat, epsilon float32) bool {
return Abs(q1.Normalize().Dot(q2.Normalize())) > 1-epsilon
}
// QuatSlerp is *S*pherical *L*inear Int*erp*olation, a method of interpolating
// between two quaternions. This always takes the straightest and shortest path on the sphere between
// the two quaternions, and maintains constant velocity.
//
// However, it's expensive and QuatSlerp(q1,q2) is not the same as QuatSlerp(q2,q1)
func QuatSlerp(q1, q2 Quat, amount float32) Quat {
q1, q2 = q1.Normalize(), q2.Normalize()
dot := q1.Dot(q2)
// Make sure we take the shortest path in case dot product is negative.
if dot < 0.0 {
q2 = q2.Scale(-1)
dot = -dot
}
// If the inputs are too close for comfort, linearly interpolate and normalize the result.
if dot > 0.9995 {
return QuatNlerp(q1, q2, amount)
}
// This is here for precision errors, I'm perfectly aware that *technically* the dot is bound [-1,1], but since Acos will freak out if it's not (even if it's just a liiiiitle bit over due to normal error) we need to clamp it
dot = Clamp(dot, -1, 1)
theta := float32(math.Acos(float64(dot))) * amount
sn, cs := math.Sincos(float64(theta))
s, c := float32(sn), float32(cs)
rel := q2.Sub(q1.Scale(dot)).Normalize()
return q1.Scale(c).Add(rel.Scale(s))
}
// QuatLerp is a *L*inear Int*erp*olation between two Quaternions, cheap and simple.
//
// Not excessively useful, but uses can be found.
func QuatLerp(q1, q2 Quat, amount float32) Quat {
return q1.Add(q2.Sub(q1).Scale(amount))
}
// QuatNlerp is a *Normalized* *L*inear Int*erp*olation between two Quaternions. Cheaper than Slerp
// and usually just as good. This is literally Lerp with Normalize() called on it.
//
// Unlike Slerp, constant velocity isn't maintained, but it's much faster and
// Nlerp(q1,q2) and Nlerp(q2,q1) return the same path. You should probably
// use this more often unless you're suffering from choppiness due to the
// non-constant velocity problem.
func QuatNlerp(q1, q2 Quat, amount float32) Quat {
return QuatLerp(q1, q2, amount).Normalize()
}
// AnglesToQuat performs a rotation in the specified order. If the order is not
// a valid RotationOrder, this function will panic
//
// The rotation "order" is more of an axis descriptor. For instance XZX would
// tell the function to interpret angle1 as a rotation about the X axis, angle2 about
// the Z axis, and angle3 about the X axis again.
//
// Based off the code for the Matlab function "angle2quat", though this implementation
// only supports 3 single angles as opposed to multiple angles.
func AnglesToQuat(angle1, angle2, angle3 float32, order RotationOrder) Quat {
var s [3]float64
var c [3]float64
s[0], c[0] = math.Sincos(float64(angle1 / 2))
s[1], c[1] = math.Sincos(float64(angle2 / 2))
s[2], c[2] = math.Sincos(float64(angle3 / 2))
ret := Quat{}
switch order {
case ZYX:
ret.W = float32(c[0]*c[1]*c[2] + s[0]*s[1]*s[2])
ret.V = Vec3{float32(c[0]*c[1]*s[2] - s[0]*s[1]*c[2]),
float32(c[0]*s[1]*c[2] + s[0]*c[1]*s[2]),
float32(s[0]*c[1]*c[2] - c[0]*s[1]*s[2]),
}
case ZYZ:
ret.W = float32(c[0]*c[1]*c[2] - s[0]*c[1]*s[2])
ret.V = Vec3{float32(c[0]*s[1]*s[2] - s[0]*s[1]*c[2]),
float32(c[0]*s[1]*c[2] + s[0]*s[1]*s[2]),
float32(s[0]*c[1]*c[2] + c[0]*c[1]*s[2]),
}
case ZXY:
ret.W = float32(c[0]*c[1]*c[2] - s[0]*s[1]*s[2])
ret.V = Vec3{float32(c[0]*s[1]*c[2] - s[0]*c[1]*s[2]),
float32(c[0]*c[1]*s[2] + s[0]*s[1]*c[2]),
float32(c[0]*s[1]*s[2] + s[0]*c[1]*c[2]),
}
case ZXZ:
ret.W = float32(c[0]*c[1]*c[2] - s[0]*c[1]*s[2])
ret.V = Vec3{float32(c[0]*s[1]*c[2] + s[0]*s[1]*s[2]),
float32(s[0]*s[1]*c[2] - c[0]*s[1]*s[2]),
float32(c[0]*c[1]*s[2] + s[0]*c[1]*c[2]),
}
case YXZ:
ret.W = float32(c[0]*c[1]*c[2] + s[0]*s[1]*s[2])
ret.V = Vec3{float32(c[0]*s[1]*c[2] + s[0]*c[1]*s[2]),
float32(s[0]*c[1]*c[2] - c[0]*s[1]*s[2]),
float32(c[0]*c[1]*s[2] - s[0]*s[1]*c[2]),
}
case YXY:
ret.W = float32(c[0]*c[1]*c[2] - s[0]*c[1]*s[2])
ret.V = Vec3{float32(c[0]*s[1]*c[2] + s[0]*s[1]*s[2]),
float32(s[0]*c[1]*c[2] + c[0]*c[1]*s[2]),
float32(c[0]*s[1]*s[2] - s[0]*s[1]*c[2]),
}
case YZX:
ret.W = float32(c[0]*c[1]*c[2] - s[0]*s[1]*s[2])
ret.V = Vec3{float32(c[0]*c[1]*s[2] + s[0]*s[1]*c[2]),
float32(c[0]*s[1]*s[2] + s[0]*c[1]*c[2]),
float32(c[0]*s[1]*c[2] - s[0]*c[1]*s[2]),
}
case YZY:
ret.W = float32(c[0]*c[1]*c[2] - s[0]*c[1]*s[2])
ret.V = Vec3{float32(s[0]*s[1]*c[2] - c[0]*s[1]*s[2]),
float32(c[0]*c[1]*s[2] + s[0]*c[1]*c[2]),
float32(c[0]*s[1]*c[2] + s[0]*s[1]*s[2]),
}
case XYZ:
ret.W = float32(c[0]*c[1]*c[2] - s[0]*s[1]*s[2])
ret.V = Vec3{float32(c[0]*s[1]*s[2] + s[0]*c[1]*c[2]),
float32(c[0]*s[1]*c[2] - s[0]*c[1]*s[2]),
float32(c[0]*c[1]*s[2] + s[0]*s[1]*c[2]),
}
case XYX:
ret.W = float32(c[0]*c[1]*c[2] - s[0]*c[1]*s[2])
ret.V = Vec3{float32(c[0]*c[1]*s[2] + s[0]*c[1]*c[2]),
float32(c[0]*s[1]*c[2] + s[0]*s[1]*s[2]),
float32(s[0]*s[1]*c[2] - c[0]*s[1]*s[2]),
}
case XZY:
ret.W = float32(c[0]*c[1]*c[2] + s[0]*s[1]*s[2])
ret.V = Vec3{float32(s[0]*c[1]*c[2] - c[0]*s[1]*s[2]),
float32(c[0]*c[1]*s[2] - s[0]*s[1]*c[2]),
float32(c[0]*s[1]*c[2] + s[0]*c[1]*s[2]),
}
case XZX:
ret.W = float32(c[0]*c[1]*c[2] - s[0]*c[1]*s[2])
ret.V = Vec3{float32(c[0]*c[1]*s[2] + s[0]*c[1]*c[2]),
float32(c[0]*s[1]*s[2] - s[0]*s[1]*c[2]),
float32(c[0]*s[1]*c[2] + s[0]*s[1]*s[2]),
}
default:
panic("Unsupported rotation order")
}
return ret
}
// Mat4ToQuat converts a pure rotation matrix into a quaternion
func Mat4ToQuat(m Mat4) Quat {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
if tr := m[0] + m[5] + m[10]; tr > 0 {
s := float32(0.5 / math.Sqrt(float64(tr+1.0)))
return Quat{
0.25 / s,
Vec3{
(m[6] - m[9]) * s,
(m[8] - m[2]) * s,
(m[1] - m[4]) * s,
},
}
}
if (m[0] > m[5]) && (m[0] > m[10]) {
s := float32(2.0 * math.Sqrt(float64(1.0+m[0]-m[5]-m[10])))
return Quat{
(m[6] - m[9]) / s,
Vec3{
0.25 * s,
(m[4] + m[1]) / s,
(m[8] + m[2]) / s,
},
}
}
if m[5] > m[10] {
s := float32(2.0 * math.Sqrt(float64(1.0+m[5]-m[0]-m[10])))
return Quat{
(m[8] - m[2]) / s,
Vec3{
(m[4] + m[1]) / s,
0.25 * s,
(m[9] + m[6]) / s,
},
}
}
s := float32(2.0 * math.Sqrt(float64(1.0+m[10]-m[0]-m[5])))
return Quat{
(m[1] - m[4]) / s,
Vec3{
(m[8] + m[2]) / s,
(m[9] + m[6]) / s,
0.25 * s,
},
}
}
// QuatLookAtV creates a rotation from an eye vector to a center vector
//
// It assumes the front of the rotated object at Z- and up at Y+
func QuatLookAtV(eye, center, up Vec3) Quat {
// http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/#I_need_an_equivalent_of_gluLookAt__How_do_I_orient_an_object_towards_a_point__
// https://bitbucket.org/sinbad/ogre/src/d2ef494c4a2f5d6e2f0f17d3bfb9fd936d5423bb/OgreMain/src/OgreCamera.cpp?at=default#cl-161
direction := center.Sub(eye).Normalize()
// Find the rotation between the front of the object (that we assume towards Z-,
// but this depends on your model) and the desired direction
rotDir := QuatBetweenVectors(Vec3{0, 0, -1}, direction)
// Recompute up so that it's perpendicular to the direction
// You can skip that part if you really want to force up
//right := direction.Cross(up)
//up = right.Cross(direction)
// Because of the 1rst rotation, the up is probably completely screwed up.
// Find the rotation between the "up" of the rotated object, and the desired up
upCur := rotDir.Rotate(Vec3{0, 1, 0})
rotUp := QuatBetweenVectors(upCur, up)
rotTarget := rotUp.Mul(rotDir) // remember, in reverse order.
return rotTarget.Inverse() // camera rotation should be inversed!
}
// QuatBetweenVectors calculates the rotation between two vectors
func QuatBetweenVectors(start, dest Vec3) Quat {
// http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/#I_need_an_equivalent_of_gluLookAt__How_do_I_orient_an_object_towards_a_point__
// https://github.com/g-truc/glm/blob/0.9.5/glm/gtx/quaternion.inl#L225
// https://bitbucket.org/sinbad/ogre/src/d2ef494c4a2f5d6e2f0f17d3bfb9fd936d5423bb/OgreMain/include/OgreVector3.h?at=default#cl-654
start = start.Normalize()
dest = dest.Normalize()
epsilon := float32(0.001)
cosTheta := start.Dot(dest)
if cosTheta < -1.0+epsilon {
// special case when vectors in opposite directions:
// there is no "ideal" rotation axis
// So guess one; any will do as long as it's perpendicular to start
axis := Vec3{1, 0, 0}.Cross(start)
if axis.Dot(axis) < epsilon {
// bad luck, they were parallel, try again!
axis = Vec3{0, 1, 0}.Cross(start)
}
return QuatRotate(math.Pi, axis.Normalize())
}
axis := start.Cross(dest)
s := float32(math.Sqrt(float64(1.0+cosTheta) * 2.0))
return Quat{
s * 0.5,
axis.Mul(1.0 / s),
}
}
+321
View File
@@ -0,0 +1,321 @@
// Copyright 2014 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mgl32
import (
"fmt"
"math"
)
// Circle generates a circle centered at (0,0) with a given radius.
// The radii are assumed to be in GL's coordinate sizing.
//
// Technically this draws an ellipse with two axes that match with the X and Y axes, the reason it has a radiusX and radiusY is because GL's coordinate system
// is proportional to screen width and screen height. So if you have a non-square viewport, a single radius will appear
// to "squash" the circle in one direction (usually the Y direction), so the X and Y radius allow for a circle to be made.
// A good way to get the correct radii is with mathgl.ScreenToGLCoords(radius, radius, screenWidth, screenHeight) which will get you the correct
// proportional GL coords.
//
// The numSlices argument specifies how many triangles you want your circle divided into, setting this
// number to too low a value may cause problem (and too high will cause it to take a lot of memory and time to compute
// without much gain in resolution).
//
// This uses discrete triangles, not a triangle fan
func Circle(radiusX, radiusY float32, numSlices int) []Vec2 {
twoPi := float32(2.0 * math.Pi)
circlePoints := make([]Vec2, 0, numSlices*3)
center := Vec2{0.0, 0.0}
previous := Vec2{radiusX, 0.0}
for theta := twoPi / float32(numSlices); !FloatEqual(theta, twoPi); theta = Clamp(theta+twoPi/float32(numSlices), 0.0, twoPi) {
sin, cos := math.Sincos(float64(theta))
curr := Vec2{float32(cos) * radiusX, float32(sin) * radiusY}
circlePoints = append(circlePoints, center, previous, curr)
previous = curr
}
// Now add the final point at theta=2pi
circlePoints = append(circlePoints, center, previous, Vec2{radiusX, 0.0})
return circlePoints
}
// Rect generates a 2-triangle rectangle for use with GL_TRIANGLES. The width and height should use GL's proportions (that is, where a width of 1.0
// is equivalent to half of the width of the render target); however, the y-coordinates grow downwards, not upwards. That is, it
// assumes you want the origin of the rectangle with the top-left corner at (0.0,0.0).
//
// Keep in mind that GL's coordinate system is proportional, so width=height will not result in a square unless your viewport is square.
// If you want to maintain proportionality regardless of screen size, use the results of w,h := ScreenToGLCoordsf(absoluteWidth, absoluteHeight, screenWidth, screenHeight);
// w,h=w+1,h-1 in the call to this function. (The w+1,h-1 step maps the coordinates to start at 0.0 rather than -1.0)
func Rect(width, height float32) []Vec2 {
return []Vec2{
{0.0, 0.0},
{0.0, -height},
{width, -height},
{0.0, 0.0},
{width, -height},
{width, 0.0},
}
}
// QuadraticBezierCurve2D interpolates the point t on the given bezier curve.
func QuadraticBezierCurve2D(t float32, cPoint1, cPoint2, cPoint3 Vec2) Vec2 {
if t < 0.0 || t > 1.0 {
panic("Can't interpolate on bezier curve with t out of range [0.0,1.0]")
}
return cPoint1.Mul((1.0 - t) * (1.0 - t)).Add(cPoint2.Mul(2 * (1 - t) * t)).Add(cPoint3.Mul(t * t))
}
// QuadraticBezierCurve3D interpolates the point t on the given bezier curve.
func QuadraticBezierCurve3D(t float32, cPoint1, cPoint2, cPoint3 Vec3) Vec3 {
if t < 0.0 || t > 1.0 {
panic("Can't interpolate on bezier curve with t out of range [0.0,1.0]")
}
return cPoint1.Mul((1.0 - t) * (1.0 - t)).Add(cPoint2.Mul(2 * (1 - t) * t)).Add(cPoint3.Mul(t * t))
}
// CubicBezierCurve2D interpolates the point t on the given bezier curve.
func CubicBezierCurve2D(t float32, cPoint1, cPoint2, cPoint3, cPoint4 Vec2) Vec2 {
if t < 0.0 || t > 1.0 {
panic("Can't interpolate on bezier curve with t out of range [0.0,1.0]")
}
sum14 := cPoint1.Mul((1 - t) * (1 - t) * (1 - t)).Add(cPoint4.Mul(t * t * t))
sum23 := cPoint2.Mul(3 * (1 - t) * (1 - t) * t).Add(cPoint3.Mul(3 * (1 - t) * t * t))
return sum14.Add(sum23)
}
// CubicBezierCurve3D interpolates the point t on the given bezier curve.
func CubicBezierCurve3D(t float32, cPoint1, cPoint2, cPoint3, cPoint4 Vec3) Vec3 {
if t < 0.0 || t > 1.0 {
panic("Can't interpolate on bezier curve with t out of range [0.0,1.0]")
}
sum14 := cPoint1.Mul((1 - t) * (1 - t) * (1 - t)).Add(cPoint4.Mul(t * t * t))
sum23 := cPoint2.Mul(3 * (1 - t) * (1 - t) * t).Add(cPoint3.Mul(3 * (1 - t) * t * t))
return sum14.Add(sum23)
}
// BezierCurve2D returns the point at point t along an n-control point Bezier curve
//
// t must be in the range 0.0 and 1.0 or this function will panic. Consider [0.0,1.0] to be similar to a percentage,
// 0.0 is first control point, and the point at 1.0 is the last control point. Any point in between is how far along the path you are between 0 and 1.
//
// This function is not sensitive to the coordinate system of the control points. It will correctly interpolate regardless of whether they're in screen coords,
// gl coords, or something else entirely
func BezierCurve2D(t float32, cPoints []Vec2) Vec2 {
if t < 0.0 || t > 1.0 {
panic("Input to bezier has t not in range [0,1]. If you think this is a precision error, use mathgl.Clamp[f|d] before calling this function")
}
n := len(cPoints) - 1
point := cPoints[0].Mul(float32(math.Pow(float64(1.0-t), float64(n))))
for i := 1; i <= n; i++ {
point = point.Add(cPoints[i].Mul(float32(float64(choose(n, i)) * math.Pow(float64(1-t), float64(n-i)) * math.Pow(float64(t), float64(i))))) // P += P_i * nCi * (1-t)^(n-i) * t^i
}
return point
}
// BezierCurve3D same as the 2D version, except the line is in 3D space
func BezierCurve3D(t float32, cPoints []Vec3) Vec3 {
if t < 0.0 || t > 1.0 {
panic("Input to bezier has t not in range [0,1]. If you think this is a precision error, use mathgl.Clamp[f|d] before calling this function")
}
n := len(cPoints) - 1
point := cPoints[0].Mul(float32(math.Pow(float64(1.0-t), float64(n))))
for i := 1; i <= n; i++ {
point = point.Add(cPoints[i].Mul(float32(float64(choose(n, i)) * math.Pow(float64(1-t), float64(n-i)) * math.Pow(float64(t), float64(i))))) // P += P_i * nCi * (1-t)^(n-i) * t^i
}
return point
}
// MakeBezierCurve2D generates a bezier curve with controlPoints cPoints. The
// numPoints argument determines how many "samples" it makes along the line. For
// instance, a call to this with numPoints 2 will have exactly two points: the
// start and end points For any points above 2 it will divide it into
// numPoints-1 chunks (which means it will generate numPoints-2 vertices other
// than the beginning and end). So for 3 points it will divide it in half, 4
// points into thirds, and so on.
//
// This is likely to get rather expensive for anything over perhaps a cubic
// curve.
func MakeBezierCurve2D(numPoints int, cPoints []Vec2) (line []Vec2) {
line = make([]Vec2, numPoints)
if numPoints == 0 {
return
} else if numPoints == 1 {
line[0] = cPoints[0]
return
} else if numPoints == 2 {
line[0] = cPoints[0]
line[1] = cPoints[len(cPoints)-1]
return
}
line[0] = cPoints[0]
for i := 1; i < numPoints-1; i++ {
line[i] = BezierCurve2D(Clamp(float32(i)/float32(numPoints-1), 0.0, 1.0), cPoints)
}
line[numPoints-1] = cPoints[len(cPoints)-1]
return
}
// MakeBezierCurve3D same as the 2D version, except with the line in 3D space.
func MakeBezierCurve3D(numPoints int, cPoints []Vec3) (line []Vec3) {
line = make([]Vec3, numPoints)
if numPoints == 0 {
return
} else if numPoints == 1 {
line[0] = cPoints[0]
return
} else if numPoints == 2 {
line[0] = cPoints[0]
line[1] = cPoints[len(cPoints)-1]
return
}
line[0] = cPoints[0]
for i := 1; i < numPoints-1; i++ {
line[i] = BezierCurve3D(Clamp(float32(i)/float32(numPoints-1), 0.0, 1.0), cPoints)
}
line[numPoints-1] = cPoints[len(cPoints)-1]
return
}
// BezierSurface creates a 2-dimensional Bezier surface of arbitrary degree in
// 3D Space Like the curve functions, if u or v are not in the range [0.0,1.0]
// the function will panic, use Clamp[f|d] to ensure it is correct.
//
// The control point matrix must not be jagged, or this will end up panicking
// from an index out of bounds exception
func BezierSurface(u, v float32, cPoints [][]Vec3) Vec3 {
if u < 0.0 || u > 1.0 || v < 1.0 || v > 1.0 {
panic("u or v not in range [0.0,1.0] in BezierSurface")
}
n := len(cPoints) - 1
m := len(cPoints[0]) - 1
point := cPoints[0][0].Mul(float32(math.Pow(float64(1.0-u), float64(n)) * math.Pow(float64(1.0-v), float64(m))))
for i := 0; i <= n; i++ {
for j := 0; j <= m; j++ {
if i == 0 && j == 0 {
continue
}
point = point.Add(cPoints[i][j].Mul(float32(float64(choose(n, i)) * math.Pow(float64(u), float64(i)) * math.Pow(float64(1.0-u), float64(n-i)) * float64(choose(m, j)) * math.Pow(float64(v), float64(j)) * math.Pow(float64(1.0-v), float64(m-j)))))
}
}
return point
}
// BezierSplineInterpolate2D does interpolation over a spline of several bezier
// curves. Each bezier curve must have a finite range, though the spline may be
// disjoint. The bezier curves are not required to be in any particular order.
//
// If t is out of the range of all given curves, this function will panic
func BezierSplineInterpolate2D(t float32, ranges [][2]float32, cPoints [][]Vec2) Vec2 {
if len(ranges) != len(cPoints) {
panic("Each bezier curve needs a range")
}
for i, curveRange := range ranges {
if t >= curveRange[0] && t <= curveRange[1] {
return BezierCurve2D((t-curveRange[0])/(curveRange[1]-curveRange[0]), cPoints[i])
}
}
panic("t is out of the range of all bezier curves in this spline")
}
// BezierSplineInterpolate3D does interpolation over a spline of several bezier
// curves. Each bezier curve must have a finite range, though the spline may be
// disjoint. The bezier curves are not required to be in any particular order.
//
// If t is out of the range of all given curves, this function will panic
func BezierSplineInterpolate3D(t float32, ranges [][2]float32, cPoints [][]Vec3) Vec3 {
if len(ranges) != len(cPoints) {
panic("Each bezier curve needs a range")
}
for i, curveRange := range ranges {
if t >= curveRange[0] && t <= curveRange[1] {
return BezierCurve3D((t-curveRange[0])/(curveRange[1]-curveRange[0]), cPoints[i])
}
}
panic("t is out of the range of all bezier curves in this spline")
}
// ReticulateSplines reticulates ALL the Splines.
//
// For the overly serious: the function is just for fun. It does nothing except prints a Maxis reference. Technically you could "reticulate splines"
// by joining a bunch of splines together, but that ruins the joke.
func ReticulateSplines(ranges [][][2]float32, cPoints [][][]Vec2, withLlamas bool) {
if !withLlamas {
fmt.Println("You can't reticulate splines without llamas, silly.")
} else {
fmt.Println("Actually, you can't even reticulate splines WITH llamas")
}
}
// ScreenToGLCoords transforms from pixel coordinates to GL coordinates.
//
// This assumes that your pixel coordinate system considers its origin to be in the top left corner (GL's is in the bottom left).
// The coordinates x and y may be out of the range [0,screenWidth-1] and [0,screeneHeight-1].
//
// GL's coordinate system maps [screenWidth-1,0] to [1.0,1.0] and [0,screenHeight-1] to [-1.0,-1.0]. If x and y are out of the range, they'll still
// be mapped correctly, just off the screen. (e.g. if y = 2*(screenHeight-1) you'll get -3.0 for yOut)
//
// This is similar to Unproject, except for 2D cases and much simpler (especially since an inverse may always be found)
func ScreenToGLCoords(x, y int, screenWidth, screenHeight int) (xOut, yOut float32) {
xOut = 2.0*float32(x)/float32(screenWidth-1) - 1.0
yOut = -2.0*float32(y)/float32(screenHeight-1) + 1.0
return
}
// GLToScreenCoords transforms from GL's proportional system to pixel coordinates.
//
// Assumes the pixel coordinate system has its origin in the top left corner. (GL's is in the bottom left)
//
// GL's coordinate system maps [screenWidth-1,0] to [1.0,1.0] and [0,screenHeight-1] to [-1.0,-1.0]. If x and y are out of the range, they'll still
// be mapped correctly, just off the screen. (e.g. if y=-3.0, you'll get 2*(screenHeight-1) for yOut)
//
// This is similar to Project, except for 2D cases and much simpler
func GLToScreenCoords(x, y float32, screenWidth, screenHeight int) (xOut, yOut int) {
xOut = int((x + 1.0) * float32(screenWidth-1) / 2.0)
yOut = int((1.0 - y) * float32(screenHeight-1) / 2.0)
return
}
// choose calculates the binomial coefficient C(n,k) aka nCk
func choose(n, k int) int {
if k == 0 {
return 1
} else if n == 0 {
return 0
}
result := float32(n - (k - 1))
for i := 2; i <= k; i++ {
result *= float32(n-(k-i)) / float32(i)
}
return int(result)
}
+234
View File
@@ -0,0 +1,234 @@
// Copyright 2014 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mgl32
import "math"
// Rotate2D returns a rotation Matrix about a angle in 2-D space. Specifically about the origin.
// It is a 2x2 matrix, if you need a 3x3 for Homogeneous math (e.g. composition with a Translation matrix)
// see HomogRotate2D
func Rotate2D(angle float32) Mat2 {
//angle = (angle * math.Pi) / 180.0
sn, cs := math.Sincos(float64(angle))
sin, cos := float32(sn), float32(cs)
return Mat2{cos, sin, -sin, cos}
}
// Rotate3DX returns a 3x3 (non-homogeneous) Matrix that rotates by angle about the X-axis
//
// Where c is cos(angle) and s is sin(angle)
//
// [1 0 0]
// [0 c -s]
// [0 s c ]
func Rotate3DX(angle float32) Mat3 {
//angle = (angle * math.Pi) / 180.0
sn, cs := math.Sincos(float64(angle))
sin, cos := float32(sn), float32(cs)
return Mat3{1, 0, 0, 0, cos, sin, 0, -sin, cos}
}
// Rotate3DY returns a 3x3 (non-homogeneous) Matrix that rotates by angle about the Y-axis
//
// Where c is cos(angle) and s is sin(angle)
//
// [c 0 s]
// [0 1 0]
// [s 0 c ]
func Rotate3DY(angle float32) Mat3 {
//angle = (angle * math.Pi) / 180.0
sn, cs := math.Sincos(float64(angle))
sin, cos := float32(sn), float32(cs)
return Mat3{cos, 0, -sin, 0, 1, 0, sin, 0, cos}
}
// Rotate3DZ returns a 3x3 (non-homogeneous) Matrix that rotates by angle about the Z-axis
//
// Where c is cos(angle) and s is sin(angle)
//
// [c -s 0]
// [s c 0]
// [0 0 1 ]
func Rotate3DZ(angle float32) Mat3 {
//angle = (angle * math.Pi) / 180.0
sn, cs := math.Sincos(float64(angle))
sin, cos := float32(sn), float32(cs)
return Mat3{cos, sin, 0, -sin, cos, 0, 0, 0, 1}
}
// Translate2D returns a homogeneous (3x3 for 2D-space) Translation matrix that moves a point by Tx units in the x-direction and Ty units in the y-direction
//
// [[1, 0, Tx]]
// [[0, 1, Ty]]
// [[0, 0, 1 ]]
func Translate2D(Tx, Ty float32) Mat3 {
return Mat3{1, 0, 0, 0, 1, 0, float32(Tx), float32(Ty), 1}
}
// Translate3D returns a homogeneous (4x4 for 3D-space) Translation matrix that moves a point by Tx units in the x-direction, Ty units in the y-direction,
// and Tz units in the z-direction
//
// [[1, 0, 0, Tx]]
// [[0, 1, 0, Ty]]
// [[0, 0, 1, Tz]]
// [[0, 0, 0, 1 ]]
func Translate3D(Tx, Ty, Tz float32) Mat4 {
return Mat4{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, float32(Tx), float32(Ty), float32(Tz), 1}
}
// HomogRotate2D is the same as Rotate2D, except homogeneous (3x3 with the extra row/col being all zeroes with a one in the bottom right)
func HomogRotate2D(angle float32) Mat3 {
//angle = (angle * math.Pi) / 180.0
sn, cs := math.Sincos(float64(angle))
sin, cos := float32(sn), float32(cs)
return Mat3{cos, sin, 0, -sin, cos, 0, 0, 0, 1}
}
// HomogRotate3DX is the same as Rotate3DX, except homogeneous (4x4 with the extra row/col being all zeroes with a one in the bottom right)
func HomogRotate3DX(angle float32) Mat4 {
//angle = (angle * math.Pi) / 180.0
sn, cs := math.Sincos(float64(angle))
sin, cos := float32(sn), float32(cs)
return Mat4{1, 0, 0, 0, 0, cos, sin, 0, 0, -sin, cos, 0, 0, 0, 0, 1}
}
// HomogRotate3DY is the same as Rotate3DY, except homogeneous (4x4 with the extra row/col being all zeroes with a one in the bottom right)
func HomogRotate3DY(angle float32) Mat4 {
//angle = (angle * math.Pi) / 180.0
sn, cs := math.Sincos(float64(angle))
sin, cos := float32(sn), float32(cs)
return Mat4{cos, 0, -sin, 0, 0, 1, 0, 0, sin, 0, cos, 0, 0, 0, 0, 1}
}
// HomogRotate3DZ is the same as Rotate3DZ, except homogeneous (4x4 with the extra row/col being all zeroes with a one in the bottom right)
func HomogRotate3DZ(angle float32) Mat4 {
//angle = (angle * math.Pi) / 180.0
sn, cs := math.Sincos(float64(angle))
sin, cos := float32(sn), float32(cs)
return Mat4{cos, sin, 0, 0, -sin, cos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}
}
// Scale3D creates a homogeneous 3D scaling matrix
// [[ scaleX, 0 , 0 , 0 ]]
// [[ 0 , scaleY, 0 , 0 ]]
// [[ 0 , 0 , scaleZ, 0 ]]
// [[ 0 , 0 , 0 , 1 ]]
func Scale3D(scaleX, scaleY, scaleZ float32) Mat4 {
return Mat4{float32(scaleX), 0, 0, 0, 0, float32(scaleY), 0, 0, 0, 0, float32(scaleZ), 0, 0, 0, 0, 1}
}
// Scale2D creates a homogeneous 2D scaling matrix
// [[ scaleX, 0 , 0 ]]
// [[ 0 , scaleY, 0 ]]
// [[ 0 , 0 , 1 ]]
func Scale2D(scaleX, scaleY float32) Mat3 {
return Mat3{float32(scaleX), 0, 0, 0, float32(scaleY), 0, 0, 0, 1}
}
// ShearX2D creates a homogeneous 2D shear matrix along the X-axis
func ShearX2D(shear float32) Mat3 {
return Mat3{1, 0, 0, float32(shear), 1, 0, 0, 0, 1}
}
// ShearY2D creates a homogeneous 2D shear matrix along the Y-axis
func ShearY2D(shear float32) Mat3 {
return Mat3{1, float32(shear), 0, 0, 1, 0, 0, 0, 1}
}
// ShearX3D creates a homogeneous 3D shear matrix along the X-axis
func ShearX3D(shearY, shearZ float32) Mat4 {
return Mat4{1, float32(shearY), float32(shearZ), 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}
}
// ShearY3D creates a homogeneous 3D shear matrix along the Y-axis
func ShearY3D(shearX, shearZ float32) Mat4 {
return Mat4{1, 0, 0, 0, float32(shearX), 1, float32(shearZ), 0, 0, 0, 1, 0, 0, 0, 0, 1}
}
// ShearZ3D creates a homogeneous 3D shear matrix along the Z-axis
func ShearZ3D(shearX, shearY float32) Mat4 {
return Mat4{1, 0, 0, 0, 0, 1, 0, 0, float32(shearX), float32(shearY), 1, 0, 0, 0, 0, 1}
}
// HomogRotate3D creates a 3D rotation Matrix that rotates by (radian) angle about some arbitrary axis given by a normalized Vector.
// It produces a homogeneous matrix (4x4)
//
// Where c is cos(angle) and s is sin(angle), and x, y, and z are the first, second, and third elements of the axis vector (respectively):
//
// [[ x^2(1-c)+c, xy(1-c)-zs, xz(1-c)+ys, 0 ]]
// [[ xy(1-c)+zs, y^2(1-c)+c, yz(1-c)-xs, 0 ]]
// [[ xz(1-c)-ys, yz(1-c)+xs, z^2(1-c)+c, 0 ]]
// [[ 0 , 0 , 0 , 1 ]]
func HomogRotate3D(angle float32, axis Vec3) Mat4 {
x, y, z := axis[0], axis[1], axis[2]
sn, cs := math.Sincos(float64(angle))
s, c := float32(sn), float32(cs)
k := 1 - c
return Mat4{x*x*k + c, x*y*k + z*s, x*z*k - y*s, 0, x*y*k - z*s, y*y*k + c, y*z*k + x*s, 0, x*z*k + y*s, y*z*k - x*s, z*z*k + c, 0, 0, 0, 0, 1}
}
// Extract3DScale extracts the 3d scaling from a homogeneous matrix
func Extract3DScale(m Mat4) (x, y, z float32) {
return float32(math.Sqrt(float64(m[0]*m[0] + m[1]*m[1] + m[2]*m[2]))),
float32(math.Sqrt(float64(m[4]*m[4] + m[5]*m[5] + m[6]*m[6]))),
float32(math.Sqrt(float64(m[8]*m[8] + m[9]*m[9] + m[10]*m[10])))
}
// ExtractMaxScale extracts the maximum scaling from a homogeneous matrix
func ExtractMaxScale(m Mat4) float32 {
scaleX := float64(m[0]*m[0] + m[1]*m[1] + m[2]*m[2])
scaleY := float64(m[4]*m[4] + m[5]*m[5] + m[6]*m[6])
scaleZ := float64(m[8]*m[8] + m[9]*m[9] + m[10]*m[10])
return float32(math.Sqrt(math.Max(scaleX, math.Max(scaleY, scaleZ))))
}
// Mat4Normal calculates the Normal of the Matrix (aka the inverse transpose)
func Mat4Normal(m Mat4) Mat3 {
n := m.Inv().Transpose()
return Mat3{n[0], n[1], n[2], n[4], n[5], n[6], n[8], n[9], n[10]}
}
// TransformCoordinate multiplies a 3D vector by a transformation given by
// the homogeneous 4D matrix m, applying any translation.
// If this transformation is non-affine, it will project this
// vector onto the plane w=1 before returning the result.
//
// This is similar to saying you're transforming and projecting a point.
//
// This is effectively equivalent to the GLSL code
//
// vec4 r = (m * vec4(v,1.));
// r = r/r.w;
// vec3 newV = r.xyz;
func TransformCoordinate(v Vec3, m Mat4) Vec3 {
t := v.Vec4(1)
t = m.Mul4x1(t)
t = t.Mul(1 / t[3])
return t.Vec3()
}
// TransformNormal multiplies a 3D vector by a transformation given by
// the homogeneous 4D matrix m, NOT applying any translations.
//
// This is similar to saying you're applying a transformation
// to a direction or normal. Rotation still applies (as does scaling),
// but translating a direction or normal is meaningless.
//
// This is effectively equivalent to the GLSL code
//
// vec4 r = (m * vec4(v,0.));
// vec3 newV = r.xyz
func TransformNormal(v Vec3, m Mat4) Vec3 {
t := v.Vec4(0)
t = m.Mul4x1(t)
return t.Vec3()
}
+144
View File
@@ -0,0 +1,144 @@
// Copyright 2014 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run codegen.go -template vector.tmpl -output vector.go
//go:generate go run codegen.go -template matrix.tmpl -output matrix.go
//go:generate go run codegen.go -mgl64
package mgl32
import (
"math"
)
// Epsilon is some tiny value that determines how precisely equal we want our floats to be
// This is exported and left as a variable in case you want to change the default threshold for the
// purposes of certain methods (e.g. Unproject uses the default epsilon when determining
// if the determinant is "close enough" to zero to mean there's no inverse).
//
// This is, obviously, not mutex protected so be **absolutely sure** that no functions using Epsilon
// are being executed when you change this.
var Epsilon float32 = 1e-10
// Abs is a direct copy of the math package's Abs. This is here for the mgl32
// package, to prevent rampant type conversions during equality tests.
func Abs(a float32) float32 {
if a < 0 {
return -a
} else if a == 0 {
return 0
}
return a
}
// FloatEqual is a safe utility function to compare floats.
// It's Taken from http://floating-point-gui.de/errors/comparison/
//
// It is slightly altered to not call Abs when not needed.
func FloatEqual(a, b float32) bool {
return FloatEqualThreshold(a, b, Epsilon)
}
// FloatEqualFunc is a utility closure that will generate a function that
// always approximately compares floats like FloatEqualThreshold with a different
// threshold.
func FloatEqualFunc(epsilon float32) func(float32, float32) bool {
return func(a, b float32) bool {
return FloatEqualThreshold(a, b, epsilon)
}
}
// Various useful constants.
var (
MinNormal = float32(1.1754943508222875e-38) // 1 / 2**(127 - 1)
MinValue = float32(math.SmallestNonzeroFloat32)
MaxValue = float32(math.MaxFloat32)
InfPos = float32(math.Inf(1))
InfNeg = float32(math.Inf(-1))
NaN = float32(math.NaN())
)
// FloatEqualThreshold is a utility function to compare floats.
// It's Taken from http://floating-point-gui.de/errors/comparison/
//
// It is slightly altered to not call Abs when not needed.
//
// This differs from FloatEqual in that it lets you pass in your comparison threshold, so that you can adjust the comparison value to your specific needs
func FloatEqualThreshold(a, b, epsilon float32) bool {
if a == b { // Handles the case of inf or shortcuts the loop when no significant error has accumulated
return true
}
diff := Abs(a - b)
if a*b == 0 || diff < MinNormal { // If a or b are 0 or both are extremely close to it
return diff < epsilon*epsilon
}
// Else compare difference
return diff/(Abs(a)+Abs(b)) < epsilon
}
// Clamp takes in a value and two thresholds. If the value is smaller than the low
// threshold, it returns the low threshold. If it's bigger than the high threshold
// it returns the high threshold. Otherwise it returns the value.
//
// Useful to prevent some functions from freaking out because a value was
// teeeeechnically out of range.
func Clamp(a, low, high float32) float32 {
if a < low {
return low
} else if a > high {
return high
}
return a
}
// ClampFunc generates a closure that returns its parameter
// clamped to the range [low,high].
func ClampFunc(low, high float32) func(float32) float32 {
return func(a float32) float32 {
return Clamp(a, low, high)
}
}
// IsClamped checks if a is clamped between low and high as if
// Clamp(a, low, high) had been called.
//
// In most cases it's probably better to just call Clamp
// without checking this since it's relatively cheap.
//
// The IsClamped functions use strict equality (meaning: not the FloatEqual
// function) there shouldn't be any major issues with this since clamp is often
// used to fix minor errors
func IsClamped(a, low, high float32) bool {
return a >= low && a <= high
}
// SetMin sets a to b if a > b.
func SetMin(a, b *float32) {
if *b < *a {
*a = *b
}
}
// SetMax sets a to b if a < b.
func SetMax(a, b *float32) {
if *a < *b {
*a = *b
}
}
// Round shortens a float32 value to a specified precision (number of digits after the decimal point)
// with "round half up" tie-braking rule. Half-way values (23.5) are always rounded up (24).
func Round(v float32, precision int) float32 {
p := float64(precision)
t := float64(v) * math.Pow(10, p)
if t >= 0 {
return float32(math.Floor(t+0.5) / math.Pow(10, p))
}
return float32(math.Ceil(t-0.5) / math.Pow(10, p))
}
+371
View File
@@ -0,0 +1,371 @@
// Copyright 2014 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mgl32
import (
"math"
)
// VecN represents a vector of N elements backed by a slice.
//
// As with MatMxN, this is not for hardcore linear algebra with large dimensions. Use github.com/gonum/matrix
// or something like BLAS/LAPACK for that. This is for corner cases in 3D math where you require
// something a little bigger that 4D, but still relatively small.
//
// This VecN uses several sync.Pool objects as a memory pool. The rule is that for any sized vector, the backing slice
// has CAPACITY (not length) of 2^p where p is Ceil(log_2(N)) -- or in other words, rounding up the base-2
// log of the size of the vector. E.G. a VecN of size 17 will have a backing slice of Cap 32.
type VecN struct {
vec []float32
}
// NewVecNFromData creates a new vector with a backing slice filled with the contents
// of initial. It is NOT backed by initial, but rather a slice with cap
// 2^p where p is Ceil(log_2(len(initial))), with the data from initial copied into
// it.
func NewVecNFromData(initial []float32) *VecN {
if initial == nil {
return &VecN{}
}
var internal []float32
if shouldPool {
internal = grabFromPool(len(initial))
} else {
internal = make([]float32, len(initial))
}
copy(internal, initial)
return &VecN{vec: internal}
}
// NewVecN creates a new vector with a backing slice of
// 2^p where p = Ceil(log_2(n))
func NewVecN(n int) *VecN {
if shouldPool {
return &VecN{vec: grabFromPool(n)}
} else {
return &VecN{vec: make([]float32, n)}
}
}
// Raw returns the raw slice backing the VecN
//
// This may be sent back to the memory pool at any time
// and you aren't advised to rely on this value
func (vn VecN) Raw() []float32 {
return vn.vec
}
// Get the element at index i from the vector. This does not bounds check, and
// will panic if i is out of range.
func (vn VecN) Get(i int) float32 {
return vn.vec[i]
}
// Set the element at index i to val.
func (vn *VecN) Set(i int, val float32) {
vn.vec[i] = val
}
// Sends the allocated memory through the callback if it exists
func (vn *VecN) destroy() {
if vn == nil || vn.vec == nil {
return
}
if shouldPool {
returnToPool(vn.vec)
}
vn.vec = nil
}
// Resize the underlying slice to the desired amount, reallocating or retrieving
// from the pool if necessary. The values after a Resize cannot be expected to
// be related to the values before a Resize.
//
// If the caller is a nil pointer, this returns a value as if NewVecN(n) had
// been called, otherwise it simply returns the caller.
func (vn *VecN) Resize(n int) *VecN {
if vn == nil {
return NewVecN(n)
}
if n <= cap(vn.vec) {
if vn.vec != nil {
vn.vec = vn.vec[:n]
} else {
vn.vec = []float32{}
}
return vn
}
if shouldPool && vn.vec != nil {
returnToPool(vn.vec)
}
*vn = (*NewVecN(n))
return vn
}
// SetBackingSlice sets the vector's backing slice to the given
// new one.
func (vn *VecN) SetBackingSlice(newSlice []float32) {
vn.vec = newSlice
}
// Size returns the len of the vector's underlying slice.
// This is not titled Len because it conflicts the package's
// convention of calling the Norm the Len.
func (vn *VecN) Size() int {
return len(vn.vec)
}
// Cap Returns the cap of the vector's underlying slice.
func (vn *VecN) Cap() int {
return cap(vn.vec)
}
// Zero sets the vector's size to n and zeroes out the vector.
// If n is bigger than the vector's size, it will realloc.
func (vn *VecN) Zero(n int) {
vn.Resize(n)
for i := range vn.vec {
vn.vec[i] = 0
}
}
// Add adds vn and addend, storing the result in dst.
// If dst does not have sufficient size it will be resized
// Dst may be one of the other arguments. If dst is nil, it will be allocated.
// The value returned is dst, for easier method chaining
//
// If vn and addend are not the same size, this function will add min(vn.Size(), addend.Size())
// elements.
func (vn *VecN) Add(dst *VecN, subtrahend *VecN) *VecN {
if vn == nil || subtrahend == nil {
return nil
}
size := intMin(len(vn.vec), len(subtrahend.vec))
dst = dst.Resize(size)
for i := 0; i < size; i++ {
dst.vec[i] = vn.vec[i] + subtrahend.vec[i]
}
return dst
}
// Sub subtracts addend from vn, storing the result in dst.
// If dst does not have sufficient size it will be resized
// Dst may be one of the other arguments. If dst is nil, it will be allocated.
// The value returned is dst, for easier method chaining
//
// If vn and addend are not the same size, this function will add min(vn.Size(), addend.Size())
// elements.
func (vn *VecN) Sub(dst *VecN, addend *VecN) *VecN {
if vn == nil || addend == nil {
return nil
}
size := intMin(len(vn.vec), len(addend.vec))
dst = dst.Resize(size)
for i := 0; i < size; i++ {
dst.vec[i] = vn.vec[i] - addend.vec[i]
}
return dst
}
// Cross takes the binary cross product of vn and other, and stores it in dst.
// If either vn or other are not of size 3 this function will panic
//
// If dst is not of sufficient size, or is nil, a new slice is allocated.
// Dst is permitted to be one of the other arguments
func (vn *VecN) Cross(dst *VecN, other *VecN) *VecN {
if vn == nil || other == nil {
return nil
}
if len(vn.vec) != 3 || len(other.vec) != 3 {
panic("Cannot take binary cross product of non-3D elements (7D cross product not implemented)")
}
dst = dst.Resize(3)
dst.vec[0], dst.vec[1], dst.vec[2] = vn.vec[1]*other.vec[2]-vn.vec[2]*other.vec[1], vn.vec[2]*other.vec[0]-vn.vec[0]*other.vec[2], vn.vec[0]*other.vec[1]-vn.vec[1]*other.vec[0]
return dst
}
func intMin(a, b int) int {
if a < b {
return a
}
return b
}
// Dot computes the dot product of two VecNs, if
// the two vectors are not of the same length -- this
// will return NaN.
func (vn *VecN) Dot(other *VecN) float32 {
if vn == nil || other == nil || len(vn.vec) != len(other.vec) {
return float32(math.NaN())
}
var result float32 = 0.0
for i, el := range vn.vec {
result += el * other.vec[i]
}
return result
}
// Len computes the vector length (also called the Norm) of the
// vector. Equivalent to math.Sqrt(vn.Dot(vn)) with the appropriate
// type conversions.
//
// If vn is nil, this returns NaN
func (vn *VecN) Len() float32 {
if vn == nil {
return float32(math.NaN())
}
if len(vn.vec) == 0 {
return 0
}
return float32(math.Sqrt(float64(vn.Dot(vn))))
}
// LenSqr returns the vector's square length. This is equivalent to the sum of the squares of all elements.
func (vn *VecN) LenSqr() float32 {
if vn == nil {
return float32(math.NaN())
}
if len(vn.vec) == 0 {
return 0
}
return vn.Dot(vn)
}
// Normalize the vector and stores the result in dst, which
// will be returned. Dst will be appropraitely resized to the
// size of vn.
//
// The destination can be vn itself and nothing will go wrong.
//
// This is equivalent to vn.Mul(dst, 1/vn.Len())
func (vn *VecN) Normalize(dst *VecN) *VecN {
if vn == nil {
return nil
}
return vn.Mul(dst, 1/vn.Len())
}
// Mul multiplies the vector by some scalar value and stores the result in dst,
// which will be returned. Dst will be appropriately resized to the size of vn.
//
// The destination can be vn itself and nothing will go wrong.
func (vn *VecN) Mul(dst *VecN, c float32) *VecN {
if vn == nil {
return nil
}
dst = dst.Resize(len(vn.vec))
for i, el := range vn.vec {
dst.vec[i] = el * c
}
return dst
}
// OuterProd performs the vector outer product between vn and v2.
// The outer product is like a "reverse" dot product. Where the dot product
// aligns both vectors with the "sized" part facing "inward" (Vec3*Vec3=Mat1x3*Mat3x1=Mat1x1=Scalar).
// The outer product multiplied them with it facing "outward"
// (Vec3*Vec3=Mat3x1*Mat1x3=Mat3x3).
//
// The matrix dst will be Reshaped to the correct size, if vn or v2 are nil,
// this returns nil.
func (vn *VecN) OuterProd(dst *MatMxN, v2 *VecN) *MatMxN {
if vn == nil || v2 == nil {
return nil
}
dst = dst.Reshape(len(vn.vec), len(v2.vec))
for c, el1 := range v2.vec {
for r, el2 := range vn.vec {
dst.Set(r, c, el1*el2)
}
}
return dst
}
// ApproxEqual returns whether the two vectors are approximately equal (See
// FloatEqual).
func (vn *VecN) ApproxEqual(vn2 *VecN) bool {
if vn == nil || vn2 == nil || len(vn.vec) != len(vn2.vec) {
return false
}
for i, el := range vn.vec {
if !FloatEqual(el, vn2.vec[i]) {
return false
}
}
return true
}
// ApproxEqualThreshold returns whether the two vectors are approximately equal
// to within the given threshold given by "epsilon" (See ApproxEqualThreshold).
func (vn *VecN) ApproxEqualThreshold(vn2 *VecN, epsilon float32) bool {
if vn == nil || vn2 == nil || len(vn.vec) != len(vn2.vec) {
return false
}
for i, el := range vn.vec {
if !FloatEqualThreshold(el, vn2.vec[i], epsilon) {
return false
}
}
return true
}
// ApproxEqualFunc returns whether the two vectors are approximately equal,
// given a function which compares two scalar elements.
func (vn *VecN) ApproxEqualFunc(vn2 *VecN, comp func(float32, float32) bool) bool {
if vn == nil || vn2 == nil || len(vn.vec) != len(vn2.vec) {
return false
}
for i, el := range vn.vec {
if !comp(el, vn2.vec[i]) {
return false
}
}
return true
}
// Vec2 constructs a 2-dimensional vector by discarding coordinates.
func (vn *VecN) Vec2() Vec2 {
raw := vn.Raw()
return Vec2{raw[0], raw[1]}
}
// Vec3 constructs a 3-dimensional vector by discarding coordinates.
func (vn *VecN) Vec3() Vec3 {
raw := vn.Raw()
return Vec3{raw[0], raw[1], raw[2]}
}
// Vec4 constructs a 4-dimensional vector by discarding coordinates.
func (vn *VecN) Vec4() Vec4 {
raw := vn.Raw()
return Vec4{raw[0], raw[1], raw[2], raw[3]}
}
+591
View File
@@ -0,0 +1,591 @@
// Copyright 2014 The go-gl/mathgl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file is generated by codegen.go; DO NOT EDIT
// Edit vector.tmpl and run "go generate" to make changes.
package mgl32
import (
"math"
)
type Vec2 [2]float32
type Vec3 [3]float32
type Vec4 [4]float32
// Vec3 constructs a 3-dimensional vector by appending the given coordinates.
func (v Vec2) Vec3(z float32) Vec3 {
return Vec3{v[0], v[1], z}
}
// Vec4 constructs a 4-dimensional vector by appending the given coordinates.
func (v Vec2) Vec4(z, w float32) Vec4 {
return Vec4{v[0], v[1], z, w}
}
// Vec4 constructs a 4-dimensional vector by appending the given coordinates.
func (v Vec3) Vec4(w float32) Vec4 {
return Vec4{v[0], v[1], v[2], w}
}
// Vec2 constructs a 2-dimensional vector by discarding coordinates.
func (v Vec3) Vec2() Vec2 {
return Vec2{v[0], v[1]}
}
// Vec2 constructs a 2-dimensional vector by discarding coordinates.
func (v Vec4) Vec2() Vec2 {
return Vec2{v[0], v[1]}
}
// Vec3 constructs a 3-dimensional vector by discarding coordinates.
func (v Vec4) Vec3() Vec3 {
return Vec3{v[0], v[1], v[2]}
}
// Elem extracts the elements of the vector for direct value assignment.
func (v Vec2) Elem() (x, y float32) {
return v[0], v[1]
}
// Elem extracts the elements of the vector for direct value assignment.
func (v Vec3) Elem() (x, y, z float32) {
return v[0], v[1], v[2]
}
// Elem extracts the elements of the vector for direct value assignment.
func (v Vec4) Elem() (x, y, z, w float32) {
return v[0], v[1], v[2], v[3]
}
// Cross is the vector cross product. This operation is only defined on 3D
// vectors. It is equivalent to Vec3{v1[1]*v2[2]-v1[2]*v2[1],
// v1[2]*v2[0]-v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}. Another interpretation
// is that it's the vector whose magnitude is |v1||v2|sin(theta) where theta is
// the angle between v1 and v2.
//
// The cross product is most often used for finding surface normals. The cross
// product of vectors will generate a vector that is perpendicular to the plane
// they form.
//
// Technically, a generalized cross product exists as an "(N-1)ary" operation
// (that is, the 4D cross product requires 3 4D vectors). But the binary 3D (and
// 7D) cross product is the most important. It can be considered the area of a
// parallelogram with sides v1 and v2.
//
// Like the dot product, the cross product is roughly a measure of
// directionality. Two normalized perpendicular vectors will return a vector
// with a magnitude of 1.0 or -1.0 and two parallel vectors will return a vector
// with magnitude 0.0. The cross product is "anticommutative" meaning
// v1.Cross(v2) = -v2.Cross(v1), this property can be useful to know when
// finding normals, as taking the wrong cross product can lead to the opposite
// normal of the one you want.
func (v1 Vec3) Cross(v2 Vec3) Vec3 {
return Vec3{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}
}
// Quat reinterprets this vector as a quaternion, with the individual elements
// staying the same.
func (v Vec4) Quat() Quat {
return Quat{v[3], Vec3{v[0], v[1], v[2]}}
}
// Add performs element-wise addition between two vectors. It is equivalent to iterating
// over every element of v1 and adding the corresponding element of v2 to it.
func (v1 Vec2) Add(v2 Vec2) Vec2 {
return Vec2{v1[0] + v2[0], v1[1] + v2[1]}
}
// Sub performs element-wise subtraction between two vectors. It is equivalent to iterating
// over every element of v1 and subtracting the corresponding element of v2 from it.
func (v1 Vec2) Sub(v2 Vec2) Vec2 {
return Vec2{v1[0] - v2[0], v1[1] - v2[1]}
}
// Mul performs a scalar multiplication between the vector and some constant value
// c. This is equivalent to iterating over every vector element and multiplying by c.
func (v1 Vec2) Mul(c float32) Vec2 {
return Vec2{v1[0] * c, v1[1] * c}
}
// Dot returns the dot product of this vector with another. There are multiple ways
// to describe this value. One is the multiplication of their lengths and cos(theta) where
// theta is the angle between the vectors: v1.v2 = |v1||v2|cos(theta).
//
// The other (and what is actually done) is the sum of the element-wise multiplication of all
// elements. So for instance, two Vec3s would yield v1.x * v2.x + v1.y * v2.y + v1.z * v2.z.
//
// This means that the dot product of a vector and itself is the square of its Len (within
// the bounds of floating points error).
//
// The dot product is roughly a measure of how closely two vectors are to pointing in the same
// direction. If both vectors are normalized, the value will be -1 for opposite pointing,
// one for same pointing, and 0 for perpendicular vectors.
func (v1 Vec2) Dot(v2 Vec2) float32 {
return v1[0]*v2[0] + v1[1]*v2[1]
}
// Len returns the vector's length. Note that this is NOT the dimension of
// the vector (len(v)), but the mathematical length. This is equivalent to the square
// root of the sum of the squares of all elements. E.G. for a Vec2 it's
// math.Hypot(v[0], v[1]).
func (v1 Vec2) Len() float32 {
return float32(math.Hypot(float64(v1[0]), float64(v1[1])))
}
// LenSqr returns the vector's square length. This is equivalent to the sum of the squares of all elements.
func (v1 Vec2) LenSqr() float32 {
return v1[0]*v1[0] + v1[1]*v1[1]
}
// Normalize normalizes the vector. Normalization is (1/|v|)*v,
// making this equivalent to v.Scale(1/v.Len()). If the len is 0.0,
// this function will return an infinite value for all elements due
// to how floating point division works in Go (n/0.0 = math.Inf(Sign(n))).
//
// Normalization makes a vector's Len become 1.0 (within the margin of floating point error),
// while maintaining its directionality.
//
// (Can be seen here: http://play.golang.org/p/Aaj7SnbqIp )
func (v1 Vec2) Normalize() Vec2 {
l := 1.0 / v1.Len()
return Vec2{v1[0] * l, v1[1] * l}
}
// ApproxEqual takes in a vector and does an element-wise approximate float
// comparison as if FloatEqual had been used
func (v1 Vec2) ApproxEqual(v2 Vec2) bool {
for i := range v1 {
if !FloatEqual(v1[i], v2[i]) {
return false
}
}
return true
}
// ApproxEqualThreshold takes in a threshold for comparing two floats, and uses
// it to do an element-wise comparison of the vector to another.
func (v1 Vec2) ApproxEqualThreshold(v2 Vec2, threshold float32) bool {
for i := range v1 {
if !FloatEqualThreshold(v1[i], v2[i], threshold) {
return false
}
}
return true
}
// ApproxFuncEqual takes in a func that compares two floats, and uses it to do an element-wise
// comparison of the vector to another. This is intended to be used with FloatEqualFunc
func (v1 Vec2) ApproxFuncEqual(v2 Vec2, eq func(float32, float32) bool) bool {
for i := range v1 {
if !eq(v1[i], v2[i]) {
return false
}
}
return true
}
// X is an element access func, it is equivalent to v[n] where
// n is some valid index. The mappings are XYZW (X=0, Y=1 etc). Benchmarks
// show that this is more or less as fast as direct acces, probably due to
// inlining, so use v[0] or v.X() depending on personal preference.
func (v Vec2) X() float32 {
return v[0]
}
// Y is an element access func, it is equivalent to v[n] where
// n is some valid index. The mappings are XYZW (X=0, Y=1 etc). Benchmarks
// show that this is more or less as fast as direct acces, probably due to
// inlining, so use v[0] or v.X() depending on personal preference.
func (v Vec2) Y() float32 {
return v[1]
}
// OuterProd2 does the vector outer product
// of two vectors. The outer product produces an
// 2x2 matrix. E.G. a Vec2 * Vec2 = Mat2.
//
// The outer product can be thought of as the "opposite"
// of the Dot product. The Dot product treats both vectors like matrices
// oriented such that the left one has N columns and the right has N rows.
// So Vec3.Vec3 = Mat1x3*Mat3x1 = Mat1 = Scalar.
//
// The outer product orients it so they're facing "outward": Vec2*Vec3
// = Mat2x1*Mat1x3 = Mat2x3.
func (v1 Vec2) OuterProd2(v2 Vec2) Mat2 {
return Mat2{v1[0] * v2[0], v1[1] * v2[0], v1[0] * v2[1], v1[1] * v2[1]}
}
// OuterProd3 does the vector outer product
// of two vectors. The outer product produces an
// 2x3 matrix. E.G. a Vec2 * Vec3 = Mat2x3.
//
// The outer product can be thought of as the "opposite"
// of the Dot product. The Dot product treats both vectors like matrices
// oriented such that the left one has N columns and the right has N rows.
// So Vec3.Vec3 = Mat1x3*Mat3x1 = Mat1 = Scalar.
//
// The outer product orients it so they're facing "outward": Vec2*Vec3
// = Mat2x1*Mat1x3 = Mat2x3.
func (v1 Vec2) OuterProd3(v2 Vec3) Mat2x3 {
return Mat2x3{v1[0] * v2[0], v1[1] * v2[0], v1[0] * v2[1], v1[1] * v2[1], v1[0] * v2[2], v1[1] * v2[2]}
}
// OuterProd4 does the vector outer product
// of two vectors. The outer product produces an
// 2x4 matrix. E.G. a Vec2 * Vec4 = Mat2x4.
//
// The outer product can be thought of as the "opposite"
// of the Dot product. The Dot product treats both vectors like matrices
// oriented such that the left one has N columns and the right has N rows.
// So Vec3.Vec3 = Mat1x3*Mat3x1 = Mat1 = Scalar.
//
// The outer product orients it so they're facing "outward": Vec2*Vec3
// = Mat2x1*Mat1x3 = Mat2x3.
func (v1 Vec2) OuterProd4(v2 Vec4) Mat2x4 {
return Mat2x4{v1[0] * v2[0], v1[1] * v2[0], v1[0] * v2[1], v1[1] * v2[1], v1[0] * v2[2], v1[1] * v2[2], v1[0] * v2[3], v1[1] * v2[3]}
}
// Add performs element-wise addition between two vectors. It is equivalent to iterating
// over every element of v1 and adding the corresponding element of v2 to it.
func (v1 Vec3) Add(v2 Vec3) Vec3 {
return Vec3{v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2]}
}
// Sub performs element-wise subtraction between two vectors. It is equivalent to iterating
// over every element of v1 and subtracting the corresponding element of v2 from it.
func (v1 Vec3) Sub(v2 Vec3) Vec3 {
return Vec3{v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]}
}
// Mul performs a scalar multiplication between the vector and some constant value
// c. This is equivalent to iterating over every vector element and multiplying by c.
func (v1 Vec3) Mul(c float32) Vec3 {
return Vec3{v1[0] * c, v1[1] * c, v1[2] * c}
}
// Dot returns the dot product of this vector with another. There are multiple ways
// to describe this value. One is the multiplication of their lengths and cos(theta) where
// theta is the angle between the vectors: v1.v2 = |v1||v2|cos(theta).
//
// The other (and what is actually done) is the sum of the element-wise multiplication of all
// elements. So for instance, two Vec3s would yield v1.x * v2.x + v1.y * v2.y + v1.z * v2.z.
//
// This means that the dot product of a vector and itself is the square of its Len (within
// the bounds of floating points error).
//
// The dot product is roughly a measure of how closely two vectors are to pointing in the same
// direction. If both vectors are normalized, the value will be -1 for opposite pointing,
// one for same pointing, and 0 for perpendicular vectors.
func (v1 Vec3) Dot(v2 Vec3) float32 {
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
}
// Len returns the vector's length. Note that this is NOT the dimension of
// the vector (len(v)), but the mathematical length. This is equivalent to the square
// root of the sum of the squares of all elements. E.G. for a Vec2 it's
// math.Hypot(v[0], v[1]).
func (v1 Vec3) Len() float32 {
return float32(math.Sqrt(float64(v1[0]*v1[0] + v1[1]*v1[1] + v1[2]*v1[2])))
}
// LenSqr returns the vector's square length. This is equivalent to the sum of the squares of all elements.
func (v1 Vec3) LenSqr() float32 {
return v1[0]*v1[0] + v1[1]*v1[1] + v1[2]*v1[2]
}
// Normalize normalizes the vector. Normalization is (1/|v|)*v,
// making this equivalent to v.Scale(1/v.Len()). If the len is 0.0,
// this function will return an infinite value for all elements due
// to how floating point division works in Go (n/0.0 = math.Inf(Sign(n))).
//
// Normalization makes a vector's Len become 1.0 (within the margin of floating point error),
// while maintaining its directionality.
//
// (Can be seen here: http://play.golang.org/p/Aaj7SnbqIp )
func (v1 Vec3) Normalize() Vec3 {
l := 1.0 / v1.Len()
return Vec3{v1[0] * l, v1[1] * l, v1[2] * l}
}
// ApproxEqual takes in a vector and does an element-wise approximate float
// comparison as if FloatEqual had been used
func (v1 Vec3) ApproxEqual(v2 Vec3) bool {
for i := range v1 {
if !FloatEqual(v1[i], v2[i]) {
return false
}
}
return true
}
// ApproxEqualThreshold takes in a threshold for comparing two floats, and uses
// it to do an element-wise comparison of the vector to another.
func (v1 Vec3) ApproxEqualThreshold(v2 Vec3, threshold float32) bool {
for i := range v1 {
if !FloatEqualThreshold(v1[i], v2[i], threshold) {
return false
}
}
return true
}
// ApproxFuncEqual takes in a func that compares two floats, and uses it to do an element-wise
// comparison of the vector to another. This is intended to be used with FloatEqualFunc
func (v1 Vec3) ApproxFuncEqual(v2 Vec3, eq func(float32, float32) bool) bool {
for i := range v1 {
if !eq(v1[i], v2[i]) {
return false
}
}
return true
}
// X is an element access func, it is equivalent to v[n] where
// n is some valid index. The mappings are XYZW (X=0, Y=1 etc). Benchmarks
// show that this is more or less as fast as direct acces, probably due to
// inlining, so use v[0] or v.X() depending on personal preference.
func (v Vec3) X() float32 {
return v[0]
}
// Y is an element access func, it is equivalent to v[n] where
// n is some valid index. The mappings are XYZW (X=0, Y=1 etc). Benchmarks
// show that this is more or less as fast as direct acces, probably due to
// inlining, so use v[0] or v.X() depending on personal preference.
func (v Vec3) Y() float32 {
return v[1]
}
// Z is an element access func, it is equivalent to v[n] where
// n is some valid index. The mappings are XYZW (X=0, Y=1 etc). Benchmarks
// show that this is more or less as fast as direct acces, probably due to
// inlining, so use v[0] or v.X() depending on personal preference.
func (v Vec3) Z() float32 {
return v[2]
}
// OuterProd2 does the vector outer product
// of two vectors. The outer product produces an
// 3x2 matrix. E.G. a Vec3 * Vec2 = Mat3x2.
//
// The outer product can be thought of as the "opposite"
// of the Dot product. The Dot product treats both vectors like matrices
// oriented such that the left one has N columns and the right has N rows.
// So Vec3.Vec3 = Mat1x3*Mat3x1 = Mat1 = Scalar.
//
// The outer product orients it so they're facing "outward": Vec2*Vec3
// = Mat2x1*Mat1x3 = Mat2x3.
func (v1 Vec3) OuterProd2(v2 Vec2) Mat3x2 {
return Mat3x2{v1[0] * v2[0], v1[1] * v2[0], v1[2] * v2[0], v1[0] * v2[1], v1[1] * v2[1], v1[2] * v2[1]}
}
// OuterProd3 does the vector outer product
// of two vectors. The outer product produces an
// 3x3 matrix. E.G. a Vec3 * Vec3 = Mat3.
//
// The outer product can be thought of as the "opposite"
// of the Dot product. The Dot product treats both vectors like matrices
// oriented such that the left one has N columns and the right has N rows.
// So Vec3.Vec3 = Mat1x3*Mat3x1 = Mat1 = Scalar.
//
// The outer product orients it so they're facing "outward": Vec2*Vec3
// = Mat2x1*Mat1x3 = Mat2x3.
func (v1 Vec3) OuterProd3(v2 Vec3) Mat3 {
return Mat3{v1[0] * v2[0], v1[1] * v2[0], v1[2] * v2[0], v1[0] * v2[1], v1[1] * v2[1], v1[2] * v2[1], v1[0] * v2[2], v1[1] * v2[2], v1[2] * v2[2]}
}
// OuterProd4 does the vector outer product
// of two vectors. The outer product produces an
// 3x4 matrix. E.G. a Vec3 * Vec4 = Mat3x4.
//
// The outer product can be thought of as the "opposite"
// of the Dot product. The Dot product treats both vectors like matrices
// oriented such that the left one has N columns and the right has N rows.
// So Vec3.Vec3 = Mat1x3*Mat3x1 = Mat1 = Scalar.
//
// The outer product orients it so they're facing "outward": Vec2*Vec3
// = Mat2x1*Mat1x3 = Mat2x3.
func (v1 Vec3) OuterProd4(v2 Vec4) Mat3x4 {
return Mat3x4{v1[0] * v2[0], v1[1] * v2[0], v1[2] * v2[0], v1[0] * v2[1], v1[1] * v2[1], v1[2] * v2[1], v1[0] * v2[2], v1[1] * v2[2], v1[2] * v2[2], v1[0] * v2[3], v1[1] * v2[3], v1[2] * v2[3]}
}
// Add performs element-wise addition between two vectors. It is equivalent to iterating
// over every element of v1 and adding the corresponding element of v2 to it.
func (v1 Vec4) Add(v2 Vec4) Vec4 {
return Vec4{v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2], v1[3] + v2[3]}
}
// Sub performs element-wise subtraction between two vectors. It is equivalent to iterating
// over every element of v1 and subtracting the corresponding element of v2 from it.
func (v1 Vec4) Sub(v2 Vec4) Vec4 {
return Vec4{v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2], v1[3] - v2[3]}
}
// Mul performs a scalar multiplication between the vector and some constant value
// c. This is equivalent to iterating over every vector element and multiplying by c.
func (v1 Vec4) Mul(c float32) Vec4 {
return Vec4{v1[0] * c, v1[1] * c, v1[2] * c, v1[3] * c}
}
// Dot returns the dot product of this vector with another. There are multiple ways
// to describe this value. One is the multiplication of their lengths and cos(theta) where
// theta is the angle between the vectors: v1.v2 = |v1||v2|cos(theta).
//
// The other (and what is actually done) is the sum of the element-wise multiplication of all
// elements. So for instance, two Vec3s would yield v1.x * v2.x + v1.y * v2.y + v1.z * v2.z.
//
// This means that the dot product of a vector and itself is the square of its Len (within
// the bounds of floating points error).
//
// The dot product is roughly a measure of how closely two vectors are to pointing in the same
// direction. If both vectors are normalized, the value will be -1 for opposite pointing,
// one for same pointing, and 0 for perpendicular vectors.
func (v1 Vec4) Dot(v2 Vec4) float32 {
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2] + v1[3]*v2[3]
}
// Len returns the vector's length. Note that this is NOT the dimension of
// the vector (len(v)), but the mathematical length. This is equivalent to the square
// root of the sum of the squares of all elements. E.G. for a Vec2 it's
// math.Hypot(v[0], v[1]).
func (v1 Vec4) Len() float32 {
return float32(math.Sqrt(float64(v1[0]*v1[0] + v1[1]*v1[1] + v1[2]*v1[2] + v1[3]*v1[3])))
}
// LenSqr returns the vector's square length. This is equivalent to the sum of the squares of all elements.
func (v1 Vec4) LenSqr() float32 {
return v1[0]*v1[0] + v1[1]*v1[1] + v1[2]*v1[2] + v1[3]*v1[3]
}
// Normalize normalizes the vector. Normalization is (1/|v|)*v,
// making this equivalent to v.Scale(1/v.Len()). If the len is 0.0,
// this function will return an infinite value for all elements due
// to how floating point division works in Go (n/0.0 = math.Inf(Sign(n))).
//
// Normalization makes a vector's Len become 1.0 (within the margin of floating point error),
// while maintaining its directionality.
//
// (Can be seen here: http://play.golang.org/p/Aaj7SnbqIp )
func (v1 Vec4) Normalize() Vec4 {
l := 1.0 / v1.Len()
return Vec4{v1[0] * l, v1[1] * l, v1[2] * l, v1[3] * l}
}
// ApproxEqual takes in a vector and does an element-wise approximate float
// comparison as if FloatEqual had been used
func (v1 Vec4) ApproxEqual(v2 Vec4) bool {
for i := range v1 {
if !FloatEqual(v1[i], v2[i]) {
return false
}
}
return true
}
// ApproxEqualThreshold takes in a threshold for comparing two floats, and uses
// it to do an element-wise comparison of the vector to another.
func (v1 Vec4) ApproxEqualThreshold(v2 Vec4, threshold float32) bool {
for i := range v1 {
if !FloatEqualThreshold(v1[i], v2[i], threshold) {
return false
}
}
return true
}
// ApproxFuncEqual takes in a func that compares two floats, and uses it to do an element-wise
// comparison of the vector to another. This is intended to be used with FloatEqualFunc
func (v1 Vec4) ApproxFuncEqual(v2 Vec4, eq func(float32, float32) bool) bool {
for i := range v1 {
if !eq(v1[i], v2[i]) {
return false
}
}
return true
}
// X is an element access func, it is equivalent to v[n] where
// n is some valid index. The mappings are XYZW (X=0, Y=1 etc). Benchmarks
// show that this is more or less as fast as direct acces, probably due to
// inlining, so use v[0] or v.X() depending on personal preference.
func (v Vec4) X() float32 {
return v[0]
}
// Y is an element access func, it is equivalent to v[n] where
// n is some valid index. The mappings are XYZW (X=0, Y=1 etc). Benchmarks
// show that this is more or less as fast as direct acces, probably due to
// inlining, so use v[0] or v.X() depending on personal preference.
func (v Vec4) Y() float32 {
return v[1]
}
// Z is an element access func, it is equivalent to v[n] where
// n is some valid index. The mappings are XYZW (X=0, Y=1 etc). Benchmarks
// show that this is more or less as fast as direct acces, probably due to
// inlining, so use v[0] or v.X() depending on personal preference.
func (v Vec4) Z() float32 {
return v[2]
}
// W is an element access func, it is equivalent to v[n] where
// n is some valid index. The mappings are XYZW (X=0, Y=1 etc). Benchmarks
// show that this is more or less as fast as direct acces, probably due to
// inlining, so use v[0] or v.X() depending on personal preference.
func (v Vec4) W() float32 {
return v[3]
}
// OuterProd2 does the vector outer product
// of two vectors. The outer product produces an
// 4x2 matrix. E.G. a Vec4 * Vec2 = Mat4x2.
//
// The outer product can be thought of as the "opposite"
// of the Dot product. The Dot product treats both vectors like matrices
// oriented such that the left one has N columns and the right has N rows.
// So Vec3.Vec3 = Mat1x3*Mat3x1 = Mat1 = Scalar.
//
// The outer product orients it so they're facing "outward": Vec2*Vec3
// = Mat2x1*Mat1x3 = Mat2x3.
func (v1 Vec4) OuterProd2(v2 Vec2) Mat4x2 {
return Mat4x2{v1[0] * v2[0], v1[1] * v2[0], v1[2] * v2[0], v1[3] * v2[0], v1[0] * v2[1], v1[1] * v2[1], v1[2] * v2[1], v1[3] * v2[1]}
}
// OuterProd3 does the vector outer product
// of two vectors. The outer product produces an
// 4x3 matrix. E.G. a Vec4 * Vec3 = Mat4x3.
//
// The outer product can be thought of as the "opposite"
// of the Dot product. The Dot product treats both vectors like matrices
// oriented such that the left one has N columns and the right has N rows.
// So Vec3.Vec3 = Mat1x3*Mat3x1 = Mat1 = Scalar.
//
// The outer product orients it so they're facing "outward": Vec2*Vec3
// = Mat2x1*Mat1x3 = Mat2x3.
func (v1 Vec4) OuterProd3(v2 Vec3) Mat4x3 {
return Mat4x3{v1[0] * v2[0], v1[1] * v2[0], v1[2] * v2[0], v1[3] * v2[0], v1[0] * v2[1], v1[1] * v2[1], v1[2] * v2[1], v1[3] * v2[1], v1[0] * v2[2], v1[1] * v2[2], v1[2] * v2[2], v1[3] * v2[2]}
}
// OuterProd4 does the vector outer product
// of two vectors. The outer product produces an
// 4x4 matrix. E.G. a Vec4 * Vec4 = Mat4.
//
// The outer product can be thought of as the "opposite"
// of the Dot product. The Dot product treats both vectors like matrices
// oriented such that the left one has N columns and the right has N rows.
// So Vec3.Vec3 = Mat1x3*Mat3x1 = Mat1 = Scalar.
//
// The outer product orients it so they're facing "outward": Vec2*Vec3
// = Mat2x1*Mat1x3 = Mat2x3.
func (v1 Vec4) OuterProd4(v2 Vec4) Mat4 {
return Mat4{v1[0] * v2[0], v1[1] * v2[0], v1[2] * v2[0], v1[3] * v2[0], v1[0] * v2[1], v1[1] * v2[1], v1[2] * v2[1], v1[3] * v2[1], v1[0] * v2[2], v1[1] * v2[2], v1[2] * v2[2], v1[3] * v2[2], v1[0] * v2[3], v1[1] * v2[3], v1[2] * v2[3], v1[3] * v2[3]}
}
+226
View File
@@ -0,0 +1,226 @@
// Copyright 2014 The go-gl/mathgl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// <<.Comment>>
// Edit <<.TemplateName>> and run "go generate" to make changes.
package mgl32
import (
"math"
)
type Vec2 [2]float32
type Vec3 [3]float32
type Vec4 [4]float32
// Vec3 constructs a 3-dimensional vector by appending the given coordinates.
func (v Vec2) Vec3(z float32) Vec3 {
return Vec3{v[0], v[1], z}
}
// Vec4 constructs a 4-dimensional vector by appending the given coordinates.
func (v Vec2) Vec4(z, w float32) Vec4 {
return Vec4{v[0], v[1], z, w}
}
// Vec4 constructs a 4-dimensional vector by appending the given coordinates.
func (v Vec3) Vec4(w float32) Vec4 {
return Vec4{v[0], v[1], v[2], w}
}
// Vec2 constructs a 2-dimensional vector by discarding coordinates.
func (v Vec3) Vec2() Vec2 {
return Vec2{v[0], v[1]}
}
// Vec2 constructs a 2-dimensional vector by discarding coordinates.
func (v Vec4) Vec2() Vec2 {
return Vec2{v[0], v[1]}
}
// Vec3 constructs a 3-dimensional vector by discarding coordinates.
func (v Vec4) Vec3() Vec3 {
return Vec3{v[0], v[1], v[2]}
}
// Elem extracts the elements of the vector for direct value assignment.
func (v Vec2) Elem() (x, y float32) {
return v[0], v[1]
}
// Elem extracts the elements of the vector for direct value assignment.
func (v Vec3) Elem() (x, y, z float32) {
return v[0], v[1], v[2]
}
// Elem extracts the elements of the vector for direct value assignment.
func (v Vec4) Elem() (x, y, z, w float32) {
return v[0], v[1], v[2], v[3]
}
// Cross is the vector cross product. This operation is only defined on 3D
// vectors. It is equivalent to Vec3{v1[1]*v2[2]-v1[2]*v2[1],
// v1[2]*v2[0]-v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}. Another interpretation
// is that it's the vector whose magnitude is |v1||v2|sin(theta) where theta is
// the angle between v1 and v2.
//
// The cross product is most often used for finding surface normals. The cross
// product of vectors will generate a vector that is perpendicular to the plane
// they form.
//
// Technically, a generalized cross product exists as an "(N-1)ary" operation
// (that is, the 4D cross product requires 3 4D vectors). But the binary 3D (and
// 7D) cross product is the most important. It can be considered the area of a
// parallelogram with sides v1 and v2.
//
// Like the dot product, the cross product is roughly a measure of
// directionality. Two normalized perpendicular vectors will return a vector
// with a magnitude of 1.0 or -1.0 and two parallel vectors will return a vector
// with magnitude 0.0. The cross product is "anticommutative" meaning
// v1.Cross(v2) = -v2.Cross(v1), this property can be useful to know when
// finding normals, as taking the wrong cross product can lead to the opposite
// normal of the one you want.
func (v1 Vec3) Cross(v2 Vec3) Vec3 {
return Vec3{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}
}
// Quat reinterprets this vector as a quaternion, with the individual elements
// staying the same.
func (v Vec4) Quat() Quat {
return Quat{v[3], Vec3{v[0], v[1], v[2]}}
}
<</* Common functions for all vectors */>>
<<range $m := enum 2 3 4>>
<<$type := typename $m 1>>
// Add performs element-wise addition between two vectors. It is equivalent to iterating
// over every element of v1 and adding the corresponding element of v2 to it.
func (v1 <<$type>>) Add(v2 <<$type>>) <<$type>> {
return <<$type>>{<<range $i := iter 0 $m>> v1[<<$i>>] + v2[<<$i>>], <<end>>}
}
// Sub performs element-wise subtraction between two vectors. It is equivalent to iterating
// over every element of v1 and subtracting the corresponding element of v2 from it.
func (v1 <<$type>>) Sub(v2 <<$type>>) <<$type>> {
return <<$type>>{<<range $i := iter 0 $m>> v1[<<$i>>] - v2[<<$i>>], <<end>>}
}
// Mul performs a scalar multiplication between the vector and some constant value
// c. This is equivalent to iterating over every vector element and multiplying by c.
func (v1 <<$type>>) Mul(c float32) <<$type>> {
return <<$type>>{<<range $i := iter 0 $m>> v1[<<$i>>] * c, <<end>>}
}
// Dot returns the dot product of this vector with another. There are multiple ways
// to describe this value. One is the multiplication of their lengths and cos(theta) where
// theta is the angle between the vectors: v1.v2 = |v1||v2|cos(theta).
//
// The other (and what is actually done) is the sum of the element-wise multiplication of all
// elements. So for instance, two Vec3s would yield v1.x * v2.x + v1.y * v2.y + v1.z * v2.z.
//
// This means that the dot product of a vector and itself is the square of its Len (within
// the bounds of floating points error).
//
// The dot product is roughly a measure of how closely two vectors are to pointing in the same
// direction. If both vectors are normalized, the value will be -1 for opposite pointing,
// one for same pointing, and 0 for perpendicular vectors.
func (v1 <<$type>>) Dot(v2 <<$type>>) float32 {
return <<range $i := iter 0 $m>><<sep "+" $i>> v1[<<$i>>]*v2[<<$i>>] <<end>>
}
// Len returns the vector's length. Note that this is NOT the dimension of
// the vector (len(v)), but the mathematical length. This is equivalent to the square
// root of the sum of the squares of all elements. E.G. for a Vec2 it's
// math.Hypot(v[0], v[1]).
func (v1 <<$type>>) Len() float32 {
<<if eq $m 2 >>
return float32(math.Hypot(float64(v1[0]), float64(v1[1])))
<<else>>
return float32(math.Sqrt(float64(<<repeat $m "v1[%d]*v1[%d]" "+">>)))
<<end>>
}
// LenSqr returns the vector's square length. This is equivalent to the sum of the squares of all elements.
func (v1 <<$type>>) LenSqr() float32 {
return <<repeat $m "v1[%d]*v1[%d]" "+">>
}
// Normalize normalizes the vector. Normalization is (1/|v|)*v,
// making this equivalent to v.Scale(1/v.Len()). If the len is 0.0,
// this function will return an infinite value for all elements due
// to how floating point division works in Go (n/0.0 = math.Inf(Sign(n))).
//
// Normalization makes a vector's Len become 1.0 (within the margin of floating point error),
// while maintaining its directionality.
//
// (Can be seen here: http://play.golang.org/p/Aaj7SnbqIp )
func (v1 <<$type>>) Normalize() <<$type>> {
l := 1.0 / v1.Len()
return <<$type>>{<<range $i := iter 0 $m>>v1[<<$i>>] * l,<<end>>}
}
// ApproxEqual takes in a vector and does an element-wise approximate float
// comparison as if FloatEqual had been used
func (v1 <<$type>>) ApproxEqual(v2 <<$type>>) bool {
for i := range v1 {
if !FloatEqual(v1[i], v2[i]) {
return false
}
}
return true
}
// ApproxEqualThreshold takes in a threshold for comparing two floats, and uses
// it to do an element-wise comparison of the vector to another.
func (v1 <<$type>>) ApproxEqualThreshold(v2 <<$type>>, threshold float32) bool {
for i := range v1 {
if !FloatEqualThreshold(v1[i], v2[i], threshold) {
return false
}
}
return true
}
// ApproxFuncEqual takes in a func that compares two floats, and uses it to do an element-wise
// comparison of the vector to another. This is intended to be used with FloatEqualFunc
func (v1 <<$type>>) ApproxFuncEqual(v2 <<$type>>, eq func(float32, float32) bool) bool {
for i := range v1 {
if !eq(v1[i], v2[i]) {
return false
}
}
return true
}
<<range $i := iter 0 $m>>
// <<elementname $i>> is an element access func, it is equivalent to v[n] where
// n is some valid index. The mappings are XYZW (X=0, Y=1 etc). Benchmarks
// show that this is more or less as fast as direct acces, probably due to
// inlining, so use v[0] or v.X() depending on personal preference.
func (v <<$type>>) <<elementname $i>>() float32 {
return v[<<$i>>]
}
<<end>>
<<range $n := enum 2 3 4>>
// OuterProd<<$n>> does the vector outer product
// of two vectors. The outer product produces an
// <<$m>>x<<$n>> matrix. E.G. a Vec<<$m>> * Vec<<$n>> = <<typename $m $n>>.
//
// The outer product can be thought of as the "opposite"
// of the Dot product. The Dot product treats both vectors like matrices
// oriented such that the left one has N columns and the right has N rows.
// So Vec3.Vec3 = Mat1x3*Mat3x1 = Mat1 = Scalar.
//
// The outer product orients it so they're facing "outward": Vec2*Vec3
// = Mat2x1*Mat1x3 = Mat2x3.
func (v1 <<$type>>) OuterProd<<$n>>(v2 <<typename $n 1>>) <<typename $m $n>> {
return <<typename $m $n>>{<<range $i := matiter $m $n>>v1[<<$i.M>>] * v2[<<$i.N>>], <<end>>}
}
<<end>>
<<end>> <</* range $m */>>
+50
View File
@@ -0,0 +1,50 @@
# How to Contribute
## Getting Started
- Fork the repository on GitHub
- Read the [README](README.markdown) for build and test instructions
- Play with the project, submit bugs, submit patches!
## Contribution Flow
This is a rough outline of what a contributor's workflow looks like:
- Create a topic branch from where you want to base your work (usually master).
- Make commits of logical units.
- Make sure your commit messages are in the proper format (see below).
- Push your changes to a topic branch in your fork of the repository.
- Make sure the tests pass, and add any new tests as appropriate.
- Submit a pull request to the original repository.
Thanks for your contributions!
### Format of the Commit Message
We follow a rough convention for commit messages that is designed to answer two
questions: what changed and why. The subject line should feature the what and
the body of the commit should describe the why.
```
scripts: add the test-cluster command
this uses tmux to setup a test cluster that you can easily kill and
start for debugging.
Fixes #38
```
The format can be described more formally as follows:
```
<subsystem>: <what changed>
<BLANK LINE>
<why this change was made>
<BLANK LINE>
<footer>
```
The first line is the subject and should be no longer than 70 characters, the
second line is always blank, and other lines should be wrapped at 80 characters.
This allows the message to be easier to read on GitHub as well as in various
git tools.
+25
View File
@@ -0,0 +1,25 @@
Copyright (c) 2013, Georg Reinke (<guelfey at gmail dot com>), Google
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+3
View File
@@ -0,0 +1,3 @@
Brandon Philips <brandon@ifup.org> (@philips)
Brian Waldon <brian@waldon.cc> (@bcwaldon)
John Southworth <jsouthwo@brocade.com> (@jsouthworth)
+46
View File
@@ -0,0 +1,46 @@
![Build Status](https://github.com/godbus/dbus/workflows/Go/badge.svg)
dbus
----
dbus is a simple library that implements native Go client bindings for the
D-Bus message bus system.
### Features
* Complete native implementation of the D-Bus message protocol
* Go-like API (channels for signals / asynchronous method calls, Goroutine-safe connections)
* Subpackages that help with the introspection / property interfaces
### Installation
This packages requires Go 1.12 or later. It can be installed by running the command below:
```
go get github.com/godbus/dbus/v5
```
### Usage
The complete package documentation and some simple examples are available at
[godoc.org](http://godoc.org/github.com/godbus/dbus). Also, the
[_examples](https://github.com/godbus/dbus/tree/master/_examples) directory
gives a short overview over the basic usage.
#### Projects using godbus
- [fyne](https://github.com/fyne-io/fyne) a cross platform GUI in Go inspired by Material Design.
- [fynedesk](https://github.com/fyne-io/fynedesk) a full desktop environment for Linux/Unix using Fyne.
- [go-bluetooth](https://github.com/muka/go-bluetooth) provides a bluetooth client over bluez dbus API.
- [iwd](https://github.com/shibumi/iwd) go bindings for the internet wireless daemon "iwd".
- [notify](https://github.com/esiqveland/notify) provides desktop notifications over dbus into a library.
- [playerbm](https://github.com/altdesktop/playerbm) a bookmark utility for media players.
Please note that the API is considered unstable for now and may change without
further notice.
### License
go.dbus is available under the Simplified BSD License; see LICENSE for the full
text.
Nearly all of the credit for this library goes to github.com/guelfey/go.dbus.
+257
View File
@@ -0,0 +1,257 @@
package dbus
import (
"bufio"
"bytes"
"errors"
"io"
"os"
"strconv"
)
// AuthStatus represents the Status of an authentication mechanism.
type AuthStatus byte
const (
// AuthOk signals that authentication is finished; the next command
// from the server should be an OK.
AuthOk AuthStatus = iota
// AuthContinue signals that additional data is needed; the next command
// from the server should be a DATA.
AuthContinue
// AuthError signals an error; the server sent invalid data or some
// other unexpected thing happened and the current authentication
// process should be aborted.
AuthError
)
type authState byte
const (
waitingForData authState = iota
waitingForOk
waitingForReject
)
// Auth defines the behaviour of an authentication mechanism.
type Auth interface {
// Return the name of the mechanism, the argument to the first AUTH command
// and the next status.
FirstData() (name, resp []byte, status AuthStatus)
// Process the given DATA command, and return the argument to the DATA
// command and the next status. If len(resp) == 0, no DATA command is sent.
HandleData(data []byte) (resp []byte, status AuthStatus)
}
// Auth authenticates the connection, trying the given list of authentication
// mechanisms (in that order). If nil is passed, the EXTERNAL and
// DBUS_COOKIE_SHA1 mechanisms are tried for the current user. For private
// connections, this method must be called before sending any messages to the
// bus. Auth must not be called on shared connections.
func (conn *Conn) Auth(methods []Auth) error {
if methods == nil {
uid := strconv.Itoa(os.Geteuid())
methods = []Auth{AuthExternal(uid), AuthCookieSha1(uid, getHomeDir())}
}
in := bufio.NewReader(conn.transport)
err := conn.transport.SendNullByte()
if err != nil {
return err
}
err = authWriteLine(conn.transport, []byte("AUTH"))
if err != nil {
return err
}
s, err := authReadLine(in)
if err != nil {
return err
}
if len(s) < 2 || !bytes.Equal(s[0], []byte("REJECTED")) {
return errors.New("dbus: authentication protocol error")
}
s = s[1:]
for _, v := range s {
for _, m := range methods {
if name, _, status := m.FirstData(); bytes.Equal(v, name) {
var ok bool
err = authWriteLine(conn.transport, []byte("AUTH"), v)
if err != nil {
return err
}
switch status {
case AuthOk:
err, ok = conn.tryAuth(m, waitingForOk, in)
case AuthContinue:
err, ok = conn.tryAuth(m, waitingForData, in)
default:
panic("dbus: invalid authentication status")
}
if err != nil {
return err
}
if ok {
if conn.transport.SupportsUnixFDs() {
err = authWriteLine(conn, []byte("NEGOTIATE_UNIX_FD"))
if err != nil {
return err
}
line, err := authReadLine(in)
if err != nil {
return err
}
switch {
case bytes.Equal(line[0], []byte("AGREE_UNIX_FD")):
conn.EnableUnixFDs()
conn.unixFD = true
case bytes.Equal(line[0], []byte("ERROR")):
default:
return errors.New("dbus: authentication protocol error")
}
}
err = authWriteLine(conn.transport, []byte("BEGIN"))
if err != nil {
return err
}
go conn.inWorker()
return nil
}
}
}
}
return errors.New("dbus: authentication failed")
}
// tryAuth tries to authenticate with m as the mechanism, using state as the
// initial authState and in for reading input. It returns (nil, true) on
// success, (nil, false) on a REJECTED and (someErr, false) if some other
// error occurred.
func (conn *Conn) tryAuth(m Auth, state authState, in *bufio.Reader) (error, bool) {
for {
s, err := authReadLine(in)
if err != nil {
return err, false
}
switch {
case state == waitingForData && string(s[0]) == "DATA":
if len(s) != 2 {
err = authWriteLine(conn.transport, []byte("ERROR"))
if err != nil {
return err, false
}
continue
}
data, status := m.HandleData(s[1])
switch status {
case AuthOk, AuthContinue:
if len(data) != 0 {
err = authWriteLine(conn.transport, []byte("DATA"), data)
if err != nil {
return err, false
}
}
if status == AuthOk {
state = waitingForOk
}
case AuthError:
err = authWriteLine(conn.transport, []byte("ERROR"))
if err != nil {
return err, false
}
}
case state == waitingForData && string(s[0]) == "REJECTED":
return nil, false
case state == waitingForData && string(s[0]) == "ERROR":
err = authWriteLine(conn.transport, []byte("CANCEL"))
if err != nil {
return err, false
}
state = waitingForReject
case state == waitingForData && string(s[0]) == "OK":
if len(s) != 2 {
err = authWriteLine(conn.transport, []byte("CANCEL"))
if err != nil {
return err, false
}
state = waitingForReject
} else {
conn.uuid = string(s[1])
return nil, true
}
case state == waitingForData:
err = authWriteLine(conn.transport, []byte("ERROR"))
if err != nil {
return err, false
}
case state == waitingForOk && string(s[0]) == "OK":
if len(s) != 2 {
err = authWriteLine(conn.transport, []byte("CANCEL"))
if err != nil {
return err, false
}
state = waitingForReject
} else {
conn.uuid = string(s[1])
return nil, true
}
case state == waitingForOk && string(s[0]) == "DATA":
err = authWriteLine(conn.transport, []byte("DATA"))
if err != nil {
return err, false
}
case state == waitingForOk && string(s[0]) == "REJECTED":
return nil, false
case state == waitingForOk && string(s[0]) == "ERROR":
err = authWriteLine(conn.transport, []byte("CANCEL"))
if err != nil {
return err, false
}
state = waitingForReject
case state == waitingForOk:
err = authWriteLine(conn.transport, []byte("ERROR"))
if err != nil {
return err, false
}
case state == waitingForReject && string(s[0]) == "REJECTED":
return nil, false
case state == waitingForReject:
return errors.New("dbus: authentication protocol error"), false
default:
panic("dbus: invalid auth state")
}
}
}
// authReadLine reads a line and separates it into its fields.
func authReadLine(in *bufio.Reader) ([][]byte, error) {
data, err := in.ReadBytes('\n')
if err != nil {
return nil, err
}
data = bytes.TrimSuffix(data, []byte("\r\n"))
return bytes.Split(data, []byte{' '}), nil
}
// authWriteLine writes the given line in the authentication protocol format
// (elements of data separated by a " " and terminated by "\r\n").
func authWriteLine(out io.Writer, data ...[]byte) error {
buf := make([]byte, 0)
for i, v := range data {
buf = append(buf, v...)
if i != len(data)-1 {
buf = append(buf, ' ')
}
}
buf = append(buf, '\r')
buf = append(buf, '\n')
n, err := out.Write(buf)
if err != nil {
return err
}
if n != len(buf) {
return io.ErrUnexpectedEOF
}
return nil
}
+16
View File
@@ -0,0 +1,16 @@
package dbus
// AuthAnonymous returns an Auth that uses the ANONYMOUS mechanism.
func AuthAnonymous() Auth {
return &authAnonymous{}
}
type authAnonymous struct{}
func (a *authAnonymous) FirstData() (name, resp []byte, status AuthStatus) {
return []byte("ANONYMOUS"), nil, AuthOk
}
func (a *authAnonymous) HandleData(data []byte) (resp []byte, status AuthStatus) {
return nil, AuthError
}
+26
View File
@@ -0,0 +1,26 @@
package dbus
import (
"encoding/hex"
)
// AuthExternal returns an Auth that authenticates as the given user with the
// EXTERNAL mechanism.
func AuthExternal(user string) Auth {
return authExternal{user}
}
// AuthExternal implements the EXTERNAL authentication mechanism.
type authExternal struct {
user string
}
func (a authExternal) FirstData() ([]byte, []byte, AuthStatus) {
b := make([]byte, 2*len(a.user))
hex.Encode(b, []byte(a.user))
return []byte("EXTERNAL"), b, AuthOk
}
func (a authExternal) HandleData(b []byte) ([]byte, AuthStatus) {
return nil, AuthError
}
+102
View File
@@ -0,0 +1,102 @@
package dbus
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/sha1"
"encoding/hex"
"os"
)
// AuthCookieSha1 returns an Auth that authenticates as the given user with the
// DBUS_COOKIE_SHA1 mechanism. The home parameter should specify the home
// directory of the user.
func AuthCookieSha1(user, home string) Auth {
return authCookieSha1{user, home}
}
type authCookieSha1 struct {
user, home string
}
func (a authCookieSha1) FirstData() ([]byte, []byte, AuthStatus) {
b := make([]byte, 2*len(a.user))
hex.Encode(b, []byte(a.user))
return []byte("DBUS_COOKIE_SHA1"), b, AuthContinue
}
func (a authCookieSha1) HandleData(data []byte) ([]byte, AuthStatus) {
challenge := make([]byte, len(data)/2)
_, err := hex.Decode(challenge, data)
if err != nil {
return nil, AuthError
}
b := bytes.Split(challenge, []byte{' '})
if len(b) != 3 {
return nil, AuthError
}
context := b[0]
id := b[1]
svchallenge := b[2]
cookie := a.getCookie(context, id)
if cookie == nil {
return nil, AuthError
}
clchallenge := a.generateChallenge()
if clchallenge == nil {
return nil, AuthError
}
hash := sha1.New()
hash.Write(bytes.Join([][]byte{svchallenge, clchallenge, cookie}, []byte{':'}))
hexhash := make([]byte, 2*hash.Size())
hex.Encode(hexhash, hash.Sum(nil))
data = append(clchallenge, ' ')
data = append(data, hexhash...)
resp := make([]byte, 2*len(data))
hex.Encode(resp, data)
return resp, AuthOk
}
// getCookie searches for the cookie identified by id in context and returns
// the cookie content or nil. (Since HandleData can't return a specific error,
// but only whether an error occurred, this function also doesn't bother to
// return an error.)
func (a authCookieSha1) getCookie(context, id []byte) []byte {
file, err := os.Open(a.home + "/.dbus-keyrings/" + string(context))
if err != nil {
return nil
}
defer file.Close()
rd := bufio.NewReader(file)
for {
line, err := rd.ReadBytes('\n')
if err != nil {
return nil
}
line = line[:len(line)-1]
b := bytes.Split(line, []byte{' '})
if len(b) != 3 {
return nil
}
if bytes.Equal(b[0], id) {
return b[2]
}
}
}
// generateChallenge returns a random, hex-encoded challenge, or nil on error
// (see above).
func (a authCookieSha1) generateChallenge() []byte {
b := make([]byte, 16)
n, err := rand.Read(b)
if err != nil {
return nil
}
if n != 16 {
return nil
}
enc := make([]byte, 32)
hex.Encode(enc, b)
return enc
}
+69
View File
@@ -0,0 +1,69 @@
package dbus
import (
"context"
"errors"
)
var errSignature = errors.New("dbus: mismatched signature")
// Call represents a pending or completed method call.
type Call struct {
Destination string
Path ObjectPath
Method string
Args []interface{}
// Strobes when the call is complete.
Done chan *Call
// After completion, the error status. If this is non-nil, it may be an
// error message from the peer (with Error as its type) or some other error.
Err error
// Holds the response once the call is done.
Body []interface{}
// ResponseSequence stores the sequence number of the DBus message containing
// the call response (or error). This can be compared to the sequence number
// of other call responses and signals on this connection to determine their
// relative ordering on the underlying DBus connection.
// For errors, ResponseSequence is populated only if the error came from a
// DBusMessage that was received or if there was an error receiving. In case of
// failure to make the call, ResponseSequence will be NoSequence.
ResponseSequence Sequence
// tracks context and canceler
ctx context.Context
ctxCanceler context.CancelFunc
}
func (c *Call) Context() context.Context {
if c.ctx == nil {
return context.Background()
}
return c.ctx
}
func (c *Call) ContextCancel() {
if c.ctxCanceler != nil {
c.ctxCanceler()
}
}
// 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 {
if c.Err != nil {
return c.Err
}
return Store(c.Body, retvalues...)
}
func (c *Call) done() {
c.Done <- c
c.ContextCancel()
}
+996
View File
@@ -0,0 +1,996 @@
package dbus
import (
"context"
"errors"
"io"
"os"
"strings"
"sync"
)
var (
systemBus *Conn
systemBusLck sync.Mutex
sessionBus *Conn
sessionBusLck sync.Mutex
)
// ErrClosed is the error returned by calls on a closed connection.
var ErrClosed = errors.New("dbus: connection closed by user")
// Conn represents a connection to a message bus (usually, the system or
// session bus).
//
// Connections are either shared or private. Shared connections
// are shared between calls to the functions that return them. As a result,
// the methods Close, Auth and Hello must not be called on them.
//
// Multiple goroutines may invoke methods on a connection simultaneously.
type Conn struct {
transport
ctx context.Context
cancelCtx context.CancelFunc
closeOnce sync.Once
closeErr error
busObj BusObject
unixFD bool
uuid string
handler Handler
signalHandler SignalHandler
serialGen SerialGenerator
inInt Interceptor
outInt Interceptor
auth []Auth
names *nameTracker
calls *callTracker
outHandler *outputHandler
eavesdropped chan<- *Message
eavesdroppedLck sync.Mutex
}
// SessionBus returns a shared connection to the session bus, connecting to it
// if not already done.
func SessionBus() (conn *Conn, err error) {
sessionBusLck.Lock()
defer sessionBusLck.Unlock()
if sessionBus != nil &&
sessionBus.Connected() {
return sessionBus, nil
}
defer func() {
if conn != nil {
sessionBus = conn
}
}()
conn, err = ConnectSessionBus()
return
}
func getSessionBusAddress(autolaunch bool) (string, error) {
if address := os.Getenv("DBUS_SESSION_BUS_ADDRESS"); address != "" && address != "autolaunch:" {
return address, nil
} else if address := tryDiscoverDbusSessionBusAddress(); address != "" {
os.Setenv("DBUS_SESSION_BUS_ADDRESS", address)
return address, nil
}
if !autolaunch {
return "", errors.New("dbus: couldn't determine address of session bus")
}
return getSessionBusPlatformAddress()
}
// SessionBusPrivate returns a new private connection to the session bus.
func SessionBusPrivate(opts ...ConnOption) (*Conn, error) {
address, err := getSessionBusAddress(true)
if err != nil {
return nil, err
}
return Dial(address, opts...)
}
// SessionBusPrivate 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)
if err != nil {
return nil, err
}
return Dial(address, opts...)
}
// SessionBusPrivate returns a new private connection to the session bus.
//
// Deprecated: use SessionBusPrivate with options instead.
func SessionBusPrivateHandler(handler Handler, signalHandler SignalHandler) (*Conn, error) {
return SessionBusPrivate(WithHandler(handler), WithSignalHandler(signalHandler))
}
// SystemBus returns a shared connection to the system bus, connecting to it if
// not already done.
func SystemBus() (conn *Conn, err error) {
systemBusLck.Lock()
defer systemBusLck.Unlock()
if systemBus != nil &&
systemBus.Connected() {
return systemBus, nil
}
defer func() {
if conn != nil {
systemBus = conn
}
}()
conn, err = ConnectSystemBus()
return
}
// ConnectSessionBus connects to the session bus.
func ConnectSessionBus(opts ...ConnOption) (*Conn, error) {
address, err := getSessionBusAddress(true)
if err != nil {
return nil, err
}
return Connect(address, opts...)
}
// ConnectSystemBus connects to the system bus.
func ConnectSystemBus(opts ...ConnOption) (*Conn, error) {
return Connect(getSystemBusPlatformAddress(), opts...)
}
// Connect connects to the given address.
//
// Returned connection is ready to use and doesn't require calling
// Auth and Hello methods to make it usable.
func Connect(address string, opts ...ConnOption) (*Conn, error) {
conn, err := Dial(address, 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
}
// SystemBusPrivate returns a new private connection to the system bus.
// Note: this connection is not ready to use. One must perform Auth and Hello
// on the connection before it is usable.
func SystemBusPrivate(opts ...ConnOption) (*Conn, error) {
return Dial(getSystemBusPlatformAddress(), opts...)
}
// SystemBusPrivateHandler returns a new private connection to the system bus, using the provided handlers.
//
// Deprecated: use SystemBusPrivate with options instead.
func SystemBusPrivateHandler(handler Handler, signalHandler SignalHandler) (*Conn, error) {
return SystemBusPrivate(WithHandler(handler), WithSignalHandler(signalHandler))
}
// Dial establishes a new private connection to the message bus specified by address.
func Dial(address string, opts ...ConnOption) (*Conn, error) {
tr, err := getTransport(address)
if err != nil {
return nil, err
}
return newConn(tr, opts...)
}
// DialHandler establishes a new private connection to the message bus specified by address, using the supplied handlers.
//
// Deprecated: use Dial with options instead.
func DialHandler(address string, handler Handler, signalHandler SignalHandler) (*Conn, error) {
return Dial(address, WithHandler(handler), WithSignalHandler(signalHandler))
}
// ConnOption is a connection option.
type ConnOption func(conn *Conn) error
// WithHandler overrides the default handler.
func WithHandler(handler Handler) ConnOption {
return func(conn *Conn) error {
conn.handler = handler
return nil
}
}
// WithSignalHandler overrides the default signal handler.
func WithSignalHandler(handler SignalHandler) ConnOption {
return func(conn *Conn) error {
conn.signalHandler = handler
return nil
}
}
// WithSerialGenerator overrides the default signals generator.
func WithSerialGenerator(gen SerialGenerator) ConnOption {
return func(conn *Conn) error {
conn.serialGen = gen
return nil
}
}
// WithAuth sets authentication methods for the auth conversation.
func WithAuth(methods ...Auth) ConnOption {
return func(conn *Conn) error {
conn.auth = methods
return nil
}
}
// Interceptor intercepts incoming and outgoing messages.
type Interceptor func(msg *Message)
// WithIncomingInterceptor sets the given interceptor for incoming messages.
func WithIncomingInterceptor(interceptor Interceptor) ConnOption {
return func(conn *Conn) error {
conn.inInt = interceptor
return nil
}
}
// WithOutgoingInterceptor sets the given interceptor for outgoing messages.
func WithOutgoingInterceptor(interceptor Interceptor) ConnOption {
return func(conn *Conn) error {
conn.outInt = interceptor
return nil
}
}
// WithContext overrides the default context for the connection.
func WithContext(ctx context.Context) ConnOption {
return func(conn *Conn) error {
conn.ctx = ctx
return nil
}
}
// NewConn creates a new private *Conn from an already established connection.
func NewConn(conn io.ReadWriteCloser, opts ...ConnOption) (*Conn, error) {
return newConn(genericTransport{conn}, opts...)
}
// NewConnHandler creates a new private *Conn from an already established connection, using the supplied handlers.
//
// Deprecated: use NewConn with options instead.
func NewConnHandler(conn io.ReadWriteCloser, handler Handler, signalHandler SignalHandler) (*Conn, error) {
return NewConn(genericTransport{conn}, WithHandler(handler), WithSignalHandler(signalHandler))
}
// newConn creates a new *Conn from a transport.
func newConn(tr transport, opts ...ConnOption) (*Conn, error) {
conn := new(Conn)
conn.transport = tr
for _, opt := range opts {
if err := opt(conn); err != nil {
return nil, err
}
}
if conn.ctx == nil {
conn.ctx = context.Background()
}
conn.ctx, conn.cancelCtx = context.WithCancel(conn.ctx)
conn.calls = newCallTracker()
if conn.handler == nil {
conn.handler = NewDefaultHandler()
}
if conn.signalHandler == nil {
conn.signalHandler = NewDefaultSignalHandler()
}
if conn.serialGen == nil {
conn.serialGen = newSerialGenerator()
}
conn.outHandler = &outputHandler{conn: conn}
conn.names = newNameTracker()
conn.busObj = conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus")
go func() {
<-conn.ctx.Done()
conn.Close()
}()
return conn, nil
}
// BusObject returns the object owned by the bus daemon which handles
// administrative requests.
func (conn *Conn) BusObject() BusObject {
return conn.busObj
}
// Close closes the connection. Any blocked operations will return with errors
// and the channels passed to Eavesdrop and Signal are closed. This method must
// not be called on shared connections.
func (conn *Conn) Close() error {
conn.closeOnce.Do(func() {
conn.outHandler.close()
if term, ok := conn.signalHandler.(Terminator); ok {
term.Terminate()
}
if term, ok := conn.handler.(Terminator); ok {
term.Terminate()
}
conn.eavesdroppedLck.Lock()
if conn.eavesdropped != nil {
close(conn.eavesdropped)
}
conn.eavesdroppedLck.Unlock()
conn.cancelCtx()
conn.closeErr = conn.transport.Close()
})
return conn.closeErr
}
// Context returns the context associated with the connection. The
// context will be cancelled when the connection is closed.
func (conn *Conn) Context() context.Context {
return conn.ctx
}
// Connected returns whether conn is connected
func (conn *Conn) Connected() bool {
return conn.ctx.Err() == nil
}
// Eavesdrop causes conn to send all incoming messages to the given channel
// without further processing. Method replies, errors and signals will not be
// sent to the appropriate channels and method calls will not be handled. If nil
// is passed, the normal behaviour is restored.
//
// The caller has to make sure that ch is sufficiently buffered;
// if a message arrives when a write to ch is not possible, the message is
// discarded.
func (conn *Conn) Eavesdrop(ch chan<- *Message) {
conn.eavesdroppedLck.Lock()
conn.eavesdropped = ch
conn.eavesdroppedLck.Unlock()
}
// getSerial returns an unused serial.
func (conn *Conn) getSerial() uint32 {
return conn.serialGen.GetSerial()
}
// Hello sends the initial org.freedesktop.DBus.Hello call. This method must be
// called after authentication, but before sending any other messages to the
// bus. Hello must not be called for shared connections.
func (conn *Conn) Hello() error {
var s string
err := conn.busObj.Call("org.freedesktop.DBus.Hello", 0).Store(&s)
if err != nil {
return err
}
conn.names.acquireUniqueConnectionName(s)
return nil
}
// inWorker runs in an own goroutine, reading incoming messages from the
// transport and dispatching them appropriately.
func (conn *Conn) inWorker() {
sequenceGen := newSequenceGenerator()
for {
msg, err := conn.ReadMessage()
if err != nil {
if _, ok := err.(InvalidMessageError); !ok {
// Some read error occurred (usually EOF); we can't really do
// anything but to shut down all stuff and returns errors to all
// pending replies.
conn.Close()
conn.calls.finalizeAllWithError(sequenceGen, err)
return
}
// invalid messages are ignored
continue
}
conn.eavesdroppedLck.Lock()
if conn.eavesdropped != nil {
select {
case conn.eavesdropped <- msg:
default:
}
conn.eavesdroppedLck.Unlock()
continue
}
conn.eavesdroppedLck.Unlock()
dest, _ := msg.Headers[FieldDestination].value.(string)
found := dest == "" ||
!conn.names.uniqueNameIsKnown() ||
conn.names.isKnownName(dest)
if !found {
// Eavesdropped a message, but no channel for it is registered.
// Ignore it.
continue
}
if conn.inInt != nil {
conn.inInt(msg)
}
sequence := sequenceGen.next()
switch msg.Type {
case TypeError:
conn.serialGen.RetireSerial(conn.calls.handleDBusError(sequence, msg))
case TypeMethodReply:
conn.serialGen.RetireSerial(conn.calls.handleReply(sequence, msg))
case TypeSignal:
conn.handleSignal(sequence, msg)
case TypeMethodCall:
go conn.handleCall(msg)
}
}
}
func (conn *Conn) handleSignal(sequence Sequence, msg *Message) {
iface := msg.Headers[FieldInterface].value.(string)
member := msg.Headers[FieldMember].value.(string)
// as per http://dbus.freedesktop.org/doc/dbus-specification.html ,
// sender is optional for signals.
sender, _ := msg.Headers[FieldSender].value.(string)
if iface == "org.freedesktop.DBus" && sender == "org.freedesktop.DBus" {
if member == "NameLost" {
// If we lost the name on the bus, remove it from our
// tracking list.
name, ok := msg.Body[0].(string)
if !ok {
panic("Unable to read the lost name")
}
conn.names.loseName(name)
} else if member == "NameAcquired" {
// If we acquired the name on the bus, add it to our
// tracking list.
name, ok := msg.Body[0].(string)
if !ok {
panic("Unable to read the acquired name")
}
conn.names.acquireName(name)
}
}
signal := &Signal{
Sender: sender,
Path: msg.Headers[FieldPath].value.(ObjectPath),
Name: iface + "." + member,
Body: msg.Body,
Sequence: sequence,
}
conn.signalHandler.DeliverSignal(iface, member, signal)
}
// Names returns the list of all names that are currently owned by this
// connection. The slice is always at least one element long, the first element
// being the unique name of the connection.
func (conn *Conn) Names() []string {
return conn.names.listKnownNames()
}
// Object returns the object identified by the given destination name and path.
func (conn *Conn) Object(dest string, path ObjectPath) BusObject {
return &Object{conn, dest, path}
}
func (conn *Conn) sendMessageAndIfClosed(msg *Message, ifClosed func()) {
if msg.serial == 0 {
msg.serial = conn.getSerial()
}
if conn.outInt != nil {
conn.outInt(msg)
}
err := conn.outHandler.sendAndIfClosed(msg, ifClosed)
if err != nil {
conn.handleSendError(msg, err)
} else if msg.Type != TypeMethodCall {
conn.serialGen.RetireSerial(msg.serial)
}
}
func (conn *Conn) handleSendError(msg *Message, err error) {
if msg.Type == TypeMethodCall {
conn.calls.handleSendError(msg, err)
} else if msg.Type == TypeMethodReply {
if _, ok := err.(FormatError); ok {
conn.sendError(err, msg.Headers[FieldDestination].value.(string), msg.Headers[FieldReplySerial].value.(uint32))
}
}
conn.serialGen.RetireSerial(msg.serial)
}
// Send sends the given message to the message bus. You usually don't need to
// use this; use the higher-level equivalents (Call / Go, Emit and Export)
// instead. If msg is a method call and NoReplyExpected is not set, a non-nil
// call is returned and the same value is sent to ch (which must be buffered)
// once the call is complete. Otherwise, ch is ignored and a Call structure is
// returned of which only the Err member is valid.
func (conn *Conn) Send(msg *Message, ch chan *Call) *Call {
return conn.send(context.Background(), msg, ch)
}
// SendWithContext acts like Send but takes a context
func (conn *Conn) SendWithContext(ctx context.Context, msg *Message, ch chan *Call) *Call {
return conn.send(ctx, msg, ch)
}
func (conn *Conn) send(ctx context.Context, msg *Message, ch chan *Call) *Call {
if ctx == nil {
panic("nil context")
}
if ch == nil {
ch = make(chan *Call, 1)
} else if cap(ch) == 0 {
panic("dbus: unbuffered channel passed to (*Conn).Send")
}
var call *Call
ctx, canceler := context.WithCancel(ctx)
msg.serial = conn.getSerial()
if msg.Type == TypeMethodCall && msg.Flags&FlagNoReplyExpected == 0 {
call = new(Call)
call.Destination, _ = msg.Headers[FieldDestination].value.(string)
call.Path, _ = msg.Headers[FieldPath].value.(ObjectPath)
iface, _ := msg.Headers[FieldInterface].value.(string)
member, _ := msg.Headers[FieldMember].value.(string)
call.Method = iface + "." + member
call.Args = msg.Body
call.Done = ch
call.ctx = ctx
call.ctxCanceler = canceler
conn.calls.track(msg.serial, call)
if ctx.Err() != nil {
// short path: don't even send the message if context already cancelled
conn.calls.handleSendError(msg, ctx.Err())
return call
}
go func() {
<-ctx.Done()
conn.calls.handleSendError(msg, ctx.Err())
}()
conn.sendMessageAndIfClosed(msg, func() {
conn.calls.handleSendError(msg, ErrClosed)
canceler()
})
} else {
canceler()
call = &Call{Err: nil, Done: ch}
ch <- call
conn.sendMessageAndIfClosed(msg, func() {
call = &Call{Err: ErrClosed}
})
}
return call
}
// sendError creates an error message corresponding to the parameters and sends
// it to conn.out.
func (conn *Conn) sendError(err error, dest string, serial uint32) {
var e *Error
switch em := err.(type) {
case Error:
e = &em
case *Error:
e = em
case DBusError:
name, body := em.DBusError()
e = NewError(name, body)
default:
e = MakeFailedError(err)
}
msg := new(Message)
msg.Type = TypeError
msg.Headers = make(map[HeaderField]Variant)
if dest != "" {
msg.Headers[FieldDestination] = MakeVariant(dest)
}
msg.Headers[FieldErrorName] = MakeVariant(e.Name)
msg.Headers[FieldReplySerial] = MakeVariant(serial)
msg.Body = e.Body
if len(e.Body) > 0 {
msg.Headers[FieldSignature] = MakeVariant(SignatureOf(e.Body...))
}
conn.sendMessageAndIfClosed(msg, nil)
}
// 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{}) {
msg := new(Message)
msg.Type = TypeMethodReply
msg.Headers = make(map[HeaderField]Variant)
if dest != "" {
msg.Headers[FieldDestination] = MakeVariant(dest)
}
msg.Headers[FieldReplySerial] = MakeVariant(serial)
msg.Body = values
if len(values) > 0 {
msg.Headers[FieldSignature] = MakeVariant(SignatureOf(values...))
}
conn.sendMessageAndIfClosed(msg, nil)
}
// AddMatchSignal registers the given match rule to receive broadcast
// signals based on their contents.
func (conn *Conn) AddMatchSignal(options ...MatchOption) error {
return conn.AddMatchSignalContext(context.Background(), options...)
}
// AddMatchSignalContext acts like AddMatchSignal but takes a context.
func (conn *Conn) AddMatchSignalContext(ctx context.Context, options ...MatchOption) error {
options = append([]MatchOption{withMatchType("signal")}, options...)
return conn.busObj.CallWithContext(
ctx,
"org.freedesktop.DBus.AddMatch", 0,
formatMatchOptions(options),
).Store()
}
// RemoveMatchSignal removes the first rule that matches previously registered with AddMatchSignal.
func (conn *Conn) RemoveMatchSignal(options ...MatchOption) error {
return conn.RemoveMatchSignalContext(context.Background(), options...)
}
// RemoveMatchSignalContext acts like RemoveMatchSignal but takes a context.
func (conn *Conn) RemoveMatchSignalContext(ctx context.Context, options ...MatchOption) error {
options = append([]MatchOption{withMatchType("signal")}, options...)
return conn.busObj.CallWithContext(
ctx,
"org.freedesktop.DBus.RemoveMatch", 0,
formatMatchOptions(options),
).Store()
}
// Signal registers the given channel to be passed all received signal messages.
//
// Multiple of these channels can be registered at the same time. The channel is
// closed if the Conn is closed; it should not be closed by the caller before
// RemoveSignal was called on it.
//
// These channels are "overwritten" by Eavesdrop; i.e., if there currently is a
// channel for eavesdropped messages, this channel receives all signals, and
// none of the channels passed to Signal will receive any signals.
//
// Panics if the signal handler is not a `SignalRegistrar`.
func (conn *Conn) Signal(ch chan<- *Signal) {
handler, ok := conn.signalHandler.(SignalRegistrar)
if !ok {
panic("cannot use this method with a non SignalRegistrar handler")
}
handler.AddSignal(ch)
}
// RemoveSignal removes the given channel from the list of the registered channels.
//
// Panics if the signal handler is not a `SignalRegistrar`.
func (conn *Conn) RemoveSignal(ch chan<- *Signal) {
handler, ok := conn.signalHandler.(SignalRegistrar)
if !ok {
panic("cannot use this method with a non SignalRegistrar handler")
}
handler.RemoveSignal(ch)
}
// SupportsUnixFDs returns whether the underlying transport supports passing of
// unix file descriptors. If this is false, method calls containing unix file
// descriptors will return an error and emitted signals containing them will
// not be sent.
func (conn *Conn) SupportsUnixFDs() bool {
return conn.unixFD
}
// Error represents a D-Bus message of type Error.
type Error struct {
Name string
Body []interface{}
}
func NewError(name string, body []interface{}) *Error {
return &Error{name, body}
}
func (e Error) Error() string {
if len(e.Body) >= 1 {
s, ok := e.Body[0].(string)
if ok {
return s
}
}
return e.Name
}
// Signal represents a D-Bus message of type Signal. The name member is given in
// "interface.member" notation, e.g. org.freedesktop.D-Bus.NameLost.
type Signal struct {
Sender string
Path ObjectPath
Name string
Body []interface{}
Sequence Sequence
}
// transport is a D-Bus transport.
type transport interface {
// Read and Write raw data (for example, for the authentication protocol).
io.ReadWriteCloser
// Send the initial null byte used for the EXTERNAL mechanism.
SendNullByte() error
// Returns whether this transport supports passing Unix FDs.
SupportsUnixFDs() bool
// Signal the transport that Unix FD passing is enabled for this connection.
EnableUnixFDs()
// Read / send a message, handling things like Unix FDs.
ReadMessage() (*Message, error)
SendMessage(*Message) error
}
var (
transports = make(map[string]func(string) (transport, error))
)
func getTransport(address string) (transport, error) {
var err error
var t transport
addresses := strings.Split(address, ";")
for _, v := range addresses {
i := strings.IndexRune(v, ':')
if i == -1 {
err = errors.New("dbus: invalid bus address (no transport)")
continue
}
f := transports[v[:i]]
if f == nil {
err = errors.New("dbus: invalid bus address (invalid or unsupported transport)")
continue
}
t, err = f(v[i+1:])
if err == nil {
return t, nil
}
}
return nil, err
}
// 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])
if err != nil {
// No way to return an error.
return ""
}
return val
}
}
return ""
}
type outputHandler struct {
conn *Conn
sendLck sync.Mutex
closed struct {
isClosed bool
lck sync.RWMutex
}
}
func (h *outputHandler) sendAndIfClosed(msg *Message, ifClosed func()) error {
h.closed.lck.RLock()
defer h.closed.lck.RUnlock()
if h.closed.isClosed {
if ifClosed != nil {
ifClosed()
}
return nil
}
h.sendLck.Lock()
defer h.sendLck.Unlock()
return h.conn.SendMessage(msg)
}
func (h *outputHandler) close() {
h.closed.lck.Lock()
defer h.closed.lck.Unlock()
h.closed.isClosed = true
}
type serialGenerator struct {
lck sync.Mutex
nextSerial uint32
serialUsed map[uint32]bool
}
func newSerialGenerator() *serialGenerator {
return &serialGenerator{
serialUsed: map[uint32]bool{0: true},
nextSerial: 1,
}
}
func (gen *serialGenerator) GetSerial() uint32 {
gen.lck.Lock()
defer gen.lck.Unlock()
n := gen.nextSerial
for gen.serialUsed[n] {
n++
}
gen.serialUsed[n] = true
gen.nextSerial = n + 1
return n
}
func (gen *serialGenerator) RetireSerial(serial uint32) {
gen.lck.Lock()
defer gen.lck.Unlock()
delete(gen.serialUsed, serial)
}
type nameTracker struct {
lck sync.RWMutex
unique string
names map[string]struct{}
}
func newNameTracker() *nameTracker {
return &nameTracker{names: map[string]struct{}{}}
}
func (tracker *nameTracker) acquireUniqueConnectionName(name string) {
tracker.lck.Lock()
defer tracker.lck.Unlock()
tracker.unique = name
}
func (tracker *nameTracker) acquireName(name string) {
tracker.lck.Lock()
defer tracker.lck.Unlock()
tracker.names[name] = struct{}{}
}
func (tracker *nameTracker) loseName(name string) {
tracker.lck.Lock()
defer tracker.lck.Unlock()
delete(tracker.names, name)
}
func (tracker *nameTracker) uniqueNameIsKnown() bool {
tracker.lck.RLock()
defer tracker.lck.RUnlock()
return tracker.unique != ""
}
func (tracker *nameTracker) isKnownName(name string) bool {
tracker.lck.RLock()
defer tracker.lck.RUnlock()
_, ok := tracker.names[name]
return ok || name == tracker.unique
}
func (tracker *nameTracker) listKnownNames() []string {
tracker.lck.RLock()
defer tracker.lck.RUnlock()
out := make([]string, 0, len(tracker.names)+1)
out = append(out, tracker.unique)
for k := range tracker.names {
out = append(out, k)
}
return out
}
type callTracker struct {
calls map[uint32]*Call
lck sync.RWMutex
}
func newCallTracker() *callTracker {
return &callTracker{calls: map[uint32]*Call{}}
}
func (tracker *callTracker) track(sn uint32, call *Call) {
tracker.lck.Lock()
tracker.calls[sn] = call
tracker.lck.Unlock()
}
func (tracker *callTracker) handleReply(sequence Sequence, msg *Message) uint32 {
serial := msg.Headers[FieldReplySerial].value.(uint32)
tracker.lck.RLock()
_, ok := tracker.calls[serial]
tracker.lck.RUnlock()
if ok {
tracker.finalizeWithBody(serial, sequence, msg.Body)
}
return serial
}
func (tracker *callTracker) handleDBusError(sequence Sequence, msg *Message) uint32 {
serial := msg.Headers[FieldReplySerial].value.(uint32)
tracker.lck.RLock()
_, ok := tracker.calls[serial]
tracker.lck.RUnlock()
if ok {
name, _ := msg.Headers[FieldErrorName].value.(string)
tracker.finalizeWithError(serial, sequence, Error{name, msg.Body})
}
return serial
}
func (tracker *callTracker) handleSendError(msg *Message, err error) {
if err == nil {
return
}
tracker.lck.RLock()
_, ok := tracker.calls[msg.serial]
tracker.lck.RUnlock()
if ok {
tracker.finalizeWithError(msg.serial, NoSequence, err)
}
}
// finalize was the only func that did not strobe Done
func (tracker *callTracker) finalize(sn uint32) {
tracker.lck.Lock()
defer tracker.lck.Unlock()
c, ok := tracker.calls[sn]
if ok {
delete(tracker.calls, sn)
c.ContextCancel()
}
}
func (tracker *callTracker) finalizeWithBody(sn uint32, sequence Sequence, body []interface{}) {
tracker.lck.Lock()
c, ok := tracker.calls[sn]
if ok {
delete(tracker.calls, sn)
}
tracker.lck.Unlock()
if ok {
c.Body = body
c.ResponseSequence = sequence
c.done()
}
}
func (tracker *callTracker) finalizeWithError(sn uint32, sequence Sequence, err error) {
tracker.lck.Lock()
c, ok := tracker.calls[sn]
if ok {
delete(tracker.calls, sn)
}
tracker.lck.Unlock()
if ok {
c.Err = err
c.ResponseSequence = sequence
c.done()
}
}
func (tracker *callTracker) finalizeAllWithError(sequenceGen *sequenceGenerator, err error) {
tracker.lck.Lock()
closedCalls := make([]*Call, 0, len(tracker.calls))
for sn := range tracker.calls {
closedCalls = append(closedCalls, tracker.calls[sn])
}
tracker.calls = map[uint32]*Call{}
tracker.lck.Unlock()
for _, call := range closedCalls {
call.Err = err
call.ResponseSequence = sequenceGen.next()
call.done()
}
}
+37
View File
@@ -0,0 +1,37 @@
package dbus
import (
"errors"
"fmt"
"os"
"os/exec"
)
const defaultSystemBusAddress = "unix:path=/opt/local/var/run/dbus/system_bus_socket"
func getSessionBusPlatformAddress() (string, error) {
cmd := exec.Command("launchctl", "getenv", "DBUS_LAUNCHD_SESSION_BUS_SOCKET")
b, err := cmd.CombinedOutput()
if err != nil {
return "", err
}
if len(b) == 0 {
return "", errors.New("dbus: couldn't determine address of session bus")
}
return "unix:path=" + string(b[:len(b)-1]), nil
}
func getSystemBusPlatformAddress() string {
address := os.Getenv("DBUS_LAUNCHD_SESSION_BUS_SOCKET")
if address != "" {
return fmt.Sprintf("unix:path=%s", address)
}
return defaultSystemBusAddress
}
func tryDiscoverDbusSessionBusAddress() string {
return ""
}
+90
View File
@@ -0,0 +1,90 @@
// +build !darwin
package dbus
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/user"
"path"
"strings"
)
var execCommand = exec.Command
func getSessionBusPlatformAddress() (string, error) {
cmd := execCommand("dbus-launch")
b, err := cmd.CombinedOutput()
if err != nil {
return "", err
}
i := bytes.IndexByte(b, '=')
j := bytes.IndexByte(b, '\n')
if i == -1 || j == -1 || i > j {
return "", errors.New("dbus: couldn't determine address of session bus")
}
env, addr := string(b[0:i]), string(b[i+1:j])
os.Setenv(env, addr)
return addr, nil
}
// tryDiscoverDbusSessionBusAddress tries to discover an existing dbus session
// and return the value of its DBUS_SESSION_BUS_ADDRESS.
// It tries different techniques employed by different operating systems,
// returning the first valid address it finds, or an empty string.
//
// * /run/user/<uid>/bus if this exists, it *is* the bus socket. present on
// Ubuntu 18.04
// * /run/user/<uid>/dbus-session: if this exists, it can be parsed for the bus
// address. present on Ubuntu 16.04
//
// See https://dbus.freedesktop.org/doc/dbus-launch.1.html
func tryDiscoverDbusSessionBusAddress() string {
if runtimeDirectory, err := getRuntimeDirectory(); err == nil {
if runUserBusFile := path.Join(runtimeDirectory, "bus"); fileExists(runUserBusFile) {
// if /run/user/<uid>/bus exists, that file itself
// *is* the unix socket, so return its path
return fmt.Sprintf("unix:path=%s", EscapeBusAddressValue(runUserBusFile))
}
if runUserSessionDbusFile := path.Join(runtimeDirectory, "dbus-session"); fileExists(runUserSessionDbusFile) {
// if /run/user/<uid>/dbus-session exists, it's a
// 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
}
}
}
}
return ""
}
func getRuntimeDirectory() (string, error) {
if currentUser, err := user.Current(); err != nil {
return "", err
} else {
return fmt.Sprintf("/run/user/%s", currentUser.Uid), nil
}
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return !os.IsNotExist(err)
}
+17
View File
@@ -0,0 +1,17 @@
//+build !windows,!solaris,!darwin
package dbus
import (
"os"
)
const defaultSystemBusAddress = "unix:path=/var/run/dbus/system_bus_socket"
func getSystemBusPlatformAddress() string {
address := os.Getenv("DBUS_SYSTEM_BUS_ADDRESS")
if address != "" {
return address
}
return defaultSystemBusAddress
}
+15
View File
@@ -0,0 +1,15 @@
//+build windows
package dbus
import "os"
const defaultSystemBusAddress = "tcp:host=127.0.0.1,port=12434"
func getSystemBusPlatformAddress() string {
address := os.Getenv("DBUS_SYSTEM_BUS_ADDRESS")
if address != "" {
return address
}
return defaultSystemBusAddress
}
+430
View File
@@ -0,0 +1,430 @@
package dbus
import (
"errors"
"fmt"
"reflect"
"strings"
)
var (
byteType = reflect.TypeOf(byte(0))
boolType = reflect.TypeOf(false)
uint8Type = reflect.TypeOf(uint8(0))
int16Type = reflect.TypeOf(int16(0))
uint16Type = reflect.TypeOf(uint16(0))
intType = reflect.TypeOf(int(0))
uintType = reflect.TypeOf(uint(0))
int32Type = reflect.TypeOf(int32(0))
uint32Type = reflect.TypeOf(uint32(0))
int64Type = reflect.TypeOf(int64(0))
uint64Type = reflect.TypeOf(uint64(0))
float64Type = reflect.TypeOf(float64(0))
stringType = reflect.TypeOf("")
signatureType = reflect.TypeOf(Signature{""})
objectPathType = reflect.TypeOf(ObjectPath(""))
variantType = reflect.TypeOf(Variant{Signature{""}, nil})
interfacesType = reflect.TypeOf([]interface{}{})
interfaceType = reflect.TypeOf((*interface{})(nil)).Elem()
unixFDType = reflect.TypeOf(UnixFD(0))
unixFDIndexType = reflect.TypeOf(UnixFDIndex(0))
errType = reflect.TypeOf((*error)(nil)).Elem()
)
// An InvalidTypeError signals that a value which cannot be represented in the
// D-Bus wire format was passed to a function.
type InvalidTypeError struct {
Type reflect.Type
}
func (e InvalidTypeError) Error() string {
return "dbus: invalid type " + e.Type.String()
}
// Store copies the values contained in src to dest, which must be a slice of
// 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 {
if len(src) != len(dest) {
return errors.New("dbus.Store: length mismatch")
}
for i := range src {
if err := storeInterfaces(src[i], dest[i]); err != nil {
return err
}
}
return nil
}
func storeInterfaces(src, dest interface{}) error {
return store(reflect.ValueOf(dest), reflect.ValueOf(src))
}
func store(dest, src reflect.Value) error {
if dest.Kind() == reflect.Ptr {
if dest.IsNil() {
dest.Set(reflect.New(dest.Type().Elem()))
}
return store(dest.Elem(), src)
}
switch src.Kind() {
case reflect.Slice:
return storeSlice(dest, src)
case reflect.Map:
return storeMap(dest, src)
default:
return storeBase(dest, src)
}
}
func storeBase(dest, src reflect.Value) error {
return setDest(dest, src)
}
func setDest(dest, src reflect.Value) error {
if !isVariant(src.Type()) && isVariant(dest.Type()) {
//special conversion for dbus.Variant
dest.Set(reflect.ValueOf(MakeVariant(src.Interface())))
return nil
}
if isVariant(src.Type()) && !isVariant(dest.Type()) {
src = getVariantValue(src)
return store(dest, src)
}
if !src.Type().ConvertibleTo(dest.Type()) {
return fmt.Errorf(
"dbus.Store: type mismatch: cannot convert %s to %s",
src.Type(), dest.Type())
}
dest.Set(src.Convert(dest.Type()))
return nil
}
func kindsAreCompatible(dest, src reflect.Type) bool {
switch {
case isVariant(dest):
return true
case dest.Kind() == reflect.Interface:
return true
default:
return dest.Kind() == src.Kind()
}
}
func isConvertibleTo(dest, src reflect.Type) bool {
switch {
case isVariant(dest):
return true
case dest.Kind() == reflect.Interface:
return true
case dest.Kind() == reflect.Slice:
return src.Kind() == reflect.Slice &&
isConvertibleTo(dest.Elem(), src.Elem())
case dest.Kind() == reflect.Ptr:
dest = dest.Elem()
return isConvertibleTo(dest, src)
case dest.Kind() == reflect.Struct:
return src == interfacesType || dest.Kind() == src.Kind()
default:
return src.ConvertibleTo(dest)
}
}
func storeMap(dest, src reflect.Value) error {
switch {
case !kindsAreCompatible(dest.Type(), src.Type()):
return fmt.Errorf(
"dbus.Store: type mismatch: "+
"map: cannot store a value of %s into %s",
src.Type(), dest.Type())
case isVariant(dest.Type()):
return storeMapIntoVariant(dest, src)
case dest.Kind() == reflect.Interface:
return storeMapIntoInterface(dest, src)
case isConvertibleTo(dest.Type().Key(), src.Type().Key()) &&
isConvertibleTo(dest.Type().Elem(), src.Type().Elem()):
return storeMapIntoMap(dest, src)
default:
return fmt.Errorf(
"dbus.Store: type mismatch: "+
"map: cannot convert a value of %s into %s",
src.Type(), dest.Type())
}
}
func storeMapIntoVariant(dest, src reflect.Value) error {
dv := reflect.MakeMap(src.Type())
err := store(dv, src)
if err != nil {
return err
}
return storeBase(dest, dv)
}
func storeMapIntoInterface(dest, src reflect.Value) error {
var dv reflect.Value
if isVariant(src.Type().Elem()) {
//Convert variants to interface{} recursively when converting
//to interface{}
dv = reflect.MakeMap(
reflect.MapOf(src.Type().Key(), interfaceType))
} else {
dv = reflect.MakeMap(src.Type())
}
err := store(dv, src)
if err != nil {
return err
}
return storeBase(dest, dv)
}
func storeMapIntoMap(dest, src reflect.Value) error {
if dest.IsNil() {
dest.Set(reflect.MakeMap(dest.Type()))
}
keys := src.MapKeys()
for _, key := range keys {
dkey := key.Convert(dest.Type().Key())
dval := reflect.New(dest.Type().Elem()).Elem()
err := store(dval, getVariantValue(src.MapIndex(key)))
if err != nil {
return err
}
dest.SetMapIndex(dkey, dval)
}
return nil
}
func storeSlice(dest, src reflect.Value) error {
switch {
case src.Type() == interfacesType && dest.Kind() == reflect.Struct:
//The decoder always decodes structs as slices of interface{}
return storeStruct(dest, src)
case !kindsAreCompatible(dest.Type(), src.Type()):
return fmt.Errorf(
"dbus.Store: type mismatch: "+
"slice: cannot store a value of %s into %s",
src.Type(), dest.Type())
case isVariant(dest.Type()):
return storeSliceIntoVariant(dest, src)
case dest.Kind() == reflect.Interface:
return storeSliceIntoInterface(dest, src)
case isConvertibleTo(dest.Type().Elem(), src.Type().Elem()):
return storeSliceIntoSlice(dest, src)
default:
return fmt.Errorf(
"dbus.Store: type mismatch: "+
"slice: cannot convert a value of %s into %s",
src.Type(), dest.Type())
}
}
func storeStruct(dest, src reflect.Value) error {
if isVariant(dest.Type()) {
return storeBase(dest, src)
}
dval := make([]interface{}, 0, dest.NumField())
dtype := dest.Type()
for i := 0; i < dest.NumField(); i++ {
field := dest.Field(i)
ftype := dtype.Field(i)
if ftype.PkgPath != "" {
continue
}
if ftype.Tag.Get("dbus") == "-" {
continue
}
dval = append(dval, field.Addr().Interface())
}
if src.Len() != len(dval) {
return fmt.Errorf(
"dbus.Store: type mismatch: "+
"destination struct does not have "+
"enough fields need: %d have: %d",
src.Len(), len(dval))
}
return Store(src.Interface().([]interface{}), dval...)
}
func storeSliceIntoVariant(dest, src reflect.Value) error {
dv := reflect.MakeSlice(src.Type(), src.Len(), src.Cap())
err := store(dv, src)
if err != nil {
return err
}
return storeBase(dest, dv)
}
func storeSliceIntoInterface(dest, src reflect.Value) error {
var dv reflect.Value
if isVariant(src.Type().Elem()) {
//Convert variants to interface{} recursively when converting
//to interface{}
dv = reflect.MakeSlice(reflect.SliceOf(interfaceType),
src.Len(), src.Cap())
} else {
dv = reflect.MakeSlice(src.Type(), src.Len(), src.Cap())
}
err := store(dv, src)
if err != nil {
return err
}
return storeBase(dest, dv)
}
func storeSliceIntoSlice(dest, src reflect.Value) error {
if dest.IsNil() || dest.Len() < src.Len() {
dest.Set(reflect.MakeSlice(dest.Type(), src.Len(), src.Cap()))
} else if dest.Len() > src.Len() {
dest.Set(dest.Slice(0, src.Len()))
}
for i := 0; i < src.Len(); i++ {
err := store(dest.Index(i), getVariantValue(src.Index(i)))
if err != nil {
return err
}
}
return nil
}
func getVariantValue(in reflect.Value) reflect.Value {
if isVariant(in.Type()) {
return reflect.ValueOf(in.Interface().(Variant).Value())
}
return in
}
func isVariant(t reflect.Type) bool {
return t == variantType
}
// An ObjectPath is an object path as defined by the D-Bus spec.
type ObjectPath string
// IsValid returns whether the object path is valid.
func (o ObjectPath) IsValid() bool {
s := string(o)
if len(s) == 0 {
return false
}
if s[0] != '/' {
return false
}
if s[len(s)-1] == '/' && len(s) != 1 {
return false
}
// probably not used, but technically possible
if s == "/" {
return true
}
split := strings.Split(s[1:], "/")
for _, v := range split {
if len(v) == 0 {
return false
}
for _, c := range v {
if !isMemberChar(c) {
return false
}
}
}
return true
}
// A UnixFD is a Unix file descriptor sent over the wire. See the package-level
// documentation for more information about Unix file descriptor passsing.
type UnixFD int32
// A UnixFDIndex is the representation of a Unix file descriptor in a message.
type UnixFDIndex uint32
// alignment returns the alignment of values of type t.
func alignment(t reflect.Type) int {
switch t {
case variantType:
return 1
case objectPathType:
return 4
case signatureType:
return 1
case interfacesType:
return 4
}
switch t.Kind() {
case reflect.Uint8:
return 1
case reflect.Uint16, reflect.Int16:
return 2
case reflect.Uint, reflect.Int, reflect.Uint32, reflect.Int32, reflect.String, reflect.Array, reflect.Slice, reflect.Map:
return 4
case reflect.Uint64, reflect.Int64, reflect.Float64, reflect.Struct:
return 8
case reflect.Ptr:
return alignment(t.Elem())
}
return 1
}
// isKeyType returns whether t is a valid type for a D-Bus dict.
func isKeyType(t reflect.Type) bool {
switch t.Kind() {
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Int16, reflect.Int32, reflect.Int64, reflect.Float64,
reflect.String, reflect.Uint, reflect.Int:
return true
}
return false
}
// isValidInterface returns whether s is a valid name for an interface.
func isValidInterface(s string) bool {
if len(s) == 0 || len(s) > 255 || s[0] == '.' {
return false
}
elem := strings.Split(s, ".")
if len(elem) < 2 {
return false
}
for _, v := range elem {
if len(v) == 0 {
return false
}
if v[0] >= '0' && v[0] <= '9' {
return false
}
for _, c := range v {
if !isMemberChar(c) {
return false
}
}
}
return true
}
// isValidMember returns whether s is a valid name for a member.
func isValidMember(s string) bool {
if len(s) == 0 || len(s) > 255 {
return false
}
i := strings.Index(s, ".")
if i != -1 {
return false
}
if s[0] >= '0' && s[0] <= '9' {
return false
}
for _, c := range s {
if !isMemberChar(c) {
return false
}
}
return true
}
func isMemberChar(c rune) bool {
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') || c == '_'
}
+292
View File
@@ -0,0 +1,292 @@
package dbus
import (
"encoding/binary"
"io"
"reflect"
)
type decoder struct {
in io.Reader
order binary.ByteOrder
pos int
fds []int
}
// newDecoder returns a new decoder that reads values from in. The input is
// expected to be in the given byte order.
func newDecoder(in io.Reader, order binary.ByteOrder, fds []int) *decoder {
dec := new(decoder)
dec.in = in
dec.order = order
dec.fds = fds
return dec
}
// align aligns the input to the given boundary and panics on error.
func (dec *decoder) align(n int) {
if dec.pos%n != 0 {
newpos := (dec.pos + n - 1) & ^(n - 1)
empty := make([]byte, newpos-dec.pos)
if _, err := io.ReadFull(dec.in, empty); err != nil {
panic(err)
}
dec.pos = newpos
}
}
// Calls binary.Read(dec.in, dec.order, v) and panics on read errors.
func (dec *decoder) binread(v interface{}) {
if err := binary.Read(dec.in, dec.order, v); err != nil {
panic(err)
}
}
func (dec *decoder) Decode(sig Signature) (vs []interface{}, err error) {
defer func() {
var ok bool
v := recover()
if err, ok = v.(error); ok {
if err == io.EOF || err == io.ErrUnexpectedEOF {
err = FormatError("unexpected EOF")
}
}
}()
vs = make([]interface{}, 0)
s := sig.str
for s != "" {
err, rem := validSingle(s, &depthCounter{})
if err != nil {
return nil, err
}
v := dec.decode(s[:len(s)-len(rem)], 0)
vs = append(vs, v)
s = rem
}
return vs, nil
}
func (dec *decoder) decode(s string, depth int) interface{} {
dec.align(alignment(typeFor(s)))
switch s[0] {
case 'y':
var b [1]byte
if _, err := dec.in.Read(b[:]); err != nil {
panic(err)
}
dec.pos++
return b[0]
case 'b':
i := dec.decode("u", depth).(uint32)
switch {
case i == 0:
return false
case i == 1:
return true
default:
panic(FormatError("invalid value for boolean"))
}
case 'n':
var i int16
dec.binread(&i)
dec.pos += 2
return i
case 'i':
var i int32
dec.binread(&i)
dec.pos += 4
return i
case 'x':
var i int64
dec.binread(&i)
dec.pos += 8
return i
case 'q':
var i uint16
dec.binread(&i)
dec.pos += 2
return i
case 'u':
var i uint32
dec.binread(&i)
dec.pos += 4
return i
case 't':
var i uint64
dec.binread(&i)
dec.pos += 8
return i
case 'd':
var f float64
dec.binread(&f)
dec.pos += 8
return f
case 's':
length := dec.decode("u", depth).(uint32)
b := make([]byte, int(length)+1)
if _, err := io.ReadFull(dec.in, b); err != nil {
panic(err)
}
dec.pos += int(length) + 1
return string(b[:len(b)-1])
case 'o':
return ObjectPath(dec.decode("s", depth).(string))
case 'g':
length := dec.decode("y", depth).(byte)
b := make([]byte, int(length)+1)
if _, err := io.ReadFull(dec.in, b); err != nil {
panic(err)
}
dec.pos += int(length) + 1
sig, err := ParseSignature(string(b[:len(b)-1]))
if err != nil {
panic(err)
}
return sig
case 'v':
if depth >= 64 {
panic(FormatError("input exceeds container depth limit"))
}
var variant Variant
sig := dec.decode("g", depth).(Signature)
if len(sig.str) == 0 {
panic(FormatError("variant signature is empty"))
}
err, rem := validSingle(sig.str, &depthCounter{})
if err != nil {
panic(err)
}
if rem != "" {
panic(FormatError("variant signature has multiple types"))
}
variant.sig = sig
variant.value = dec.decode(sig.str, depth+1)
return variant
case 'h':
idx := dec.decode("u", depth).(uint32)
if int(idx) < len(dec.fds) {
return UnixFD(dec.fds[idx])
}
return UnixFDIndex(idx)
case 'a':
if len(s) > 1 && s[1] == '{' {
ksig := s[2:3]
vsig := s[3 : len(s)-1]
v := reflect.MakeMap(reflect.MapOf(typeFor(ksig), typeFor(vsig)))
if depth >= 63 {
panic(FormatError("input exceeds container depth limit"))
}
length := dec.decode("u", depth).(uint32)
// Even for empty maps, the correct padding must be included
dec.align(8)
spos := dec.pos
for dec.pos < spos+int(length) {
dec.align(8)
if !isKeyType(v.Type().Key()) {
panic(InvalidTypeError{v.Type()})
}
kv := dec.decode(ksig, depth+2)
vv := dec.decode(vsig, depth+2)
v.SetMapIndex(reflect.ValueOf(kv), reflect.ValueOf(vv))
}
return v.Interface()
}
if depth >= 64 {
panic(FormatError("input exceeds container depth limit"))
}
sig := s[1:]
length := dec.decode("u", depth).(uint32)
// capacity can be determined only for fixed-size element types
var capacity int
if s := sigByteSize(sig); s != 0 {
capacity = int(length) / s
}
v := reflect.MakeSlice(reflect.SliceOf(typeFor(sig)), 0, capacity)
// Even for empty arrays, the correct padding must be included
align := alignment(typeFor(s[1:]))
if len(s) > 1 && s[1] == '(' {
//Special case for arrays of structs
//structs decode as a slice of interface{} values
//but the dbus alignment does not match this
align = 8
}
dec.align(align)
spos := dec.pos
for dec.pos < spos+int(length) {
ev := dec.decode(s[1:], depth+1)
v = reflect.Append(v, reflect.ValueOf(ev))
}
return v.Interface()
case '(':
if depth >= 64 {
panic(FormatError("input exceeds container depth limit"))
}
dec.align(8)
v := make([]interface{}, 0)
s = s[1 : len(s)-1]
for s != "" {
err, rem := validSingle(s, &depthCounter{})
if err != nil {
panic(err)
}
ev := dec.decode(s[:len(s)-len(rem)], depth+1)
v = append(v, ev)
s = rem
}
return v
default:
panic(SignatureError{Sig: s})
}
}
// sigByteSize tries to calculates size of the given signature in bytes.
//
// It returns zero when it can't, for example when it contains non-fixed size
// types such as strings, maps and arrays that require reading of the transmitted
// data, for that we would need to implement the unread method for Decoder first.
func sigByteSize(sig string) int {
var total int
for offset := 0; offset < len(sig); {
switch sig[offset] {
case 'y':
total += 1
offset += 1
case 'n', 'q':
total += 2
offset += 1
case 'b', 'i', 'u', 'h':
total += 4
offset += 1
case 'x', 't', 'd':
total += 8
offset += 1
case '(':
i := 1
depth := 1
for i < len(sig[offset:]) && depth != 0 {
if sig[offset+i] == '(' {
depth++
} else if sig[offset+i] == ')' {
depth--
}
i++
}
s := sigByteSize(sig[offset+1 : offset+i-1])
if s == 0 {
return 0
}
total += s
offset += i
default:
return 0
}
}
return total
}
// A FormatError is an error in the wire format.
type FormatError string
func (e FormatError) Error() string {
return "dbus: wire format error: " + string(e)
}
+342
View File
@@ -0,0 +1,342 @@
package dbus
import (
"bytes"
"reflect"
"strings"
"sync"
)
func newIntrospectIntf(h *defaultHandler) *exportedIntf {
methods := make(map[string]Method)
methods["Introspect"] = exportedMethod{
reflect.ValueOf(func(msg Message) (string, *Error) {
path := msg.Headers[FieldPath].value.(ObjectPath)
return h.introspectPath(path), nil
}),
}
return newExportedIntf(methods, true)
}
//NewDefaultHandler returns an instance of the default
//call handler. This is useful if you want to implement only
//one of the two handlers but not both.
//
// Deprecated: this is the default value, don't use it, it will be unexported.
func NewDefaultHandler() *defaultHandler {
h := &defaultHandler{
objects: make(map[ObjectPath]*exportedObj),
defaultIntf: make(map[string]*exportedIntf),
}
h.defaultIntf["org.freedesktop.DBus.Introspectable"] = newIntrospectIntf(h)
return h
}
type defaultHandler struct {
sync.RWMutex
objects map[ObjectPath]*exportedObj
defaultIntf map[string]*exportedIntf
}
func (h *defaultHandler) PathExists(path ObjectPath) bool {
_, ok := h.objects[path]
return ok
}
func (h *defaultHandler) introspectPath(path ObjectPath) string {
subpath := make(map[string]struct{})
var xml bytes.Buffer
xml.WriteString("<node>")
for obj := range h.objects {
p := string(path)
if p != "/" {
p += "/"
}
if strings.HasPrefix(string(obj), p) {
node_name := strings.Split(string(obj[len(p):]), "/")[0]
subpath[node_name] = struct{}{}
}
}
for s := range subpath {
xml.WriteString("\n\t<node name=\"" + s + "\"/>")
}
xml.WriteString("\n</node>")
return xml.String()
}
func (h *defaultHandler) LookupObject(path ObjectPath) (ServerObject, bool) {
h.RLock()
defer h.RUnlock()
object, ok := h.objects[path]
if ok {
return object, ok
}
// If an object wasn't found for this exact path,
// look for a matching subtree registration
subtreeObject := newExportedObject()
path = path[:strings.LastIndex(string(path), "/")]
for len(path) > 0 {
object, ok = h.objects[path]
if ok {
for name, iface := range object.interfaces {
// Only include this handler if it registered for the subtree
if iface.isFallbackInterface() {
subtreeObject.interfaces[name] = iface
}
}
break
}
path = path[:strings.LastIndex(string(path), "/")]
}
for name, intf := range h.defaultIntf {
if _, exists := subtreeObject.interfaces[name]; exists {
continue
}
subtreeObject.interfaces[name] = intf
}
return subtreeObject, true
}
func (h *defaultHandler) AddObject(path ObjectPath, object *exportedObj) {
h.Lock()
h.objects[path] = object
h.Unlock()
}
func (h *defaultHandler) DeleteObject(path ObjectPath) {
h.Lock()
delete(h.objects, path)
h.Unlock()
}
type exportedMethod struct {
reflect.Value
}
func (m exportedMethod) Call(args ...interface{}) ([]interface{}, error) {
t := m.Type()
params := make([]reflect.Value, len(args))
for i := 0; i < len(args); i++ {
params[i] = reflect.ValueOf(args[i]).Elem()
}
ret := m.Value.Call(params)
var err error
nilErr := false // The reflection will find almost-nils, let's only pass back clean ones!
if t.NumOut() > 0 {
if e, ok := ret[t.NumOut()-1].Interface().(*Error); ok { // godbus *Error
nilErr = ret[t.NumOut()-1].IsNil()
ret = ret[:t.NumOut()-1]
err = e
} else if ret[t.NumOut()-1].Type().Implements(errType) { // Go error
i := ret[t.NumOut()-1].Interface()
if i == nil {
nilErr = ret[t.NumOut()-1].IsNil()
} else {
err = i.(error)
}
ret = ret[:t.NumOut()-1]
}
}
out := make([]interface{}, len(ret))
for i, val := range ret {
out[i] = val.Interface()
}
if nilErr || err == nil {
//concrete type to interface nil is a special case
return out, nil
}
return out, err
}
func (m exportedMethod) NumArguments() int {
return m.Value.Type().NumIn()
}
func (m exportedMethod) ArgumentValue(i int) interface{} {
return reflect.Zero(m.Type().In(i)).Interface()
}
func (m exportedMethod) NumReturns() int {
return m.Value.Type().NumOut()
}
func (m exportedMethod) ReturnValue(i int) interface{} {
return reflect.Zero(m.Type().Out(i)).Interface()
}
func newExportedObject() *exportedObj {
return &exportedObj{
interfaces: make(map[string]*exportedIntf),
}
}
type exportedObj struct {
mu sync.RWMutex
interfaces map[string]*exportedIntf
}
func (obj *exportedObj) LookupInterface(name string) (Interface, bool) {
if name == "" {
return obj, true
}
obj.mu.RLock()
defer obj.mu.RUnlock()
intf, exists := obj.interfaces[name]
return intf, exists
}
func (obj *exportedObj) AddInterface(name string, iface *exportedIntf) {
obj.mu.Lock()
defer obj.mu.Unlock()
obj.interfaces[name] = iface
}
func (obj *exportedObj) DeleteInterface(name string) {
obj.mu.Lock()
defer obj.mu.Unlock()
delete(obj.interfaces, name)
}
func (obj *exportedObj) LookupMethod(name string) (Method, bool) {
obj.mu.RLock()
defer obj.mu.RUnlock()
for _, intf := range obj.interfaces {
method, exists := intf.LookupMethod(name)
if exists {
return method, exists
}
}
return nil, false
}
func (obj *exportedObj) isFallbackInterface() bool {
return false
}
func newExportedIntf(methods map[string]Method, includeSubtree bool) *exportedIntf {
return &exportedIntf{
methods: methods,
includeSubtree: includeSubtree,
}
}
type exportedIntf struct {
methods map[string]Method
// Whether or not this export is for the entire subtree
includeSubtree bool
}
func (obj *exportedIntf) LookupMethod(name string) (Method, bool) {
out, exists := obj.methods[name]
return out, exists
}
func (obj *exportedIntf) isFallbackInterface() bool {
return obj.includeSubtree
}
//NewDefaultSignalHandler returns an instance of the default
//signal handler. This is useful if you want to implement only
//one of the two handlers but not both.
//
// Deprecated: this is the default value, don't use it, it will be unexported.
func NewDefaultSignalHandler() *defaultSignalHandler {
return &defaultSignalHandler{}
}
type defaultSignalHandler struct {
mu sync.RWMutex
closed bool
signals []*signalChannelData
}
func (sh *defaultSignalHandler) DeliverSignal(intf, name string, signal *Signal) {
sh.mu.RLock()
defer sh.mu.RUnlock()
if sh.closed {
return
}
for _, scd := range sh.signals {
scd.deliver(signal)
}
}
func (sh *defaultSignalHandler) Terminate() {
sh.mu.Lock()
defer sh.mu.Unlock()
if sh.closed {
return
}
for _, scd := range sh.signals {
scd.close()
close(scd.ch)
}
sh.closed = true
sh.signals = nil
}
func (sh *defaultSignalHandler) AddSignal(ch chan<- *Signal) {
sh.mu.Lock()
defer sh.mu.Unlock()
if sh.closed {
return
}
sh.signals = append(sh.signals, &signalChannelData{
ch: ch,
done: make(chan struct{}),
})
}
func (sh *defaultSignalHandler) RemoveSignal(ch chan<- *Signal) {
sh.mu.Lock()
defer sh.mu.Unlock()
if sh.closed {
return
}
for i := len(sh.signals) - 1; i >= 0; i-- {
if ch == sh.signals[i].ch {
sh.signals[i].close()
copy(sh.signals[i:], sh.signals[i+1:])
sh.signals[len(sh.signals)-1] = nil
sh.signals = sh.signals[:len(sh.signals)-1]
}
}
}
type signalChannelData struct {
wg sync.WaitGroup
ch chan<- *Signal
done chan struct{}
}
func (scd *signalChannelData) deliver(signal *Signal) {
select {
case scd.ch <- signal:
case <-scd.done:
return
default:
scd.wg.Add(1)
go scd.deferredDeliver(signal)
}
}
func (scd *signalChannelData) deferredDeliver(signal *Signal) {
select {
case scd.ch <- signal:
case <-scd.done:
}
scd.wg.Done()
}
func (scd *signalChannelData) close() {
close(scd.done)
scd.wg.Wait() // wait until all spawned goroutines return
}
+71
View File
@@ -0,0 +1,71 @@
/*
Package dbus implements bindings to the D-Bus message bus system.
To use the message bus API, you first need to connect to a bus (usually the
session or system bus). The acquired connection then can be used to call methods
on remote objects and emit or receive signals. Using the Export method, you can
arrange D-Bus methods calls to be directly translated to method calls on a Go
value.
Conversion Rules
For outgoing messages, Go types are automatically converted to the
corresponding D-Bus types. See the official specification at
https://dbus.freedesktop.org/doc/dbus-specification.html#type-system for more
information on the D-Bus type system. The following types are directly encoded
as their respective D-Bus equivalents:
Go type | D-Bus type
------------+-----------
byte | BYTE
bool | BOOLEAN
int16 | INT16
uint16 | UINT16
int | INT32
uint | UINT32
int32 | INT32
uint32 | UINT32
int64 | INT64
uint64 | UINT64
float64 | DOUBLE
string | STRING
ObjectPath | OBJECT_PATH
Signature | SIGNATURE
Variant | VARIANT
interface{} | VARIANT
UnixFDIndex | UNIX_FD
Slices and arrays encode as ARRAYs of their element type.
Maps encode as DICTs, provided that their key type can be used as a key for
a DICT.
Structs other than Variant and Signature encode as a STRUCT containing their
exported fields in order. Fields whose tags contain `dbus:"-"` and unexported
fields will be skipped.
Pointers encode as the value they're pointed to.
Types convertible to one of the base types above will be mapped as the
base type.
Trying to encode any other type or a slice, map or struct containing an
unsupported type will result in an InvalidTypeError.
For incoming messages, the inverse of these rules are used, with the exception
of STRUCTs. Incoming STRUCTS are represented as a slice of empty interfaces
containing the struct fields in the correct order. The Store function can be
used to convert such values to Go structs.
Unix FD passing
Handling Unix file descriptors deserves special mention. To use them, you should
first check that they are supported on a connection by calling SupportsUnixFDs.
If it returns true, all method of Connection will translate messages containing
UnixFD's to messages that are accompanied by the given file descriptors with the
UnixFD values being substituted by the correct indices. Similarly, the indices
of incoming messages are automatically resolved. It shouldn't be necessary to use
UnixFDIndex.
*/
package dbus
+235
View File
@@ -0,0 +1,235 @@
package dbus
import (
"bytes"
"encoding/binary"
"io"
"reflect"
"strings"
"unicode/utf8"
)
// An encoder encodes values to the D-Bus wire format.
type encoder struct {
out io.Writer
fds []int
order binary.ByteOrder
pos int
}
// NewEncoder returns a new encoder that writes to out in the given byte order.
func newEncoder(out io.Writer, order binary.ByteOrder, fds []int) *encoder {
enc := newEncoderAtOffset(out, 0, order, fds)
return enc
}
// newEncoderAtOffset returns a new encoder that writes to out in the given
// byte order. Specify the offset to initialize pos for proper alignment
// computation.
func newEncoderAtOffset(out io.Writer, offset int, order binary.ByteOrder, fds []int) *encoder {
enc := new(encoder)
enc.out = out
enc.order = order
enc.pos = offset
enc.fds = fds
return enc
}
// Aligns the next output to be on a multiple of n. Panics on write errors.
func (enc *encoder) align(n int) {
pad := enc.padding(0, n)
if pad > 0 {
empty := make([]byte, pad)
if _, err := enc.out.Write(empty); err != nil {
panic(err)
}
enc.pos += pad
}
}
// pad returns the number of bytes of padding, based on current position and additional offset.
// and alignment.
func (enc *encoder) padding(offset, algn int) int {
abs := enc.pos + offset
if abs%algn != 0 {
newabs := (abs + algn - 1) & ^(algn - 1)
return newabs - abs
}
return 0
}
// Calls binary.Write(enc.out, enc.order, v) and panics on write errors.
func (enc *encoder) binwrite(v interface{}) {
if err := binary.Write(enc.out, enc.order, v); err != nil {
panic(err)
}
}
// 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) {
defer func() {
err, _ = recover().(error)
}()
for _, v := range vs {
enc.encode(reflect.ValueOf(v), 0)
}
return nil
}
// encode encodes the given value to the writer and panics on error. depth holds
// the depth of the container nesting.
func (enc *encoder) encode(v reflect.Value, depth int) {
if depth > 64 {
panic(FormatError("input exceeds depth limitation"))
}
enc.align(alignment(v.Type()))
switch v.Kind() {
case reflect.Uint8:
var b [1]byte
b[0] = byte(v.Uint())
if _, err := enc.out.Write(b[:]); err != nil {
panic(err)
}
enc.pos++
case reflect.Bool:
if v.Bool() {
enc.encode(reflect.ValueOf(uint32(1)), depth)
} else {
enc.encode(reflect.ValueOf(uint32(0)), depth)
}
case reflect.Int16:
enc.binwrite(int16(v.Int()))
enc.pos += 2
case reflect.Uint16:
enc.binwrite(uint16(v.Uint()))
enc.pos += 2
case reflect.Int, reflect.Int32:
if v.Type() == unixFDType {
fd := v.Int()
idx := len(enc.fds)
enc.fds = append(enc.fds, int(fd))
enc.binwrite(uint32(idx))
} else {
enc.binwrite(int32(v.Int()))
}
enc.pos += 4
case reflect.Uint, reflect.Uint32:
enc.binwrite(uint32(v.Uint()))
enc.pos += 4
case reflect.Int64:
enc.binwrite(v.Int())
enc.pos += 8
case reflect.Uint64:
enc.binwrite(v.Uint())
enc.pos += 8
case reflect.Float64:
enc.binwrite(v.Float())
enc.pos += 8
case reflect.String:
str := v.String()
if !utf8.ValidString(str) {
panic(FormatError("input has a not-utf8 char in string"))
}
if strings.IndexByte(str, byte(0)) != -1 {
panic(FormatError("input has a null char('\\000') in string"))
}
if v.Type() == objectPathType {
if !ObjectPath(str).IsValid() {
panic(FormatError("invalid object path"))
}
}
enc.encode(reflect.ValueOf(uint32(len(str))), depth)
b := make([]byte, v.Len()+1)
copy(b, str)
b[len(b)-1] = 0
n, err := enc.out.Write(b)
if err != nil {
panic(err)
}
enc.pos += n
case reflect.Ptr:
enc.encode(v.Elem(), depth)
case reflect.Slice, reflect.Array:
// Lookahead offset: 4 bytes for uint32 length (with alignment),
// plus alignment for elements.
n := enc.padding(0, 4) + 4
offset := enc.pos + n + enc.padding(n, alignment(v.Type().Elem()))
var buf bytes.Buffer
bufenc := newEncoderAtOffset(&buf, offset, enc.order, enc.fds)
for i := 0; i < v.Len(); i++ {
bufenc.encode(v.Index(i), depth+1)
}
if buf.Len() > 1<<26 {
panic(FormatError("input exceeds array size limitation"))
}
enc.fds = bufenc.fds
enc.encode(reflect.ValueOf(uint32(buf.Len())), depth)
length := buf.Len()
enc.align(alignment(v.Type().Elem()))
if _, err := buf.WriteTo(enc.out); err != nil {
panic(err)
}
enc.pos += length
case reflect.Struct:
switch t := v.Type(); t {
case signatureType:
str := v.Field(0)
enc.encode(reflect.ValueOf(byte(str.Len())), depth)
b := make([]byte, str.Len()+1)
copy(b, str.String())
b[len(b)-1] = 0
n, err := enc.out.Write(b)
if err != nil {
panic(err)
}
enc.pos += n
case variantType:
variant := v.Interface().(Variant)
enc.encode(reflect.ValueOf(variant.sig), depth+1)
enc.encode(reflect.ValueOf(variant.value), depth+1)
default:
for i := 0; i < v.Type().NumField(); i++ {
field := t.Field(i)
if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
enc.encode(v.Field(i), depth+1)
}
}
}
case reflect.Map:
// Maps are arrays of structures, so they actually increase the depth by
// 2.
if !isKeyType(v.Type().Key()) {
panic(InvalidTypeError{v.Type()})
}
keys := v.MapKeys()
// Lookahead offset: 4 bytes for uint32 length (with alignment),
// plus 8-byte alignment
n := enc.padding(0, 4) + 4
offset := enc.pos + n + enc.padding(n, 8)
var buf bytes.Buffer
bufenc := newEncoderAtOffset(&buf, offset, enc.order, enc.fds)
for _, k := range keys {
bufenc.align(8)
bufenc.encode(k, depth+2)
bufenc.encode(v.MapIndex(k), depth+2)
}
enc.fds = bufenc.fds
enc.encode(reflect.ValueOf(uint32(buf.Len())), depth)
length := buf.Len()
enc.align(8)
if _, err := buf.WriteTo(enc.out); err != nil {
panic(err)
}
enc.pos += length
case reflect.Interface:
enc.encode(reflect.ValueOf(MakeVariant(v.Interface())), depth)
default:
panic(InvalidTypeError{v.Type()})
}
}
+84
View File
@@ -0,0 +1,84 @@
package dbus
import "net/url"
// EscapeBusAddressValue implements a requirement to escape the values
// in D-Bus server addresses, as defined by the D-Bus specification at
// https://dbus.freedesktop.org/doc/dbus-specification.html#addresses.
func EscapeBusAddressValue(val string) string {
toEsc := strNeedsEscape(val)
if toEsc == 0 {
// Avoid unneeded allocation/copying.
return val
}
// Avoid allocation for short paths.
var buf [64]byte
var out []byte
// Every to-be-escaped byte needs 2 extra bytes.
required := len(val) + 2*toEsc
if required <= len(buf) {
out = buf[:required]
} else {
out = make([]byte, required)
}
j := 0
for i := 0; i < len(val); i++ {
if ch := val[i]; needsEscape(ch) {
// Convert ch to %xx, where xx is hex value.
out[j] = '%'
out[j+1] = hexchar(ch >> 4)
out[j+2] = hexchar(ch & 0x0F)
j += 3
} else {
out[j] = ch
j++
}
}
return string(out)
}
// UnescapeBusAddressValue unescapes values in D-Bus server addresses,
// as defined by the D-Bus specification at
// https://dbus.freedesktop.org/doc/dbus-specification.html#addresses.
func UnescapeBusAddressValue(val string) (string, error) {
// Looks like url.PathUnescape does exactly what is required.
return url.PathUnescape(val)
}
// hexchar returns an octal representation of a n, where n < 16.
// For invalid values of n, the function panics.
func hexchar(n byte) byte {
const hex = "0123456789abcdef"
// For n >= len(hex), runtime will panic.
return hex[n]
}
// needsEscape tells if a byte is NOT one of optionally-escaped bytes.
func needsEscape(c byte) bool {
if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' {
return false
}
switch c {
case '-', '_', '/', '\\', '.', '*':
return false
}
return true
}
// strNeedsEscape tells how many bytes in the string need escaping.
func strNeedsEscape(val string) int {
count := 0
for i := 0; i < len(val); i++ {
if needsEscape(val[i]) {
count++
}
}
return count
}
+463
View File
@@ -0,0 +1,463 @@
package dbus
import (
"errors"
"fmt"
"os"
"reflect"
"strings"
)
var (
ErrMsgInvalidArg = Error{
"org.freedesktop.DBus.Error.InvalidArgs",
[]interface{}{"Invalid type / number of args"},
}
ErrMsgNoObject = Error{
"org.freedesktop.DBus.Error.NoSuchObject",
[]interface{}{"No such object"},
}
ErrMsgUnknownMethod = Error{
"org.freedesktop.DBus.Error.UnknownMethod",
[]interface{}{"Unknown / invalid method"},
}
ErrMsgUnknownInterface = Error{
"org.freedesktop.DBus.Error.UnknownInterface",
[]interface{}{"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))},
}
}
func MakeUnknownMethodError(methodName string) Error {
return Error{
"org.freedesktop.DBus.Error.UnknownMethod",
[]interface{}{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)},
}
}
func MakeFailedError(err error) *Error {
return &Error{
"org.freedesktop.DBus.Error.Failed",
[]interface{}{err.Error()},
}
}
// Sender is a type which can be used in exported methods to receive the message
// sender.
type Sender string
func computeMethodName(name string, mapping map[string]string) string {
newname, ok := mapping[name]
if ok {
name = newname
}
return name
}
func getMethods(in interface{}, mapping map[string]string) map[string]reflect.Value {
if in == nil {
return nil
}
methods := make(map[string]reflect.Value)
val := reflect.ValueOf(in)
typ := val.Type()
for i := 0; i < typ.NumMethod(); i++ {
methtype := typ.Method(i)
method := val.Method(i)
t := method.Type()
// only track valid methods must return *Error as last arg
// and must be exported
if t.NumOut() == 0 ||
t.Out(t.NumOut()-1) != reflect.TypeOf(&ErrMsgInvalidArg) ||
methtype.PkgPath != "" {
continue
}
// map names while building table
methods[computeMethodName(methtype.Name, mapping)] = method
}
return methods
}
func getAllMethods(in interface{}, mapping map[string]string) map[string]reflect.Value {
if in == nil {
return nil
}
methods := make(map[string]reflect.Value)
val := reflect.ValueOf(in)
typ := val.Type()
for i := 0; i < typ.NumMethod(); i++ {
methtype := typ.Method(i)
method := val.Method(i)
// map names while building table
methods[computeMethodName(methtype.Name, mapping)] = method
}
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))
for i := 0; i < m.NumArguments(); i++ {
tp := reflect.TypeOf(m.ArgumentValue(i))
val := reflect.New(tp)
pointers[i] = val.Interface()
if tp == reflect.TypeOf((*Sender)(nil)).Elem() {
val.Elem().SetString(sender)
} else if tp == reflect.TypeOf((*Message)(nil)).Elem() {
val.Elem().Set(reflect.ValueOf(*msg))
} else {
decode = append(decode, pointers[i])
}
}
if len(decode) != len(body) {
return nil, ErrMsgInvalidArg
}
if err := Store(body, decode...); err != nil {
return nil, ErrMsgInvalidArg
}
return pointers, nil
}
func (conn *Conn) decodeArguments(m Method, sender string, msg *Message) ([]interface{}, error) {
if decoder, ok := m.(ArgumentDecoder); ok {
return decoder.DecodeArguments(conn, sender, msg, msg.Body)
}
return standardMethodArgumentDecode(m, sender, msg, msg.Body)
}
// handleCall handles the given method call (i.e. looks if it's one of the
// pre-implemented ones and searches for a corresponding handler if not).
func (conn *Conn) handleCall(msg *Message) {
name := msg.Headers[FieldMember].value.(string)
path := msg.Headers[FieldPath].value.(ObjectPath)
ifaceName, _ := msg.Headers[FieldInterface].value.(string)
sender, hasSender := msg.Headers[FieldSender].value.(string)
serial := msg.serial
if len(name) == 0 {
conn.sendError(ErrMsgUnknownMethod, sender, serial)
}
if ifaceName == "org.freedesktop.DBus.Peer" {
switch name {
case "Ping":
conn.sendReply(sender, serial)
case "GetMachineId":
conn.sendReply(sender, serial, conn.uuid)
default:
conn.sendError(MakeUnknownMethodError(name), sender, serial)
}
return
}
object, ok := conn.handler.LookupObject(path)
if !ok {
conn.sendError(MakeNoObjectError(path), sender, serial)
return
}
iface, exists := object.LookupInterface(ifaceName)
if !exists {
conn.sendError(MakeUnknownInterfaceError(ifaceName), sender, serial)
return
}
m, exists := iface.LookupMethod(name)
if !exists {
conn.sendError(MakeUnknownMethodError(name), sender, serial)
return
}
args, err := conn.decodeArguments(m, sender, msg)
if err != nil {
conn.sendError(err, sender, serial)
return
}
ret, err := m.Call(args...)
if err != nil {
conn.sendError(err, sender, serial)
return
}
if msg.Flags&FlagNoReplyExpected == 0 {
reply := new(Message)
reply.Type = TypeMethodReply
reply.Headers = make(map[HeaderField]Variant)
if hasSender {
reply.Headers[FieldDestination] = msg.Headers[FieldSender]
}
reply.Headers[FieldReplySerial] = MakeVariant(msg.serial)
reply.Body = make([]interface{}, len(ret))
for i := 0; i < len(ret); i++ {
reply.Body[i] = ret[i]
}
reply.Headers[FieldSignature] = MakeVariant(SignatureOf(reply.Body...))
if err := reply.IsValid(); err != nil {
fmt.Fprintf(os.Stderr, "dbus: dropping invalid reply to %s.%s on obj %s: %s\n", ifaceName, name, path, err)
} else {
conn.sendMessageAndIfClosed(reply, nil)
}
}
}
// 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 {
i := strings.LastIndex(name, ".")
if i == -1 {
return errors.New("dbus: invalid method name")
}
iface := name[:i]
member := name[i+1:]
msg := new(Message)
msg.Type = TypeSignal
msg.Headers = make(map[HeaderField]Variant)
msg.Headers[FieldInterface] = MakeVariant(iface)
msg.Headers[FieldMember] = MakeVariant(member)
msg.Headers[FieldPath] = MakeVariant(path)
msg.Body = values
if len(values) > 0 {
msg.Headers[FieldSignature] = MakeVariant(SignatureOf(values...))
}
if err := msg.IsValid(); err != nil {
return err
}
var closed bool
conn.sendMessageAndIfClosed(msg, func() {
closed = true
})
if closed {
return ErrClosed
}
return nil
}
// Export registers the given value to be exported as an object on the
// message bus.
//
// If a method call on the given path and interface is received, an exported
// method with the same name is called with v as the receiver if the
// parameters match and the last return value is of type *Error. If this
// *Error 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.
//
// Any parameters with the special type Sender are set to the sender of the
// dbus message when the method is called. Parameters of this type do not
// contribute to the dbus signature of the method (i.e. the method is exposed
// as if the parameters of type Sender were not there).
//
// Similarly, any parameters with the type Message are set to the raw message
// received on the bus. Again, parameters of this type do not contribute to the
// dbus signature of the method.
//
// Every method call is executed in a new goroutine, so the method may be called
// in multiple goroutines at once.
//
// Method calls on the interface org.freedesktop.DBus.Peer will be automatically
// handled for every object.
//
// Passing nil as the first parameter will cause conn to cease handling calls on
// 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 {
return conn.ExportWithMap(v, nil, path, iface)
}
// ExportAll registers all exported methods defined by the given object on
// the message bus.
//
// Unlike Export there is no requirement to have the last parameter as type
// *Error. If you want to be able to return error then you can append an 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 {
return conn.export(getAllMethods(v, nil), path, iface, false)
}
// ExportWithMap works exactly like Export but provides the ability to remap
// method names (e.g. export a lower-case method).
//
// 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 {
return conn.export(getMethods(v, mapping), path, iface, false)
}
// ExportSubtree works exactly like Export but registers the given value for
// an entire subtree rather under the root path provided.
//
// In order to make this useful, one parameter in each of the value's exported
// methods should be a Message, in which case it will contain the raw message
// (allowing one to get access to the path that caused the method to be called).
//
// 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 {
return conn.ExportSubtreeWithMap(v, nil, path, iface)
}
// ExportSubtreeWithMap works exactly like ExportSubtree but provides the
// ability to remap method names (e.g. export a lower-case method).
//
// 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 {
return conn.export(getMethods(v, mapping), path, iface, true)
}
// ExportMethodTable like Export registers the given methods as an object
// on the message bus. Unlike Export the it uses a method table to define
// the object instead of a native go object.
//
// The method table is a map from method name to function closure
// representing the method. This allows an object exported on the bus to not
// necessarily be a native go object. It can be useful for generating exposed
// 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 {
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 {
return conn.exportMethodTable(methods, path, iface, true)
}
func (conn *Conn) exportMethodTable(methods map[string]interface{}, path ObjectPath, iface string, includeSubtree bool) error {
var out map[string]reflect.Value
if methods != nil {
out = make(map[string]reflect.Value)
for name, method := range methods {
rval := reflect.ValueOf(method)
if rval.Kind() != reflect.Func {
continue
}
t := rval.Type()
// only track valid methods must return *Error as last arg
if t.NumOut() == 0 ||
t.Out(t.NumOut()-1) != reflect.TypeOf(&ErrMsgInvalidArg) {
continue
}
out[name] = rval
}
}
return conn.export(out, path, iface, includeSubtree)
}
func (conn *Conn) unexport(h *defaultHandler, path ObjectPath, iface string) error {
if h.PathExists(path) {
obj := h.objects[path]
obj.DeleteInterface(iface)
if len(obj.interfaces) == 0 {
h.DeleteObject(path)
}
}
return nil
}
// export is the worker function for all exports/registrations.
func (conn *Conn) export(methods map[string]reflect.Value, path ObjectPath, iface string, includeSubtree bool) error {
h, ok := conn.handler.(*defaultHandler)
if !ok {
return fmt.Errorf(
`dbus: export only allowed on the default handler. Received: %T"`,
conn.handler)
}
if !path.IsValid() {
return fmt.Errorf(`dbus: Invalid path name: "%s"`, path)
}
// Remove a previous export if the interface is nil
if methods == nil {
return conn.unexport(h, path, iface)
}
// If this is the first handler for this path, make a new map to hold all
// handlers for this path.
if !h.PathExists(path) {
h.AddObject(path, newExportedObject())
}
exportedMethods := make(map[string]Method)
for name, method := range methods {
exportedMethods[name] = exportedMethod{method}
}
// Finally, save this handler
obj := h.objects[path]
obj.AddInterface(iface, newExportedIntf(exportedMethods, includeSubtree))
return nil
}
// ReleaseName calls org.freedesktop.DBus.ReleaseName and awaits a response.
func (conn *Conn) ReleaseName(name string) (ReleaseNameReply, error) {
var r uint32
err := conn.busObj.Call("org.freedesktop.DBus.ReleaseName", 0, name).Store(&r)
if err != nil {
return 0, err
}
return ReleaseNameReply(r), nil
}
// RequestName calls org.freedesktop.DBus.RequestName and awaits a response.
func (conn *Conn) RequestName(name string, flags RequestNameFlags) (RequestNameReply, error) {
var r uint32
err := conn.busObj.Call("org.freedesktop.DBus.RequestName", 0, name, flags).Store(&r)
if err != nil {
return 0, err
}
return RequestNameReply(r), nil
}
// ReleaseNameReply is the reply to a ReleaseName call.
type ReleaseNameReply uint32
const (
ReleaseNameReplyReleased ReleaseNameReply = 1 + iota
ReleaseNameReplyNonExistent
ReleaseNameReplyNotOwner
)
// RequestNameFlags represents the possible flags for a RequestName call.
type RequestNameFlags uint32
const (
NameFlagAllowReplacement RequestNameFlags = 1 << iota
NameFlagReplaceExisting
NameFlagDoNotQueue
)
// RequestNameReply is the reply to a RequestName call.
type RequestNameReply uint32
const (
RequestNameReplyPrimaryOwner RequestNameReply = 1 + iota
RequestNameReplyInQueue
RequestNameReplyExists
RequestNameReplyAlreadyOwner
)
+25
View File
@@ -0,0 +1,25 @@
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 "/"
}
+89
View File
@@ -0,0 +1,89 @@
package dbus
import (
"strconv"
"strings"
)
// MatchOption specifies option for dbus routing match rule. Options can be constructed with WithMatch* helpers.
// For full list of available options consult
// https://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing-match-rules
type MatchOption struct {
key string
value string
}
func formatMatchOptions(options []MatchOption) string {
items := make([]string, 0, len(options))
for _, option := range options {
items = append(items, option.key+"='"+option.value+"'")
}
return strings.Join(items, ",")
}
// WithMatchOption creates match option with given key and value
func WithMatchOption(key, value string) MatchOption {
return MatchOption{key, value}
}
// doesn't make sense to export this option because clients can only
// subscribe to messages with signal type.
func withMatchType(typ string) MatchOption {
return WithMatchOption("type", typ)
}
// WithMatchSender sets sender match option.
func WithMatchSender(sender string) MatchOption {
return WithMatchOption("sender", sender)
}
// WithMatchSender sets interface match option.
func WithMatchInterface(iface string) MatchOption {
return WithMatchOption("interface", iface)
}
// WithMatchMember sets member match option.
func WithMatchMember(member string) MatchOption {
return WithMatchOption("member", member)
}
// WithMatchObjectPath creates match option that filters events based on given path
func WithMatchObjectPath(path ObjectPath) MatchOption {
return WithMatchOption("path", string(path))
}
// WithMatchPathNamespace sets path_namespace match option.
func WithMatchPathNamespace(namespace ObjectPath) MatchOption {
return WithMatchOption("path_namespace", string(namespace))
}
// WithMatchDestination sets destination match option.
func WithMatchDestination(destination string) MatchOption {
return WithMatchOption("destination", destination)
}
// WithMatchArg sets argN match option, range of N is 0 to 63.
func WithMatchArg(argIdx int, value string) MatchOption {
if argIdx < 0 || argIdx > 63 {
panic("range of argument index is 0 to 63")
}
return WithMatchOption("arg"+strconv.Itoa(argIdx), value)
}
// WithMatchArgPath sets argN path match option, range of N is 0 to 63.
func WithMatchArgPath(argIdx int, path string) MatchOption {
if argIdx < 0 || argIdx > 63 {
panic("range of argument index is 0 to 63")
}
return WithMatchOption("arg"+strconv.Itoa(argIdx)+"path", path)
}
// WithMatchArg0Namespace sets arg0namespace match option.
func WithMatchArg0Namespace(arg0Namespace string) MatchOption {
return WithMatchOption("arg0namespace", arg0Namespace)
}
// WithMatchEavesdrop sets eavesdrop match option.
func WithMatchEavesdrop(eavesdrop bool) MatchOption {
return WithMatchOption("eavesdrop", strconv.FormatBool(eavesdrop))
}
+390
View File
@@ -0,0 +1,390 @@
package dbus
import (
"bytes"
"encoding/binary"
"errors"
"io"
"reflect"
"strconv"
)
const protoVersion byte = 1
// Flags represents the possible flags of a D-Bus message.
type Flags byte
const (
// FlagNoReplyExpected signals that the message is not expected to generate
// a reply. If this flag is set on outgoing messages, any possible reply
// will be discarded.
FlagNoReplyExpected Flags = 1 << iota
// FlagNoAutoStart signals that the message bus should not automatically
// start an application when handling this message.
FlagNoAutoStart
// FlagAllowInteractiveAuthorization may be set on a method call
// message to inform the receiving side that the caller is prepared
// to wait for interactive authorization, which might take a
// considerable time to complete. For instance, if this flag is set,
// it would be appropriate to query the user for passwords or
// confirmation via Polkit or a similar framework.
FlagAllowInteractiveAuthorization
)
// Type represents the possible types of a D-Bus message.
type Type byte
const (
TypeMethodCall Type = 1 + iota
TypeMethodReply
TypeError
TypeSignal
typeMax
)
func (t Type) String() string {
switch t {
case TypeMethodCall:
return "method call"
case TypeMethodReply:
return "reply"
case TypeError:
return "error"
case TypeSignal:
return "signal"
}
return "invalid"
}
// HeaderField represents the possible byte codes for the headers
// of a D-Bus message.
type HeaderField byte
const (
FieldPath HeaderField = 1 + iota
FieldInterface
FieldMember
FieldErrorName
FieldReplySerial
FieldDestination
FieldSender
FieldSignature
FieldUnixFDs
fieldMax
)
// An InvalidMessageError describes the reason why a D-Bus message is regarded as
// invalid.
type InvalidMessageError string
func (e InvalidMessageError) Error() string {
return "dbus: invalid message: " + string(e)
}
// fieldType are the types of the various header fields.
var fieldTypes = [fieldMax]reflect.Type{
FieldPath: objectPathType,
FieldInterface: stringType,
FieldMember: stringType,
FieldErrorName: stringType,
FieldReplySerial: uint32Type,
FieldDestination: stringType,
FieldSender: stringType,
FieldSignature: signatureType,
FieldUnixFDs: uint32Type,
}
// requiredFields lists the header fields that are required by the different
// message types.
var requiredFields = [typeMax][]HeaderField{
TypeMethodCall: {FieldPath, FieldMember},
TypeMethodReply: {FieldReplySerial},
TypeError: {FieldErrorName, FieldReplySerial},
TypeSignal: {FieldPath, FieldInterface, FieldMember},
}
// Message represents a single D-Bus message.
type Message struct {
Type
Flags
Headers map[HeaderField]Variant
Body []interface{}
serial uint32
}
type header struct {
Field byte
Variant
}
func DecodeMessageWithFDs(rd io.Reader, fds []int) (msg *Message, err error) {
var order binary.ByteOrder
var hlength, length uint32
var typ, flags, proto byte
var headers []header
b := make([]byte, 1)
_, err = rd.Read(b)
if err != nil {
return
}
switch b[0] {
case 'l':
order = binary.LittleEndian
case 'B':
order = binary.BigEndian
default:
return nil, InvalidMessageError("invalid byte order")
}
dec := newDecoder(rd, order, fds)
dec.pos = 1
msg = new(Message)
vs, err := dec.Decode(Signature{"yyyuu"})
if err != nil {
return nil, err
}
if err = Store(vs, &typ, &flags, &proto, &length, &msg.serial); err != nil {
return nil, err
}
msg.Type = Type(typ)
msg.Flags = Flags(flags)
// get the header length separately because we need it later
b = make([]byte, 4)
_, err = io.ReadFull(rd, b)
if err != nil {
return nil, err
}
binary.Read(bytes.NewBuffer(b), order, &hlength)
if hlength+length+16 > 1<<27 {
return nil, InvalidMessageError("message is too long")
}
dec = newDecoder(io.MultiReader(bytes.NewBuffer(b), rd), order, fds)
dec.pos = 12
vs, err = dec.Decode(Signature{"a(yv)"})
if err != nil {
return nil, err
}
if err = Store(vs, &headers); err != nil {
return nil, err
}
msg.Headers = make(map[HeaderField]Variant)
for _, v := range headers {
msg.Headers[HeaderField(v.Field)] = v.Variant
}
dec.align(8)
body := make([]byte, int(length))
if length != 0 {
_, err := io.ReadFull(rd, body)
if err != nil {
return nil, err
}
}
if err = msg.IsValid(); err != nil {
return nil, err
}
sig, _ := msg.Headers[FieldSignature].value.(Signature)
if sig.str != "" {
buf := bytes.NewBuffer(body)
dec = newDecoder(buf, order, fds)
vs, err := dec.Decode(sig)
if err != nil {
return nil, err
}
msg.Body = vs
}
return
}
// DecodeMessage tries to decode a single message in the D-Bus wire format
// from the given reader. The byte order is figured out from the first byte.
// The possibly returned error can be an error of the underlying reader, an
// InvalidMessageError or a FormatError.
func DecodeMessage(rd io.Reader) (msg *Message, err error) {
return DecodeMessageWithFDs(rd, make([]int, 0))
}
type nullwriter struct{}
func (nullwriter) Write(p []byte) (cnt int, err error) {
return len(p), nil
}
func (msg *Message) CountFds() (int, error) {
if len(msg.Body) == 0 {
return 0, nil
}
enc := newEncoder(nullwriter{}, nativeEndian, make([]int, 0))
err := enc.Encode(msg.Body...)
return len(enc.fds), err
}
func (msg *Message) EncodeToWithFDs(out io.Writer, order binary.ByteOrder) (fds []int, err error) {
if err := msg.validateHeader(); err != nil {
return nil, err
}
var vs [7]interface{}
switch order {
case binary.LittleEndian:
vs[0] = byte('l')
case binary.BigEndian:
vs[0] = byte('B')
default:
return nil, errors.New("dbus: invalid byte order")
}
body := new(bytes.Buffer)
fds = make([]int, 0)
enc := newEncoder(body, order, fds)
if len(msg.Body) != 0 {
err = enc.Encode(msg.Body...)
if err != nil {
return
}
}
vs[1] = msg.Type
vs[2] = msg.Flags
vs[3] = protoVersion
vs[4] = uint32(len(body.Bytes()))
vs[5] = msg.serial
headers := make([]header, 0, len(msg.Headers))
for k, v := range msg.Headers {
headers = append(headers, header{byte(k), v})
}
vs[6] = headers
var buf bytes.Buffer
enc = newEncoder(&buf, order, enc.fds)
err = enc.Encode(vs[:]...)
if err != nil {
return
}
enc.align(8)
body.WriteTo(&buf)
if buf.Len() > 1<<27 {
return make([]int, 0), InvalidMessageError("message is too long")
}
if _, err := buf.WriteTo(out); err != nil {
return make([]int, 0), err
}
return enc.fds, nil
}
// EncodeTo encodes and sends a message to the given writer. The byte order must
// be either binary.LittleEndian or binary.BigEndian. If the message is not
// valid or an error occurs when writing, an error is returned.
func (msg *Message) EncodeTo(out io.Writer, order binary.ByteOrder) (err error) {
_, err = msg.EncodeToWithFDs(out, order)
return err
}
// IsValid checks whether msg is a valid message and returns an
// InvalidMessageError or FormatError if it is not.
func (msg *Message) IsValid() error {
var b bytes.Buffer
return msg.EncodeTo(&b, nativeEndian)
}
func (msg *Message) validateHeader() error {
if msg.Flags & ^(FlagNoAutoStart|FlagNoReplyExpected|FlagAllowInteractiveAuthorization) != 0 {
return InvalidMessageError("invalid flags")
}
if msg.Type == 0 || msg.Type >= typeMax {
return InvalidMessageError("invalid message type")
}
for k, v := range msg.Headers {
if k == 0 || k >= fieldMax {
return InvalidMessageError("invalid header")
}
if reflect.TypeOf(v.value) != fieldTypes[k] {
return InvalidMessageError("invalid type of header field")
}
}
for _, v := range requiredFields[msg.Type] {
if _, ok := msg.Headers[v]; !ok {
return InvalidMessageError("missing required header")
}
}
if path, ok := msg.Headers[FieldPath]; ok {
if !path.value.(ObjectPath).IsValid() {
return InvalidMessageError("invalid path name")
}
}
if iface, ok := msg.Headers[FieldInterface]; ok {
if !isValidInterface(iface.value.(string)) {
return InvalidMessageError("invalid interface name")
}
}
if member, ok := msg.Headers[FieldMember]; ok {
if !isValidMember(member.value.(string)) {
return InvalidMessageError("invalid member name")
}
}
if errname, ok := msg.Headers[FieldErrorName]; ok {
if !isValidInterface(errname.value.(string)) {
return InvalidMessageError("invalid error name")
}
}
if len(msg.Body) != 0 {
if _, ok := msg.Headers[FieldSignature]; !ok {
return InvalidMessageError("missing signature")
}
}
return nil
}
// Serial returns the message's serial number. The returned value is only valid
// for messages received by eavesdropping.
func (msg *Message) Serial() uint32 {
return msg.serial
}
// String returns a string representation of a message similar to the format of
// dbus-monitor.
func (msg *Message) String() string {
if err := msg.IsValid(); err != nil {
return "<invalid>"
}
s := msg.Type.String()
if v, ok := msg.Headers[FieldSender]; ok {
s += " from " + v.value.(string)
}
if v, ok := msg.Headers[FieldDestination]; ok {
s += " to " + v.value.(string)
}
s += " serial " + strconv.FormatUint(uint64(msg.serial), 10)
if v, ok := msg.Headers[FieldReplySerial]; ok {
s += " reply_serial " + strconv.FormatUint(uint64(v.value.(uint32)), 10)
}
if v, ok := msg.Headers[FieldUnixFDs]; ok {
s += " unixfds " + strconv.FormatUint(uint64(v.value.(uint32)), 10)
}
if v, ok := msg.Headers[FieldPath]; ok {
s += " path " + string(v.value.(ObjectPath))
}
if v, ok := msg.Headers[FieldInterface]; ok {
s += " interface " + v.value.(string)
}
if v, ok := msg.Headers[FieldErrorName]; ok {
s += " error " + v.value.(string)
}
if v, ok := msg.Headers[FieldMember]; ok {
s += " member " + v.value.(string)
}
if len(msg.Body) != 0 {
s += "\n"
}
for i, v := range msg.Body {
s += " " + MakeVariant(v).String()
if i != len(msg.Body)-1 {
s += "\n"
}
}
return s
}
+174
View File
@@ -0,0 +1,174 @@
package dbus
import (
"context"
"errors"
"strings"
)
// 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
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
Destination() string
Path() ObjectPath
}
// Object represents a remote object on which methods can be invoked.
type Object struct {
conn *Conn
dest string
path ObjectPath
}
// Call calls a method with (*Object).Go and waits for its reply.
func (o *Object) Call(method string, flags Flags, args ...interface{}) *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 {
return <-o.createCall(ctx, method, flags, make(chan *Call, 1), args...).Done
}
// AddMatchSignal subscribes BusObject to signals from specified interface,
// method (member). Additional filter rules can be added via WithMatch* option constructors.
// Note: To filter events by object path you have to specify this path via an option.
//
// Deprecated: use (*Conn) AddMatchSignal instead.
func (o *Object) AddMatchSignal(iface, member string, options ...MatchOption) *Call {
base := []MatchOption{
withMatchType("signal"),
WithMatchInterface(iface),
WithMatchMember(member),
}
options = append(base, options...)
return o.conn.BusObject().Call(
"org.freedesktop.DBus.AddMatch",
0,
formatMatchOptions(options),
)
}
// RemoveMatchSignal unsubscribes BusObject from signals from specified interface,
// method (member). Additional filter rules can be added via WithMatch* option constructors
//
// Deprecated: use (*Conn) RemoveMatchSignal instead.
func (o *Object) RemoveMatchSignal(iface, member string, options ...MatchOption) *Call {
base := []MatchOption{
withMatchType("signal"),
WithMatchInterface(iface),
WithMatchMember(member),
}
options = append(base, options...)
return o.conn.BusObject().Call(
"org.freedesktop.DBus.RemoveMatch",
0,
formatMatchOptions(options),
)
}
// Go calls a method with the given arguments asynchronously. It returns a
// Call structure representing this method call. The passed channel will
// return the same value once the call is done. If ch is nil, a new channel
// will be allocated. Otherwise, ch has to be buffered or Go will panic.
//
// If the flags include FlagNoReplyExpected, ch is ignored and a Call structure
// is returned with any error in Err and a closed channel in Done containing
// the returned Call as it's one entry.
//
// 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 {
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 {
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 {
if ctx == nil {
panic("nil context")
}
iface := ""
i := strings.LastIndex(method, ".")
if i != -1 {
iface = method[:i]
}
method = method[i+1:]
msg := new(Message)
msg.Type = TypeMethodCall
msg.Flags = flags & (FlagNoAutoStart | FlagNoReplyExpected)
msg.Headers = make(map[HeaderField]Variant)
msg.Headers[FieldPath] = MakeVariant(o.path)
msg.Headers[FieldDestination] = MakeVariant(o.dest)
msg.Headers[FieldMember] = MakeVariant(method)
if iface != "" {
msg.Headers[FieldInterface] = MakeVariant(iface)
}
msg.Body = args
if len(args) > 0 {
msg.Headers[FieldSignature] = MakeVariant(SignatureOf(args...))
}
return o.conn.SendWithContext(ctx, msg, ch)
}
// GetProperty calls org.freedesktop.DBus.Properties.Get on the given
// object. The property name must be given in interface.member notation.
func (o *Object) GetProperty(p string) (Variant, error) {
var result Variant
err := o.StoreProperty(p, &result)
return result, err
}
// 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 {
idx := strings.LastIndex(p, ".")
if idx == -1 || idx+1 == len(p) {
return errors.New("dbus: invalid property " + p)
}
iface := p[:idx]
prop := p[idx+1:]
return o.Call("org.freedesktop.DBus.Properties.Get", 0, iface, prop).
Store(value)
}
// SetProperty calls org.freedesktop.DBus.Properties.Set on the given
// object. The property name must be given in interface.member notation.
func (o *Object) SetProperty(p string, v interface{}) error {
idx := strings.LastIndex(p, ".")
if idx == -1 || idx+1 == len(p) {
return errors.New("dbus: invalid property " + p)
}
iface := p[:idx]
prop := p[idx+1:]
return o.Call("org.freedesktop.DBus.Properties.Set", 0, iface, prop, v).Err
}
// Destination returns the destination that calls on (o *Object) are sent to.
func (o *Object) Destination() string {
return o.dest
}
// Path returns the path that calls on (o *Object") are sent to.
func (o *Object) Path() ObjectPath {
return o.path
}
+24
View File
@@ -0,0 +1,24 @@
package dbus
// Sequence represents the value of a monotonically increasing counter.
type Sequence uint64
const (
// NoSequence indicates the absence of a sequence value.
NoSequence Sequence = 0
)
// sequenceGenerator represents a monotonically increasing counter.
type sequenceGenerator struct {
nextSequence Sequence
}
func (generator *sequenceGenerator) next() Sequence {
result := generator.nextSequence
generator.nextSequence++
return result
}
func newSequenceGenerator() *sequenceGenerator {
return &sequenceGenerator{nextSequence: 1}
}
+125
View File
@@ -0,0 +1,125 @@
package dbus
import (
"sync"
)
// NewSequentialSignalHandler returns an instance of a new
// signal handler that guarantees sequential processing of signals. It is a
// guarantee of this signal handler that signals will be written to
// channels in the order they are received on the DBus connection.
func NewSequentialSignalHandler() SignalHandler {
return &sequentialSignalHandler{}
}
type sequentialSignalHandler struct {
mu sync.RWMutex
closed bool
signals []*sequentialSignalChannelData
}
func (sh *sequentialSignalHandler) DeliverSignal(intf, name string, signal *Signal) {
sh.mu.RLock()
defer sh.mu.RUnlock()
if sh.closed {
return
}
for _, scd := range sh.signals {
scd.deliver(signal)
}
}
func (sh *sequentialSignalHandler) Terminate() {
sh.mu.Lock()
defer sh.mu.Unlock()
if sh.closed {
return
}
for _, scd := range sh.signals {
scd.close()
close(scd.ch)
}
sh.closed = true
sh.signals = nil
}
func (sh *sequentialSignalHandler) AddSignal(ch chan<- *Signal) {
sh.mu.Lock()
defer sh.mu.Unlock()
if sh.closed {
return
}
sh.signals = append(sh.signals, newSequentialSignalChannelData(ch))
}
func (sh *sequentialSignalHandler) RemoveSignal(ch chan<- *Signal) {
sh.mu.Lock()
defer sh.mu.Unlock()
if sh.closed {
return
}
for i := len(sh.signals) - 1; i >= 0; i-- {
if ch == sh.signals[i].ch {
sh.signals[i].close()
copy(sh.signals[i:], sh.signals[i+1:])
sh.signals[len(sh.signals)-1] = nil
sh.signals = sh.signals[:len(sh.signals)-1]
}
}
}
type sequentialSignalChannelData struct {
ch chan<- *Signal
in chan *Signal
done chan struct{}
}
func newSequentialSignalChannelData(ch chan<- *Signal) *sequentialSignalChannelData {
scd := &sequentialSignalChannelData{
ch: ch,
in: make(chan *Signal),
done: make(chan struct{}),
}
go scd.bufferSignals()
return scd
}
func (scd *sequentialSignalChannelData) bufferSignals() {
defer close(scd.done)
// Ensure that signals are delivered to scd.ch in the same
// order they are received from scd.in.
var queue []*Signal
for {
if len(queue) == 0 {
signal, ok := <- scd.in
if !ok {
return
}
queue = append(queue, signal)
}
select {
case scd.ch <- queue[0]:
copy(queue, queue[1:])
queue[len(queue)-1] = nil
queue = queue[:len(queue)-1]
case signal, ok := <-scd.in:
if !ok {
return
}
queue = append(queue, signal)
}
}
}
func (scd *sequentialSignalChannelData) deliver(signal *Signal) {
scd.in <- signal
}
func (scd *sequentialSignalChannelData) close() {
close(scd.in)
// Ensure that bufferSignals() has exited and won't attempt
// any future sends on scd.ch
<-scd.done
}
+107
View File
@@ -0,0 +1,107 @@
package dbus
// Terminator allows a handler to implement a shutdown mechanism that
// is called when the connection terminates.
type Terminator interface {
Terminate()
}
// Handler is the representation of a D-Bus Application.
//
// The Handler must have a way to lookup objects given
// an ObjectPath. The returned object must implement the
// ServerObject interface.
type Handler interface {
LookupObject(path ObjectPath) (ServerObject, bool)
}
// ServerObject is the representation of an D-Bus Object.
//
// Objects are registered at a path for a given Handler.
// The Objects implement D-Bus interfaces. The semantics
// of Interface lookup is up to the implementation of
// the ServerObject. The ServerObject implementation may
// choose to implement empty string as a valid interface
// represeting all methods or not per the D-Bus specification.
type ServerObject interface {
LookupInterface(name string) (Interface, bool)
}
// An Interface is the representation of a D-Bus Interface.
//
// Interfaces are a grouping of methods implemented by the Objects.
// Interfaces are responsible for routing method calls.
type Interface interface {
LookupMethod(name string) (Method, bool)
}
// 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)
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{}
// 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{}
}
// An Argument Decoder can decode arguments using the non-standard mechanism
//
// If a method implements this interface then the non-standard
// decoder will be used.
//
// Method arguments must be decoded from the message.
// The mechanism for doing this will vary based on the
// implementation of the method. A normal approach is provided
// as part of this library, but may be replaced with
// any other decoding scheme.
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)
}
// A SignalHandler is responsible for delivering a signal.
//
// Signal delivery may be changed from the default channel
// based approach by Handlers implementing the SignalHandler
// interface.
type SignalHandler interface {
DeliverSignal(iface, name string, signal *Signal)
}
// SignalRegistrar manages signal delivery channels.
//
// This is an optional set of methods for `SignalHandler`.
type SignalRegistrar interface {
AddSignal(ch chan<- *Signal)
RemoveSignal(ch chan<- *Signal)
}
// A DBusError is used to convert a generic object to a D-Bus error.
//
// Any custom error mechanism may implement this interface to provide
// a custom encoding of the error on D-Bus. By default if a normal
// error is returned, it will be encoded as the generic
// "org.freedesktop.DBus.Error.Failed" error. By implementing this
// interface as well a custom encoding may be provided.
type DBusError interface {
DBusError() (string, []interface{})
}
// SerialGenerator is responsible for serials generation.
//
// Different approaches for the serial generation can be used,
// maintaining a map guarded with a mutex (the standard way) or
// simply increment an atomic counter.
type SerialGenerator interface {
GetSerial() uint32
RetireSerial(serial uint32)
}
+293
View File
@@ -0,0 +1,293 @@
package dbus
import (
"fmt"
"reflect"
"strings"
)
var sigToType = map[byte]reflect.Type{
'y': byteType,
'b': boolType,
'n': int16Type,
'q': uint16Type,
'i': int32Type,
'u': uint32Type,
'x': int64Type,
't': uint64Type,
'd': float64Type,
's': stringType,
'g': signatureType,
'o': objectPathType,
'v': variantType,
'h': unixFDIndexType,
}
// Signature represents a correct type signature as specified by the D-Bus
// specification. The zero value represents the empty signature, "".
type Signature struct {
str string
}
// 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 {
var s string
for _, v := range vs {
s += getSignature(reflect.TypeOf(v), &depthCounter{})
}
return Signature{s}
}
// SignatureOfType returns the signature of the given type. It panics if the
// type is not representable in D-Bus.
func SignatureOfType(t reflect.Type) Signature {
return Signature{getSignature(t, &depthCounter{})}
}
// getSignature returns the signature of the given type and panics on unknown types.
func getSignature(t reflect.Type, depth *depthCounter) (sig string) {
if !depth.Valid() {
panic("container nesting too deep")
}
defer func() {
if len(sig) > 255 {
panic("signature exceeds the length limitation")
}
}()
// handle simple types first
switch t.Kind() {
case reflect.Uint8:
return "y"
case reflect.Bool:
return "b"
case reflect.Int16:
return "n"
case reflect.Uint16:
return "q"
case reflect.Int, reflect.Int32:
if t == unixFDType {
return "h"
}
return "i"
case reflect.Uint, reflect.Uint32:
if t == unixFDIndexType {
return "h"
}
return "u"
case reflect.Int64:
return "x"
case reflect.Uint64:
return "t"
case reflect.Float64:
return "d"
case reflect.Ptr:
return getSignature(t.Elem(), depth)
case reflect.String:
if t == objectPathType {
return "o"
}
return "s"
case reflect.Struct:
if t == variantType {
return "v"
} else if t == signatureType {
return "g"
}
var s string
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
s += getSignature(t.Field(i).Type, depth.EnterStruct())
}
}
if len(s) == 0 {
panic(InvalidTypeError{t})
}
return "(" + s + ")"
case reflect.Array, reflect.Slice:
return "a" + getSignature(t.Elem(), depth.EnterArray())
case reflect.Map:
if !isKeyType(t.Key()) {
panic(InvalidTypeError{t})
}
return "a{" + getSignature(t.Key(), depth.EnterArray().EnterDictEntry()) + getSignature(t.Elem(), depth.EnterArray().EnterDictEntry()) + "}"
case reflect.Interface:
return "v"
}
panic(InvalidTypeError{t})
}
// ParseSignature returns the signature represented by this string, or a
// SignatureError if the string is not a valid signature.
func ParseSignature(s string) (sig Signature, err error) {
if len(s) == 0 {
return
}
if len(s) > 255 {
return Signature{""}, SignatureError{s, "too long"}
}
sig.str = s
for err == nil && len(s) != 0 {
err, s = validSingle(s, &depthCounter{})
}
if err != nil {
sig = Signature{""}
}
return
}
// ParseSignatureMust behaves like ParseSignature, except that it panics if s
// is not valid.
func ParseSignatureMust(s string) Signature {
sig, err := ParseSignature(s)
if err != nil {
panic(err)
}
return sig
}
// Empty returns whether the signature is the empty signature.
func (s Signature) Empty() bool {
return s.str == ""
}
// Single returns whether the signature represents a single, complete type.
func (s Signature) Single() bool {
err, r := validSingle(s.str, &depthCounter{})
return err != nil && r == ""
}
// String returns the signature's string representation.
func (s Signature) String() string {
return s.str
}
// A SignatureError indicates that a signature passed to a function or received
// on a connection is not a valid signature.
type SignatureError struct {
Sig string
Reason string
}
func (e SignatureError) Error() string {
return fmt.Sprintf("dbus: invalid signature: %q (%s)", e.Sig, e.Reason)
}
type depthCounter struct {
arrayDepth, structDepth, dictEntryDepth int
}
func (cnt *depthCounter) Valid() bool {
return cnt.arrayDepth <= 32 && cnt.structDepth <= 32 && cnt.dictEntryDepth <= 32
}
func (cnt depthCounter) EnterArray() *depthCounter {
cnt.arrayDepth++
return &cnt
}
func (cnt depthCounter) EnterStruct() *depthCounter {
cnt.structDepth++
return &cnt
}
func (cnt depthCounter) EnterDictEntry() *depthCounter {
cnt.dictEntryDepth++
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) {
if s == "" {
return SignatureError{Sig: s, Reason: "empty signature"}, ""
}
if !depth.Valid() {
return SignatureError{Sig: s, Reason: "container nesting too deep"}, ""
}
switch s[0] {
case 'y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 'd', 's', 'g', 'o', 'v', 'h':
return nil, s[1:]
case 'a':
if len(s) > 1 && s[1] == '{' {
i := findMatching(s[1:], '{', '}')
if i == -1 {
return SignatureError{Sig: s, Reason: "unmatched '{'"}, ""
}
i++
rem = s[i+1:]
s = s[2:i]
if err, _ = validSingle(s[:1], depth.EnterArray().EnterDictEntry()); err != nil {
return err, ""
}
err, nr := validSingle(s[1:], depth.EnterArray().EnterDictEntry())
if err != nil {
return err, ""
}
if nr != "" {
return SignatureError{Sig: s, Reason: "too many types in dict"}, ""
}
return nil, rem
}
return validSingle(s[1:], depth.EnterArray())
case '(':
i := findMatching(s, '(', ')')
if i == -1 {
return SignatureError{Sig: s, Reason: "unmatched ')'"}, ""
}
rem = s[i+1:]
s = s[1:i]
for err == nil && s != "" {
err, s = validSingle(s, depth.EnterStruct())
}
if err != nil {
rem = ""
}
return
}
return SignatureError{Sig: s, Reason: "invalid type character"}, ""
}
func findMatching(s string, left, right rune) int {
n := 0
for i, v := range s {
if v == left {
n++
} else if v == right {
n--
}
if n == 0 {
return i
}
}
return -1
}
// typeFor returns the type of the given signature. It ignores any left over
// characters and panics if s doesn't start with a valid type signature.
func typeFor(s string) (t reflect.Type) {
err, _ := validSingle(s, &depthCounter{})
if err != nil {
panic(err)
}
if t, ok := sigToType[s[0]]; ok {
return t
}
switch s[0] {
case 'a':
if s[1] == '{' {
i := strings.LastIndex(s, "}")
t = reflect.MapOf(sigToType[s[2]], typeFor(s[3:i]))
} else {
t = reflect.SliceOf(typeFor(s[1:]))
}
case '(':
t = interfacesType
}
return
}
+6
View File
@@ -0,0 +1,6 @@
package dbus
func (t *unixTransport) SendNullByte() error {
_, err := t.Write([]byte{0})
return err
}
+52
View File
@@ -0,0 +1,52 @@
package dbus
import (
"encoding/binary"
"errors"
"io"
"unsafe"
)
var nativeEndian binary.ByteOrder
func detectEndianness() binary.ByteOrder {
var x uint32 = 0x01020304
if *(*byte)(unsafe.Pointer(&x)) == 0x01 {
return binary.BigEndian
}
return binary.LittleEndian
}
func init() {
nativeEndian = detectEndianness()
}
type genericTransport struct {
io.ReadWriteCloser
}
func (t genericTransport) SendNullByte() error {
_, err := t.Write([]byte{0})
return err
}
func (t genericTransport) SupportsUnixFDs() bool {
return false
}
func (t genericTransport) EnableUnixFDs() {}
func (t genericTransport) ReadMessage() (*Message, error) {
return DecodeMessage(t)
}
func (t genericTransport) SendMessage(msg *Message) error {
fds, err := msg.CountFds()
if err != nil {
return err
}
if fds != 0 {
return errors.New("dbus: unix fd passing not enabled")
}
return msg.EncodeTo(t, nativeEndian)
}
+39
View File
@@ -0,0 +1,39 @@
//+build !windows
package dbus
import (
"errors"
"io/ioutil"
"net"
)
func init() {
transports["nonce-tcp"] = newNonceTcpTransport
}
func newNonceTcpTransport(keys string) (transport, error) {
host := getKey(keys, "host")
port := getKey(keys, "port")
noncefile := getKey(keys, "noncefile")
if host == "" || port == "" || noncefile == "" {
return nil, errors.New("dbus: unsupported address (must set host, port and noncefile)")
}
protocol, err := tcpFamily(keys)
if err != nil {
return nil, err
}
socket, err := net.Dial(protocol, net.JoinHostPort(host, port))
if err != nil {
return nil, err
}
b, err := ioutil.ReadFile(noncefile)
if err != nil {
return nil, err
}
_, err = socket.Write(b)
if err != nil {
return nil, err
}
return NewConn(socket)
}
+41
View File
@@ -0,0 +1,41 @@
package dbus
import (
"errors"
"net"
)
func init() {
transports["tcp"] = newTcpTransport
}
func tcpFamily(keys string) (string, error) {
switch getKey(keys, "family") {
case "":
return "tcp", nil
case "ipv4":
return "tcp4", nil
case "ipv6":
return "tcp6", nil
default:
return "", errors.New("dbus: invalid tcp family (must be ipv4 or ipv6)")
}
}
func newTcpTransport(keys string) (transport, error) {
host := getKey(keys, "host")
port := getKey(keys, "port")
if host == "" || port == "" {
return nil, errors.New("dbus: unsupported address (must set host and port)")
}
protocol, err := tcpFamily(keys)
if err != nil {
return nil, err
}
socket, err := net.Dial(protocol, net.JoinHostPort(host, port))
if err != nil {
return nil, err
}
return NewConn(socket)
}
+212
View File
@@ -0,0 +1,212 @@
//+build !windows,!solaris
package dbus
import (
"bytes"
"encoding/binary"
"errors"
"io"
"net"
"syscall"
)
type oobReader struct {
conn *net.UnixConn
oob []byte
buf [4096]byte
}
func (o *oobReader) Read(b []byte) (n int, err error) {
n, oobn, flags, _, err := o.conn.ReadMsgUnix(b, o.buf[:])
if err != nil {
return n, err
}
if flags&syscall.MSG_CTRUNC != 0 {
return n, errors.New("dbus: control data truncated (too many fds received)")
}
o.oob = append(o.oob, o.buf[:oobn]...)
return n, nil
}
type unixTransport struct {
*net.UnixConn
rdr *oobReader
hasUnixFDs bool
}
func newUnixTransport(keys string) (transport, error) {
var err error
t := new(unixTransport)
abstract := getKey(keys, "abstract")
path := getKey(keys, "path")
switch {
case abstract == "" && path == "":
return nil, errors.New("dbus: invalid address (neither path nor abstract set)")
case abstract != "" && path == "":
t.UnixConn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: "@" + abstract, Net: "unix"})
if err != nil {
return nil, err
}
return t, nil
case abstract == "" && path != "":
t.UnixConn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: path, Net: "unix"})
if err != nil {
return nil, err
}
return t, nil
default:
return nil, errors.New("dbus: invalid address (both path and abstract set)")
}
}
func init() {
transports["unix"] = newUnixTransport
}
func (t *unixTransport) EnableUnixFDs() {
t.hasUnixFDs = true
}
func (t *unixTransport) ReadMessage() (*Message, error) {
var (
blen, hlen uint32
csheader [16]byte
headers []header
order binary.ByteOrder
unixfds uint32
)
// To be sure that all bytes of out-of-band data are read, we use a special
// reader that uses ReadUnix on the underlying connection instead of Read
// and gathers the out-of-band data in a buffer.
if t.rdr == nil {
t.rdr = &oobReader{conn: t.UnixConn}
} else {
t.rdr.oob = nil
}
// read the first 16 bytes (the part of the header that has a constant size),
// from which we can figure out the length of the rest of the message
if _, err := io.ReadFull(t.rdr, csheader[:]); err != nil {
return nil, err
}
switch csheader[0] {
case 'l':
order = binary.LittleEndian
case 'B':
order = binary.BigEndian
default:
return nil, InvalidMessageError("invalid byte order")
}
// csheader[4:8] -> length of message body, csheader[12:16] -> length of
// header fields (without alignment)
binary.Read(bytes.NewBuffer(csheader[4:8]), order, &blen)
binary.Read(bytes.NewBuffer(csheader[12:]), order, &hlen)
if hlen%8 != 0 {
hlen += 8 - (hlen % 8)
}
// decode headers and look for unix fds
headerdata := make([]byte, hlen+4)
copy(headerdata, csheader[12:])
if _, err := io.ReadFull(t.rdr, headerdata[4:]); err != nil {
return nil, err
}
dec := newDecoder(bytes.NewBuffer(headerdata), order, make([]int, 0))
dec.pos = 12
vs, err := dec.Decode(Signature{"a(yv)"})
if err != nil {
return nil, err
}
Store(vs, &headers)
for _, v := range headers {
if v.Field == byte(FieldUnixFDs) {
unixfds, _ = v.Variant.value.(uint32)
}
}
all := make([]byte, 16+hlen+blen)
copy(all, csheader[:])
copy(all[16:], headerdata[4:])
if _, err := io.ReadFull(t.rdr, all[16+hlen:]); err != nil {
return nil, err
}
if unixfds != 0 {
if !t.hasUnixFDs {
return nil, errors.New("dbus: got unix fds on unsupported transport")
}
// read the fds from the OOB data
scms, err := syscall.ParseSocketControlMessage(t.rdr.oob)
if err != nil {
return nil, err
}
if len(scms) != 1 {
return nil, errors.New("dbus: received more than one socket control message")
}
fds, err := syscall.ParseUnixRights(&scms[0])
if err != nil {
return nil, err
}
msg, err := DecodeMessageWithFDs(bytes.NewBuffer(all), fds)
if err != nil {
return nil, err
}
// substitute the values in the message body (which are indices for the
// array receiver via OOB) with the actual values
for i, v := range msg.Body {
switch index := v.(type) {
case UnixFDIndex:
if uint32(index) >= unixfds {
return nil, InvalidMessageError("invalid index for unix fd")
}
msg.Body[i] = UnixFD(fds[index])
case []UnixFDIndex:
fdArray := make([]UnixFD, len(index))
for k, j := range index {
if uint32(j) >= unixfds {
return nil, InvalidMessageError("invalid index for unix fd")
}
fdArray[k] = UnixFD(fds[j])
}
msg.Body[i] = fdArray
}
}
return msg, nil
}
return DecodeMessage(bytes.NewBuffer(all))
}
func (t *unixTransport) SendMessage(msg *Message) error {
fdcnt, err := msg.CountFds()
if err != nil {
return err
}
if fdcnt != 0 {
if !t.hasUnixFDs {
return errors.New("dbus: unix fd passing not enabled")
}
msg.Headers[FieldUnixFDs] = MakeVariant(uint32(fdcnt))
buf := new(bytes.Buffer)
fds, err := msg.EncodeToWithFDs(buf, nativeEndian)
if err != nil {
return err
}
oob := syscall.UnixRights(fds...)
n, oobn, err := t.UnixConn.WriteMsgUnix(buf.Bytes(), oob, nil)
if err != nil {
return err
}
if n != buf.Len() || oobn != len(oob) {
return io.ErrShortWrite
}
} else {
if err := msg.EncodeTo(t, nativeEndian); err != nil {
return err
}
}
return nil
}
func (t *unixTransport) SupportsUnixFDs() bool {
return true
}
@@ -0,0 +1,95 @@
// The UnixCredentials system call is currently only implemented on Linux
// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
// https://golang.org/s/go1.4-syscall
// http://code.google.com/p/go/source/browse/unix/sockcmsg_linux.go?repo=sys
// Local implementation of the UnixCredentials system call for DragonFly BSD
package dbus
/*
#include <sys/ucred.h>
*/
import "C"
import (
"io"
"os"
"syscall"
"unsafe"
)
// http://golang.org/src/pkg/syscall/ztypes_linux_amd64.go
// http://golang.org/src/pkg/syscall/ztypes_dragonfly_amd64.go
type Ucred struct {
Pid int32
Uid uint32
Gid uint32
}
// http://golang.org/src/pkg/syscall/types_linux.go
// http://golang.org/src/pkg/syscall/types_dragonfly.go
// https://github.com/DragonFlyBSD/DragonFlyBSD/blob/master/sys/sys/ucred.h
const (
SizeofUcred = C.sizeof_struct_ucred
)
// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
func cmsgAlignOf(salen int) int {
// From http://golang.org/src/pkg/syscall/sockcmsg_unix.go
//salign := sizeofPtr
// NOTE: It seems like 64-bit Darwin and DragonFly BSD kernels
// still require 32-bit aligned access to network subsystem.
//if darwin64Bit || dragonfly64Bit {
// salign = 4
//}
salign := 4
return (salen + salign - 1) & ^(salign - 1)
}
// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
func cmsgData(h *syscall.Cmsghdr) unsafe.Pointer {
return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(syscall.SizeofCmsghdr)))
}
// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
// UnixCredentials encodes credentials into a socket control message
// for sending to another process. This can be used for
// authentication.
func UnixCredentials(ucred *Ucred) []byte {
b := make([]byte, syscall.CmsgSpace(SizeofUcred))
h := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
h.Level = syscall.SOL_SOCKET
h.Type = syscall.SCM_CREDS
h.SetLen(syscall.CmsgLen(SizeofUcred))
*((*Ucred)(cmsgData(h))) = *ucred
return b
}
// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
// ParseUnixCredentials decodes a socket control message that contains
// credentials in a Ucred structure. To receive such a message, the
// SO_PASSCRED option must be enabled on the socket.
func ParseUnixCredentials(m *syscall.SocketControlMessage) (*Ucred, error) {
if m.Header.Level != syscall.SOL_SOCKET {
return nil, syscall.EINVAL
}
if m.Header.Type != syscall.SCM_CREDS {
return nil, syscall.EINVAL
}
ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0]))
return &ucred, nil
}
func (t *unixTransport) SendNullByte() error {
ucred := &Ucred{Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid())}
b := UnixCredentials(ucred)
_, oobn, err := t.UnixConn.WriteMsgUnix([]byte{0}, b, nil)
if err != nil {
return err
}
if oobn != len(b) {
return io.ErrShortWrite
}
return nil
}
+92
View File
@@ -0,0 +1,92 @@
// The UnixCredentials system call is currently only implemented on Linux
// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
// https://golang.org/s/go1.4-syscall
// http://code.google.com/p/go/source/browse/unix/sockcmsg_linux.go?repo=sys
// Local implementation of the UnixCredentials system call for FreeBSD
package dbus
/*
const int sizeofPtr = sizeof(void*);
#define _WANT_UCRED
#include <sys/types.h>
#include <sys/ucred.h>
*/
import "C"
import (
"io"
"os"
"syscall"
"unsafe"
)
// http://golang.org/src/pkg/syscall/ztypes_linux_amd64.go
// https://golang.org/src/syscall/ztypes_freebsd_amd64.go
type Ucred struct {
Pid int32
Uid uint32
Gid uint32
}
// http://golang.org/src/pkg/syscall/types_linux.go
// https://golang.org/src/syscall/types_freebsd.go
// https://github.com/freebsd/freebsd/blob/master/sys/sys/ucred.h
const (
SizeofUcred = C.sizeof_struct_ucred
)
// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
func cmsgAlignOf(salen int) int {
salign := C.sizeofPtr
return (salen + salign - 1) & ^(salign - 1)
}
// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
func cmsgData(h *syscall.Cmsghdr) unsafe.Pointer {
return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(syscall.SizeofCmsghdr)))
}
// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
// UnixCredentials encodes credentials into a socket control message
// for sending to another process. This can be used for
// authentication.
func UnixCredentials(ucred *Ucred) []byte {
b := make([]byte, syscall.CmsgSpace(SizeofUcred))
h := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
h.Level = syscall.SOL_SOCKET
h.Type = syscall.SCM_CREDS
h.SetLen(syscall.CmsgLen(SizeofUcred))
*((*Ucred)(cmsgData(h))) = *ucred
return b
}
// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
// ParseUnixCredentials decodes a socket control message that contains
// credentials in a Ucred structure. To receive such a message, the
// SO_PASSCRED option must be enabled on the socket.
func ParseUnixCredentials(m *syscall.SocketControlMessage) (*Ucred, error) {
if m.Header.Level != syscall.SOL_SOCKET {
return nil, syscall.EINVAL
}
if m.Header.Type != syscall.SCM_CREDS {
return nil, syscall.EINVAL
}
ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0]))
return &ucred, nil
}
func (t *unixTransport) SendNullByte() error {
ucred := &Ucred{Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid())}
b := UnixCredentials(ucred)
_, oobn, err := t.UnixConn.WriteMsgUnix([]byte{0}, b, nil)
if err != nil {
return err
}
if oobn != len(b) {
return io.ErrShortWrite
}
return nil
}
+25
View File
@@ -0,0 +1,25 @@
// The UnixCredentials system call is currently only implemented on Linux
// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
// https://golang.org/s/go1.4-syscall
// http://code.google.com/p/go/source/browse/unix/sockcmsg_linux.go?repo=sys
package dbus
import (
"io"
"os"
"syscall"
)
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)
if err != nil {
return err
}
if oobn != len(b) {
return io.ErrShortWrite
}
return nil
}

Some files were not shown because too many files have changed in this diff Show More