-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.go
665 lines (565 loc) · 17.6 KB
/
server.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
// Copyright (c) 2015 Monetas.
// Copyright 2016 Daniel Krawisz.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"crypto/aes"
"crypto/sha256"
"errors"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
rpc "github.com/DanielKrawisz/bmagent/bmrpc"
"github.com/DanielKrawisz/bmagent/cmd"
"github.com/DanielKrawisz/bmagent/idmgr/keys"
"github.com/DanielKrawisz/bmagent/powmgr"
"github.com/DanielKrawisz/bmagent/store"
"github.com/DanielKrawisz/bmagent/user"
"github.com/DanielKrawisz/bmagent/user/email"
"github.com/DanielKrawisz/bmutil"
"github.com/DanielKrawisz/bmutil/cipher"
"github.com/DanielKrawisz/bmutil/hash"
"github.com/DanielKrawisz/bmutil/identity"
"github.com/DanielKrawisz/bmutil/pow"
"github.com/DanielKrawisz/bmutil/wire"
"github.com/DanielKrawisz/bmutil/wire/obj"
"github.com/jordwest/imap-server"
)
const (
// pkCheckerInterval is the interval after which bmclient should query bmd
// for retrieving any new public identities (that we queried for before).
pkCheckerInterval = time.Minute * 2
// powCheckerInterval is the interval after with bmclient should check the
// proof-of-work queue and process next item.
powCheckerInterval = time.Second * 5
// saveInterval is the interval after which data in memory should be saved
// to disk.
saveInterval = time.Minute * 5
)
// server struct manages everything that a running instance of bmclient
// comprises of and would need.
type server struct {
bmd *rpc.Client
rpcServer *cmd.RPCServer
users map[uint32]*User
store *store.Store
pk *store.PKRequests
pow *powmgr.Pow
started int32
shutdown int32
msgCounter uint64
broadcastCounter uint64
getpubkeyCounter uint64
smtp *user.SMTPServer
smtpListeners []net.Listener
imap *imap.Server
imapUser map[uint32]*user.User
imapListeners []net.Listener
quit chan struct{}
wg sync.WaitGroup
}
// newServer initializes a new instance of server.
func newServer(rpcc *rpc.ClientConfig, u *User, s *store.Store, pk *store.PKRequests) (*server, error) {
srvr := &server{
users: make(map[uint32]*User),
store: s,
pk: pk,
smtpListeners: make([]net.Listener, 0, len(cfg.SMTPListeners)),
imapListeners: make([]net.Listener, 0, len(cfg.IMAPListeners)),
quit: make(chan struct{}),
imapUser: make(map[uint32]*user.User),
pow: powmgr.New(cfg.powHandler),
}
var err error
srvr.bmd, err = rpc.NewClient(rpcc, srvr.newMessage, srvr.newBroadcast, srvr.newGetpubkey)
if err != nil {
log.Errorf("Cannot create bmd server RPC client: %v", err)
return nil, err
}
// TODO allow for more than one user. Right now there is just 1 user.
srvr.users[1] = u
userData, err := s.GetUser(u.Username)
if err != nil {
return nil, err
}
so := &serverOps{
pubIDs: make(map[string]identity.Public),
id: 1,
user: u,
server: srvr,
}
// Create an user.User from the store.
folders, err := userData.Folders()
if err != nil {
return nil, err
}
imapUser, err := user.NewUser(u.Username, u.Keys, ObjectExpiration, folders, srvr.pow, so)
if err != nil {
return nil, err
}
srvr.imapUser[1] = imapUser
// Setup SMTP and IMAP servers.
srvr.smtp = user.NewSMTPServer(&email.SMTPConfig{
RequireTLS: !cfg.DisableServerTLS,
Username: cfg.Username,
Password: cfg.Password,
}, imapUser)
srvr.imap = imap.NewServer(user.NewBitmessageStore(imapUser, &email.IMAPConfig{
RequireTLS: !cfg.DisableServerTLS,
Username: cfg.Username,
Password: cfg.Password,
}))
// Setup tracer for IMAP.
// srvr.imap.Transcript = os.Stderr
// Setup IMAP listeners.
for _, laddr := range cfg.IMAPListeners {
l, err := net.Listen("tcp", laddr)
if err != nil {
return nil, imapLog.Criticalf("Failed to listen on %s: %v", l, err)
}
srvr.imapListeners = append(srvr.imapListeners, l)
}
// Setup SMTP listeners.
for _, laddr := range cfg.SMTPListeners {
l, err := net.Listen("tcp", laddr)
if err != nil {
return nil, smtpLog.Criticalf("Failed to listen on %s: %v", l, err)
}
srvr.smtpListeners = append(srvr.smtpListeners, l)
}
// Setup rpc server.
if cfg.EnableRPC {
srvr.rpcServer, err = cmd.GRPCServer(srvr.imapUser[1], cfg.RPCConfig())
if err != nil {
return nil, err
}
}
// Load counter values from store.
srvr.msgCounter, err = s.GetCounter(wire.ObjectTypeMsg)
if err != nil {
serverLog.Critical("Failed to get message counter:", err)
}
srvr.broadcastCounter, err = s.GetCounter(wire.ObjectTypeBroadcast)
if err != nil {
serverLog.Critical("Failed to get broadcast counter:", err)
}
srvr.getpubkeyCounter, err = s.GetCounter(wire.ObjectTypeGetPubKey)
if err != nil {
serverLog.Critical("Failed to get getpubkey counter:", err)
}
return srvr, nil
}
// Start starts all the servers one by one and returns an error if any fails.
func (s *server) Start() {
// Already started?
if atomic.AddInt32(&s.started, 1) != 1 {
return
}
// Start RPC client.
serverLog.Info("Starting RPC client handlers.")
s.bmd.Start(s.msgCounter, s.broadcastCounter, s.getpubkeyCounter)
// Start IMAP server.
for _, l := range s.imapListeners {
imapLog.Infof("Listening on %s", l.Addr())
go s.imap.Serve(l)
}
// Start SMTP server.
for _, l := range s.smtpListeners {
smtpLog.Infof("Listening on %s", l.Addr())
go s.smtp.Serve(l)
}
// Start RPC server.
if s.rpcServer != nil {
s.rpcServer.Start()
}
// Start public key request handler.
serverLog.Info("Starting public key request handler.")
s.wg.Add(1)
go s.pkRequestHandler()
// Start saving data periodically.
s.wg.Add(1)
go s.savePeriodically()
}
var errSuccessCode = errors.New("decryption successful")
// newMessage is called when a new message is received by the RPC client.
// Messages are guaranteed to be received in ascending order of counter value.
func (s *server) newMessage(counter uint64, object []byte) {
// Store counter value.
atomic.StoreUint64(&s.msgCounter, counter)
msg := &obj.Message{}
err := msg.Decode(bytes.NewReader(object))
if err != nil {
serverLog.Errorf("Failed to decode message #%d from bytes: %v", counter,
err)
return // Ignore message.
}
// Is this an ack message we are expecting?
if len(object) == cipher.AckLength {
for _, u := range s.imapUser {
h := hash.InventoryHash(object)
err = u.DeliverAckReply(h)
if err != user.ErrUnrecognizedAck {
if err != nil {
serverLog.Errorf("Error returned receiving ack: %v", err)
}
serverLog.Infof("Delivered ack with hash %s", h.String())
return
}
}
return
}
// Check if message is smaller than expected.
// IV + Curve params/X/Y + 1 block + HMAC-256
if len(msg.Encrypted) <= aes.BlockSize+70+aes.BlockSize+sha256.Size {
return
}
// Contains the address of the identity used to decrypt the message.
var address string
// Whether the message was received from a channel.
var ofChan bool
var id uint32
var message *cipher.Message
// Try decrypting with all available identities.
for uid, user := range s.users {
err = user.Keys.ForEach(func(id *keys.PrivateID) error {
var decryptErr error
message, decryptErr = cipher.TryDecryptAndVerifyMessage(msg, id.Private)
if decryptErr == nil {
address = id.Address().String()
ofChan = id.IsChan
//id = uid
return errSuccessCode
}
return nil
})
if err != nil {
id = uid
// Decryption successful.
break
}
}
if message == nil {
// Decryption unsuccessful.
return
}
// Decryption was successful.
// TODO Store public key of the sender in bmagent
// Read message.
bmsg, err := email.MsgRead(message, address, ofChan)
if err != nil {
log.Errorf("Failed to decode message #%d: %v", counter, err)
return
}
rpccLog.Info("Bitmessage received from " + bmsg.From + " to " + bmsg.To)
err = s.imapUser[id].DeliverFromBMNet(bmsg)
if err != nil {
log.Errorf("Failed to save message #%d: %v", counter, err)
return
}
// Check if length of Ack is correct and message isn't from a channel.
ack := message.Ack()
if ack == nil || len(ack) < wire.MessageHeaderSize || ofChan {
log.Debugf("No ack found #%d", counter)
return
} else if len(ack) < wire.MessageHeaderSize || ofChan {
log.Errorf("Ack too big #%d.", counter)
return
}
// Send ack message if it exists.
ackObj := ack[wire.MessageHeaderSize:]
err = (&wire.MsgObject{}).Decode(bytes.NewReader(ackObj))
if err != nil { // Can't send invalid Ack.
log.Errorf("Failed to decode ack #%d: %v", counter, err)
return
}
_, err = s.bmd.SendObject(ack)
if err != nil {
log.Infof("Failed to send ack for message #%d: %v", counter, err)
return
}
rpccLog.Info("There was an ack included and sent back.")
}
// newBroadcast is called when a new broadcast is received by the RPC client.
// Broadcasts are guaranteed to be received in ascending order of counter value.
func (s *server) newBroadcast(counter uint64, object []byte) {
// Store counter value.
atomic.StoreUint64(&s.broadcastCounter, counter)
msg, err := obj.DecodeBroadcast(object)
if err != nil {
serverLog.Errorf("Failed to decode broadcast #%d from bytes: %v",
counter, err)
return // Ignore message.
}
// Check if broadcast is smaller than expected.
// IV + Curve params/X/Y + 1 block + HMAC-256
if len(msg.Encrypted()) <= aes.BlockSize+70+aes.BlockSize+sha256.Size {
return
}
for _, user := range s.store.Users() {
err := user.BroadcastAddresses.ForEach(func(addr bmutil.Address) error {
var fromAddress string
broadcast, err := cipher.TryDecryptAndVerifyBroadcast(msg, addr)
if err == nil {
fromAddress = addr.String()
}
// Read message.
bmsg, err := email.BroadcastRead(broadcast)
if err != nil {
return fmt.Errorf("Failed to decode message #%d: %v", counter, err)
}
rpccLog.Trace("Bitmessage broadcast received from " + bmsg.From + " to " + bmsg.To)
err = s.imapUser[1].DeliverFromBMNet(bmsg)
if err != nil {
return fmt.Errorf("Failed to save message #%d: %v", counter, err)
}
serverLog.Infof("Got new broadcast from %s", fromAddress)
return errSuccessCode
})
if err != nil && err != errSuccessCode {
log.Error(err)
}
}
}
// newGetpubkey is called when a new getpubkey is received by the RPC client.
// Getpubkey requests are guaranteed to be received in ascending order of
// counter value.
func (s *server) newGetpubkey(counter uint64, object []byte) {
// Store counter value.
atomic.StoreUint64(&s.getpubkeyCounter, counter)
msg := &obj.GetPubKey{}
err := msg.Decode(bytes.NewReader(object))
if err != nil {
serverLog.Errorf("Failed to decode getpubkey #%d from bytes: %v",
counter, err)
return // Ignore message.
}
var privID *keys.PrivateID
header := msg.Header()
// Check if the getpubkey request corresponds to any of our identities.
for _, user := range s.users {
err = user.Keys.ForEach(func(id *keys.PrivateID) error {
if id.Disabled || id.IsChan { // We don't care about these.
return nil
}
var cond bool // condition to satisfy
address := id.Private.Address()
switch header.Version {
case obj.SimplePubKeyVersion, obj.ExtendedPubKeyVersion:
cond = bytes.Equal(address.RipeHash()[:], msg.Ripe[:])
case obj.TagGetPubKeyVersion:
cond = bytes.Equal(bmutil.Tag(address)[:], msg.Tag[:])
}
if cond {
privID = id
return errors.New("We have a match.")
}
return nil
})
if err != nil {
break
}
}
if err == nil {
return
}
addr := privID.Address()
serverLog.Infof("Received a getpubkey request for %s; sending out the pubkey.", addr)
// Generate a pubkey message.
pkMsg, err := cipher.GeneratePubKey(privID.Private, defaultPubkeyExpiry)
if err != nil {
serverLog.Errorf("Failed to generate pubkey for %s: %v", addr, err)
return
}
// Add it to pow queue.
pkObj := pkMsg.Object()
pkHeader := pkObj.Header()
b := wire.Encode(pkObj)[8:] // exclude nonce
target := pow.CalculateTarget(uint64(len(b)),
uint64(pkHeader.Expiration().Sub(time.Now()).Seconds()),
pow.Default)
s.pow.Run(target, b, func(nonce pow.Nonce) {
s.Send(append(nonce.Bytes(), b...))
})
}
// pkRequestHandler manages the pubkey request store. It periodically checks
// with bmd whether the requested identities have been received. If they have,
// it removes them from the pubkey request store and processes messages that
// need that identity.
func (s *server) pkRequestHandler() {
defer s.wg.Done()
t := time.NewTicker(pkCheckerInterval)
for {
select {
case <-s.quit:
return
case <-t.C:
var mtx sync.Mutex // Protect the following map
addresses := make(map[string]identity.Public)
var wg sync.WaitGroup
// Go through our store and check if server has any new public
// identity.
s.pk.ForEach(func(address string, reqCount uint32,
lastReqTime time.Time) error {
serverLog.Debugf("Checking whether we have public key for %s.",
address)
wg.Add(1)
// Run requests in parellel because they're I/O dependent.
go func(addr string) {
defer wg.Done()
public, err := s.bmd.GetIdentity(addr)
if err == rpc.ErrIdentityNotFound {
serverLog.Debug("identity not found for ", addr)
// TODO Check whether lastReqTime has exceeded a set
// constant. If it has, send a new request.
// TODO Check whether reqCount has exceeded a set
// constant. If it has, delete the message from queue
// and generate a bounce message.
return
} else if err != nil {
rpccLog.Errorf("GetIdentity(%s) gave unexpected error %v",
addr, err)
return
}
mtx.Lock()
addresses[addr] = public
mtx.Unlock()
}(address)
return nil
})
wg.Wait()
for address, public := range addresses {
serverLog.Debugf("Received pubkey for %s. Processing pending messages.",
address)
// Process pending messages with this public identity and add
// them to pow queue.
for _, user := range s.imapUser {
err := user.DeliverPublic(address, public)
if err != nil {
serverLog.Error("DeliverPublic failed: ", err)
}
}
// Now that we have the public identities, remove them from the
// PK request store.
err := s.pk.Remove(address)
if err != nil {
serverLog.Critical("Failed to remove address from public"+
" key request store: ", err)
}
}
}
}
}
// Send the object out on the network.
func (s *server) Send(obj []byte) error {
_, err := s.bmd.SendObject(obj)
if err != nil {
serverLog.Error("Failed to send object:", err)
return err
}
return nil
}
// savePeriodically periodically saves data in memory to the disk. This is to
// ensure that everything isn't lost in case of power failure/sudden shutdown.
func (s *server) savePeriodically() {
defer s.wg.Done()
t := time.NewTicker(saveInterval)
for {
select {
case <-s.quit:
return
case <-t.C:
s.saveData()
}
}
}
// saveData saves any data in memory to disk. This includes writing the keyfile
// and counter values to the store.
func (s *server) saveData() {
for _, user := range s.users {
user.SaveKeyfile()
}
// Save counter values to store.
err := s.store.SetCounter(wire.ObjectTypeMsg,
atomic.LoadUint64(&s.msgCounter))
if err != nil {
serverLog.Critical("Failed to save message counter:", err)
}
err = s.store.SetCounter(wire.ObjectTypeBroadcast,
atomic.LoadUint64(&s.broadcastCounter))
if err != nil {
serverLog.Critical("Failed to save broadcast counter:", err)
}
err = s.store.SetCounter(wire.ObjectTypeGetPubKey,
atomic.LoadUint64(&s.getpubkeyCounter))
if err != nil {
serverLog.Critical("Failed to save getpubkey counter:", err)
}
}
// getOrRequestPublicIdentity retrieves the needed public identity from bmd
// or sends a getpubkey request if it doesn't exist in its database. If both
// return types are nil, it means a getpubkey request has been queued.
func (s *server) getOrRequestPublicIdentity(user uint32, address string) (identity.Public, error) {
serverLog.Debug("getOrRequestPublicIdentity called for ", address)
id, err := s.bmd.GetIdentity(address)
if err == nil {
return id, nil
} else if err != rpc.ErrIdentityNotFound {
return nil, err
}
addr, err := bmutil.DecodeAddress(address)
if err != nil {
return nil, fmt.Errorf("Failed to decode address: %v", err)
}
serverLog.Debug("getOrRequestPublicIdentity: address not found, send pubkey request.")
// We don't have the identity so craft a getpubkey request.
msg := obj.NewGetPubKey(0, time.Now().Add(defaultGetpubkeyExpiry), addr)
// Enqueue the request for proof-of-work.
b := wire.Encode(msg)[8:] // exclude nonce
target := pow.CalculateTarget(uint64(len(b)),
uint64(msg.Header().Expiration().Sub(time.Now()).Seconds()),
pow.Default)
s.pow.Run(target, b, func(nonce pow.Nonce) {
err := s.Send(append(nonce.Bytes(), b...))
if err != nil {
serverLog.Error("Could not run pow: ", err)
}
// Store a record of the public key request.
count, _ := s.pk.New(address)
serverLog.Tracef("getOrRequestPublicIdentity: Requested address %s %d time(s).",
address, count)
})
return nil, nil
}
// Stop shutdowns all the servers.
func (s *server) Stop() {
// Make sure this only happens once.
if atomic.AddInt32(&s.shutdown, 1) != 1 {
return
}
// Save any data in memory.
s.saveData()
// Close all SMTP listeners.
for _, l := range s.smtpListeners {
l.Close()
}
// Close all IMAP listeners.
for _, l := range s.imapListeners {
l.Close()
}
s.imapUser = nil // Prevent pointer cycle.
s.bmd.Stop()
if s.rpcServer != nil {
s.rpcServer.Stop()
}
close(s.quit)
}
// WaitForShutdown waits until all the servers and RPC client have stopped
// before returning.
func (s *server) WaitForShutdown() {
s.wg.Wait()
s.bmd.WaitForShutdown()
}