conn_other.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // +build !darwin
  2. package dbus
  3. import (
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "os/user"
  11. "path"
  12. "strings"
  13. )
  14. var execCommand = exec.Command
  15. func getSessionBusPlatformAddress() (string, error) {
  16. cmd := execCommand("dbus-launch")
  17. b, err := cmd.CombinedOutput()
  18. if err != nil {
  19. return "", err
  20. }
  21. i := bytes.IndexByte(b, '=')
  22. j := bytes.IndexByte(b, '\n')
  23. if i == -1 || j == -1 || i > j {
  24. return "", errors.New("dbus: couldn't determine address of session bus")
  25. }
  26. env, addr := string(b[0:i]), string(b[i+1:j])
  27. os.Setenv(env, addr)
  28. return addr, nil
  29. }
  30. // tryDiscoverDbusSessionBusAddress tries to discover an existing dbus session
  31. // and return the value of its DBUS_SESSION_BUS_ADDRESS.
  32. // It tries different techniques employed by different operating systems,
  33. // returning the first valid address it finds, or an empty string.
  34. //
  35. // * /run/user/<uid>/bus if this exists, it *is* the bus socket. present on
  36. // Ubuntu 18.04
  37. // * /run/user/<uid>/dbus-session: if this exists, it can be parsed for the bus
  38. // address. present on Ubuntu 16.04
  39. //
  40. // See https://dbus.freedesktop.org/doc/dbus-launch.1.html
  41. func tryDiscoverDbusSessionBusAddress() string {
  42. if runtimeDirectory, err := getRuntimeDirectory(); err == nil {
  43. if runUserBusFile := path.Join(runtimeDirectory, "bus"); fileExists(runUserBusFile) {
  44. // if /run/user/<uid>/bus exists, that file itself
  45. // *is* the unix socket, so return its path
  46. return fmt.Sprintf("unix:path=%s", EscapeBusAddressValue(runUserBusFile))
  47. }
  48. if runUserSessionDbusFile := path.Join(runtimeDirectory, "dbus-session"); fileExists(runUserSessionDbusFile) {
  49. // if /run/user/<uid>/dbus-session exists, it's a
  50. // text file // containing the address of the socket, e.g.:
  51. // DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-E1c73yNqrG
  52. if f, err := ioutil.ReadFile(runUserSessionDbusFile); err == nil {
  53. fileContent := string(f)
  54. prefix := "DBUS_SESSION_BUS_ADDRESS="
  55. if strings.HasPrefix(fileContent, prefix) {
  56. address := strings.TrimRight(strings.TrimPrefix(fileContent, prefix), "\n\r")
  57. return address
  58. }
  59. }
  60. }
  61. }
  62. return ""
  63. }
  64. func getRuntimeDirectory() (string, error) {
  65. if currentUser, err := user.Current(); err != nil {
  66. return "", err
  67. } else {
  68. return fmt.Sprintf("/run/user/%s", currentUser.Uid), nil
  69. }
  70. }
  71. func fileExists(filename string) bool {
  72. _, err := os.Stat(filename)
  73. return !os.IsNotExist(err)
  74. }