/
admin.go
410 lines (364 loc) · 10.9 KB
/
admin.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package db
import (
"bytes"
"errors"
"fmt"
"strings"
"time"
"github.com/awgh/bencrypt/bc"
"github.com/awgh/debouncer"
"github.com/awgh/ratnet/api"
"github.com/awgh/ratnet/api/chunking"
"github.com/awgh/ratnet/api/events"
)
// CID : Return content key
func (node *Node) CID() (bc.PubKey, error) {
return node.contentKey.GetPubKey(), nil
}
// GetContact : Return a list of keys
func (node *Node) GetContact(name string) (*api.Contact, error) {
pubs, err := node.dbGetContactPubKey(name)
if err != nil {
return nil, err
} else if pubs == "" {
return nil, nil
}
contact := new(api.Contact)
contact.Name = name
contact.Pubkey = pubs
return contact, nil
}
// GetContacts : Return a list of keys
func (node *Node) GetContacts() ([]api.Contact, error) {
return node.dbGetContacts()
}
// AddContact : Add or Update a contact key to this node's database
func (node *Node) AddContact(name string, key string) error {
return node.dbAddContact(name, key)
}
// DeleteContact : Remove a contact from this node's database
func (node *Node) DeleteContact(name string) error {
node.dbDeleteContact(name)
return nil
}
// GetChannel : Return a channel by name
func (node *Node) GetChannel(name string) (*api.Channel, error) {
privkey, err := node.dbGetChannelPrivKey(name)
if err != nil {
return nil, err
}
prv := node.contentKey.Clone()
if err := prv.FromB64(privkey); err != nil {
return nil, err
}
channel := new(api.Channel)
channel.Name = name
channel.Pubkey = prv.GetPubKey().ToB64()
return channel, nil
}
// GetChannels : Return list of channels known to this node
func (node *Node) GetChannels() ([]api.Channel, error) {
return node.dbGetChannels()
}
// AddChannel : Add a channel to this node's database
func (node *Node) AddChannel(name string, privkey string) error {
if err := node.dbAddChannel(name, privkey); err != nil {
return err
}
node.refreshChannels()
return nil
}
// DeleteChannel : Remove a channel from this node's database
func (node *Node) DeleteChannel(name string) error {
node.dbDeleteChannel(name)
return nil
}
// GetProfile : Retrieve a profiles
func (node *Node) GetProfile(name string) (*api.Profile, error) {
return node.dbGetProfile(name)
}
// GetProfiles : Retrieve the list of profiles for this node
func (node *Node) GetProfiles() ([]api.Profile, error) {
return node.dbGetProfiles()
}
// AddProfile : Add or Update a profile to this node's database
func (node *Node) AddProfile(name string, enabled bool) error {
return node.dbAddProfile(name, enabled)
}
// DeleteProfile : Remove a profile from this node's database
func (node *Node) DeleteProfile(name string) error {
node.dbDeleteProfile(name)
return nil
}
// LoadProfile : Load a profile key from the database as the content key
func (node *Node) LoadProfile(name string) (bc.PubKey, error) {
pk := node.dbGetProfilePrivateKey(name)
profileKey := node.contentKey.Clone()
if err := profileKey.FromB64(pk); err != nil {
events.Error(node, err)
return nil, err
}
node.contentKey = profileKey
events.Debug(node, "Profile Loaded: "+profileKey.GetPubKey().ToB64())
return profileKey.GetPubKey(), nil
}
// privProfile : Internal call to load secret key only for decryption operation
func (node *Node) privProfile(name string) (bc.KeyPair, error) {
pk := node.dbGetProfilePrivateKey(name)
if pk == "" {
return nil, errors.New("No matching profile key found")
}
profileKey := node.contentKey.Clone()
if err := profileKey.FromB64(pk); err != nil {
events.Error(node, err)
return nil, err
}
events.Debug(node, "Profile Loaded: "+profileKey.GetPubKey().ToB64())
return profileKey, nil
}
// GetPeer : Retrieve a peer by name
func (node *Node) GetPeer(name string) (*api.Peer, error) {
return node.dbGetPeer(name)
}
// GetPeers : Retrieve a list of peers in this node's database
func (node *Node) GetPeers(group ...string) ([]api.Peer, error) {
// if we don't have a specified group, it's ""
groupName := strings.Join(group, " ")
return node.dbGetPeers(groupName)
}
// AddPeer : Add or Update a peer configuration
func (node *Node) AddPeer(name string, enabled bool, uri string, group ...string) error {
// if we don't have a specified group, it's ""
groupName := strings.Join(group, " ")
return node.dbAddPeer(name, enabled, uri, groupName)
}
// DeletePeer : Remove a peer from this node's database
func (node *Node) DeletePeer(name string) error {
node.dbDeletePeer(name)
return nil
}
// Send : Transmit a message to a single key
func (node *Node) Send(contactName string, data []byte, pubkey ...bc.PubKey) error {
var destkey bc.PubKey
if pubkey != nil && len(pubkey) > 0 && pubkey[0] != nil { // third argument is optional pubkey override
destkey = pubkey[0]
} else {
s, err := node.dbGetContactPubKey(contactName)
if err != nil {
return err
} else if s == "" {
return errors.New("Unknown Contact")
}
destkey = node.contentKey.GetPubKey().Clone()
if err := destkey.FromB64(s); err != nil {
return err
}
}
return node.SendMsg(api.Msg{Name: contactName, Content: bytes.NewBuffer(data), IsChan: false, PubKey: destkey, Chunked: false})
}
// SendChannel : Transmit a message to a channel
func (node *Node) SendChannel(channelName string, data []byte, pubkey ...bc.PubKey) error {
var destkey bc.PubKey
if pubkey != nil && len(pubkey) > 0 && pubkey[0] != nil { // third argument is optional PubKey override
destkey = pubkey[0]
} else {
key, ok := node.channelKeys[channelName]
if !ok {
return errors.New("No public key for Channel")
}
destkey = key.GetPubKey()
}
if destkey == nil {
events.Critical(node, "nil DestKey in SendChannel")
}
return node.SendMsg(api.Msg{Name: channelName, Content: bytes.NewBuffer(data), IsChan: true, PubKey: destkey, Chunked: false})
}
// SendMsg : Transmits a message
func (node *Node) SendMsg(msg api.Msg) error {
// determine if we need to chunk
chunkSize := chunking.ChunkSize(node) // finds the minimum transport byte limit
if msg.Content.Len() > 0 && uint32(msg.Content.Len()) > chunkSize { // we need to chunk
if msg.Chunked { // we're already chunked, freak out!
return errors.New("Chunked message needs to be chunked, bailing out")
}
return chunking.SendChunked(node, chunkSize, msg)
}
data, err := node.contentKey.EncryptMessage(msg.Content.Bytes(), msg.PubKey)
if err != nil {
return err
}
flags := uint8(0)
if msg.IsChan {
flags |= api.ChannelFlag
}
if msg.Chunked {
flags |= api.ChunkedFlag
}
if msg.StreamHeader {
flags |= api.StreamHeaderFlag
}
rxsum := []byte{flags} // prepend flags byte
if msg.IsChan {
// prepend a uint16 of channel name length, little-endian
t := uint16(len(msg.Name))
rxsum = append(rxsum, byte(t>>8), byte(t&0xFF))
rxsum = append(rxsum, []byte(msg.Name)...)
}
data = append(rxsum, data...)
ts := time.Now().UnixNano()
if msg.IsChan {
return node.dbOutboxEnqueue(msg.Name, data, ts, false)
}
return node.dbOutboxEnqueue("", data, ts, false)
}
// SendBulk : Transmit messages to a single key
func (node *Node) SendBulk(contactName string, data [][]byte, pubkey ...bc.PubKey) error {
var destkey bc.PubKey
if pubkey != nil && len(pubkey) > 0 && pubkey[0] != nil { // third argument is optional pubkey override
destkey = pubkey[0]
} else {
s, err := node.dbGetContactPubKey(contactName)
if err != nil {
return err
}
if s == "" {
return errors.New("Unknown Contact")
}
destkey = node.contentKey.GetPubKey().Clone()
if err := destkey.FromB64(s); err != nil {
return err
}
}
return node.sendBulk("", destkey, data)
}
// SendChannelBulk : Transmit messages to a channel
func (node *Node) SendChannelBulk(channelName string, data [][]byte, pubkey ...bc.PubKey) error {
var destkey bc.PubKey
if pubkey != nil && len(pubkey) > 0 && pubkey[0] != nil { // third argument is optional PubKey override
destkey = pubkey[0]
} else {
key, ok := node.channelKeys[channelName]
if !ok {
return errors.New("No public key for Channel")
}
destkey = key.GetPubKey()
}
if destkey == nil {
events.Critical(node, "nil DestKey in SendChannel")
}
return node.sendBulk(channelName, destkey, data)
}
func (node *Node) sendBulk(channelName string, destkey bc.PubKey, msg [][]byte) error {
isChan := (channelName != "")
flags := uint8(0)
if isChan {
flags |= api.ChannelFlag
}
rxsum := []byte{flags} // prepend flags byte
if isChan {
// prepend a uint16 of channel name length, little-endian
t := uint16(len(channelName))
rxsum = append(rxsum, byte(t>>8), byte(t&0xFF))
rxsum = append(rxsum, []byte(channelName)...)
}
// todo: is this passing msg by reference or not???
data := make([][]byte, len(msg))
for i := range msg {
var err error
data[i], err = node.contentKey.EncryptMessage(msg[i], destkey)
if err != nil {
return err
}
data[i] = append(rxsum, data[i]...)
}
ts := time.Now().UnixNano()
node.outboxBulkInsert(channelName, ts, data)
return nil
}
// Start : starts the Connection Policy threads
func (node *Node) Start() error {
// do not start again if the node is already running
if node.IsRunning() {
return nil
}
node.setIsRunning(true)
// start the policies
if node.policies != nil {
for i := 0; i < len(node.policies); i++ {
if err := node.policies[i].RunPolicy(); err != nil {
return err
}
}
}
// input loop
go func() {
for {
// check if we should stop running
if !node.IsRunning() {
break
}
// read message off the input channel
message, more := <-node.In()
if !more {
break
}
if err := node.SendMsg(message); err != nil {
events.Error(node, err.Error())
}
}
}()
node.trigggerMutex.Lock()
defer node.trigggerMutex.Unlock()
node.debouncer = debouncer.New(10*time.Millisecond, func() {
node.trigggerMutex.Lock()
defer node.trigggerMutex.Unlock()
// check if we should stop running
if !node.IsRunning() {
return
}
// get all streams
streams, err := node.dbGetStreams()
if err != nil {
events.Critical(node, err.Error())
}
// for each stream, count chunks for that header
for _, stream := range streams {
count, err := node.dbGetChunkCount(stream.StreamID)
if err != nil {
events.Critical(node, err.Error())
}
// if chunks == total chunks, re-assemble Msg and call Handle
if count == uint64(stream.NumChunks) {
chunks, err := node.dbGetChunks(stream.StreamID)
if err != nil {
events.Critical(node, err.Error())
}
buf := bytes.NewBuffer([]byte{})
for _, chunk := range chunks {
buf.Write(chunk.Data)
}
var msg api.Msg
if len(stream.ChannelName) > 0 {
msg.IsChan = true
msg.Name = stream.ChannelName
}
msg.Content = buf
select {
case node.Out() <- msg:
events.Debug(node, "Sent message "+fmt.Sprint(msg.Content.Bytes()))
node.dbClearStream(stream.StreamID)
default:
events.Debug(node, "No message sent")
}
}
}
})
return nil
}
// Stop : sets the isRunning flag to false, indicating that all go routines should end
func (node *Node) Stop() {
for _, policy := range node.policies {
policy.Stop()
}
node.setIsRunning(false)
}