forked from povsister/scp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprotocol.go
1018 lines (928 loc) · 25.6 KB
/
protocol.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package scp
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/crypto/ssh"
)
var (
// DebugMode controls the debug output.
// If true, the debug information of remote scp server
// will be printed in Stderr.
DebugMode = false
)
var MIN_BUFFSIZE int64 = 32 * 1024 // 32kB, the common buffsize
var MAX_BUFFSIZE int64 = 1024 * 1024 // 1MB for small size transfer improvements
var ErrInvalidWrite = errors.New("invalid write result")
// copyWithCallback function is an adaptation of io.copyBuffer designed to
// fit the specific requirement of making callback calls to report the
// progress of data transfer. This method reads data from the src reader
// and writes it to the dst writer using the provided buffer buf. During
// the transfer, it triggers callbacks to provide updates on the progress,
// allowing for real-time monitoring of the data being transmitted. The
// function returns the total number of bytes successfully written and an
// error if one occurs during the operation.
func copyWithCallback(dst io.Writer, src io.Reader, buf []byte, cb func(n int64)) (written int64, err error) {
cb(0)
for {
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw < 0 || nr < nw {
nw = 0
if ew == nil {
// the Writer did not return err but
// the writen bytes is more than
// readed bytes :O
ew = ErrInvalidWrite
}
}
// Update written bytes and callback
written += int64(nw)
// callback written bytes
cb(written)
// on write err, stop write
if ew != nil {
err = ew
break
}
// on read/write inconsistency, stop write
if nr != nw {
err = io.ErrShortWrite
break
}
}
// on read error, stop write
if er != nil {
if er != io.EOF {
err = er
}
break
}
}
return written, err
}
// streamTransferInfo is an Implementation of TransferInfo interface
type streamTransferInfo struct {
name string
path string
totalSize int64
transferredSize int64
lastUpdate time.Time
err error
}
func (i *streamTransferInfo) Name() string {
return i.name
}
func (i *streamTransferInfo) Path() string {
return i.path
}
func (i *streamTransferInfo) TotalSize() int64 {
return i.totalSize
}
func (i *streamTransferInfo) TransferredSize() int64 {
return i.transferredSize
}
func (i *streamTransferInfo) LastUpdate() time.Time {
return i.lastUpdate
}
func (i *streamTransferInfo) Err() error {
return i.err
}
type sessionStream struct {
In io.WriteCloser
Out io.Reader
ErrOut io.Reader
observerCallback func(ObserveEventType, TransferInfo)
mu sync.Mutex
}
func (s *sessionStream) Close() error {
return s.In.Close()
}
// get function reads data from s.In and writes it to the w writer,
// taking into account the ti.TotalSize attribute to limit the reading
// to the exact size of the file being transferred. This ensures that
// only the specified amount of data is read and written, preventing
// any excess data from being processed. The function returns the total
// number of bytes successfully transferred (n) and an error (err) if
// any issues occur during the operation.
func (s *sessionStream) get(w io.Writer, ti *streamTransferInfo) (n int64, err error) {
var buf []byte
// for small file sizes a bigger bufer improves the performance
if ti.totalSize < MAX_BUFFSIZE {
buf = make([]byte, MAX_BUFFSIZE)
} else {
buf = make([]byte, MIN_BUFFSIZE)
}
s.callbackTransferStart(ti)
c := make(chan struct{})
tk := make(chan int64, 100)
go func() {
for {
select {
case wb := <-tk:
s.callbackTransferTick(ti, wb)
case <-c:
return
}
}
}()
n, err = copyWithCallback(w, io.LimitReader(s.Out, ti.totalSize), buf, func(wb int64) { go func() { tk <- wb }() })
c <- struct{}{}
s.callbackTransferTick(ti, n)
s.callbackTransferEnd(ti, err)
return n, err
}
// similar to get
func (s *sessionStream) put(r io.Reader, ti *streamTransferInfo) (n int64, err error) {
var buf []byte
// for small file sizes a bigger bufer improves the performance
if ti.totalSize < MAX_BUFFSIZE {
buf = make([]byte, MAX_BUFFSIZE)
} else {
buf = make([]byte, MIN_BUFFSIZE)
}
s.callbackTransferStart(ti)
c := make(chan struct{})
tk := make(chan int64, 100)
go func() {
for {
select {
case wb := <-tk:
s.callbackTransferTick(ti, wb)
case <-c:
return
}
}
}()
n, err = copyWithCallback(s.In, r, buf, func(wb int64) { go func() { tk <- wb }() })
c <- struct{}{}
s.callbackTransferTick(ti, n)
s.callbackTransferEnd(ti, err)
return n, err
}
// setObserverCallback function allows setting a callback function (cb)
// that will be invoked during specific events related to file transfers.
// This callback is triggered at the start and end of a file transfer, as
// well as periodically during the transfer to report progress. The callback
// function receives an ObserveEventType, which indicates the type of event
// (e.g., start, tick, end), and TransferInfo, which contains details about
// the transfer. This setup enables real-time monitoring and handling of
// file transfer events.
func (s *sessionStream) setObserverCallback(cb func(ObserveEventType, TransferInfo)) {
s.observerCallback = cb
}
func (s *sessionStream) callbackTransferStart(ti *streamTransferInfo) {
if s.observerCallback == nil {
return
}
// because we are calling callbacks funcs in go routines, a sysnc is
// needed to prevent race conditions betweeen callbacks
s.mu.Lock()
defer s.mu.Unlock()
roti := *ti
s.observerCallback(ObserveEventStart, &roti)
}
func (s *sessionStream) callbackTransferTick(ti *streamTransferInfo, n int64) {
if s.observerCallback == nil {
return
}
// because we are calling callbacks funcs in go routines, a sysnc is
// needed to prevent race conditions betweeen callbacks
s.mu.Lock()
defer s.mu.Unlock()
ti.transferredSize = n
ti.lastUpdate = time.Now()
roti := *ti // read only copy of ti
s.observerCallback(ObserveEventTick, &roti)
}
func (s *sessionStream) callbackTransferEnd(ti *streamTransferInfo, err error) {
if s.observerCallback == nil {
return
}
// because we are calling callbacks funcs in go routines, a sysnc is
// needed to prevent race conditions betweeen callbacks
s.mu.Lock()
defer s.mu.Unlock()
ti.err = err
roti := *ti
s.observerCallback(ObserveEventEnd, &roti)
}
func (c *Client) sessionAndStream() (*ssh.Session, *sessionStream, error) {
s, err := c.NewSession()
if err != nil {
return nil, nil, err
}
ss := &sessionStream{}
for _, f := range []func() error{
func() (err error) {
ss.In, err = s.StdinPipe()
return
},
func() (err error) {
ss.Out, err = s.StdoutPipe()
return
},
func() (err error) {
ss.ErrOut, err = s.StderrPipe()
return
},
} {
if err = f(); err != nil {
return nil, nil, err
}
}
return s, ss, nil
}
// represents the remote scp server working mode
type scpServerMode string
const (
// Used like "scp user@remote.server:~/something ./"
scpRemoteToLocal scpServerMode = "f"
// Used like "scp ./something user@remote.server:~/"
scpLocalToRemote scpServerMode = "t"
)
type remoteServerOption struct {
Mode scpServerMode
Recursive bool
Preserve bool // preserve time and modes
}
func (c *Client) launchScpServerOnRemote(o remoteServerOption, s *ssh.Session, st *sessionStream, remotePath string, readyCh chan<- struct{}, errCh chan<- error) {
remoteExec := c.scpOpt.RemoteBinary
if c.scpOpt.Sudo && !c.isRootUser() {
remoteExec = fmt.Sprintf("sudo %s", c.scpOpt.RemoteBinary)
}
flags := []string{"-q", fmt.Sprintf("-%s", o.Mode)}
if o.Recursive {
flags = append(flags, "-r")
}
if o.Preserve {
flags = append(flags, "-p")
}
if DebugMode {
flags = append(flags, "-v")
}
cmd := fmt.Sprintf("%s %s '%s'", remoteExec, strings.Join(flags, " "), remotePath)
err := s.Start(cmd)
if err != nil {
errCh <- fmt.Errorf("error executing command %q on remote: %s", cmd, err)
return
}
<-remoteServerReady(o.Mode, st)
close(readyCh)
err = s.Wait()
if err != nil {
errCh <- fmt.Errorf("unexpected remote scp server failure: %s", err)
return
}
}
func remoteServerReady(mode scpServerMode, s *sessionStream) <-chan struct{} {
ch := make(chan struct{})
switch mode {
case scpLocalToRemote:
go func() {
defer func() {
// does not care about the panic msg.
recover()
close(ch)
}()
// read the first OK response from remote receiver server
checkResponse(s)
}()
case scpRemoteToLocal:
// for remote sending server.
// It doe not send back any thing until
// the first OK response is received.
close(ch)
default:
panicf("programmer error: unknown scpServerMode %q", mode)
}
return ch
}
type transferType string
const (
// indicate a timestamp
timestamp transferType = "timestamp"
// indicate a file transfer
file transferType = "file"
// indicate a directory transfer
directory transferType = "directory"
// exit the scp server (at the root directory)
// or back to the previous directory (equals to "cd ..")
exit transferType = "exit"
)
type sendJob struct {
Type transferType
Size int64
Reader io.Reader // the content reader
Destination string // must be file or directory name. Path is not supported in send
Perm os.FileMode
AccessTime *time.Time // can be nil
ModifiedTime *time.Time // must be both set or nil with atime
close bool // close the reader after using it. internal usage.
}
var (
// represent a "E" signal
exitJob = sendJob{Type: exit}
)
// it accepts a single "sendJob" or "<-chan sendJob"
func (c *Client) sendToRemote(cancel context.CancelFunc, jobs interface{}, stream *sessionStream, finished chan<- struct{}, errCh chan<- error) {
defer func() {
if r := recover(); r != nil {
if cancel != nil {
// cancel the traverse goroutine on error
cancel()
}
// empty the chan and close the fd in buffer
if jobCh, ok := jobs.(<-chan sendJob); ok {
for {
j, ok := <-jobCh
if !ok {
break
}
if j.close && j.Reader != nil {
if rc, ok := j.Reader.(io.ReadCloser); ok {
_ = rc.Close()
}
}
}
}
errCh <- fmt.Errorf("%v", r)
}
}()
setupDebug(stream.ErrOut)
switch js := jobs.(type) {
case sendJob:
handleSend(js, stream)
case <-chan sendJob:
for {
j, ok := <-js
if !ok {
// jobCh closed
break
}
handleSend(j, stream)
}
default:
panicf("programmer error: unknown type %T", jobs)
}
if finished != nil {
close(finished)
}
}
func handleSend(j sendJob, stream *sessionStream) {
switch j.Type {
case file:
// close if required
if j.close {
if rc, ok := j.Reader.(io.ReadCloser); ok {
defer rc.Close()
}
}
// set timestamp for the next coming file
if j.AccessTime != nil && j.ModifiedTime != nil {
sendTimestamp(j, stream)
}
// send signal
_, err := fmt.Fprintf(stream.In, "C0%o %d %s\n", j.Perm, j.Size, j.Destination)
if err != nil {
panicf("error sending signal C: %s", err)
}
checkResponse(stream)
// send file
_, err = stream.put(j.Reader, &streamTransferInfo{
name: filepath.Base(j.Destination),
path: j.Destination,
totalSize: j.Size,
transferredSize: 0,
lastUpdate: time.Now(),
})
if err != nil {
panicf("error sending file %q: %s", j.Destination, err)
}
_, err = fmt.Fprint(stream.In, "\x00")
if err != nil {
panicf("error finishing file %q: %s", j.Destination, err)
}
checkResponse(stream)
case directory:
if j.AccessTime != nil && j.ModifiedTime != nil {
sendTimestamp(j, stream)
}
// size is always 0 for directory
_, err := fmt.Fprintf(stream.In, "D0%o 0 %s\n", j.Perm, j.Destination)
if err != nil {
panicf("error sending signal D: %s", err)
}
checkResponse(stream)
case exit:
_, err := fmt.Fprintf(stream.In, "E\n")
if err != nil {
panicf("error sending signal E: %s", err)
}
checkResponse(stream)
default:
panicf("programmer error: unknown transferType %q", j.Type)
}
}
func sendTimestamp(j sendJob, stream *sessionStream) {
_, err := fmt.Fprintf(stream.In, "T%d 0 %d 0\n", j.ModifiedTime.Unix(), j.AccessTime.Unix())
if err != nil {
panicf("error sending signal T: %s", err)
}
checkResponse(stream)
}
func setupDebug(errReader io.Reader) {
if errReader == nil {
return
}
if DebugMode {
go io.Copy(os.Stderr, errReader)
} else {
go io.Copy(ioutil.Discard, errReader)
}
}
type receiveJob struct {
Type transferType
Writer io.Writer
Path string
Perm os.FileMode
close bool // close writer
recursive bool // recursive receive
}
func (c *Client) receiveFromRemote(job receiveJob, stream *sessionStream, finished chan<- struct{}, errCh chan<- error) {
defer func() {
if r := recover(); r != nil {
if job.close {
if rc, ok := job.Writer.(io.WriteCloser); ok {
_ = rc.Close()
}
}
errCh <- fmt.Errorf("%v", r)
}
}()
setupDebug(stream.ErrOut)
switch job.Type {
case file:
handleReceive(job, stream)
case directory:
handleReceive(job, stream)
default:
panicf("programmer error: unsupported receive type %q", job.Type)
}
if finished != nil {
close(finished)
}
}
func handleReceive(recv receiveJob, stream *sessionStream) {
var path []string
if len(recv.Path) > 0 {
path = append(path, recv.Path)
}
// signal the remote to start
sendResponse(stream.In, statusOK)
// a flag to indicate if first loop
firstLoop := true
for {
j := readTransaction(stream)
if !recv.recursive && j.Type == directory {
sendResponse(stream.In, statusErr, "protocol error: directory received in non-recursive mode")
}
switch j.Type {
case directory:
// On the first loop. skip the root directory transfer
if firstLoop {
// The root directory should already exists
setTimestamp(stream.In, recv.Path, j.ModifiedTime, j.AccessTime)
sendResponse(stream.In, statusOK)
firstLoop = false
continue
}
path = append(path, j.Destination)
toOpen := filepath.Join(path...)
mkdir(stream.In, toOpen, j.Perm)
setTimestamp(stream.In, toOpen, j.ModifiedTime, j.AccessTime)
// confirm D command
sendResponse(stream.In, statusOK)
case file:
// recursive recv
if recv.recursive && len(path) >= 1 && recv.Writer == nil {
toOpen := filepath.Join(append(path, j.Destination)...)
fd := openFile(stream.In, toOpen, j.Perm)
saveFile(fd, stream, &streamTransferInfo{
name: filepath.Base(j.Destination),
path: toOpen,
totalSize: j.Size,
transferredSize: 0,
lastUpdate: time.Now(),
}, true)
setTimestamp(stream.In, toOpen, j.ModifiedTime, j.AccessTime)
} else {
// single file transfer
// write to buffer
if recv.Writer == nil {
// if buffer is not set. Means it's a file transfer.
perm := j.Perm
if recv.Perm != 0 {
// overrides the file permission bits if needed
perm = recv.Perm
}
recv.Writer = openFile(stream.In, recv.Path, perm)
}
saveFile(recv.Writer, stream, &streamTransferInfo{
name: filepath.Base(recv.Path),
path: recv.Path,
totalSize: j.Size,
transferredSize: 0,
lastUpdate: time.Now(),
}, recv.close)
// if path is specified. Means its a file transfer.
if len(recv.Path) > 0 {
setTimestamp(stream.In, recv.Path, j.ModifiedTime, j.AccessTime)
}
}
// confirm recv ok
sendResponse(stream.In, statusOK)
if !recv.recursive {
return
}
case exit:
sendResponse(stream.In, statusOK)
if recv.recursive {
if l := len(path); l >= 2 {
// exit to parent directory
path = path[0 : l-1]
} else {
// exit to root directory.
// Means exit
return
}
} else {
// buffer or single file write. just exit
return
}
default:
sendResponse(stream.In, statusErr, "programmer error: unexpected receive transaction ", string(j.Type))
}
if firstLoop {
firstLoop = false
}
}
}
func openFile(w io.Writer, path string, perm os.FileMode) *os.File {
fd, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
sendResponse(w, statusErr, err.Error())
}
return fd
}
// mkdir makes the dir if not exist
func mkdir(w io.Writer, path string, perm os.FileMode) {
if stat, err := os.Stat(path); err != nil {
if err = os.Mkdir(path, perm); err != nil {
sendResponse(w, statusErr, err.Error())
}
} else {
if !stat.IsDir() {
sendResponse(w, statusErr, path, "is not a directory")
}
}
}
// setTimestamp sets the atime and mtime for file/directory
func setTimestamp(w io.Writer, path string, mtime, atime *time.Time) {
if mtime == nil || atime == nil {
return
}
err := os.Chtimes(path, *atime, *mtime)
if err != nil && w != nil {
sendResponse(w, statusErr, fmt.Sprintf("error setting mtime and atime %s ", path), err.Error())
}
}
// saveFile saves the file received to io.Writer.
// It will first confirm the command C and then start recv
func saveFile(w io.Writer, stream *sessionStream, ti *streamTransferInfo, close bool) {
defer func() {
if close {
if rc, ok := w.(io.ReadCloser); ok {
_ = rc.Close()
}
}
if r := recover(); r != nil {
sendResponse(w, statusErr, fmt.Sprintf("%s", r))
}
}()
// confirm C command and starting transfer
sendResponse(stream.In, statusOK)
// stream.get() will take care about size using
// ti.TotalSize ErrInvalidWrite or ErrShortWrite
// will be returned on transfer inconsistency
_, err := stream.get(w, ti)
if err != nil {
panicf("error reading file from remote: %s", err)
}
readDelimiter(stream.Out, 0, 1)
}
// read commands as a sendJob from remote
func readTransaction(stream *sessionStream) sendJob {
// read the first command
c := readCommand(stream)
j := sendJob{}
// read next if T command
if c.Type == timestamp {
sendResponse(stream.In, statusOK)
next := readCommand(stream)
switch next.Type {
case file, directory:
j.Type, j.Destination = next.Type, next.Destination
j.ModifiedTime, j.AccessTime = c.Mtime, c.Atime
j.Perm, j.Size = next.Perm, next.Size
case timestamp:
sendResponse(stream.In, statusErr, "protocol error: unexpected T after T")
case exit:
sendResponse(stream.In, statusErr, "protocol error: unexpected E after T")
default:
panic("programmer error: impossible switch case")
}
} else {
j.Type, j.Destination = c.Type, c.Destination
j.Perm, j.Size = c.Perm, c.Size
}
return j
}
type command struct {
Type transferType
// common field for file/directory
Destination string
Perm os.FileMode
// timestamp
Mtime, Atime *time.Time
// file
Size int64
}
var (
// the command signal length in byte
commandLenByte = 1
// the length limit for destination.
// Typically the filename/directory is limited to 255 characters
destinationLimit = 1<<8 - 1
// the length limit for representing a file size in byte.
// Using the length of MaxInt64 (9223372036854775807)
fileSizeLenLimit = 19
)
func readCommand(stream *sessionStream) command {
defer func() {
if r := recover(); r != nil {
errStr := fmt.Sprintf("%v", r)
// if protocol error occurs.
// Send it back to remote server
if strings.HasPrefix(errStr, "protocol error") {
// sendResponse continue panic on Err
sendResponse(stream.In, statusErr, errStr)
}
// continue panic
panic(errStr)
}
}()
buf := make([]byte, commandLenByte)
n, err := stream.Out.Read(buf)
if err != nil {
panicf("error receiving signal from remote scp server: %s", err)
}
if n != commandLenByte {
panicf("expecting read %d byte, but got %d", commandLenByte, n)
}
var c command
switch string(buf) {
case "T":
c.Type = timestamp
c.Mtime = readUnixTimestamp(stream.Out)
readDelimiter(stream.Out, ' ', 1)
readDelimiter(stream.Out, '0', 1)
readDelimiter(stream.Out, ' ', 1)
c.Atime = readUnixTimestamp(stream.Out)
readDelimiter(stream.Out, ' ', 1)
readDelimiter(stream.Out, '0', 1)
readDelimiter(stream.Out, '\n', 1)
case "C":
c.Type = file
c.Perm = readPerm(stream.Out)
readDelimiter(stream.Out, ' ', 1)
c.Size = readFileSize(stream.Out) // reads Delimiter ' ' as well
c.Destination = readDestination(stream.Out) // reads Delimiter '\n' as well
case "D":
c.Type = directory
c.Perm = readPerm(stream.Out)
readDelimiter(stream.Out, ' ', 1)
readDelimiter(stream.Out, '0', 1)
readDelimiter(stream.Out, ' ', 1)
c.Destination = readDestination(stream.Out)
case "E":
c.Type = exit
readDelimiter(stream.Out, '\n', 1)
case string(statusOK):
// do nothing
case string(statusErr), string(statusFatal):
br := bufio.NewReader(stream.Out)
reason, err := br.ReadString('\n')
if err != nil {
panicf("error reading failure reason from remote scp server: %s", err)
}
panic(trimErrMsg(reason))
default:
panicf("protocol error: unknown signal %s", buf)
}
return c
}
// send a response back to remote scp server.
// if the response is not statusOK, it will panic after send.
func sendResponse(w io.Writer, respType responseStatus, msg ...string) {
var resp []byte
if respType != statusOK {
if len(msg) > 0 {
for _, m := range msg {
resp = append(resp, []byte(m)...)
}
}
resp = append(resp, '\n')
}
header := []byte(respType)
var err error
if respType != statusOK {
_, err = w.Write(append(header, append([]byte("scp: "), resp...)...))
} else {
_, err = w.Write(header)
}
if err != nil {
panicf("error sending response to remote scp server: %s", err)
}
if respType != statusOK {
panic(string(resp))
}
}
func readUnixTimestamp(r io.Reader) *time.Time {
unixTime := make([]byte, 10)
n, err := r.Read(unixTime)
if err != nil {
panicf("error receiving timestamp from remote scp server: %s", err)
}
if n != 10 {
panicf("expecting read %d byte, but got %d", 10, n)
}
unix, err := strconv.ParseInt(string(unixTime), 10, 64)
if err != nil {
panicf("protocol error: invalid timestamp %s %s", unixTime, err)
}
t := time.Unix(unix, 0)
return &t
}
func readDelimiter(r io.Reader, sep byte, repeat int) {
read := make([]byte, repeat)
n, err := r.Read(read)
if err != nil {
panicf("error reading from remote scp server: %s", err)
}
if n != repeat {
panicf("expecting read %d bytes, but got %d", 10, n)
}
for _, perByte := range read {
if perByte != sep {
panicf("protocol error: expecting delimiter %s but got %s", string(sep), read)
}
}
}
func readPerm(r io.Reader) os.FileMode {
read := make([]byte, 4)
n, err := r.Read(read)
if err != nil {
panicf("error reading mode from remote scp server: %s", err)
}
if n != 4 {
panicf("expecting read %d byte, but got %d", 4, n)
}
mode, err := strconv.ParseInt(string(read), 8, 32)
if err != nil {
panicf("protocol error: invalid mode %s %s", read, err)
}
return os.FileMode(mode)
}
func readFileSize(r io.Reader) (result int64) {
readByte := make([]byte, 1)
var n, totalLen int
var err error
var read []byte
for {
if totalLen > fileSizeLenLimit {
panicf("file size exceeding limit: %s", read)
}
n, err = r.Read(readByte)
if err != nil {
panicf("error reading file size from remote scp server: %s", err)
}
if n != 1 {
panicf("expecting read %d byte, but got %d", 1, n)
}
totalLen += n
if readByte[0] == ' ' {
break
} else if readByte[0] >= '0' && readByte[0] <= '9' {
read = append(read, readByte[0])
} else {
panicf("protocol error: invalid file size num %s", readByte)
}
}
if len(read) == 0 {
panicf("protocol error: file size missing")
}
result, err = strconv.ParseInt(string(read), 10, 64)
if err != nil {
panicf("protocol error: invalid file size %s %s", read, err)
}
return
}
func readDestination(r io.Reader) string {
readByte := make([]byte, 1)
var n, totalLen int
var err error
var read []byte
for {
if totalLen > destinationLimit {
panicf("file or directory name is too long: %s", read)
}
n, err = r.Read(readByte)
if err != nil {
panicf("error reading file or directory name from remote scp server: %s", err)
}
if n != 1 {
panicf("expecting read %d byte, but got %d", 1, n)
}
totalLen += n
if readByte[0] == '\n' {
break
} else {
read = append(read, readByte[0])
}
}
if len(read) == 0 {
panicf("protocol error: empty file or directory name")
}
return string(read)
}
type responseStatus string
const (
// There are 3 types of responses that the remote can send back:
// OK, Error and Fatal
//
// The difference between Error and Fatal is that the connection is not closed by the remote.
// However, a Error can indicate a file transfer failure (such as invalid destination directory)
//
// All responses except for the OK always have a message (although they can be empty)
// Normal OK
statusOK responseStatus = "\x00"
// A failure operation
statusErr responseStatus = "\x01"
// Indicate a Fatal error, though no one actually use it.
statusFatal responseStatus = "\x02"
// The byte length for representing a status
statusByteLen = 1
)
// check response from remote scp
// panic on error
func checkResponse(stream *sessionStream) {
status := make([]byte, statusByteLen)
n, err := stream.Out.Read(status)
if err != nil {
panicf("error reading server response status: %s", err)
}
if n != statusByteLen {
panicf("expecting read %d byte, but got %d", statusByteLen, n)
}
st := responseStatus(status[0:statusByteLen])
switch st {
case statusErr, statusFatal:
buf := bufio.NewReader(stream.Out)
errMsg, err := buf.ReadString('\n')