conn_other.go 2.4 KB

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