-
Notifications
You must be signed in to change notification settings - Fork 56
/
send.go
665 lines (558 loc) · 13.4 KB
/
send.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
package wormhole
import (
"archive/zip"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/psanford/wormhole-william/internal/crypto"
"github.com/psanford/wormhole-william/rendezvous"
"github.com/psanford/wormhole-william/wordlist"
"golang.org/x/crypto/nacl/secretbox"
)
// SendText sends a text message via the wormhole protocol.
//
// It returns the nameplate+passphrase code to give to the receiver, a result chan
// that gets written to once the receiver actually attempts to read the message
// (either successfully or not).
func (c *Client) SendText(ctx context.Context, msg string, opts ...SendOption) (string, chan SendResult, error) {
sideID := crypto.RandSideID()
appID := c.appID()
var options sendOptions
for _, opt := range opts {
err := opt.setOption(&options)
if err != nil {
return "", nil, err
}
}
rc := rendezvous.NewClient(c.url(), sideID, appID)
_, err := rc.Connect(ctx)
if err != nil {
return "", nil, err
}
var pwStr string
if options.code == "" {
nameplate, err := rc.CreateMailbox(ctx)
if err != nil {
return "", nil, err
}
pwStr = nameplate + "-" + wordlist.ChooseWords(c.wordCount())
} else {
pwStr = options.code
nameplate, err := nameplaceFromCode(pwStr)
if err != nil {
return "", nil, err
}
err = rc.AttachMailbox(ctx, nameplate)
if err != nil {
return "", nil, err
}
}
clientProto := newClientProtocol(ctx, rc, sideID, appID)
ch := make(chan SendResult, 1)
go func() {
var returnErr error
defer func() {
mood := rendezvous.Errory
if returnErr == nil {
mood = rendezvous.Happy
} else if returnErr == errDecryptFailed {
mood = rendezvous.Scary
}
rc.Close(ctx, mood)
}()
sendErr := func(err error) {
ch <- SendResult{
Error: err,
}
returnErr = err
close(ch)
return
}
err = clientProto.WritePake(ctx, pwStr)
if err != nil {
sendErr(err)
return
}
err = clientProto.ReadPake()
if err != nil {
sendErr(err)
return
}
err = clientProto.WriteVersion(ctx)
if err != nil {
sendErr(err)
return
}
_, err = clientProto.ReadVersion()
if err != nil {
sendErr(err)
return
}
if c.VerifierOk != nil {
verifier, err := clientProto.Verifier()
if err != nil {
sendErr(err)
return
}
if ok := c.VerifierOk(hex.EncodeToString(verifier)); !ok {
errMsg := "sender rejected verification check, abandoned transfer"
writeErr := clientProto.WriteAppData(ctx, &genericMessage{
Error: &errMsg,
})
if writeErr != nil {
sendErr(writeErr)
return
}
sendErr(errors.New(errMsg))
return
}
}
offer := &genericMessage{
Offer: &offerMsg{
Message: &msg,
},
}
err = clientProto.WriteAppData(ctx, offer)
if err != nil {
sendErr(err)
return
}
collector, err := clientProto.Collect()
if err != nil {
sendErr(err)
return
}
defer collector.close()
var answer answerMsg
err = collector.waitFor(&answer)
if err != nil {
sendErr(err)
return
}
if answer.MessageAck == "ok" {
ch <- SendResult{
OK: true,
}
close(ch)
return
} else {
sendErr(fmt.Errorf("Unexpected answer"))
return
}
}()
return pwStr, ch, nil
}
func (c *Client) sendFileDirectory(ctx context.Context, offer *offerMsg, r io.Reader, opts ...SendOption) (string, chan SendResult, error) {
if err := c.validateRelayAddr(); err != nil {
return "", nil, fmt.Errorf("Invalid TransitRelayAddress: %s", err)
}
var options sendOptions
for _, opt := range opts {
err := opt.setOption(&options)
if err != nil {
return "", nil, err
}
}
sideID := crypto.RandSideID()
appID := c.appID()
rc := rendezvous.NewClient(c.url(), sideID, appID)
_, err := rc.Connect(ctx)
if err != nil {
return "", nil, err
}
var pwStr string
if options.code == "" {
nameplate, err := rc.CreateMailbox(ctx)
if err != nil {
return "", nil, err
}
pwStr = nameplate + "-" + wordlist.ChooseWords(c.wordCount())
} else {
pwStr = options.code
nameplate, err := nameplaceFromCode(pwStr)
if err != nil {
return "", nil, err
}
err = rc.AttachMailbox(ctx, nameplate)
if err != nil {
return "", nil, err
}
}
clientProto := newClientProtocol(ctx, rc, sideID, appID)
ch := make(chan SendResult, 1)
go func() {
var returnErr error
defer func() {
mood := rendezvous.Errory
if returnErr == nil {
mood = rendezvous.Happy
} else if returnErr == errDecryptFailed {
mood = rendezvous.Scary
}
rc.Close(ctx, mood)
}()
sendErr := func(err error) {
ch <- SendResult{
Error: err,
}
returnErr = err
close(ch)
return
}
err = clientProto.WritePake(ctx, pwStr)
if err != nil {
sendErr(err)
return
}
err = clientProto.ReadPake()
if err != nil {
sendErr(err)
return
}
err = clientProto.WriteVersion(ctx)
if err != nil {
sendErr(err)
return
}
_, err = clientProto.ReadVersion()
if err != nil {
sendErr(err)
return
}
if c.VerifierOk != nil {
verifier, err := clientProto.Verifier()
if err != nil {
sendErr(err)
return
}
if ok := c.VerifierOk(hex.EncodeToString(verifier)); !ok {
errMsg := "sender rejected verification check, abandoned transfer"
writeErr := clientProto.WriteAppData(ctx, &genericMessage{
Error: &errMsg,
})
if writeErr != nil {
sendErr(writeErr)
return
}
sendErr(errors.New(errMsg))
return
}
}
transitKey := deriveTransitKey(clientProto.sharedKey, appID)
transport := newFileTransport(transitKey, appID, c.relayAddr())
err = transport.listen()
if err != nil {
sendErr(err)
return
}
err = transport.listenRelay()
if err != nil {
sendErr(err)
return
}
transit, err := transport.makeTransitMsg()
if err != nil {
sendErr(fmt.Errorf("Make transit msg error: %s", err))
return
}
err = clientProto.WriteAppData(ctx, &genericMessage{
Transit: transit,
})
if err != nil {
sendErr(err)
return
}
gmOffer := &genericMessage{
Offer: offer,
}
err = clientProto.WriteAppData(ctx, gmOffer)
if err != nil {
sendErr(err)
return
}
collector, err := clientProto.Collect()
if err != nil {
sendErr(err)
return
}
defer collector.close()
var answer answerMsg
err = collector.waitFor(&answer)
if err != nil {
sendErr(err)
return
}
if answer.FileAck != "ok" {
sendErr(fmt.Errorf("Unexpected answer"))
return
}
conn, err := transport.acceptConnection(ctx)
if err != nil {
sendErr(err)
return
}
cryptor := newTransportCryptor(conn, transitKey, "transit_record_receiver_key", "transit_record_sender_key")
recordSize := (1 << 14)
// chunk
recordSlice := make([]byte, recordSize-secretbox.Overhead)
hasher := sha256.New()
var progress int64
var totalSize int64
if offer.File != nil {
totalSize = offer.File.FileSize
} else if offer.Directory != nil {
totalSize = offer.Directory.ZipSize
}
for {
n, err := r.Read(recordSlice)
if n > 0 {
hasher.Write(recordSlice[:n])
err = cryptor.writeRecord(recordSlice[:n])
if err != nil {
sendErr(err)
return
}
progress = progress + int64(n)
if options.progressFunc != nil {
options.progressFunc(progress, totalSize)
}
}
if err == io.EOF {
break
} else if err != nil {
sendErr(err)
return
}
}
respRec, err := cryptor.readRecord()
if err != nil {
sendErr(err)
return
}
var ack fileTransportAck
err = json.Unmarshal(respRec, &ack)
if err != nil {
sendErr(err)
return
}
if ack.Ack != "ok" {
sendErr(errors.New("Got non ok final ack from receiver"))
return
}
shaSum := fmt.Sprintf("%x", hasher.Sum(nil))
if strings.ToLower(ack.SHA256) != shaSum {
sendErr(fmt.Errorf("Receiver sha256 mismatch %s vs %s", ack.SHA256, shaSum))
return
}
ch <- SendResult{
OK: true,
}
close(ch)
return
}()
return pwStr, ch, nil
}
// SendFile sends a single file via the wormhole protocol. It returns a nameplate+passhrase code to give to the
// receiver, a result channel that will be written to after the receiver attempts to read (either successfully or not)
// and an error if one occured.
func (c *Client) SendFile(ctx context.Context, fileName string, r io.ReadSeeker, opts ...SendOption) (string, chan SendResult, error) {
if err := c.validateRelayAddr(); err != nil {
return "", nil, fmt.Errorf("Invalid TransitRelayAddress: %s", err)
}
size, err := readSeekerSize(r)
if err != nil {
return "", nil, err
}
offer := &offerMsg{
File: &offerFile{
FileName: fileName,
FileSize: size,
},
}
return c.sendFileDirectory(ctx, offer, r, opts...)
}
// A DirectoryEntry represents a single file to be sent by SendDirectory
type DirectoryEntry struct {
// Path is the relative path to the file from the top level directory.
Path string
// Mode controls the permission and mode bits for the file.
Mode os.FileMode
// Reader is a function that returns a ReadCloser for the file's content.
Reader func() (io.ReadCloser, error)
}
// SendDirectory sends a tree of files to a receiving client.
// Each DirectoryEntry Path must be prefixed by the directoryName provided to SendDirectory.
//
// It returns a nameplate+passhrase code to give to the
// receiver, a result channel that will be written to after the receiver attempts to read (either successfully or not)
// and an error if one occured.
func (c *Client) SendDirectory(ctx context.Context, directoryName string, entries []DirectoryEntry, opts ...SendOption) (string, chan SendResult, error) {
zipInfo, err := makeTmpZip(directoryName, entries)
if err != nil {
return "", nil, err
}
offer := &offerMsg{
Directory: &offerDirectory{
Dirname: directoryName,
Mode: "zipfile/deflated",
NumBytes: zipInfo.numBytes,
NumFiles: zipInfo.numFiles,
ZipSize: zipInfo.zipSize,
},
}
code, resultCh, err := c.sendFileDirectory(ctx, offer, zipInfo.file, opts...)
if err != nil {
return "", nil, err
}
// intercept result chan to close our tmpfile after we are done with it
retCh := make(chan SendResult, 1)
go func() {
r := <-resultCh
zipInfo.file.Close()
retCh <- r
}()
return code, retCh, err
}
type zipResult struct {
file *os.File
numBytes int64
numFiles int64
zipSize int64
}
func makeTmpZip(directoryName string, entries []DirectoryEntry) (*zipResult, error) {
f, err := ioutil.TempFile("", "wormhole-william-dir")
if err != nil {
return nil, err
}
if len(entries) < 1 {
return nil, errors.New("No files provided")
}
defer os.Remove(f.Name())
if strings.TrimSpace(directoryName) == "" {
return nil, errors.New("directoryName must be set")
}
prefix, _ := filepath.Split(directoryName)
if prefix != "" {
return nil, errors.New("directoryName must not include sub directories")
}
w := zip.NewWriter(f)
var totalBytes int64
for _, entry := range entries {
if !strings.HasPrefix(entry.Path, directoryName+"/") {
return nil, errors.New("Each directory entry must be prefixed with the directoryName")
}
header := &zip.FileHeader{
Name: strings.TrimPrefix(entry.Path, directoryName+"/"),
Method: zip.Deflate,
}
header.SetMode(entry.Mode)
f, err := w.CreateHeader(header)
if err != nil {
return nil, err
}
r, err := entry.Reader()
if err != nil {
return nil, err
}
var counter countWriter
_, err = io.Copy(f, io.TeeReader(r, &counter))
if err != nil {
return nil, err
}
totalBytes = totalBytes + counter.count
err = r.Close()
if err != nil {
return nil, err
}
}
err = w.Close()
if err != nil {
return nil, err
}
zipSize, err := readSeekerSize(f)
if err != nil {
return nil, err
}
result := zipResult{
file: f,
numBytes: totalBytes,
numFiles: int64(len(entries)),
zipSize: zipSize,
}
return &result, nil
}
type countWriter struct {
count int64
}
func (c *countWriter) Write(p []byte) (int, error) {
c.count = c.count + int64(len(p))
return len(p), nil
}
func readSeekerSize(r io.ReadSeeker) (int64, error) {
size, err := r.Seek(0, io.SeekEnd)
if err != nil {
return -1, err
}
_, err = r.Seek(0, io.SeekStart)
if err != nil {
return -1, err
}
return size, nil
}
type sendOptions struct {
code string
progressFunc progressFunc
}
type SendOption interface {
setOption(*sendOptions) error
}
type sendCodeOption struct {
code string
}
func (o sendCodeOption) setOption(opts *sendOptions) error {
if err := validateCode(o.code); err != nil {
return err
}
opts.code = o.code
return nil
}
func validateCode(code string) error {
if code == "" {
return nil
}
_, err := nameplaceFromCode(code)
if err != nil {
return err
}
if strings.Contains(code, " ") {
return errors.New("Code must not contain spaces")
}
return nil
}
// WithCode returns a SendOption to use a specific nameplate+code
// instead of generating one dynamically.
func WithCode(code string) SendOption {
return sendCodeOption{code: code}
}
type progressFunc func(sentBytes int64, totalBytes int64)
type progressSendOption struct {
progressFunc progressFunc
}
func (o progressSendOption) setOption(opts *sendOptions) error {
opts.progressFunc = o.progressFunc
return nil
}
// WithProgress returns a SendOption to track the progress of
// the data transfer. It takes a callback function that will
// be called for each chunk of data successfully written.
func WithProgress(f func(sentBytes int64, totalBytes int64)) SendOption {
return progressSendOption{f}
}