-
Notifications
You must be signed in to change notification settings - Fork 24
/
helpers.go
131 lines (113 loc) 路 2.31 KB
/
helpers.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
130
131
package utils
import (
"bufio"
"io"
"log"
"os"
"os/user"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
)
type sshUrl struct {
Username string
Host string
Port int
}
// ParseSSHUrl build an sshUrl object from an url string
func ParseSSHUrl(url string) *sshUrl {
parts := strings.Split(url, "@")
usr, _ := user.Current()
conf := &sshUrl{}
var host string
if len(parts) == 2 {
conf.Username = parts[0]
host = parts[1]
} else {
conf.Username = usr.Username
host = parts[0]
}
hostParts := strings.Split(host, ":")
if len(hostParts) == 2 {
port, err := strconv.Atoi(hostParts[1])
if err != nil {
log.Fatalln(err)
}
if hostParts[0] == "" {
conf.Host = "127.0.0.1"
} else {
conf.Host = hostParts[0]
}
conf.Port = port
} else {
conf.Host = host
conf.Port = 22
}
return conf
}
// ExpandUserHome resolve paths like "~/.ssh/id_rsa"
func ExpandUserHome(path string) (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
ret := path
// supports paths like "~/.ssh/id_rsa"
if strings.HasPrefix(path, "~/") {
ret = filepath.Join(usr.HomeDir, path[2:])
}
return ret, nil
}
// GetUserDefaultShell try to get the best shell for the user
func GetUserDefaultShell(username string) string {
if runtime.GOOS == "windows" {
return "c:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe"
}
fallback := "/bin/sh"
file, err := os.Open("/etc/passwd")
if err != nil {
return fallback
}
defer file.Close()
lines := bufio.NewReader(file)
for {
line, _, err := lines.ReadLine()
if err != nil {
break
}
fs := strings.Split(string(line), ":")
if len(fs) != 7 {
continue
}
if fs[0] != username {
continue
}
shell := fs[6]
return shell
}
return fallback
}
// CopyConnWithOnClose copy packets from c1 to c2 and viceversa. Calls the onClose function
// when the connection is interrupted
func CopyConnWithOnClose(c1 io.ReadWriteCloser, c2 io.ReadWriteCloser, onClose func()) {
var once sync.Once
close := func() {
c1.Close()
c2.Close()
onClose()
}
go func() {
io.Copy(c1, c2)
once.Do(close)
}()
go func() {
io.Copy(c2, c1)
once.Do(close)
}()
}
// CopyConn copy packets from c1 to c2 and viceversa
func CopyConn(c1 io.ReadWriteCloser, c2 io.ReadWriteCloser) {
CopyConnWithOnClose(c1, c2, func() {})
}