This repository has been archived by the owner on Mar 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
source.go
354 lines (304 loc) · 8.54 KB
/
source.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package scp
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"golang.org/x/crypto/ssh"
)
// Send reads a single local file content from the r,
// and copies it to the remote file with the name info.Name()
// under the directory filepath.Dir(destFile).
// The time and permission will be set with the value of info.
// The r will be closed after copying. If you don't want for r to be
// closed, you can pass the result of ioutil.NopCloser(r).
func (s *SCP) Send(info *FileInfo, r io.ReadCloser, destFile string) error {
destFile = filepath.Clean(destFile)
destFile = realPath(filepath.Dir(destFile))
return runSourceSession(s.client, destFile, false, s.SCPCommand, false, true, func(s *sourceSession) error {
err := s.WriteFile(info, r)
if err != nil {
return fmt.Errorf("failed to copy file: %w", err)
}
return nil
})
}
// SendFile copies a single local file to the remote server.
// The time and permission will be set with the value of the source file.
func (s *SCP) SendFile(srcFile, destFile string) error {
srcFile = filepath.Clean(srcFile)
destFile = realPath(filepath.Clean(destFile))
return runSourceSession(s.client, destFile, false, s.SCPCommand, false, true, func(s *sourceSession) error {
osFileInfo, err := os.Stat(srcFile)
if err != nil {
return fmt.Errorf("failed to stat source file: %w", err)
}
fi := newFileInfoFromOS(osFileInfo, "")
file, err := os.Open(srcFile)
if err != nil {
return fmt.Errorf("failed to open source file: %w", err)
}
// NOTE: file will be closed by WriteFile.
err = s.WriteFile(fi, file)
if err != nil {
return fmt.Errorf("failed to copy file: %w", err)
}
return nil
})
}
type sendWriter struct {
source *sourceSession
fileInfo *FileInfo
written int64
}
var _ io.WriteCloser = &sendWriter{}
func (s *sendWriter) Write(p []byte) (int, error) {
n, err := s.source.remIn.Write(p)
s.written += int64(n)
if err != nil {
return n, fmt.Errorf("failed to write scp file body: %w", err)
}
if s.written == s.fileInfo.size {
err = s.source.readReply()
if err != nil {
return n, err
}
_, err = s.source.remIn.Write([]byte{replyOK})
if err != nil {
return n, fmt.Errorf("failed to write scp replyOK reply: %w", err)
}
err = s.source.readReply()
if err != nil {
return n, err
}
err = s.source.CloseStdin()
if err != nil {
return n, err
}
err = s.source.Wait()
if err != nil {
return n, err
}
}
return n, err
}
func (s *sendWriter) Close() error {
return s.source.Close()
}
// SendOpen opens an io.WriteCloser to a file on the remote server.
// SendOpen will write a known number of bytes according to fileInfo to the remote file.
// The caller of SendOpen is responsible to close the returned io.WriteCloser.
// Metadata such as modified time and mode/permission of the remote will is applied from fileInfo.
func (s *SCP) SendOpen(fileInfo *FileInfo, destFile string) (io.WriteCloser, error) {
var err error
destFile = filepath.Clean(destFile)
destFile = realPath(filepath.Dir(destFile))
source, err := newSourceSession(s.client, destFile, false, s.SCPCommand, false, true)
// Caller is responsible to close sourceSession via closing the returned io.WriteCloser
if err != nil {
return nil, err
}
if !fileInfo.modTime.IsZero() || !fileInfo.accessTime.IsZero() {
err = source.setTime(fileInfo.modTime, fileInfo.accessTime)
if err != nil {
return nil, err
}
}
err = source.writeFileHeader(fileInfo.mode, fileInfo.size, fileInfo.name)
if err != nil {
return nil, err
}
writer := &sendWriter{
source: source,
fileInfo: fileInfo,
}
return writer, nil
}
// AcceptFunc is the type of the function called for each file or directory
// to determine whether is should be copied or not.
// In SendDir, parentDir will be a directory under srcDir.
// In ReceiveDir, parentDir will be a directory under destDir.
type AcceptFunc func(parentDir string, info os.FileInfo) (bool, error)
func acceptAny(string, os.FileInfo) (bool, error) {
return true, nil
}
// SendDir copies files and directories under the local srcDir to
// to the remote destDir. You can filter the files and directories to be copied with acceptFn.
// However this filtering is done at the receiver side, so all file bodies are transferred
// over the network even if some files are filtered out. If you need more efficiency,
// it is better to use another method like the tar command.
// If acceptFn is nil, all files and directories will be copied.
// The time and permission will be set to the same value of the source file or directory.
func (s *SCP) SendDir(srcDir, destDir string, acceptFn AcceptFunc) error {
srcDir = filepath.Clean(srcDir)
destDir = realPath(filepath.Clean(destDir))
if acceptFn == nil {
acceptFn = acceptAny
}
return runSourceSession(s.client, destDir, false, s.SCPCommand, true, true, func(s *sourceSession) error {
prevDirSkipped := false
endDirectories := func(prevDir, dir string) error {
rel, err := filepath.Rel(prevDir, dir)
if err != nil {
return err
}
for _, comp := range strings.Split(rel, string([]rune{filepath.Separator})) {
if comp == ".." {
if prevDirSkipped {
prevDirSkipped = false
} else {
err := s.EndDirectory()
if err != nil {
return err
}
}
}
}
return nil
}
prevDir := srcDir
myWalkFn := func(path string, info os.FileInfo, err error) error {
// We must check err is not nil first.
// See https://golang.org/pkg/path/filepath/#WalkFunc
if err != nil {
return err
}
isDir := info.IsDir()
var dir string
if isDir {
dir = path
} else {
dir = filepath.Dir(path)
}
defer func() {
prevDir = dir
}()
err = endDirectories(prevDir, dir)
if err != nil {
return err
}
scpFileInfo := newFileInfoFromOS(info, "")
accepted, err := acceptFn(filepath.Dir(path), scpFileInfo)
if err != nil {
return err
}
if isDir {
if !accepted {
prevDirSkipped = true
return filepath.SkipDir
}
err := s.StartDirectory(scpFileInfo)
if err != nil {
return err
}
} else {
if accepted {
fi := newFileInfoFromOS(info, "")
file, err := os.Open(path)
if err != nil {
return err
}
err = s.WriteFile(fi, file)
if err != nil {
return err
}
}
}
return nil
}
err := filepath.Walk(srcDir, myWalkFn)
if err != nil {
return err
}
return endDirectories(prevDir, srcDir)
})
}
type sourceSession struct {
client *ssh.Client
session *ssh.Session
remoteDestPath string
remoteDestIsDir bool
scpPath string
recursive bool
updatesPermission bool
stdin io.WriteCloser
stdout io.Reader
*sourceProtocol
}
func newSourceSession(client *ssh.Client, remoteDestPath string, remoteDestIsDir bool, scpPath string, recursive, updatesPermission bool) (*sourceSession, error) {
s := &sourceSession{
client: client,
remoteDestPath: remoteDestPath,
remoteDestIsDir: remoteDestIsDir,
scpPath: scpPath,
recursive: recursive,
updatesPermission: updatesPermission,
}
var err error
s.session, err = s.client.NewSession()
if err != nil {
return s, err
}
s.stdout, err = s.session.StdoutPipe()
if err != nil {
return s, err
}
s.stdin, err = s.session.StdinPipe()
if err != nil {
return s, err
}
if s.scpPath == "" {
s.scpPath = "scp"
}
opt := []byte("-t")
if s.updatesPermission {
opt = append(opt, 'p')
}
if s.recursive {
opt = append(opt, 'r')
}
if s.remoteDestIsDir {
opt = append(opt, 'd')
}
cmd := s.scpPath + " " + string(opt) + " " + escapeShellArg(s.remoteDestPath)
err = s.session.Start(cmd)
if err != nil {
return s, err
}
s.sourceProtocol, err = newSourceProtocol(s.stdin, s.stdout)
return s, err
}
func (s *sourceSession) Close() error {
if s == nil || s.session == nil {
return nil
}
return s.session.Close()
}
func (s *sourceSession) Wait() error {
if s == nil || s.session == nil {
return nil
}
return s.session.Wait()
}
func (s *sourceSession) CloseStdin() error {
if s == nil || s.stdin == nil {
return nil
}
return s.stdin.Close()
}
func runSourceSession(client *ssh.Client, remoteDestPath string, remoteDestIsDir bool, scpPath string, recursive, updatesPermission bool, handler func(s *sourceSession) error) error {
s, err := newSourceSession(client, remoteDestPath, remoteDestIsDir, scpPath, recursive, updatesPermission)
defer s.Close()
if err != nil {
return err
}
err = func() error {
defer s.CloseStdin()
return handler(s)
}()
if err != nil {
return err
}
return s.Wait()
}