summaryrefslogtreecommitdiffstats
path: root/src/ssl/test/runner/packet_adapter.go
blob: 671b413306d0491a28d57bc4c2b3bba014f7cd6e (plain)
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
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"encoding/binary"
	"errors"
	"net"
)

type packetAdaptor struct {
	net.Conn
}

// newPacketAdaptor wraps a reliable streaming net.Conn into a
// reliable packet-based net.Conn. Every packet is encoded with a
// 32-bit length prefix as a framing layer.
func newPacketAdaptor(conn net.Conn) net.Conn {
	return &packetAdaptor{conn}
}

func (p *packetAdaptor) Read(b []byte) (int, error) {
	var length uint32
	if err := binary.Read(p.Conn, binary.BigEndian, &length); err != nil {
		return 0, err
	}
	out := make([]byte, length)
	n, err := p.Conn.Read(out)
	if err != nil {
		return 0, err
	}
	if n != int(length) {
		return 0, errors.New("internal error: length mismatch!")
	}
	return copy(b, out), nil
}

func (p *packetAdaptor) Write(b []byte) (int, error) {
	length := uint32(len(b))
	if err := binary.Write(p.Conn, binary.BigEndian, length); err != nil {
		return 0, err
	}
	n, err := p.Conn.Write(b)
	if err != nil {
		return 0, err
	}
	if n != len(b) {
		return 0, errors.New("internal error: length mismatch!")
	}
	return len(b), nil
}

type replayAdaptor struct {
	net.Conn
	prevWrite []byte
}

// newReplayAdaptor wraps a packeted net.Conn. It transforms it into
// one which, after writing a packet, always replays the previous
// write.
func newReplayAdaptor(conn net.Conn) net.Conn {
	return &replayAdaptor{Conn: conn}
}

func (r *replayAdaptor) Write(b []byte) (int, error) {
	n, err := r.Conn.Write(b)

	// Replay the previous packet and save the current one to
	// replay next.
	if r.prevWrite != nil {
		r.Conn.Write(r.prevWrite)
	}
	r.prevWrite = append(r.prevWrite[:0], b...)

	return n, err
}

type damageAdaptor struct {
	net.Conn
	damage bool
}

// newDamageAdaptor wraps a packeted net.Conn. It transforms it into one which
// optionally damages the final byte of every Write() call.
func newDamageAdaptor(conn net.Conn) *damageAdaptor {
	return &damageAdaptor{Conn: conn}
}

func (d *damageAdaptor) setDamage(damage bool) {
	d.damage = damage
}

func (d *damageAdaptor) Write(b []byte) (int, error) {
	if d.damage && len(b) > 0 {
		b = append([]byte{}, b...)
		b[len(b)-1]++
	}
	return d.Conn.Write(b)
}