forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 2
/
scp.go
125 lines (110 loc) · 2.44 KB
/
scp.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
// Copyright 2012-2018 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Scp copies files between hosts on a network.
//
// Synopsis:
// scp [-t|-f] [FILE]
//
// Description:
// If -t is given, decode SCP protocol from stdin and write to FILE.
// If -f is given, stream FILE over SCP protocol to stdout.
//
// Options:
// -t: Act as the target
// -f: Act as the source
// -v: Passed if SCP is verbose, ignored
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
)
const (
SUCCESS = 0
)
var (
isTarget = flag.Bool("t", false, "Act as the target")
isSource = flag.Bool("f", false, "Act as the source")
_ = flag.Bool("v", false, "Ignored")
)
func scpSource(w io.Writer, path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
s, err := f.Stat()
if err != nil {
return err
}
w.Write([]byte(fmt.Sprintf("C0%o %d %s\n", s.Mode(), s.Size(), path)))
if response() != SUCCESS {
log.Fatalf("response was not success")
}
_, err = io.Copy(w, f)
if err != nil {
log.Fatalf("copy error: %v", err)
}
reply(SUCCESS)
if response() != SUCCESS {
log.Fatalf("response was not success")
}
return nil
}
func scpSink(r io.Reader, path string) error {
var mode os.FileMode
var size int64
filename := ""
if _, err := fmt.Fscanf(r, "C0%o %d %s\n", &mode, &size, &filename); err != nil {
return err
}
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, mode)
if err != nil {
log.Fatalf("open error: %v", err)
}
reply(SUCCESS)
defer f.Close()
_, err = io.CopyN(f, r, size)
if err != nil {
log.Fatalf("copy error: %v", err)
}
reply(SUCCESS)
return nil
}
func reply(r byte) {
os.Stdout.Write([]byte{r})
}
func response() byte {
b := make([]byte, 1)
os.Stdout.Read(b)
return b[0]
}
func main() {
flag.Parse()
if flag.NArg() == 0 {
log.Fatalf("no file provided")
}
if *isSource == *isTarget {
log.Fatalf("-t or -f needs to be supplied, and not both")
}
if *isSource {
// Sink->Source is started with a response
if response() != SUCCESS {
log.Fatalf("response was not success")
}
if err := scpSource(os.Stdout, flag.Args()[0]); err != nil {
log.Fatalf("scp: %v", err)
}
} else if *isTarget {
// Sink->Source starts with a response
reply(SUCCESS)
for {
if err := scpSink(os.Stdin, flag.Args()[0]); err != nil {
log.Fatalf("scp: %v", err)
}
}
}
}