-
Notifications
You must be signed in to change notification settings - Fork 3
/
pt_test.go
798 lines (743 loc) · 20 KB
/
pt_test.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
package pt
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path"
"sort"
"testing"
)
func stringIsSafe(s string) bool {
for _, c := range []byte(s) {
if c == '\x00' || c == '\n' || c > 127 {
return false
}
}
return true
}
func TestEscape(t *testing.T) {
tests := [...]string{
"",
"abc",
"a\nb",
"a\\b",
"ab\\",
"ab\\\n",
"ab\n\\",
}
check := func(input string) {
output := escape(input)
if !stringIsSafe(output) {
t.Errorf("escape(%q) → %q", input, output)
}
}
for _, input := range tests {
check(input)
}
for b := 0; b < 256; b++ {
// check one-byte string with each byte value 0–255
check(string([]byte{byte(b)}))
// check UTF-8 encoding of each character 0–255
check(string(b))
}
}
func TestGetManagedTransportVer(t *testing.T) {
badTests := [...]string{
"",
"2",
}
goodTests := [...]struct {
input, expected string
}{
{"1", "1"},
{"1,1", "1"},
{"1,2", "1"},
{"2,1", "1"},
}
Stdout = ioutil.Discard
os.Clearenv()
_, err := getManagedTransportVer()
if err == nil {
t.Errorf("empty environment unexpectedly succeeded")
}
for _, input := range badTests {
os.Setenv("TOR_PT_MANAGED_TRANSPORT_VER", input)
_, err := getManagedTransportVer()
if err == nil {
t.Errorf("TOR_PT_MANAGED_TRANSPORT_VER=%q unexpectedly succeeded", input)
}
}
for _, test := range goodTests {
os.Setenv("TOR_PT_MANAGED_TRANSPORT_VER", test.input)
output, err := getManagedTransportVer()
if err != nil {
t.Errorf("TOR_PT_MANAGED_TRANSPORT_VER=%q unexpectedly returned an error: %s", test.input, err)
}
if output != test.expected {
t.Errorf("TOR_PT_MANAGED_TRANSPORT_VER=%q → %q (expected %q)", test.input, output, test.expected)
}
}
}
// return true iff the two slices contain the same elements, possibly in a
// different order.
func stringSetsEqual(a, b []string) bool {
ac := make([]string, len(a))
bc := make([]string, len(b))
copy(ac, a)
copy(bc, b)
sort.Strings(ac)
sort.Strings(bc)
if len(ac) != len(bc) {
return false
}
for i := 0; i < len(ac); i++ {
if ac[i] != bc[i] {
return false
}
}
return true
}
func tcpAddrsEqual(a, b *net.TCPAddr) bool {
return a.IP.Equal(b.IP) && a.Port == b.Port
}
func TestGetClientTransports(t *testing.T) {
tests := [...]struct {
ptServerClientTransports string
star []string
expected []string
}{
{
"*",
[]string{},
[]string{},
},
{
"*",
[]string{"alpha", "beta", "gamma"},
[]string{"alpha", "beta", "gamma"},
},
{
"alpha,beta,gamma",
[]string{"alpha", "beta", "gamma"},
[]string{"alpha", "beta", "gamma"},
},
{
"alpha,beta",
[]string{"alpha", "beta", "gamma"},
[]string{"alpha", "beta"},
},
{
"alpha",
[]string{"alpha", "beta", "gamma"},
[]string{"alpha"},
},
{
"alpha,beta,gamma",
[]string{},
[]string{"alpha", "beta", "gamma"},
},
{
"alpha,beta",
[]string{},
[]string{"alpha", "beta"},
},
{
"alpha",
[]string{},
[]string{"alpha"},
},
// my reading of pt-spec.txt says that "*" has special meaning
// only when it is the entirety of the environment variable.
{
"alpha,*,gamma",
[]string{"alpha", "beta", "gamma"},
[]string{"alpha", "*", "gamma"},
},
{
"alpha",
[]string{"beta"},
[]string{"alpha"},
},
}
Stdout = ioutil.Discard
os.Clearenv()
_, err := getClientTransports([]string{"alpha", "beta", "gamma"})
if err == nil {
t.Errorf("empty environment unexpectedly succeeded")
}
for _, test := range tests {
os.Setenv("TOR_PT_CLIENT_TRANSPORTS", test.ptServerClientTransports)
output, err := getClientTransports(test.star)
if err != nil {
t.Errorf("TOR_PT_CLIENT_TRANSPORTS=%q unexpectedly returned an error: %s",
test.ptServerClientTransports, err)
}
if !stringSetsEqual(output, test.expected) {
t.Errorf("TOR_PT_CLIENT_TRANSPORTS=%q %q → %q (expected %q)",
test.ptServerClientTransports, test.star, output, test.expected)
}
}
}
func TestResolveAddr(t *testing.T) {
badTests := [...]string{
"",
"1.2.3.4",
"1.2.3.4:",
"9999",
":9999",
"[1:2::3:4]",
"[1:2::3:4]:",
"[1::2::3:4]",
"1:2::3:4::9999",
"1:2:3:4::9999",
"localhost:9999",
"[localhost]:9999",
"1.2.3.4:http",
"1.2.3.4:0x50",
"1.2.3.4:-65456",
"1.2.3.4:65536",
"1.2.3.4:80\x00",
"1.2.3.4:80 ",
" 1.2.3.4:80",
"1.2.3.4 : 80",
}
goodTests := [...]struct {
input string
expected net.TCPAddr
}{
{"1.2.3.4:9999", net.TCPAddr{IP: net.ParseIP("1.2.3.4"), Port: 9999}},
{"[1:2::3:4]:9999", net.TCPAddr{IP: net.ParseIP("1:2::3:4"), Port: 9999}},
{"1:2::3:4:9999", net.TCPAddr{IP: net.ParseIP("1:2::3:4"), Port: 9999}},
}
for _, input := range badTests {
output, err := resolveAddr(input)
if err == nil {
t.Errorf("%q unexpectedly succeeded: %q", input, output)
}
}
for _, test := range goodTests {
output, err := resolveAddr(test.input)
if err != nil {
t.Errorf("%q unexpectedly returned an error: %s", test.input, err)
}
if !tcpAddrsEqual(output, &test.expected) {
t.Errorf("%q → %q (expected %q)", test.input, output, test.expected)
}
}
}
func bindaddrSliceContains(s []Bindaddr, v Bindaddr) bool {
for _, sv := range s {
if sv.MethodName == v.MethodName && tcpAddrsEqual(sv.Addr, v.Addr) {
return true
}
}
return false
}
func bindaddrSetsEqual(a, b []Bindaddr) bool {
for _, v := range a {
if !bindaddrSliceContains(b, v) {
return false
}
}
for _, v := range b {
if !bindaddrSliceContains(a, v) {
return false
}
}
return true
}
func TestGetServerBindaddrs(t *testing.T) {
badTests := [...]struct {
ptServerBindaddr string
ptServerTransports string
ptServerTransportOptions string
star []string
}{
// bad TOR_PT_SERVER_BINDADDR
{
"alpha",
"alpha",
"",
[]string{"alpha", "beta", "gamma"},
},
{
"alpha-1.2.3.4",
"alpha",
"",
[]string{"alpha", "beta", "gamma"},
},
// missing TOR_PT_SERVER_TRANSPORTS
{
"alpha-1.2.3.4:1111",
"",
"alpha:key=value",
[]string{"alpha"},
},
// bad TOR_PT_SERVER_TRANSPORT_OPTIONS
{
"alpha-1.2.3.4:1111",
"alpha",
"key=value",
[]string{"alpha"},
},
}
goodTests := [...]struct {
ptServerBindaddr string
ptServerTransports string
ptServerTransportOptions string
star []string
expected []Bindaddr
}{
{
"alpha-1.2.3.4:1111,beta-[1:2::3:4]:2222",
"alpha,beta,gamma",
"alpha:k1=v1,beta:k2=v2,gamma:k3=v3",
[]string{"alpha", "beta"},
[]Bindaddr{
{"alpha", &net.TCPAddr{IP: net.ParseIP("1.2.3.4"), Port: 1111}, Args{"k1": []string{"v1"}}},
{"beta", &net.TCPAddr{IP: net.ParseIP("1:2::3:4"), Port: 2222}, Args{"k2": []string{"v2"}}},
},
},
{
"alpha-1.2.3.4:1111",
"xxx",
"",
[]string{"alpha", "beta", "gamma"},
[]Bindaddr{},
},
{
"alpha-1.2.3.4:1111",
"alpha,beta,gamma",
"",
[]string{},
[]Bindaddr{
{"alpha", &net.TCPAddr{IP: net.ParseIP("1.2.3.4"), Port: 1111}, Args{}},
},
},
{
"alpha-1.2.3.4:1111,beta-[1:2::3:4]:2222",
"*",
"",
[]string{"alpha", "beta"},
[]Bindaddr{
{"alpha", &net.TCPAddr{IP: net.ParseIP("1.2.3.4"), Port: 1111}, Args{}},
{"beta", &net.TCPAddr{IP: net.ParseIP("1:2::3:4"), Port: 2222}, Args{}},
},
},
{
"alpha-1.2.3.4:1111,beta-[1:2::3:4]:2222",
"*",
"",
[]string{"alpha", "gamma"},
[]Bindaddr{
{"alpha", &net.TCPAddr{IP: net.ParseIP("1.2.3.4"), Port: 1111}, Args{}},
},
},
{
"trebuchet-127.0.0.1:1984,ballista-127.0.0.1:4891",
"trebuchet,ballista",
"trebuchet:secret=nou;trebuchet:cache=/tmp/cache;ballista:secret=yes",
[]string{"trebuchet", "ballista"},
[]Bindaddr{
{"trebuchet", &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 1984}, Args{"secret": []string{"nou"}, "cache": []string{"/tmp/cache"}}},
{"ballista", &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 4891}, Args{"secret": []string{"yes"}}},
},
},
}
Stdout = ioutil.Discard
os.Clearenv()
_, err := getServerBindaddrs([]string{"alpha", "beta", "gamma"})
if err == nil {
t.Errorf("empty environment unexpectedly succeeded")
}
for _, test := range badTests {
os.Setenv("TOR_PT_SERVER_BINDADDR", test.ptServerBindaddr)
os.Setenv("TOR_PT_SERVER_TRANSPORTS", test.ptServerTransports)
os.Setenv("TOR_PT_SERVER_TRANSPORT_OPTIONS", test.ptServerTransportOptions)
_, err := getServerBindaddrs(test.star)
if err == nil {
t.Errorf("TOR_PT_SERVER_BINDADDR=%q TOR_PT_SERVER_TRANSPORTS=%q TOR_PT_SERVER_TRANSPORT_OPTIONS=%q %q unexpectedly succeeded",
test.ptServerBindaddr, test.ptServerTransports, test.ptServerTransportOptions, test.star)
}
}
for _, test := range goodTests {
os.Setenv("TOR_PT_SERVER_BINDADDR", test.ptServerBindaddr)
os.Setenv("TOR_PT_SERVER_TRANSPORTS", test.ptServerTransports)
os.Setenv("TOR_PT_SERVER_TRANSPORT_OPTIONS", test.ptServerTransportOptions)
output, err := getServerBindaddrs(test.star)
if err != nil {
t.Errorf("TOR_PT_SERVER_BINDADDR=%q TOR_PT_SERVER_TRANSPORTS=%q TOR_PT_SERVER_TRANSPORT_OPTIONS=%q %q unexpectedly returned an error: %s",
test.ptServerBindaddr, test.ptServerTransports, test.ptServerTransportOptions, test.star, err)
}
if !bindaddrSetsEqual(output, test.expected) {
t.Errorf("TOR_PT_SERVER_BINDADDR=%q TOR_PT_SERVER_TRANSPORTS=%q TOR_PT_SERVER_TRANSPORT_OPTIONS=%q %q → %q (expected %q)",
test.ptServerBindaddr, test.ptServerTransports, test.ptServerTransportOptions, test.star, output, test.expected)
}
}
}
func TestReadAuthCookie(t *testing.T) {
badTests := [...][]byte{
[]byte(""),
// bad header
[]byte("! Impostor ORPort Auth Cookie !\x0a0123456789ABCDEF0123456789ABCDEF"),
// too short
[]byte("! Extended ORPort Auth Cookie !\x0a0123456789ABCDEF0123456789ABCDE"),
// too long
[]byte("! Extended ORPort Auth Cookie !\x0a0123456789ABCDEF0123456789ABCDEFX"),
}
goodTests := [...][]byte{
[]byte("! Extended ORPort Auth Cookie !\x0a0123456789ABCDEF0123456789ABCDEF"),
}
for _, input := range badTests {
var buf bytes.Buffer
buf.Write(input)
_, err := readAuthCookie(&buf)
if err == nil {
t.Errorf("%q unexpectedly succeeded", input)
}
}
for _, input := range goodTests {
var buf bytes.Buffer
buf.Write(input)
cookie, err := readAuthCookie(&buf)
if err != nil {
t.Errorf("%q unexpectedly returned an error: %s", input, err)
}
if !bytes.Equal(cookie, input[32:64]) {
t.Errorf("%q → %q (expected %q)", input, cookie, input[:32])
}
}
}
func TestComputeServerHash(t *testing.T) {
authCookie := make([]byte, 32)
clientNonce := make([]byte, 32)
serverNonce := make([]byte, 32)
// hmac.new("\x00"*32, "ExtORPort authentication server-to-client hash" + "\x00"*64, hashlib.sha256).hexdigest()
expected := []byte("\x9e\x22\x19\x19\x98\x2a\x84\xf7\x5f\xaf\x60\xef\x92\x69\x49\x79\x62\x68\xc9\x78\x33\xe0\x69\x60\xff\x26\x53\x69\xa9\x0f\xd6\xd8")
hash := computeServerHash(authCookie, clientNonce, serverNonce)
if !bytes.Equal(hash, expected) {
t.Errorf("%x %x %x → %x (expected %x)", authCookie,
clientNonce, serverNonce, hash, expected)
}
}
func TestComputeClientHash(t *testing.T) {
authCookie := make([]byte, 32)
clientNonce := make([]byte, 32)
serverNonce := make([]byte, 32)
// hmac.new("\x00"*32, "ExtORPort authentication client-to-server hash" + "\x00"*64, hashlib.sha256).hexdigest()
expected := []byte("\x0f\x36\x8b\x1b\xee\x24\xaa\xbc\x54\xa9\x11\x4c\xe0\x6c\x07\x0f\x3e\xd9\x9d\x0d\x36\x8f\x59\x9c\xcc\x6d\xfd\xc8\xbf\x45\x7a\x62")
hash := computeClientHash(authCookie, clientNonce, serverNonce)
if !bytes.Equal(hash, expected) {
t.Errorf("%x %x %x → %x (expected %x)", authCookie,
clientNonce, serverNonce, hash, expected)
}
}
// Elide a byte slice in case it's really long.
func fmtBytes(s []byte) string {
if len(s) > 100 {
return fmt.Sprintf("%q...(%d bytes)", s[:5], len(s))
} else {
return fmt.Sprintf("%q", s)
}
}
func TestExtOrSendCommand(t *testing.T) {
badTests := [...]struct {
cmd uint16
body []byte
}{
{0x0, make([]byte, 65536)},
{0x1234, make([]byte, 65536)},
}
longBody := [65535 + 2 + 2]byte{0x12, 0x34, 0xff, 0xff}
goodTests := [...]struct {
cmd uint16
body []byte
expected []byte
}{
{0x0, []byte(""), []byte("\x00\x00\x00\x00")},
{0x5, []byte(""), []byte("\x00\x05\x00\x00")},
{0xfffe, []byte(""), []byte("\xff\xfe\x00\x00")},
{0xffff, []byte(""), []byte("\xff\xff\x00\x00")},
{0x1234, []byte("hello"), []byte("\x12\x34\x00\x05hello")},
{0x1234, make([]byte, 65535), longBody[:]},
}
for _, test := range badTests {
var buf bytes.Buffer
err := extOrPortSendCommand(&buf, test.cmd, test.body)
if err == nil {
t.Errorf("0x%04x %s unexpectedly succeeded", test.cmd, fmtBytes(test.body))
}
}
for _, test := range goodTests {
var buf bytes.Buffer
err := extOrPortSendCommand(&buf, test.cmd, test.body)
if err != nil {
t.Errorf("0x%04x %s unexpectedly returned an error: %s", test.cmd, fmtBytes(test.body), err)
}
p := make([]byte, 65535+2+2)
n, err := buf.Read(p)
if err != nil {
t.Fatal(err)
}
output := p[:n]
if !bytes.Equal(output, test.expected) {
t.Errorf("0x%04x %s → %s (expected %s)", test.cmd, fmtBytes(test.body),
fmtBytes(output), fmtBytes(test.expected))
}
}
}
func TestExtOrSendUserAddr(t *testing.T) {
addrs := [...]string{
"0.0.0.0:0",
"1.2.3.4:9999",
"255.255.255.255:65535",
"[::]:0",
"[ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255]:63335",
}
for _, addr := range addrs {
var buf bytes.Buffer
err := extOrPortSendUserAddr(&buf, addr)
if err != nil {
t.Errorf("%s unexpectedly returned an error: %s", addr, err)
}
var cmd, length uint16
binary.Read(&buf, binary.BigEndian, &cmd)
if cmd != extOrCmdUserAddr {
t.Errorf("%s → cmd 0x%04x (expected 0x%04x)", addr, cmd, extOrCmdUserAddr)
}
binary.Read(&buf, binary.BigEndian, &length)
p := make([]byte, length+1)
n, err := buf.Read(p)
if n != int(length) {
t.Errorf("%s said length %d but had at least %d", addr, length, n)
}
// test that parsing the address gives something equivalent to
// parsing the original.
inputAddr, err := resolveAddr(addr)
if err != nil {
t.Fatal(err)
}
outputAddr, err := resolveAddr(string(p[:n]))
if err != nil {
t.Fatal(err)
}
if !tcpAddrsEqual(inputAddr, outputAddr) {
t.Errorf("%s → %s", addr, outputAddr)
}
}
}
func TestExtOrPortSendTransport(t *testing.T) {
tests := [...]struct {
methodName string
expected []byte
}{
{"", []byte("\x00\x02\x00\x00")},
{"a", []byte("\x00\x02\x00\x01a")},
{"alpha", []byte("\x00\x02\x00\x05alpha")},
}
for _, test := range tests {
var buf bytes.Buffer
err := extOrPortSendTransport(&buf, test.methodName)
if err != nil {
t.Errorf("%q unexpectedly returned an error: %s", test.methodName, err)
}
p := make([]byte, 1024)
n, err := buf.Read(p)
if err != nil {
t.Fatal(err)
}
output := p[:n]
if !bytes.Equal(output, test.expected) {
t.Errorf("%q → %s (expected %s)", test.methodName,
fmtBytes(output), fmtBytes(test.expected))
}
}
}
func TestExtOrPortSendDone(t *testing.T) {
expected := []byte("\x00\x00\x00\x00")
var buf bytes.Buffer
err := extOrPortSendDone(&buf)
if err != nil {
t.Errorf("unexpectedly returned an error: %s", err)
}
p := make([]byte, 1024)
n, err := buf.Read(p)
if err != nil {
t.Fatal(err)
}
output := p[:n]
if !bytes.Equal(output, expected) {
t.Errorf("→ %s (expected %s)", fmtBytes(output), fmtBytes(expected))
}
}
func TestExtOrPortRecvCommand(t *testing.T) {
badTests := [...][]byte{
[]byte(""),
[]byte("\x12"),
[]byte("\x12\x34"),
[]byte("\x12\x34\x00"),
[]byte("\x12\x34\x00\x01"),
}
goodTests := [...]struct {
input []byte
cmd uint16
body []byte
leftover []byte
}{
{
[]byte("\x12\x34\x00\x00"),
0x1234, []byte(""), []byte(""),
},
{
[]byte("\x12\x34\x00\x00more"),
0x1234, []byte(""), []byte("more"),
},
{
[]byte("\x12\x34\x00\x04body"),
0x1234, []byte("body"), []byte(""),
},
{
[]byte("\x12\x34\x00\x04bodymore"),
0x1234, []byte("body"), []byte("more"),
},
}
for _, input := range badTests {
var buf bytes.Buffer
buf.Write(input)
_, _, err := extOrPortRecvCommand(&buf)
if err == nil {
t.Errorf("%q unexpectedly succeeded", fmtBytes(input))
}
}
for _, test := range goodTests {
var buf bytes.Buffer
buf.Write(test.input)
cmd, body, err := extOrPortRecvCommand(&buf)
if err != nil {
t.Errorf("%s unexpectedly returned an error: %s", fmtBytes(test.input), err)
}
if cmd != test.cmd {
t.Errorf("%s → cmd 0x%04x (expected 0x%04x)", fmtBytes(test.input), cmd, test.cmd)
}
if !bytes.Equal(body, test.body) {
t.Errorf("%s → body %s (expected %s)", fmtBytes(test.input),
fmtBytes(body), fmtBytes(test.body))
}
p := make([]byte, 1024)
n, err := buf.Read(p)
if err != nil && err != io.EOF {
t.Fatal(err)
}
leftover := p[:n]
if !bytes.Equal(leftover, test.leftover) {
t.Errorf("%s → leftover %s (expected %s)", fmtBytes(test.input),
fmtBytes(leftover), fmtBytes(test.leftover))
}
}
}
// set up so that extOrPortSetup can write to one buffer and read from another.
type MockSetupBuf struct {
bytes.Buffer
ReadBuf bytes.Buffer
}
func (buf *MockSetupBuf) Read(p []byte) (int, error) {
n, err := buf.ReadBuf.Read(p)
return n, err
}
func testExtOrPortSetupIndividual(t *testing.T, addr, methodName string) {
var err error
var buf MockSetupBuf
// fake an OKAY response.
err = extOrPortSendCommand(&buf.ReadBuf, extOrCmdOkay, []byte{})
if err != nil {
t.Fatal(err)
}
err = extOrPortSetup(&buf, addr, methodName)
if err != nil {
t.Fatalf("error in extOrPortSetup: %s", err)
}
for {
cmd, body, err := extOrPortRecvCommand(&buf.Buffer)
if err != nil {
t.Fatalf("error in extOrPortRecvCommand: %s", err)
}
if cmd == extOrCmdDone {
break
}
if addr != "" && cmd == extOrCmdUserAddr {
if string(body) != addr {
t.Errorf("addr=%q methodName=%q got USERADDR with body %q (expected %q)", addr, methodName, body, addr)
}
continue
}
if methodName != "" && cmd == extOrCmdTransport {
if string(body) != methodName {
t.Errorf("addr=%q methodName=%q got TRANSPORT with body %q (expected %q)", addr, methodName, body, methodName)
}
continue
}
t.Errorf("addr=%q methodName=%q got unknown cmd %d body %q", addr, methodName, cmd, body)
}
}
func TestExtOrPortSetup(t *testing.T) {
const addr = "127.0.0.1:40000"
const methodName = "alpha"
testExtOrPortSetupIndividual(t, "", "")
testExtOrPortSetupIndividual(t, addr, "")
testExtOrPortSetupIndividual(t, "", methodName)
testExtOrPortSetupIndividual(t, addr, methodName)
}
func TestMakeStateDir(t *testing.T) {
os.Clearenv()
// TOR_PT_STATE_LOCATION not set.
_, err := MakeStateDir()
if err == nil {
t.Errorf("empty environment unexpectedly succeeded")
}
// Setup the scratch directory.
tempDir, err := ioutil.TempDir(".", "testMakeStateDir")
if err != nil {
t.Fatalf("ioutil.TempDir failed: %s", err)
}
defer os.RemoveAll(tempDir)
goodTests := [...]string{
// Already existing directory.
tempDir,
// Nonexistent directory, parent exists.
path.Join(tempDir, "parentExists"),
// Nonexistent directory, parent doesn't exist.
path.Join(tempDir, "missingParent", "parentMissing"),
}
for _, test := range goodTests {
os.Setenv("TOR_PT_STATE_LOCATION", test)
dir, err := MakeStateDir()
if err != nil {
t.Errorf("MakeStateDir unexpectedly failed: %s", err)
}
if dir != test {
t.Errorf("MakeStateDir returned an unexpected path %s (expecting %s)", dir, test)
}
}
// Name already exists, but is an ordinary file.
tempFile := path.Join(tempDir, "file")
f, err := os.Create(tempFile)
if err != nil {
t.Fatalf("os.Create failed: %s", err)
}
defer f.Close()
os.Setenv("TOR_PT_STATE_LOCATION", tempFile)
_, err = MakeStateDir()
if err == nil {
t.Errorf("MakeStateDir with a file unexpectedly succeded")
}
// Directory name that cannot be created. (Subdir of a file)
os.Setenv("TOR_PT_STATE_LOCATION", path.Join(tempFile, "subDir"))
_, err = MakeStateDir()
if err == nil {
t.Errorf("MakeStateDir with a subdirectory of a file unexpectedly succeded")
}
}