-
Notifications
You must be signed in to change notification settings - Fork 20
/
protocol.go
88 lines (72 loc) · 1.86 KB
/
protocol.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
package protocol
import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
"github.com/libp2p/go-libp2p/core/protocol"
)
const (
Version = "0.3.0"
AuthMethod protocol.ID = "/awl/" + Version + "/auth/"
GetStatusMethod protocol.ID = "/awl/" + Version + "/status/"
TunnelPacketMethod protocol.ID = "/awl/" + Version + "/tunnel/"
)
type (
PeerStatusInfo struct {
Name string
Declined bool
}
)
func ReceiveStatus(stream io.Reader) (PeerStatusInfo, error) {
statusInfo := PeerStatusInfo{}
err := json.NewDecoder(stream).Decode(&statusInfo)
return statusInfo, err
}
func SendStatus(stream io.Writer, statusInfo PeerStatusInfo) error {
err := json.NewEncoder(stream).Encode(&statusInfo)
return err
}
type AuthPeer struct {
Name string
}
type AuthPeerResponse struct {
Confirmed bool
Declined bool
}
func ReceiveAuth(stream io.Reader) (AuthPeer, error) {
authPeer := AuthPeer{}
err := json.NewDecoder(stream).Decode(&authPeer)
return authPeer, err
}
func SendAuth(stream io.Writer, authPeer AuthPeer) error {
err := json.NewEncoder(stream).Encode(&authPeer)
return err
}
func ReceiveAuthResponse(stream io.Reader) (AuthPeerResponse, error) {
response := AuthPeerResponse{}
err := json.NewDecoder(stream).Decode(&response)
return response, err
}
func SendAuthResponse(stream io.Writer, response AuthPeerResponse) error {
err := json.NewEncoder(stream).Encode(&response)
return err
}
func ReadUint64(stream io.Reader) (uint64, error) {
var data [8]byte
n, err := stream.Read(data[:])
if err != nil {
return 0, err
}
if n != 8 {
return 0, fmt.Errorf("invalid uint64 data: %v. read %d instead of 8", data, n)
}
value := binary.BigEndian.Uint64(data[:])
return value, nil
}
func WriteUint64(stream io.Writer, number uint64) error {
var data [8]byte
binary.BigEndian.PutUint64(data[:], number)
_, err := stream.Write(data[:])
return err
}