forked from quantum1423-dustbin/kirisurf-legacy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
e2e_structs.go
77 lines (69 loc) · 1.7 KB
/
e2e_structs.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
// e2e_structs.go
package main
import (
"encoding/binary"
"io"
"sync"
)
// Structures for the end-to-end protocol.
const (
__INVALID = iota
E2E_OPEN = iota
E2E_CLOSE = iota
E2E_DATA = iota
E2E_SENDMORE = iota
)
type e2e_segment struct {
Flag int
Connid int
Body []byte
}
type gobwire struct {
conn io.ReadWriteCloser
_rlock *sync.Mutex
_slock *sync.Mutex
destroy func() error
}
func (wire *gobwire) Receive() (e2e_segment, error) {
wire._rlock.Lock()
defer wire._rlock.Unlock()
var placeholder e2e_segment
b_flag := make([]byte, 1)
b_connid := make([]byte, 2)
b_length := make([]byte, 2)
_, err := io.ReadFull(wire.conn, b_flag)
if err != nil {
return placeholder, err
}
_, err = io.ReadFull(wire.conn, b_connid)
if err != nil {
return placeholder, err
}
_, err = io.ReadFull(wire.conn, b_length)
if err != nil {
return placeholder, err
}
b_body := make([]byte, binary.LittleEndian.Uint16(b_length))
_, err = io.ReadFull(wire.conn, b_body)
if err != nil {
return placeholder, err
}
return e2e_segment{int(b_flag[0]), int(binary.LittleEndian.Uint16(b_connid)), b_body}, nil
}
func (wire *gobwire) Send(thing e2e_segment) error {
wire._slock.Lock()
defer wire._slock.Unlock()
//log.Debug("Sending: ", thing)
tosend := make([]byte, len(thing.Body)+1+2+2)
tosend[0] = byte(thing.Flag)
binary.LittleEndian.PutUint16(tosend[1:3], uint16(thing.Connid))
binary.LittleEndian.PutUint16(tosend[3:5], uint16(len(thing.Body)))
copy(tosend[5:], thing.Body)
_, err := wire.conn.Write(tosend)
//log.Debug("Sent.")
return err
}
func newGobWire(thing io.ReadWriteCloser) *gobwire {
toret := gobwire{thing, new(sync.Mutex), new(sync.Mutex), thing.Close}
return &toret
}