forked from ajm113/unix-aws-vpn-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
124 lines (96 loc) · 2.12 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
"net"
"os"
"os/exec"
"path"
"runtime"
"strings"
)
func openDefaultBrowser(url string) (err error) {
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported patform %s", runtime.GOOS)
}
return
}
func commandExists(command string) bool {
cmd := exec.Command("/bin/sh", "-c", "command -v "+command)
if err := cmd.Run(); err != nil {
return false
}
return true
}
func fileExists(filename string) bool {
if _, err := os.Stat(filename); err == nil {
return true
}
return false
}
func getHomeDirConfigPath() (foldername string, err error) {
home, err := os.UserHomeDir()
if err != nil {
return
}
configFolder := ".config"
if runtime.GOOS == "windows" {
configFolder = "AppData\\Local"
}
foldername = path.Join(home, configFolder, defaultConfigDirectoryName)
return
}
func searchConfigFilename() (string, error) {
wd, wdErr := os.Getwd()
if wdErr != nil {
return "", wdErr
}
configAtwd := path.Join(wd, defaultConfigFilename)
home, _ := getHomeDirConfigPath()
configAtHome := path.Join(home, defaultConfigFilename)
if fileExists(configAtwd) {
return configAtwd, nil
} else if fileExists(configAtHome) {
return configAtHome, nil
}
return "", os.ErrNotExist
}
func lookupIP(hostname string) (ip string, err error) {
ips, err := net.LookupIP(hostname)
if err != nil || len(ips) == 0 {
return
}
for _, ipv4 := range ips {
ip = ipv4.String()
break
}
return
}
func generateRandomToken(length int) (string, error) {
bytes := make([]byte, length)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
func extractSIDFromOpenVPN(output string) (SID string, err error) {
tokens := strings.Split(output, ":")
for _, t := range tokens {
if strings.HasPrefix(t, "instance-") {
SID = t
break
}
}
if SID == "" {
err = fmt.Errorf("sid not found")
}
return
}