-
Notifications
You must be signed in to change notification settings - Fork 31
/
slip.go
108 lines (101 loc) · 2.6 KB
/
slip.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
//
// Copyright (c) 2014-2019 Cesanta Software Limited
// All rights reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package common
import (
"io"
"github.com/juju/errors"
glog "k8s.io/klog/v2"
)
const (
// https://tools.ietf.org/html/rfc1055
slipFrameDelimiter = 0xC0
slipEscape = 0xDB
slipEscapeFrameDelimiter = 0xDC
slipEscapeEscape = 0xDD
)
type SLIPReaderWriter struct {
rw io.ReadWriter
}
func NewSLIPReaderWriter(rw io.ReadWriter) *SLIPReaderWriter {
return &SLIPReaderWriter{rw: rw}
}
func (srw *SLIPReaderWriter) Read(buf []byte) (int, error) {
n := 0
start := true
esc := false
for {
b := []byte{0}
bn, err := srw.rw.Read(b)
if err != nil || bn != 1 {
return n, errors.Annotatef(err, "error reading")
}
if start {
if b[0] != slipFrameDelimiter {
return 0, errors.Errorf("invalid SLIP starting byte: 0x%02x", b[0])
}
start = false
continue
}
if !esc {
switch b[0] {
case slipFrameDelimiter:
glog.V(4).Infof("<= (%d) %s", n, LimitStr(buf[:n], 32))
return n, nil
case slipEscape:
esc = true
default:
if n >= len(buf) {
return n, errors.Errorf("frame buffer overflow (%d)", len(buf))
}
buf[n] = b[0]
n += 1
}
} else {
if n >= len(buf) {
return n, errors.Errorf("frame buffer overflow (%d)", len(buf))
}
switch b[0] {
case slipEscapeFrameDelimiter:
buf[n] = slipFrameDelimiter
case slipEscapeEscape:
buf[n] = slipEscape
default:
return n, errors.Errorf("invalid SLIP escape sequence: %d", b[0])
}
n += 1
esc = false
}
}
}
func (srw *SLIPReaderWriter) Write(data []byte) (int, error) {
frame := []byte{slipFrameDelimiter}
for _, b := range data {
switch b {
case slipFrameDelimiter:
frame = append(frame, slipEscape)
frame = append(frame, slipEscapeFrameDelimiter)
case slipEscape:
frame = append(frame, slipEscape)
frame = append(frame, slipEscapeEscape)
default:
frame = append(frame, b)
}
}
frame = append(frame, slipFrameDelimiter)
glog.V(4).Infof("=> (%d) %s", len(data), LimitStr(data, 32))
return srw.rw.Write(frame)
}