-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathfile.go
293 lines (263 loc) · 7.26 KB
/
file.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// © 2022 Nokia.
//
// This code is a Contribution to the gNMIc project (“Work”) made under the Google Software Grant and Corporate Contributor License Agreement (“CLA”) and governed by the Apache License 2.0.
// No other rights or licenses in or to any of Nokia’s intellectual property are granted for any other purpose.
// This code is provided on an “as is” basis without any warranties of any kind.
//
// SPDX-License-Identifier: Apache-2.0
package utils
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/jlaffaye/ftp"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
const (
defaultFTPPort = 21
defaultSFTPPort = 22
)
// ReadFile reads a local or remote file and returns the read bytes,
// the location of the file is determined based on its prefix,
// http(s), (s)ftp prefixes are supported.
// no prefix means the file is local. `-` means stdin.
func ReadFile(ctx context.Context, path string) ([]byte, error) {
// read file bytes based on the path prefix
switch {
case strings.HasPrefix(path, "https://"):
return readHTTPFile(ctx, path)
case strings.HasPrefix(path, "http://"):
return readHTTPFile(ctx, path)
case strings.HasPrefix(path, "ftp://"):
return readFTPFile(ctx, path)
case strings.HasPrefix(path, "sftp://"):
return readSFTPFile(ctx, path)
default:
return readLocalFile(ctx, path)
}
}
// readHTTPFile fetches a remote from from an HTTP server,
// the response body can be yaml or json bytes.
// it then unmarshal the received bytes into a map[string]*types.TargetConfig
// and returns
func readHTTPFile(ctx context.Context, path string) ([]byte, error) {
_, err := url.Parse(path)
if err != nil {
return nil, err
}
client := new(http.Client)
if strings.HasPrefix(path, "https://") {
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, path, new(bytes.Buffer))
if err != nil {
return nil, err
}
r, err := client.Do(req)
if err != nil {
return nil, err
}
if r.StatusCode != 200 {
return nil, fmt.Errorf("unexpected HTTP status code %d, GET from %s", r.StatusCode, path)
}
defer r.Body.Close()
return io.ReadAll(r.Body)
}
// readFTPFile reads a file from a remote FTP server
// unmarshals the content into a map[string]*types.TargetConfig
// and returns
func readFTPFile(ctx context.Context, path string) ([]byte, error) {
parsedUrl, err := url.Parse(path)
if err != nil {
return nil, fmt.Errorf("failed to parse URL: %v", err)
}
// Get user name and pass
user := parsedUrl.User.Username()
pass, _ := parsedUrl.User.Password()
// Parse Host and Port
host := parsedUrl.Host
_, _, err = net.SplitHostPort(host)
if err != nil {
host = fmt.Sprintf("%s:%d", host, defaultFTPPort)
}
// connect to server
conn, err := ftp.Dial(host, ftp.DialWithContext(ctx))
if err != nil {
return nil, fmt.Errorf("failed to connect to [%s]: %v", host, err)
}
err = conn.Login(user, pass)
if err != nil {
return nil, fmt.Errorf("failed to login to [%s]: %v", host, err)
}
r, err := conn.Retr(parsedUrl.RequestURI())
if err != nil {
return nil, fmt.Errorf("failed to read remote file %q: %v", parsedUrl.RequestURI(), err)
}
defer r.Close()
return io.ReadAll(r)
}
// readSFTPFile reads a file from a remote SFTP server
// unmarshals the content into a map[string]*types.TargetConfig
// and returns
func readSFTPFile(_ context.Context, path string) ([]byte, error) {
parsedUrl, err := url.Parse(path)
if err != nil {
return nil, fmt.Errorf("failed to parse URL: %v", err)
}
// Get user name and pass
user := parsedUrl.User.Username()
pass, _ := parsedUrl.User.Password()
// Parse Host and Port
host := parsedUrl.Host
_, _, err = net.SplitHostPort(host)
if err != nil {
host = fmt.Sprintf("%s:%d", host, defaultSFTPPort)
}
hostKey, err := getHostKey(host)
if err != nil {
return nil, err
}
var auths []ssh.AuthMethod
// Try to use $SSH_AUTH_SOCK which contains the path of the unix file socket that the sshd agent uses
// for communication with other processes.
if aconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(aconn).Signers))
}
// Use password authentication if provided
if pass != "" {
auths = append(auths, ssh.Password(pass))
}
// Initialize client configuration
config := ssh.ClientConfig{
User: user,
Auth: auths,
}
if hostKey != nil {
config.HostKeyCallback = ssh.FixedHostKey(hostKey)
} else {
config.HostKeyCallback = ssh.InsecureIgnoreHostKey()
}
// Connect to server
conn, err := ssh.Dial("tcp", host, &config)
if err != nil {
return nil, fmt.Errorf("failed to connect to [%s]: %v", host, err)
}
defer conn.Close()
// Create new SFTP client
sc, err := sftp.NewClient(conn)
if err != nil {
return nil, fmt.Errorf("unable to start SFTP subsystem: %v", err)
}
defer sc.Close()
// open File
file, err := sc.Open(parsedUrl.RequestURI())
if err != nil {
return nil, fmt.Errorf("failed to open the remote file %q: %v", parsedUrl.RequestURI(), err)
}
defer file.Close()
// stat file to get its size
st, err := file.Stat()
if err != nil {
return nil, err
}
if st.IsDir() {
return nil, fmt.Errorf("remote file %q is a directory", parsedUrl.RequestURI())
}
// create a []byte with length equal to the file size
b := make([]byte, st.Size())
// read the file
_, err = file.Read(b)
return b, err
}
// readLocalFile reads a file from the local file system,
// unmarshals the content into a map[string]*types.TargetConfig
// and returns
func readLocalFile(ctx context.Context, path string) ([]byte, error) {
// read from stdin
if path == "-" {
return readFromStdin(ctx)
}
// local file
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return nil, err
}
if st.IsDir() {
return nil, fmt.Errorf("%q is a directory", path)
}
data := make([]byte, st.Size())
rd := bufio.NewReader(f)
_, err = rd.Read(data)
if err != nil && err != io.EOF {
return nil, err
}
return data, nil
}
// read bytes from stdin
func readFromStdin(ctx context.Context) ([]byte, error) {
// read from stdin
data := make([]byte, 0, 128)
rd := bufio.NewReader(os.Stdin)
buf := make([]byte, 128)
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
n, err := rd.Read(buf)
if err == io.EOF {
data = append(data, buf[:n]...)
return data, nil
}
if err != nil {
return nil, err
}
data = append(data, buf[:n]...)
}
}
}
// Get host key from local known hosts
func getHostKey(host string) (ssh.PublicKey, error) {
// parse OpenSSH known_hosts file
// ssh or use ssh-keyscan to get initial key
file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
var hostKey ssh.PublicKey
for scanner.Scan() {
fields := strings.Split(scanner.Text(), " ")
if len(fields) != 3 {
continue
}
if strings.Contains(fields[0], host) {
var err error
hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
if err != nil {
return nil, err
}
break
}
}
return hostKey, nil
}