~fnux/yggdrasil-go-coap

ref: e042d7baf5169b5c24e7261d57260a87506cb2db yggdrasil-go-coap/server_test.go -rw-r--r-- 23.4 KiB
e042d7ba — Jozef Kralik fix sending message when peerMaxMessageSize is not set 2 years ago
                                                                                
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 coap

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/binary"
	"fmt"
	"io"
	"log"
	"net"
	"strings"
	"sync"
	"testing"
	"time"

	kitNet "github.com/go-ocf/kit/net"
)

func CreateRespMessageByReq(isTCP bool, code COAPCode, req Message) Message {
	if isTCP {
		resp := &TcpMessage{
			MessageBase{
				//typ:       Acknowledgement, not used by COAP over TCP
				code: code,
				//messageID: req.MessageID(), , not used by COAP over TCP
				payload: req.Payload(),
				token:   req.Token(),
			},
		}
		resp.SetPath(req.Path())
		resp.SetOption(ContentFormat, req.Option(ContentFormat))
		return resp
	}
	resp := &DgramMessage{
		MessageBase{
			typ:       Acknowledgement,
			code:      code,
			messageID: req.MessageID(),
			payload:   req.Payload(),
			token:     req.Token(),
		},
	}
	resp.SetPath(req.Path())
	resp.SetOption(ContentFormat, req.Option(ContentFormat))
	return resp
}

func EchoServer(w ResponseWriter, r *Request) {
	if r.Msg.IsConfirmable() {
		err := w.WriteMsg(CreateRespMessageByReq(r.Client.networkSession().IsTCP(), Valid, r.Msg))
		if err != nil {
			log.Printf("Cannot write echo %v", err)
		}
	}
}

func EchoServerBadID(w ResponseWriter, r *Request) {
	if r.Msg.IsConfirmable() {
		w.WriteMsg(CreateRespMessageByReq(r.Client.networkSession().IsTCP(), BadRequest, r.Msg))
	}
}

func RunLocalServerUDPWithHandler(lnet, laddr string, BlockWiseTransfer bool, BlockWiseTransferSzx BlockWiseSzx, handler HandlerFunc) (*Server, string, chan error, error) {
	network := strings.TrimSuffix(lnet, "-mcast")

	a, err := net.ResolveUDPAddr(network, laddr)
	if err != nil {
		return nil, "", nil, err
	}
	var pc *net.UDPConn
	if strings.Contains(lnet, "-mcast") {
		pc, err = net.ListenMulticastUDP(network, nil, a)
	} else {
		pc, err = net.ListenUDP(network, a)
	}
	if err != nil {
		return nil, "", nil, err
	}
	server := &Server{Conn: pc, ReadTimeout: time.Hour, WriteTimeout: time.Hour,
		NotifySessionNewFunc: func(s *ClientConn) {
			fmt.Printf("networkSession start %v\n", s.RemoteAddr())
		},
		NotifySessionEndFunc: func(w *ClientConn, err error) {
			fmt.Printf("networkSession end %v: %v\n", w.RemoteAddr(), err)
		},
		Handler:              handler,
		BlockWiseTransfer:    &BlockWiseTransfer,
		BlockWiseTransferSzx: &BlockWiseTransferSzx,
	}

	waitLock := sync.Mutex{}
	waitLock.Lock()
	server.NotifyStartedFunc = waitLock.Unlock

	// fin must be buffered so the goroutine below won't block
	// forever if fin is never read from. This always happens
	// in RunLocalUDPServer and can happen in TestShutdownUDP.
	fin := make(chan error, 1)

	go func() {
		fin <- server.ActivateAndServe()
		pc.Close()
	}()

	waitLock.Lock()
	return server, pc.LocalAddr().String(), fin, nil
}

func RunLocalUDPServer(net, laddr string, BlockWiseTransfer bool, BlockWiseTransferSzx BlockWiseSzx) (*Server, string, chan error, error) {
	return RunLocalServerUDPWithHandler(net, laddr, BlockWiseTransfer, BlockWiseTransferSzx, nil)
}

func RunLocalServerTCPWithHandler(laddr string, BlockWiseTransfer bool, BlockWiseTransferSzx BlockWiseSzx, handler HandlerFunc) (*Server, string, chan error, error) {
	network := "tcp"
	l, err := kitNet.NewTCPListener(network, laddr, time.Millisecond*100)
	if err != nil {
		return nil, "", nil, fmt.Errorf("cannot create new tls listener: %v", err)
	}

	server := &Server{Listener: l, ReadTimeout: time.Second * 3600, WriteTimeout: time.Second * 3600,
		NotifySessionNewFunc: func(s *ClientConn) {
			fmt.Printf("networkSession start %v\n", s.RemoteAddr())
		}, NotifySessionEndFunc: func(w *ClientConn, err error) {
			fmt.Printf("networkSession end %v: %v\n", w.RemoteAddr(), err)
		}, Handler: handler,
		BlockWiseTransfer:    &BlockWiseTransfer,
		BlockWiseTransferSzx: &BlockWiseTransferSzx,
		MaxMessageSize:       ^uint32(0),
	}

	waitLock := sync.Mutex{}
	waitLock.Lock()
	server.NotifyStartedFunc = waitLock.Unlock

	// See the comment in RunLocalUDPServerWithFinChan as to
	// why fin must be buffered.
	fin := make(chan error, 1)

	go func() {
		fin <- server.ActivateAndServe()
		l.Close()
	}()

	waitLock.Lock()
	return server, l.Addr().String(), fin, nil
}

func RunLocalTCPServer(laddr string, BlockWiseTransfer bool, BlockWiseTransferSzx BlockWiseSzx) (*Server, string, chan error, error) {
	return RunLocalServerTCPWithHandler(laddr, BlockWiseTransfer, BlockWiseTransferSzx, nil)
}

func RunLocalTLSServer(laddr string, config *tls.Config) (*Server, string, chan error, error) {
	l, err := kitNet.NewTLSListener("tcp", laddr, config, time.Millisecond*100)
	if err != nil {
		return nil, "", nil, err
	}

	server := &Server{Listener: l, ReadTimeout: time.Hour, WriteTimeout: time.Hour,
		NotifySessionNewFunc: func(s *ClientConn) {
			fmt.Printf("networkSession start %v\n", s.RemoteAddr())
		}, NotifySessionEndFunc: func(w *ClientConn, err error) {
			fmt.Printf("networkSession end %v: %v\n", w.RemoteAddr(), err)
		},
		MaxMessageSize: ^uint32(0),
	}

	// fin must be buffered so the goroutine below won't block
	// forever if fin is never read from. This always happens
	// in RunLocalUDPServer and can happen in TestShutdownUDP.
	fin := make(chan error, 1)

	go func() {
		fin <- server.ActivateAndServe()
		l.Close()
	}()

	return server, l.Addr().String(), fin, nil
}

type clientHandler func(t *testing.T, payload []byte, co *ClientConn)

func testServingTCPWithMsgWithObserver(t *testing.T, net string, BlockWiseTransfer bool, BlockWiseTransferSzx BlockWiseSzx, payload []byte, ch clientHandler, observeFunc HandlerFunc) {
	HandleFunc("/test", EchoServer)
	defer HandleRemove("/test")

	var s *Server
	var addrstr string
	var err error
	c := &Client{
		Net:                  net,
		Handler:              observeFunc,
		BlockWiseTransfer:    &BlockWiseTransfer,
		BlockWiseTransferSzx: &BlockWiseTransferSzx,
		MaxMessageSize:       ^uint32(0),
	}
	var fin chan error
	switch net {
	case "tcp", "tcp4", "tcp6":
		s, addrstr, fin, err = RunLocalTCPServer(":0", BlockWiseTransfer, BlockWiseTransferSzx)
	case "udp", "udp4", "udp6":
		s, addrstr, fin, err = RunLocalUDPServer(net, ":0", BlockWiseTransfer, BlockWiseTransferSzx)
	case "tcp-tls", "tcp4-tls", "tcp6-tls":
		cert, err := tls.X509KeyPair(CertPEMBlock, KeyPEMBlock)
		if err != nil {
			t.Fatalf("unable to build certificate: %v", err)
		}
		config := tls.Config{
			Certificates: []tls.Certificate{cert},
		}
		s, addrstr, fin, err = RunLocalTLSServer(":0", &config)
		if err != nil {
			t.Fatalf("unable to run test server: %v", err)
		}
		c.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	}

	if err != nil {
		t.Fatalf("unable to run test server: %v", err)
	}
	defer func() {
		s.Shutdown()
		<-fin
	}()

	co, err := c.Dial(addrstr)
	if err != nil {
		t.Fatalf("unable to dialing: %v", err)
	}
	defer co.Close()

	ch(t, payload, co)
}

func simpleMsgToPath(t *testing.T, payload []byte, co *ClientConn, path string) {
	req, err := co.NewPostRequest(path, TextPlain, bytes.NewBuffer(payload))
	if err != nil {
		t.Fatal("cannot create request", err)
	}

	res := CreateRespMessageByReq(co.commander.networkSession.IsTCP(), Valid, req)

	m, err := co.Exchange(req)
	if err != nil {
		t.Fatal("failed to exchange", err)
	}
	if m == nil {
		t.Fatalf("Didn't receive CoAP response")
	}
	assertEqualMessages(t, res, m)
}

func simpleMsg(t *testing.T, payload []byte, co *ClientConn) {
	simpleMsgToPath(t, payload, co, "/test")
}

func pingMsg(t *testing.T, payload []byte, co *ClientConn) {
	err := co.Ping(3600 * time.Second)
	if err != nil {
		t.Fatal("failed to exchange", err)
	}
}

func testServingTCPWithMsg(t *testing.T, net string, BlockWiseTransfer bool, BlockWiseTransferSzx BlockWiseSzx, payload []byte, ch clientHandler) {
	testServingTCPWithMsgWithObserver(t, net, BlockWiseTransfer, BlockWiseTransferSzx, payload, ch, nil)
}

func TestServingUDP(t *testing.T) {
	testServingTCPWithMsg(t, "udp", false, BlockWiseSzx16, make([]byte, 128), simpleMsg)
}

func TestServingUDPPing(t *testing.T) {

	testServingTCPWithMsg(t, "udp", false, BlockWiseSzx16, nil, pingMsg)
}

func TestServingTCPPing(t *testing.T) {
	testServingTCPWithMsg(t, "tcp", false, BlockWiseSzx16, nil, pingMsg)
}

func TestServingUDPBigMsg(t *testing.T) {
	testServingTCPWithMsg(t, "udp", false, BlockWiseSzx16, make([]byte, 1024), simpleMsg)
}

func TestServingTCP(t *testing.T) {
	testServingTCPWithMsg(t, "tcp", false, BlockWiseSzx16, make([]byte, 128), simpleMsg)
}

func TestServingTCPBigMsg(t *testing.T) {
	testServingTCPWithMsg(t, "tcp", false, BlockWiseSzx16, make([]byte, 10*1024*1024), simpleMsg)
}

func TestServingTLS(t *testing.T) {
	testServingTCPWithMsg(t, "tcp-tls", false, BlockWiseSzx16, make([]byte, 128), simpleMsg)
}

func TestServingTLSBigMsg(t *testing.T) {
	testServingTCPWithMsg(t, "tcp-tls", false, BlockWiseSzx16, make([]byte, 10*1024*1024), simpleMsg)
}

func ChallegingServer(w ResponseWriter, r *Request) {
	_, err := r.Client.Post("/test", TextPlain, bytes.NewBuffer([]byte("hello, world!")))
	if err != nil {
		panic(err.Error())
	}

	w.WriteMsg(CreateRespMessageByReq(r.Client.networkSession().IsTCP(), Valid, r.Msg))
}

func ChallegingServerTimeout(w ResponseWriter, r *Request) {
	req := r.Client.NewMessage(MessageParams{
		Type:      Confirmable,
		Code:      GET,
		MessageID: 12345,
		Payload:   []byte("hello, world!"),
		Token:     []byte("abcd"),
	})
	req.SetOption(ContentFormat, TextPlain)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	_, err := r.Client.networkSession().ExchangeWithContext(ctx, req)
	if err == nil {
		panic("Error: expected timeout")
	}

	w.WriteMsg(CreateRespMessageByReq(r.Client.networkSession().IsTCP(), Valid, r.Msg))
}

func simpleChallengingMsg(t *testing.T, payload []byte, co *ClientConn) {
	simpleChallengingPathMsg(t, payload, co, "/challenging", false)
}

func simpleChallengingTimeoutMsg(t *testing.T, payload []byte, co *ClientConn) {
	simpleChallengingPathMsg(t, payload, co, "/challengingTimeout", true)
}

func simpleChallengingPathMsg(t *testing.T, payload []byte, co *ClientConn, path string, testTimeout bool) {
	req0 := co.NewMessage(MessageParams{
		Type:      Confirmable,
		Code:      POST,
		MessageID: 1234,
		Payload:   payload,
		Token:     []byte("chall"),
	},
	)
	req0.SetOption(ContentFormat, TextPlain)
	req0.SetPathString(path)

	resp0, err := co.Exchange(req0)
	if err != nil {
		t.Fatalf("unable to read msg from server: %v", err)
	}

	res := CreateRespMessageByReq(co.commander.networkSession.IsTCP(), Valid, req0)
	assertEqualMessages(t, res, resp0)
}

func TestServingChallengingClient(t *testing.T) {
	HandleFunc("/challenging", ChallegingServer)
	defer HandleRemove("/challenging")
	testServingTCPWithMsg(t, "udp", false, BlockWiseSzx16, make([]byte, 128), simpleChallengingMsg)
}

func TestServingChallengingClientTCP(t *testing.T) {
	HandleFunc("/challenging", ChallegingServer)
	defer HandleRemove("/challenging")
	testServingTCPWithMsg(t, "tcp", false, BlockWiseSzx16, make([]byte, 128), simpleChallengingMsg)
}

func TestServingChallengingClientTLS(t *testing.T) {
	HandleFunc("/challenging", ChallegingServer)
	defer HandleRemove("/challenging")
	testServingTCPWithMsg(t, "tcp-tls", false, BlockWiseSzx16, make([]byte, 128), simpleChallengingMsg)
}

func TestServingChallengingTimeoutClient(t *testing.T) {
	HandleFunc("/challengingTimeout", ChallegingServerTimeout)
	defer HandleRemove("/challengingTimeout")
	testServingTCPWithMsgWithObserver(t, "udp", false, BlockWiseSzx16, make([]byte, 128), simpleChallengingTimeoutMsg, func(w ResponseWriter, r *Request) {
		//for timeout
		time.Sleep(2 * time.Second)
	})
}

func TestServingChallengingTimeoutClientTCP(t *testing.T) {
	HandleFunc("/challengingTimeout", ChallegingServerTimeout)
	defer HandleRemove("/challengingTimeout")
	testServingTCPWithMsgWithObserver(t, "tcp", false, BlockWiseSzx16, make([]byte, 128), simpleChallengingTimeoutMsg, func(w ResponseWriter, r *Request) {
		//for timeout
		time.Sleep(2 * time.Second)
	})
}

func TestServingChallengingTimeoutClientTLS(t *testing.T) {
	HandleFunc("/challengingTimeout", ChallegingServerTimeout)
	defer HandleRemove("/challengingTimeout")
	testServingTCPWithMsgWithObserver(t, "tcp-tls", false, BlockWiseSzx16, make([]byte, 128), simpleChallengingTimeoutMsg, func(w ResponseWriter, r *Request) {
		//for timeout
		time.Sleep(2 * time.Second)
	})
}

func testServingMCast(t *testing.T, lnet, laddr string, BlockWiseTransfer bool, BlockWiseTransferSzx BlockWiseSzx, payloadLen int) {
	addrMcast := laddr
	ansArrived := make(chan bool)

	responseServerConn := make([]*ClientConn, 0)
	var lockResponseServerConn sync.Mutex
	responseServer := Client{
		Net:                  strings.Trim(lnet, "-mcast"),
		BlockWiseTransfer:    &BlockWiseTransfer,
		BlockWiseTransferSzx: &BlockWiseTransferSzx,
		Handler: func(w ResponseWriter, r *Request) {
			resp := w.NewResponse(Content)
			resp.SetPayload(make([]byte, payloadLen))
			resp.SetOption(ContentFormat, TextPlain)
			err := w.WriteMsg(resp)
			if err != nil {
				t.Fatalf("cannot send response %v", err)
			}
		},
	}

	s, _, fin, err := RunLocalServerUDPWithHandler(lnet, addrMcast, BlockWiseTransfer, BlockWiseTransferSzx, func(w ResponseWriter, r *Request) {
		resp := w.NewResponse(Content)
		resp.SetPayload(make([]byte, payloadLen))
		resp.SetOption(ContentFormat, TextPlain)
		conn, err := responseServer.Dial(r.Client.RemoteAddr().String())
		if err != nil {
			t.Fatalf("cannot create connection %v", err)
		}
		err = conn.WriteMsg(resp)
		if err != nil {
			t.Fatalf("cannot send response %v", err)
		}
		lockResponseServerConn.Lock()
		responseServerConn = append(responseServerConn, conn)
		lockResponseServerConn.Unlock()
	})
	if err != nil {
		t.Fatalf("unable to run test server: %v", err)
	}
	defer func() {
		s.Shutdown()
		lockResponseServerConn.Lock()
		for _, conn := range responseServerConn {
			conn.Close()
		}
		lockResponseServerConn.Unlock()
		<-fin
	}()

	c := MulticastClient{
		Net:                  strings.TrimSuffix(lnet, "-mcast"),
		BlockWiseTransfer:    &BlockWiseTransfer,
		BlockWiseTransferSzx: &BlockWiseTransferSzx,
	}

	co, err := c.Dial(addrMcast)
	if err != nil {
		t.Fatalf("unable to dialing: %v", err)
	}
	defer co.Close()

	rp, err := co.Publish("/test", func(req *Request) {
		ansArrived <- true
	})
	if err != nil {
		t.Fatalf("unable to publishing: %v", err)
	}
	defer rp.Cancel()

	<-ansArrived
}

func TestServingIPv4MCast(t *testing.T) {
	testServingMCast(t, "udp4-mcast", "225.0.1.187:11111", false, BlockWiseSzx16, 16)
}

func TestServingIPv6MCast(t *testing.T) {
	testServingMCast(t, "udp6-mcast", "[ff03::158]:11111", false, BlockWiseSzx16, 16)
}

func TestServingRootPath(t *testing.T) {
	HandleFunc("/", EchoServer)
	defer HandleRemove("/")
	testServingTCPWithMsg(t, "udp", false, BlockWiseSzx16, make([]byte, 128), func(t *testing.T, payload []byte, co *ClientConn) {
		simpleMsgToPath(t, payload, co, "/")
	})
	testServingTCPWithMsg(t, "udp", false, BlockWiseSzx16, make([]byte, 128), func(t *testing.T, payload []byte, co *ClientConn) {
		simpleMsgToPath(t, payload, co, "")
	})
}

func TestServingEmptyRootPath(t *testing.T) {
	HandleFunc("", EchoServer)
	defer HandleRemove("")
	testServingTCPWithMsg(t, "udp", false, BlockWiseSzx16, make([]byte, 128), func(t *testing.T, payload []byte, co *ClientConn) {
		simpleMsgToPath(t, payload, co, "/")
	})
	testServingTCPWithMsg(t, "udp", false, BlockWiseSzx16, make([]byte, 128), func(t *testing.T, payload []byte, co *ClientConn) {
		simpleMsgToPath(t, payload, co, "")
	})
}

type dataReader struct {
	data   []byte
	offset int
}

func (r *dataReader) Read(p []byte) (n int, err error) {
	l := len(p)
	if (len(r.data) - r.offset) < l {
		l = len(r.data) - r.offset
	}
	if l != 0 {
		copy(p, r.data[r.offset:r.offset+l])
		r.offset += l
	} else {
		return 0, io.EOF
	}
	return l, nil
}

func BenchmarkServe(b *testing.B) {
	b.StopTimer()
	HandleFunc("/test", EchoServer)
	defer HandleRemove("/test")

	BlockWiseTransfer := false
	BlockWiseTransferSzx := BlockWiseSzx1024

	s, addrstr, fin, err := RunLocalUDPServer("udp", ":0", BlockWiseTransfer, BlockWiseTransferSzx)
	if err != nil {
		b.Fatalf("unable to run test server: %v", err)
	}
	defer func() {
		s.Shutdown()
		<-fin
	}()

	client := Client{
		Net:                  "udp",
		BlockWiseTransfer:    &BlockWiseTransfer,
		BlockWiseTransferSzx: &BlockWiseTransferSzx,
		MaxMessageSize:       ^uint32(0),
	}
	co, err := client.Dial(addrstr)
	if err != nil {
		b.Fatalf("unable to dialing: %v", err)
	}
	defer co.Close()

	data := []byte("Content sent by client")
	b.StartTimer()
	for i := uint32(0); i < uint32(b.N); i++ {
		_, err := co.Post("/test", TextPlain, &dataReader{data: data})
		if err != nil {
			b.Fatalf("unable to read msg from server: %v", err)
		}
	}
}

func BenchmarkServeBlockWise(b *testing.B) {
	b.StopTimer()
	HandleFunc("/test", EchoServer)
	defer HandleRemove("/test")

	BlockWiseTransfer := true
	BlockWiseTransferSzx := BlockWiseSzx16

	s, addrstr, fin, err := RunLocalUDPServer("udp", ":0", BlockWiseTransfer, BlockWiseSzx1024)
	if err != nil {
		b.Fatalf("unable to run test server: %v", err)
	}
	defer func() {
		s.Shutdown()
		<-fin
	}()

	client := Client{
		Net:                  "udp",
		BlockWiseTransfer:    &BlockWiseTransfer,
		BlockWiseTransferSzx: &BlockWiseTransferSzx,
		MaxMessageSize:       ^uint32(0),
	}
	co, err := client.Dial(addrstr)
	if err != nil {
		b.Fatalf("unable to dialing: %v", err)
	}
	defer co.Close()

	data := make([]byte, 128)
	b.StartTimer()
	for i := uint32(0); i < uint32(b.N); i++ {
		_, err := co.Post("/test", TextPlain, &dataReader{data: data})
		if err != nil {
			b.Fatalf("unable to read msg from server: %v", err)
		}
	}
}

func BenchmarkServeTCP(b *testing.B) {
	b.StopTimer()
	HandleFunc("/test", EchoServer)
	defer HandleRemove("/test")

	s, addrstr, fin, err := RunLocalTCPServer(":0", false, BlockWiseSzx16)
	if err != nil {
		b.Fatalf("unable to run test server: %v", err)
	}
	defer func() {
		s.Shutdown()
		<-fin
	}()

	co, err := Dial("tcp", addrstr)
	if err != nil {
		b.Fatalf("unable dialing: %v", err)
	}
	defer co.Close()

	data := make([]byte, ^uint16(0))
	b.StartTimer()
	for i := uint32(0); i < uint32(b.N); i++ {
		_, err := co.Post("/test", TextPlain, &dataReader{data: data})
		if err != nil {
			b.Fatalf("unable to read msg from server: %v", err)
		}
	}
}

func BenchmarkServeTCPBlockwise(b *testing.B) {
	b.StopTimer()
	HandleFunc("/test", EchoServer)
	defer HandleRemove("/test")

	BlockWiseTransfer := true
	BlockWiseTransferSzx := BlockWiseSzxBERT

	s, addrstr, fin, err := RunLocalTCPServer(":0", BlockWiseTransfer, BlockWiseTransferSzx)
	if err != nil {
		b.Fatalf("unable to run test server: %v", err)
	}
	defer func() {
		s.Shutdown()
		<-fin
	}()

	client := Client{
		Net:                  "tcp",
		BlockWiseTransfer:    &BlockWiseTransfer,
		BlockWiseTransferSzx: &BlockWiseTransferSzx,
		MaxMessageSize:       ^uint32(0),
	}
	co, err := client.Dial(addrstr)
	if err != nil {
		b.Fatalf("unable dialing: %v", err)
	}
	defer co.Close()

	data := make([]byte, ^uint16(0))
	b.StartTimer()
	for i := uint32(0); i < uint32(b.N); i++ {
		_, err := co.Post("/test", TextPlain, &dataReader{data: data})
		if err != nil {
			b.Fatalf("unable to read msg from server: %v", err)
		}
	}
}

func benchmarkServeTCPStreamWithMsg(b *testing.B, req *TcpMessage) {
	b.StopTimer()
	HandleFunc("/test", EchoServer)
	defer HandleRemove("/test")

	s, addrstr, fin, err := RunLocalTCPServer(":0", false, BlockWiseSzx16)
	if err != nil {
		b.Fatalf("unable to run test server: %v", err)
	}
	defer func() {
		s.Shutdown()
		<-fin
	}()

	co, err := Dial("tcp", addrstr)
	if err != nil {
		b.Fatalf("unable dialing: %v", err)
	}
	defer co.Close()
	res := CreateRespMessageByReq(true, Valid, req)

	b.StartTimer()
	sync := make(chan bool)

	for i := uint32(0); i < uint32(b.N); i++ {
		go func(t uint32) {
			abc := *req
			token := make([]byte, 8)
			binary.LittleEndian.PutUint32(token, t)
			abc.SetToken(token)
			resp, err := co.Exchange(&abc)
			if err != nil {
				b.Fatalf("unable to read msg from server: %v", err)
			}
			if !bytes.Equal(resp.Payload(), res.Payload()) {
				b.Fatalf("bad payload: %v", err)
			}
			sync <- true
		}(i)
	}

	for i := 0; i < b.N; i++ {
		<-sync
	}

	b.StopTimer()
}

func BenchmarkServeTCPStream(b *testing.B) {
	req := &TcpMessage{
		MessageBase{
			typ:       Confirmable,
			code:      POST,
			messageID: 1234,
			payload:   []byte("Content sent by client"),
		},
	}
	req.SetOption(ContentFormat, TextPlain)
	req.SetPathString("/test")
	benchmarkServeTCPStreamWithMsg(b, req)
}

func BenchmarkServeTCPStreamBigMsg(b *testing.B) {
	req := &TcpMessage{
		MessageBase{
			typ:       Confirmable,
			code:      POST,
			messageID: 1234,
			payload:   make([]byte, 1024*1024*10),
		},
	}
	req.SetOption(ContentFormat, TextPlain)
	req.SetPathString("/test")
	benchmarkServeTCPStreamWithMsg(b, req)
}

var (
	// CertPEMBlock is a X509 data used to test TLS servers (used with tls.X509KeyPair)
	CertPEMBlock = []byte(`-----BEGIN CERTIFICATE-----
MIIDAzCCAeugAwIBAgIRAJFYMkcn+b8dpU15wjf++GgwDQYJKoZIhvcNAQELBQAw
EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xNjAxMDgxMjAzNTNaFw0xNzAxMDcxMjAz
NTNaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
ggEKAoIBAQDXjqO6skvP03k58CNjQggd9G/mt+Wa+xRU+WXiKCCHttawM8x+slq5
yfsHCwxlwsGn79HmJqecNqgHb2GWBXAvVVokFDTcC1hUP4+gp2gu9Ny27UHTjlLm
O0l/xZ5MN8tfKyYlFw18tXu3fkaPyHj8v/D1RDkuo4ARdFvGSe8TqisbhLk2+9ow
xfIGbEM9Fdiw8qByC2+d+FfvzIKz3GfQVwn0VoRom8L6NBIANq1IGrB5JefZB6nv
DnfuxkBmY7F1513HKuEJ8KsLWWZWV9OPU4j4I4Rt+WJNlKjbD2srHxyrS2RDsr91
8nCkNoWVNO3sZq0XkWKecdc921vL4ginAgMBAAGjVDBSMA4GA1UdDwEB/wQEAwIC
pDATBgNVHSUEDDAKBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MBoGA1UdEQQT
MBGCCWxvY2FsaG9zdIcEfwAAATANBgkqhkiG9w0BAQsFAAOCAQEAGcU3iyLBIVZj
aDzSvEDHUd1bnLBl1C58Xu/CyKlPqVU7mLfK0JcgEaYQTSX6fCJVNLbbCrcGLsPJ
fbjlBbyeLjTV413fxPVuona62pBFjqdtbli2Qe8FRH2KBdm41JUJGdo+SdsFu7nc
BFOcubdw6LLIXvsTvwndKcHWx1rMX709QU1Vn1GAIsbJV/DWI231Jyyb+lxAUx/C
8vce5uVxiKcGS+g6OjsN3D3TtiEQGSXLh013W6Wsih8td8yMCMZ3w8LQ38br1GUe
ahLIgUJ9l6HDguM17R7kGqxNvbElsMUHfTtXXP7UDQUiYXDakg8xDP6n9DCDhJ8Y
bSt7OLB7NQ==
-----END CERTIFICATE-----`)

	// KeyPEMBlock is a X509 data used to test TLS servers (used with tls.X509KeyPair)
	KeyPEMBlock = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA146jurJLz9N5OfAjY0IIHfRv5rflmvsUVPll4iggh7bWsDPM
frJaucn7BwsMZcLBp+/R5iannDaoB29hlgVwL1VaJBQ03AtYVD+PoKdoLvTctu1B
045S5jtJf8WeTDfLXysmJRcNfLV7t35Gj8h4/L/w9UQ5LqOAEXRbxknvE6orG4S5
NvvaMMXyBmxDPRXYsPKgcgtvnfhX78yCs9xn0FcJ9FaEaJvC+jQSADatSBqweSXn
2Qep7w537sZAZmOxdeddxyrhCfCrC1lmVlfTj1OI+COEbfliTZSo2w9rKx8cq0tk
Q7K/dfJwpDaFlTTt7GatF5FinnHXPdtby+IIpwIDAQABAoIBAAJK4RDmPooqTJrC
JA41MJLo+5uvjwCT9QZmVKAQHzByUFw1YNJkITTiognUI0CdzqNzmH7jIFs39ZeG
proKusO2G6xQjrNcZ4cV2fgyb5g4QHStl0qhs94A+WojduiGm2IaumAgm6Mc5wDv
ld6HmknN3Mku/ZCyanVFEIjOVn2WB7ZQLTBs6ZYaebTJG2Xv6p9t2YJW7pPQ9Xce
s9ohAWohyM4X/OvfnfnLtQp2YLw/BxwehBsCR5SXM3ibTKpFNtxJC8hIfTuWtxZu
2ywrmXShYBRB1WgtZt5k04bY/HFncvvcHK3YfI1+w4URKtwdaQgPUQRbVwDwuyBn
flfkCJECgYEA/eWt01iEyE/lXkGn6V9lCocUU7lCU6yk5UT8VXVUc5If4KZKPfCk
p4zJDOqwn2eM673aWz/mG9mtvAvmnugaGjcaVCyXOp/D/GDmKSoYcvW5B/yjfkLy
dK6Yaa5LDRVYlYgyzcdCT5/9Qc626NzFwKCZNI4ncIU8g7ViATRxWJ8CgYEA2Ver
vZ0M606sfgC0H3NtwNBxmuJ+lIF5LNp/wDi07lDfxRR1rnZMX5dnxjcpDr/zvm8J
WtJJX3xMgqjtHuWKL3yKKony9J5ZPjichSbSbhrzfovgYIRZLxLLDy4MP9L3+CX/
yBXnqMWuSnFX+M5fVGxdDWiYF3V+wmeOv9JvavkCgYEAiXAPDFzaY+R78O3xiu7M
r0o3wqqCMPE/wav6O/hrYrQy9VSO08C0IM6g9pEEUwWmzuXSkZqhYWoQFb8Lc/GI
T7CMXAxXQLDDUpbRgG79FR3Wr3AewHZU8LyiXHKwxcBMV4WGmsXGK3wbh8fyU1NO
6NsGk+BvkQVOoK1LBAPzZ1kCgYEAsBSmD8U33T9s4dxiEYTrqyV0lH3g/SFz8ZHH
pAyNEPI2iC1ONhyjPWKlcWHpAokiyOqeUpVBWnmSZtzC1qAydsxYB6ShT+sl9BHb
RMix/QAauzBJhQhUVJ3OIys0Q1UBDmqCsjCE8SfOT4NKOUnA093C+YT+iyrmmktZ
zDCJkckCgYEAndqM5KXGk5xYo+MAA1paZcbTUXwaWwjLU+XSRSSoyBEi5xMtfvUb
7+a1OMhLwWbuz+pl64wFKrbSUyimMOYQpjVE/1vk/kb99pxbgol27hdKyTH1d+ov
kFsxKCqxAnBVGEWAvVZAiiTOxleQFjz5RnL0BQp9Lg2cQe+dvuUmIAA=
-----END RSA PRIVATE KEY-----`)
)