/
app.go
129 lines (106 loc) · 2.29 KB
/
app.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
125
126
127
128
129
package main
import (
"fmt"
"github.com/kevinburke/ssh_config"
"github.com/shirou/gopsutil/process"
"os"
"path/filepath"
"regexp"
"strings"
)
type AppState struct {
tunnels []*Tunnel
}
type Tunnel struct {
Host string
Hostname string
Forward string
ForwardKind string
State string
Raw []ssh_config.Node
Proc *process.Process
}
func NewAppState() (*AppState, error) {
tunnels, err := load()
if err != nil {
return nil, err
}
as := AppState{
tunnels: tunnels,
}
return &as, nil
}
func (as *AppState) ReloadTunnels() error {
tunnels, err := load()
if err != nil {
return err
}
as.tunnels = tunnels
return nil
}
func (as *AppState) GetTunnels() []*Tunnel {
return as.tunnels
}
func load() ([]*Tunnel, error) {
pids, err := FindAll("ssh")
if err != nil {
return nil, err
}
var procs []*process.Process
for _, pid := range pids {
proc, _ := process.NewProcess(int32(pid))
procs = append(procs, proc)
}
f, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config"))
if err != nil {
return nil, fmt.Errorf("could not open ssh config\n %s", err)
}
cfg, err := ssh_config.Decode(f)
if err != nil {
return nil, fmt.Errorf("could not decode ssh config:\n %s", err)
}
r := regexp.MustCompile(".*(LocalForward|RemoteForward).*")
var tunnels []*Tunnel
for _, host := range cfg.Hosts {
var fwdNodes []*ssh_config.KV
for _, node := range host.Nodes {
if r.MatchString(node.String()) {
switch t := node.(type) {
case *ssh_config.KV:
fwdNodes = append(fwdNodes, t)
default:
continue
}
}
}
if len(fwdNodes) > 0 {
alias := host.Patterns[0].String()
hostname, err := cfg.Get(host.Patterns[0].String(), "Hostname")
if err != nil {
break
}
var fwdStrs []string
for _, fwd := range fwdNodes {
fwdStrs = append(fwdStrs, fmt.Sprintf("-%s %s", string(fwd.Key[0]), fwd.Value))
}
proc, err := FindProcByCmd(procs, alias)
if err != nil {
return nil, err
}
tunnel := Tunnel{
Host: alias,
Hostname: hostname,
Forward: strings.Join(fwdStrs, " "),
Raw: host.Nodes,
}
if proc != nil {
tunnel.Proc = proc
tunnel.State = "Open"
} else {
tunnel.State = "Closed"
}
tunnels = append(tunnels, &tunnel)
}
}
return tunnels, nil
}