-
Notifications
You must be signed in to change notification settings - Fork 0
/
packet.go
87 lines (77 loc) · 2.03 KB
/
packet.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
package sftp
import (
"fmt"
"io"
"reflect"
)
func marshalUint32(b []byte, v uint32) []byte {
return append(b, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}
func marshalUint64(b []byte, v uint64) []byte {
return marshalUint32(marshalUint32(b, uint32(v>>24)), uint32(v))
}
func marshalString(b []byte, v string) []byte {
return append(marshalUint32(b, uint32(len(v))), v...)
}
func marshal(b []byte, v interface{}) []byte {
switch v := v.(type) {
case uint8:
return append(b, v)
case uint32:
return marshalUint32(b, v)
case uint64:
return marshalUint64(b, v)
case string:
return marshalString(b, v)
default:
switch d := reflect.ValueOf(v); d.Kind() {
case reflect.Struct:
for i, n := 0, d.NumField(); i < n; i++ {
b = append(marshal(b, d.Field(i).Interface()))
}
return b
case reflect.Slice:
for i, n := 0, d.Len(); i < n; i++ {
b = append(marshal(b, d.Index(i).Interface()))
}
return b
default:
panic(fmt.Sprintf("marshal(%#v): cannot handle type %T", v, v))
}
}
}
func unmarshalUint32(b []byte) (uint32, []byte) {
v := uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
return v, b[4:]
}
func unmarshalUint64(b []byte) (uint64, []byte) {
h, b := unmarshalUint32(b)
l, b := unmarshalUint32(b)
return uint64(h)<<32 | uint64(l), b
}
func unmarshalString(b []byte) (string, []byte) {
n, b := unmarshalUint32(b)
return string(b[:n]), b[n:]
}
// sendPacket marshals p according to RFC 4234.
func sendPacket(w io.Writer, p interface{}) error {
fmt.Printf("sendPacket: %#v\n", p)
b := make([]byte, 4) // reserve space for the header
b = marshal(b, p)
l := uint32(len(b) - 4)
b[0], b[1], b[2], b[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l)
_, err := w.Write(b)
return err
}
func recvPacket(r io.Reader) (uint8, []byte, error) {
var b = []byte{0, 0, 0, 0}
if _, err := io.ReadFull(r, b); err != nil {
return 0, nil, err
}
l, _ := unmarshalUint32(b)
b = make([]byte, l)
if _, err := io.ReadFull(r, b); err != nil {
return 0, nil, err
}
return b[0], b[1:], nil
}