/
cli.go
401 lines (372 loc) · 9.74 KB
/
cli.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
package cli
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/schollz/croc/v8/src/croc"
"github.com/schollz/croc/v8/src/models"
"github.com/schollz/croc/v8/src/tcp"
"github.com/schollz/croc/v8/src/utils"
log "github.com/schollz/logger"
"github.com/urfave/cli"
)
// Version specifies the version
var Version string
// Run will run the command line proram
func Run() (err error) {
// use all of the processors
runtime.GOMAXPROCS(runtime.NumCPU())
app := cli.NewApp()
app.Name = "croc"
if Version == "" {
Version = "v8.0.5-97bf35b"
}
app.Version = Version
app.Compiled = time.Now()
app.Usage = "easily and securely transfer stuff from one computer to another"
app.UsageText = `Send a file:
croc send file.txt
Send a file with a custom code:
croc send --code secret-passphrase file.txt`
app.Commands = []cli.Command{
{
Name: "send",
Usage: "send a file (see options with croc send -h)",
Description: "send a file over the relay",
ArgsUsage: "[filename]",
Flags: []cli.Flag{
cli.StringFlag{Name: "code, c", Usage: "codephrase used to connect to relay"},
cli.BoolFlag{Name: "no-local", Usage: "disable local relay when sending"},
cli.BoolFlag{Name: "no-multi", Usage: "disable multiplexing"},
cli.StringFlag{Name: "ports", Value: "9009,9010,9011,9012,9013", Usage: "ports of the local relay (optional)"},
},
HelpName: "croc send",
Action: func(c *cli.Context) error {
return send(c)
},
},
{
Name: "relay",
Usage: "start your own relay (optional)",
Description: "start relay",
HelpName: "croc relay",
Action: func(c *cli.Context) error {
return relay(c)
},
Flags: []cli.Flag{
cli.StringFlag{Name: "ports", Value: "9009,9010,9011,9012,9013", Usage: "ports of the relay"},
},
},
}
app.Flags = []cli.Flag{
cli.BoolFlag{Name: "remember", Usage: "save these settings to reuse next time"},
cli.BoolFlag{Name: "debug", Usage: "toggle debug mode"},
cli.BoolFlag{Name: "yes", Usage: "automatically agree to all prompts"},
cli.BoolFlag{Name: "stdout", Usage: "redirect file to stdout"},
cli.BoolFlag{Name: "ask", Usage: "make sure sender and recipient are prompted"},
cli.StringFlag{Name: "relay", Value: models.DEFAULT_RELAY, Usage: "address of the relay"},
cli.StringFlag{Name: "out", Value: ".", Usage: "specify an output folder to receive the file"},
cli.StringFlag{Name: "pass", Value: "pass123", Usage: "password for the relay"},
}
app.EnableBashCompletion = true
app.HideHelp = false
app.HideVersion = false
app.BashComplete = func(c *cli.Context) {
fmt.Fprintf(c.App.Writer, "send\nreceive\relay")
}
app.Action = func(c *cli.Context) error {
// if trying to send but forgot send, let the user know
if c.Args().First() != "" && utils.Exists(c.Args().First()) {
_, fname := filepath.Split(c.Args().First())
yn := utils.GetInput(fmt.Sprintf("Did you mean to send '%s'? (y/n) ", fname))
if strings.ToLower(yn) == "y" {
return send(c)
}
}
return receive(c)
}
return app.Run(os.Args)
}
func getConfigDir() (homedir string, err error) {
homedir, err = os.UserHomeDir()
if err != nil {
log.Error(err)
return
}
homedir = path.Join(homedir, ".config", "croc")
if _, err = os.Stat(homedir); os.IsNotExist(err) {
log.Debugf("creating home directory %s", homedir)
err = os.MkdirAll(homedir, 0700)
}
return
}
func setDebugLevel(c *cli.Context) {
if c.GlobalBool("debug") {
log.SetLevel("debug")
log.Debug("debug mode on")
} else {
log.SetLevel("info")
}
}
func getConfigFile() string {
configFile, err := getConfigDir()
if err != nil {
log.Error(err)
return ""
}
return path.Join(configFile, "send.json")
}
func send(c *cli.Context) (err error) {
setDebugLevel(c)
crocOptions := croc.Options{
SharedSecret: c.String("code"),
IsSender: true,
Debug: c.GlobalBool("debug"),
NoPrompt: c.GlobalBool("yes"),
RelayAddress: c.GlobalString("relay"),
Stdout: c.GlobalBool("stdout"),
DisableLocal: c.Bool("no-local"),
RelayPorts: strings.Split(c.String("ports"), ","),
Ask: c.GlobalBool("ask"),
NoMultiplexing: c.Bool("no-multi"),
RelayPassword: c.GlobalString("pass"),
}
b, errOpen := ioutil.ReadFile(getConfigFile())
if errOpen == nil && !c.GlobalBool("remember") {
var rememberedOptions croc.Options
err = json.Unmarshal(b, &rememberedOptions)
if err != nil {
log.Error(err)
return
}
// update anything that isn't explicitly set
if !c.GlobalIsSet("relay") {
crocOptions.RelayAddress = rememberedOptions.RelayAddress
}
if !c.IsSet("no-local") {
crocOptions.DisableLocal = rememberedOptions.DisableLocal
}
if !c.IsSet("ports") {
crocOptions.RelayPorts = rememberedOptions.RelayPorts
}
if !c.IsSet("code") {
crocOptions.SharedSecret = rememberedOptions.SharedSecret
}
if !c.GlobalIsSet("pass") {
crocOptions.RelayPassword = rememberedOptions.RelayPassword
}
}
var fnames []string
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
fnames, err = getStdin()
if err != nil {
return
}
defer func() {
err = os.Remove(fnames[0])
if err != nil {
log.Error(err)
}
}()
} else {
fnames = append([]string{c.Args().First()}, c.Args().Tail()...)
}
if len(fnames) == 0 {
return errors.New("must specify file: croc send [filename]")
}
if len(crocOptions.SharedSecret) == 0 {
// generate code phrase
crocOptions.SharedSecret = utils.GetRandomName()
}
paths, haveFolder, err := getPaths(fnames)
if err != nil {
return
}
cr, err := croc.New(crocOptions)
if err != nil {
return
}
// save the config
saveConfig(c, crocOptions)
err = cr.Send(croc.TransferOptions{
PathToFiles: paths,
KeepPathInRemote: haveFolder,
})
return
}
func getStdin() (fnames []string, err error) {
f, err := ioutil.TempFile(".", "croc-stdin-")
if err != nil {
return
}
_, err = io.Copy(f, os.Stdin)
if err != nil {
return
}
err = f.Close()
if err != nil {
return
}
fnames = []string{f.Name()}
return
}
func getPaths(fnames []string) (paths []string, haveFolder bool, err error) {
haveFolder = false
paths = []string{}
for _, fname := range fnames {
stat, errStat := os.Stat(fname)
if errStat != nil {
err = errStat
return
}
if stat.IsDir() {
haveFolder = true
err = filepath.Walk(fname,
func(pathName string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
paths = append(paths, filepath.ToSlash(pathName))
}
return nil
})
if err != nil {
return
}
} else {
paths = append(paths, filepath.ToSlash(fname))
}
}
return
}
func saveConfig(c *cli.Context, crocOptions croc.Options) {
if c.GlobalBool("remember") {
configFile := getConfigFile()
log.Debug("saving config file")
var bConfig []byte
// if the code wasn't set, don't save it
if c.String("code") == "" {
crocOptions.SharedSecret = ""
}
bConfig, err := json.MarshalIndent(crocOptions, "", " ")
if err != nil {
log.Error(err)
return
}
err = ioutil.WriteFile(configFile, bConfig, 0644)
if err != nil {
log.Error(err)
return
}
log.Debugf("wrote %s", configFile)
}
}
func receive(c *cli.Context) (err error) {
crocOptions := croc.Options{
SharedSecret: c.String("code"),
IsSender: false,
Debug: c.GlobalBool("debug"),
NoPrompt: c.GlobalBool("yes"),
RelayAddress: c.GlobalString("relay"),
Stdout: c.GlobalBool("stdout"),
Ask: c.GlobalBool("ask"),
RelayPassword: c.GlobalString("pass"),
}
switch len(c.Args()) {
case 1:
crocOptions.SharedSecret = c.Args().First()
case 3:
var phrase []string
phrase = append(phrase, c.Args().First())
phrase = append(phrase, c.Args().Tail()...)
crocOptions.SharedSecret = strings.Join(phrase, "-")
}
// load options here
setDebugLevel(c)
configFile, err := getConfigDir()
if err != nil {
log.Error(err)
return
}
configFile = path.Join(configFile, "receive.json")
b, errOpen := ioutil.ReadFile(configFile)
if errOpen == nil && !c.GlobalBool("remember") {
var rememberedOptions croc.Options
err = json.Unmarshal(b, &rememberedOptions)
if err != nil {
log.Error(err)
return
}
// update anything that isn't explicitly set
if !c.GlobalIsSet("relay") {
crocOptions.RelayAddress = rememberedOptions.RelayAddress
}
if !c.GlobalIsSet("yes") {
crocOptions.NoPrompt = rememberedOptions.NoPrompt
}
if crocOptions.SharedSecret == "" {
crocOptions.SharedSecret = rememberedOptions.SharedSecret
}
if !c.GlobalIsSet("pass") {
crocOptions.RelayPassword = rememberedOptions.RelayPassword
}
}
if crocOptions.SharedSecret == "" {
crocOptions.SharedSecret = utils.GetInput("Enter receive code: ")
}
if c.GlobalString("out") != "" {
os.Chdir(c.GlobalString("out"))
}
cr, err := croc.New(crocOptions)
if err != nil {
return
}
// save the config
if c.GlobalBool("remember") {
log.Debug("saving config file")
var bConfig []byte
bConfig, err = json.MarshalIndent(crocOptions, "", " ")
if err != nil {
log.Error(err)
return
}
err = ioutil.WriteFile(configFile, bConfig, 0644)
if err != nil {
log.Error(err)
return
}
log.Debugf("wrote %s", configFile)
}
err = cr.Receive()
return
}
func relay(c *cli.Context) (err error) {
debugString := "info"
if c.GlobalBool("debug") {
debugString = "debug"
}
ports := strings.Split(c.String("ports"), ",")
tcpPorts := strings.Join(ports[1:], ",")
for i, port := range ports {
if i == 0 {
continue
}
go func(portStr string) {
err = tcp.Run(debugString, portStr, c.GlobalString("pass"))
if err != nil {
panic(err)
}
}(port)
}
return tcp.Run(debugString, ports[0], c.GlobalString("pass"), tcpPorts)
}