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