-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
253 lines (225 loc) · 7.25 KB
/
client.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package client
import (
"bumbleserver.org/common/envelope"
"bumbleserver.org/common/key"
"bumbleserver.org/common/message"
"bumbleserver.org/common/peer"
"code.google.com/p/go.net/websocket"
"crypto/rsa"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/url"
"strconv"
"strings"
"syscall"
)
type Client struct {
peer *peer.Peer
isAuthenticated bool
websocket *websocket.Conn
privateKey *rsa.PrivateKey
onConnectCallback func(*Client)
onDisconnectCallback func(*Client)
onAuthenticationCallback func(*Client, bool, string)
onMessageCallback func(*Client, *envelope.Envelope, *message.Header)
myRouter *peer.Peer
hostOverride string
}
type Config struct {
Name string
PrivateKey *rsa.PrivateKey
OnConnect func(*Client)
OnDisconnect func(*Client)
OnAuthentication func(*Client, bool, string)
OnMessage func(*Client, *envelope.Envelope, *message.Header)
HostOverride string
}
func NewClient(config *Config) *Client {
c := new(Client)
c.peer = peer.NewFromString(config.Name)
c.isAuthenticated = false
c.privateKey = config.PrivateKey
c.onConnectCallback = config.OnConnect
c.onDisconnectCallback = config.OnDisconnect
c.onAuthenticationCallback = config.OnAuthentication
c.onMessageCallback = config.OnMessage
c.hostOverride = config.HostOverride
return c
}
func (c *Client) Connect() error {
if c.privateKey == nil {
return errors.New("private key missing")
}
pubkey := c.peer.PublicKey()
if pubkey == nil {
publicKeyURL, err := c.peer.PublicKeyURL()
if err != nil {
fmt.Printf("Unable to locate your public key in the public key store, likely because of this error: %s\n\n", err)
} else {
fmt.Printf("Unable to locate your public key in the public key store.\n\nI expected to find the following data stored at %s\n\n%s\n", publicKeyURL, key.PublicKeyToPEM(c.privateKey.PublicKey))
}
return errors.New("public key not in public key store")
}
if pubkey.N.Cmp(c.privateKey.PublicKey.N) != 0 {
publicKeyURL, _ := c.peer.PublicKeyURL()
fmt.Printf("The global public key store has a public key that doesn't match my own public key stored locally.\n\nI expected to find the following data stored at %s\n\n%s\n", publicKeyURL, key.PublicKeyToPEM(c.privateKey.PublicKey))
return errors.New("public key does not match the key in the public key store")
}
var addrs []*net.SRV
var err error
if c.hostOverride == "" {
_, addrs, err = net.LookupSRV("bumble-client", "tcp", c.peer.Domain)
if err != nil {
return err
}
} else {
parts := strings.Split(c.hostOverride, ":")
port, _ := strconv.ParseUint(parts[1], 10, 0)
addrs = append(addrs, &net.SRV{
Target: parts[0],
Port: uint16(port),
Priority: 0,
Weight: 0,
})
}
var u *url.URL
for _, addr := range addrs {
u = new(url.URL)
u.Host = strings.Replace(fmt.Sprintf("%s:%v", addr.Target, addr.Port), ".:", ":", 1)
u.Scheme = "wss"
u.Path = "/bumble-client"
fmt.Printf("Connecting to [%s].\n", u.String())
var config *websocket.Config
config, err = websocket.NewConfig(u.String(), u.String())
config.TlsConfig = &tls.Config{
InsecureSkipVerify: true, // FIXME: this should not be used in production!
}
ws, err := websocket.DialConfig(config)
if err != nil {
fmt.Printf("Failed to connect to [%s] due to: %s\n", u.String(), err.Error())
continue
}
c.websocket = ws
c.onConnect(u)
break
}
if c.websocket == nil {
return errors.New("unable to connect to any servers")
}
incoming := make(chan *envelope.Envelope)
disconnected := make(chan bool)
go peerEnvelopeReceiver(c.websocket, incoming, disconnected)
for {
// fmt.Println("LOOP")
select {
case <-disconnected:
// fmt.Printf("ROUTER-PEER-DISCONNECTION: %s\n", p)
c.onDisconnect(u)
return errors.New("got disconnected")
case e := <-incoming:
// fmt.Printf("RECEIVED ENVELOPE: %s\n", env)
if e.GetFrom() == nil { // all envelopes have a sender
continue
}
if c.myRouter == nil && e.GetTo() == nil {
c.myRouter = e.GetFrom()
}
fromMyRouter := (e.GetFrom().String() == c.myRouter.String()) // it's from my router before I have a name
isForMe := (e.GetTo() != nil && e.GetTo().String() == c.peer.String()) // is this directed at me?
if fromMyRouter || isForMe {
err := key.VerifyBytesFromString(e.GetFrom().PublicKey(), []byte(e.GetMessageRaw()), e.GetSignature())
if err != nil {
fmt.Printf("DIRECT-RECEIVED-MESSAGE-VERIFICATION-ERROR: %s\n", err)
continue
}
m := e.GetMessage(c.privateKey)
messageHeader, err := message.HeaderParse(m)
if err != nil {
fmt.Printf("DIRECT-RECEIVED-MESSAGEHEADER-PARSE-ERROR: %s\n", err)
continue
}
if messageHeader.GetFrom().String() != e.GetFrom().String() {
// envelope from field doesn't match the message, do something? FIXME
continue
}
if e.GetTo() == nil && fromMyRouter && messageHeader.GetCode() == message.CODE_AUTHENTICATE {
msg := message.NewGeneric(message.CODE_AUTHENTICATION)
msg.SetTo(e.GetFrom())
msg.SetInfo(e.GetSignature())
c.OriginateMessage(msg)
continue
}
if fromMyRouter && messageHeader.GetType() == message.TYPE_GENERIC && messageHeader.GetCode() == message.CODE_AUTHENTICATIONRESULT {
gen, err := message.GenericParse(m)
if err == nil {
c.isAuthenticated = gen.Success
c.onAuthentication(c.isAuthenticated, gen.Error)
}
continue
}
c.onMessage(e, messageHeader)
}
}
}
return nil
}
func (c *Client) onConnect(u *url.URL) {
c.isAuthenticated = false
//fmt.Printf("Connected to [%s].\n", u.String())
go c.onConnectCallback(c)
}
func (c *Client) onDisconnect(u *url.URL) {
c.isAuthenticated = false
//fmt.Printf("Disconnected from [%s].\n", u.String())
go c.onDisconnectCallback(c)
}
func (c *Client) onMessage(e *envelope.Envelope, m *message.Header) {
//fmt.Printf("Envelope from [%s]: %s\n", e.GetFrom().String(), e)
go c.onMessageCallback(c, e, m)
}
func (c *Client) onAuthentication(s bool, error string) {
//fmt.Printf("Authenticated? %t\n", s)
go c.onAuthenticationCallback(c, s, error)
}
func peerEnvelopeReceiver(ws *websocket.Conn, incoming chan *envelope.Envelope, disconnected chan bool) {
// fmt.Println("PER ENTRY")
// defer fmt.Println("PER EXIT")
for {
var env envelope.Envelope
err := websocket.JSON.Receive(ws, &env)
if err == nil {
incoming <- &env
continue
}
if err == io.EOF || err == syscall.EINVAL || err == syscall.ECONNRESET { // peer disconnected (FIXME: want to get proper test for "read tcp ... use of closed network connection" error)
disconnected <- true
break
}
if err != nil {
fmt.Printf("PER ERR: [[[ WARNING: UNHANDLED ERROR ]]] %v\n", err)
disconnected <- true
break
}
}
}
func (c *Client) Myself() *peer.Peer {
return c.peer
}
func (c *Client) OriginateMessage(msg message.Message) (signature string, err error) {
msg.SetFrom(c.peer)
env, err := envelope.Package(msg, c.privateKey)
if err != nil {
fmt.Printf("ORIGINATEMESSAGE-PACKAGE ERROR: %s\n", err.Error())
return
}
signature = env.GetSignature()
err = websocket.JSON.Send(c.websocket, env)
if err != nil {
fmt.Printf("ORIGINATEMESSAGE-JSON-SEND ERROR: %s\n", err.Error())
return
}
return
}