/
client.go
1472 lines (1299 loc) · 41.8 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
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
// The Pond client consists of a number of goroutines:
//
// The initial goroutine handles GTK and sits in the GTK event loop most of the
// time. It reads requests to change the UI from UI.Actions() and writes UI
// events to UI.Events(). Since its sitting in a GTK mainloop, after writing to
// UI.Actions(), UI.Signal() must be called which wakes up the UI goroutine and
// triggers the processing of any pending requests.
//
// The "main" goroutine is started immediately and exclusively drives the UI.
// The reason that the "main" goroutine isn't the initial goroutine is that, on
// OS X, the system really likes the native UI calls to be made from the
// initial thread.
//
// The main goroutine drives the startup process, loads state from disk etc.
// During startup it interacts with the UI channels directly but once startup
// has completed it sits in nextEvent(). The UI goroutine is callback based
// because GTK is callback based, but the main goroutine has a synchronous
// model. The nextEvent() call reads from a number of differnet channels,
// including UI.Events() and either processes the event directly, returns the
// event to the calling function, or returns and indicates that it's a global
// event. Global events are basically clicks on the left-hand-side of the UI
// which stop the current UI flow and start a different one.
//
// There are two utility goroutines with which the main goroutine communicates:
//
// The state writing goroutine is passed the serialised state for writing to
// the disk every time c.save() is called. It avoids having disk or TPM latency
// hang the main goroutine.
//
// The network goroutine handles sending and receiving messages. It shares a
// locked queue with the main goroutine in the form of client.queue. Once
// something has been added to the queue, the network goroutine owns it. This
// is complex when it comes to handling revocations because that involves
// resigning messages that have already been queued and thus part of the
// handling has to happen on the network goroutine.
//
// Lastly there are two types of O(n) goroutines: detachment and PANDA
// goroutines.
//
// Detachment goroutines handle the encryption/decryption and upload/download
// of detactments. They feed their results back into nextEvent().
//
// PANDA goroutines handle shared-secret key exchanges. They spend most of
// their time sleeping, waiting to poll the MeetingPlace. In tests, the mock
// MeetingPlace can be gracefully shutdown but, in normal operation, these
// goroutines are just killed. Their state is preserved because it's serialised
// whenever they write a log message.
//
//
// There are two flags that affect operation: dev and testing. Development mode
// is triggered by an environment variable: POND=dev. It causes a number of
// changes, including: servers are not contacted over Tor, fetches happen once
// every 5 seconds and the default server is on localhost.
//
// In addition to dev mode, there's testing mode. (Testing mode implies dev.)
// Testing mode is used by the unittests and generally changes things so that
// the tests can fully synchonise and avoid non-determinism.
import (
"bufio"
"bytes"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"sort"
"strconv"
"sync"
"time"
"github.com/agl/ed25519"
"github.com/agl/ed25519/extra25519"
"github.com/agl/pond/bbssig"
"github.com/agl/pond/client/disk"
"github.com/agl/pond/client/ratchet"
"github.com/agl/pond/panda"
pond "github.com/agl/pond/protos"
"github.com/golang/protobuf/proto"
"golang.org/x/crypto/curve25519"
"golang.org/x/crypto/nacl/secretbox"
)
const (
// messageLifetime is the default amount of time for which we'll keep a
// message. (Counting from the time that it was received.)
messageLifetime = 7 * 24 * time.Hour
// messagePreIndicationLifetime is the amount of time that a message
// remains before the background color changes to indicate that it will
// be deleted soon.
messagePreIndicationLifetime = 6 * 24 * time.Hour
// messageGraceTime is the amount of time that we'll leave a message
// before deletion after it has been marked as not-retained, or after
// startup.
messageGraceTime = 5 * time.Minute
// The current protocol version implemented by this code.
protoVersion = 1
)
const (
shortTimeFormat = "Jan _2 15:04"
logTimeFormat = "Jan _2 15:04:05"
keyExchangePEM = "POND KEY EXCHANGE"
)
// client is the main structure containing most of the client's state.
type client struct {
// testing is true in unittests and disables some assertions that are
// needed in the real world, but which make testing difficult.
testing bool
// dev is true if POND=dev is in the environment. Unittests also set this.
dev bool
// autoFetch controls whether the network goroutine performs periodic
// transactions or waits for outside prompting.
autoFetch bool
// newMeetingPlace is a function that returns a PANDA MeetingPlace. In
// tests this can be overridden to return a testing meeting place.
newMeetingPlace func() panda.MeetingPlace
ui UI
// stateFilename is the filename of the file on disk in which we
// load/save our state.
stateFilename string
// stateLock protects the state against concurrent access by another
// program.
stateLock *disk.Lock
// torAddress contains a string like "127.0.0.1:9050", which specifies
// the address of the local Tor SOCKS proxy.
torAddress string
// server is the URL of the user's home server.
server string
// identity is a curve25519 private value that's used to authenticate
// the client to its home server.
identity, identityPublic [32]byte
// groupPriv is the group private key for the user's delivery group.
groupPriv *bbssig.PrivateKey
// prevGroupPrivs contains previous group private keys that have been
// revoked. This allows us to process messages that were inflight at
// the time of the revocation.
prevGroupPrivs []previousGroupPrivateKey
// generation is the generation number of the group private key and is
// incremented when a member of the group is revoked.
generation uint32
// priv is an Ed25519 private key.
priv [64]byte
// pub is the public key corresponding to |priv|.
pub [32]byte
rand io.Reader
// lastErasureStorageTime is the time at which we last rotated the
// erasure storage value.
lastErasureStorageTime time.Time
// writerChan is a channel that the disk goroutine reads from to
// receive updated, serialised states.
writerChan chan disk.NewState
// writerDone is a channel that is closed by the disk goroutine when it
// has finished all pending updates.
writerDone chan struct{}
// fetchNowChan is the channel that the network goroutine reads from
// that triggers an immediate network transaction. Mostly intended for
// testing.
fetchNowChan chan chan bool
log *Log
// outbox contains all outgoing messages.
outbox []*queuedMessage
drafts map[uint64]*Draft
contacts map[uint64]*Contact
inbox []*InboxMessage
// queue is a queue of messages for transmission that's shared with the
// network goroutine and protected by queueMutex.
queue []*queuedMessage
queueMutex sync.Mutex
// newMessageChan receives messages that have been read from the home
// server by the network goroutine.
newMessageChan chan NewMessage
// messageSentChan receives the ids of messages that have been sent by
// the network goroutine.
messageSentChan chan messageSendResult
// backgroundChan is used for signals from background processes - e.g.
// detachment uploads.
backgroundChan chan interface{}
// pandaChan receives messages from goroutines in runPANDA about
// changes to PANDA key exchange state.
pandaChan chan pandaUpdate
// pandaWaitGroup is incremented for each running PANDA goroutine.
pandaWaitGroup sync.WaitGroup
// signingRequestChan receives requests to sign messages for delivery,
// just before they are sent to the destination server.
signingRequestChan chan signingRequest
// usedIds records ID numbers that have been assigned in the current
// state file.
usedIds map[uint64]bool
// timerChan fires every two minutes so that messages can be erased.
timerChan <-chan time.Time
// nowFunc is a function that, if not nil, will be used by the GUI to
// get the current time. This is used in testing.
nowFunc func() time.Time
// simulateOldClient causes the client to act like a pre-ratchet client
// for testing purposes.
simulateOldClient bool
// disableV2Ratchet causes the client to advertise and process V1
// axolotl ratchet support.
disableV2Ratchet bool
// receiveHookCommand is command to run upon receiving a message.
receiveHookCommand string
}
// UI abstracts behaviour that is specific to a given interface (GUI or CLI).
// Generic code can call these functions to perform interface-specific
// behaviour.
type UI interface {
initUI()
// loadingUI shows a basic "loading" prompt while the state file is read.
loadingUI()
// torPromptUI prompts the user to start Tor.
torPromptUI() error
// sleepUI waits the given amount of time or never returns if the user
// closes the UI.
sleepUI(d time.Duration) error
// errorUI shows an error and returns.
errorUI(msg string, fatal bool)
// ShutdownAndSuspend quits the program - possibly waiting for the user
// to close the window in the case of a GUI so any error message can be
// read first.
ShutdownAndSuspend() error
createPassphraseUI() (string, error)
createErasureStorage(pw string, stateFile *disk.StateFile) error
// createAccountUI allows the user to either create a new account or to
// import from a entombed statefile. It returns whether an import
// occured and an error.
createAccountUI(stateFile *disk.StateFile, pw string) (bool, error)
keyPromptUI(stateFile *disk.StateFile) error
processFetch(msg *InboxMessage)
processServerAnnounce(announce *InboxMessage)
processAcknowledgement(ackedMsg *queuedMessage)
// processRevocationOfUs is called when a revocation is received that
// revokes our group key for a contact.
processRevocationOfUs(by *Contact)
// processRevocation is called when we have finished processing a
// revocation. This includes revocations of others and of this
// ourselves. In the latter case, this is called after
// processRevocationOfUs.
processRevocation(by *Contact)
// processMessageSent is called when an outbox message has been
// delivered to the destination server.
processMessageDelivered(msg *queuedMessage)
// processPANDAUpdateUI is called on each PANDA update to update the
// UI and unseal pending messages.
processPANDAUpdateUI(update pandaUpdate)
// removeInboxMessageUI removes a message from the inbox UI.
removeInboxMessageUI(msg *InboxMessage)
// removeOutboxMessageUI removes a message from the outbox UI.
removeOutboxMessageUI(msg *queuedMessage)
// addRevocationMessageUI notifies the UI that a new revocation message
// has been created.
addRevocationMessageUI(msg *queuedMessage)
// removeContactUI removes a contact from the UI.
removeContactUI(contact *Contact)
// logEventUI is called when an exceptional event has been logged for
// the given contact.
logEventUI(contact *Contact, event Event)
// mainUI starts the main interface.
mainUI()
}
type messageSendResult struct {
// If the id is zero then a message wasn't actually sent - this is just
// the transact goroutine poking the UI because the queue has been
// updated.
id uint64
// revocation optionally contains a revocation update that resulted
// from attempting to send a message.
revocation *pond.SignedRevocation
// extraRevocations optionally contains revocations further to
// |revocation|. This is only non-empty if |revocation| is non-nil.
extraRevocations []*pond.SignedRevocation
}
// signingRequest is a structure that is sent from the network thread to the
// main thread to request that a message be signed with a group signature for
// delivery.
type signingRequest struct {
msg *queuedMessage
resultChan chan *pond.Request
}
// pendingDecryption represents a detachment decryption/download operation
// that's in progress. These are not saved to disk.
type pendingDecryption struct {
// index is used by the UI code and indexes the list of detachments in
// a message.
index int
// cancel is a thunk that causes the task to be canceled at some point
// in the future.
cancel func()
}
// cliId represents a short, unique ID that is assigned by the command-line
// interface so that users can select an object by typing a short sequence of
// letters and digits. The value is 15 bits long and represented as a string in
// z-base-32.
type cliId uint
const invalidCliId cliId = 0
// See http://philzimmermann.com/docs/human-oriented-base-32-encoding.txt
const zBase32Chars = "ybndrfg8ejkmcpqxot1uwisza345h769"
func (id cliId) String() string {
var chars [3]byte
for i := range chars {
chars[i] = zBase32Chars[id&31]
id >>= 5
}
return string(chars[:])
}
func cliIdFromString(s string) (id cliId, ok bool) {
if len(s) != 3 {
return
}
var shift uint
NextChar:
for _, r := range s {
for i, r2 := range zBase32Chars {
if r == r2 {
id |= cliId(i) << shift
shift += 5
continue NextChar
}
}
return
}
ok = true
return
}
// InboxMessage represents a message in the client's inbox. (Acks also appear
// as InboxMessages, but their message.Body is empty.)
type InboxMessage struct {
id uint64
read bool
receivedTime time.Time
from uint64
// sealed contained the encrypted message if the contact who sent this
// message is still pending.
sealed []byte
acked bool
// message may be nil if the contact who sent this is pending. In this
// case, sealed with contain the encrypted message.
message *pond.Message
// cliId is a number, assigned by the command-line interface, to
// identity this message for the duration of the session. It's not
// saved to disk.
cliId cliId
// retained is true if the user has chosen to retain this message -
// i.e. to opt it out of the usual, time-based, auto-deletion.
retained bool
// exposureTime contains the time when the message was last "exposed".
// This is used to allow a small period of time for the user to mark a
// message as retained (messageGraceTime). For example, if a message is
// loaded at startup and has expired then it's a candidate for
// deletion, but the exposureTime will be the startup time, which
// ensures that we leave it a few minutes before deletion. Setting
// retained to false also resets the exposureTime.
exposureTime time.Time
decryptions map[uint64]*pendingDecryption
}
func (msg *InboxMessage) Strings() (sentTime, eraseTime, body string) {
isPending := msg.message == nil
if isPending {
body = "(cannot display message as key exchange is still pending)"
sentTime = "(unknown)"
} else {
sentTime = time.Unix(*msg.message.Time, 0).Format(time.RFC1123)
body = "(cannot display message as encoding is not supported)"
if msg.message.BodyEncoding != nil {
switch *msg.message.BodyEncoding {
case pond.Message_RAW:
body = string(msg.message.Body)
}
}
}
eraseTime = msg.receivedTime.Add(messageLifetime).Format(time.RFC1123)
return
}
// NewMessage is sent from the network goroutine to the client goroutine and
// contains messages fetched from the home server.
type NewMessage struct {
fetched *pond.Fetched
announce *pond.ServerAnnounce
ack chan bool
}
// Contact represents a contact to which we can send messages.
type Contact struct {
// id is only locally valid.
id uint64
// name is the friendly name that the user chose for this contact. It
// is unique for all contacts.
name string
// isPending is true if we haven't received a key exchange message from
// this contact.
isPending bool
// kxsBytes is the serialised key exchange message that we generated
// for this contact. (Only valid if |isPending| is true.)
kxsBytes []byte
// groupKey is the group member key that we gave to this contact.
// myGroupKey is the one that they gave to us.
groupKey, myGroupKey *bbssig.MemberKey
// previousTags contains bbssig tags that were previously used by this
// contact. The tag of a contact changes when a recovation is
// processed, but old messages may still be queued.
previousTags []previousTag
// generation is the current group generation number that we know for
// this contact.
generation uint32
// theirServer is the URL of the contact's home server.
theirServer string
// theirPub is their Ed25519 public key.
theirPub [32]byte
// theirIdentityPublic is the public identity that their home server
// knows them by.
theirIdentityPublic [32]byte
// supportedVersion contains the greatest protocol version number that
// we have observed from this contact.
supportedVersion int32
// revoked is true if this contact has been revoked.
revoked bool
// revokedUs is true if this contact has recoved us.
revokedUs bool
// pandaKeyExchange contains the serialised PANDA state if a key
// exchange is ongoing.
pandaKeyExchange []byte
// pandaShutdownChan is a channel that can be closed to trigger the
// shutdown of an individual PANDA exchange.
pandaShutdownChan chan struct{}
// pandaResult contains an error message in the event that a PANDA key
// exchange failed.
pandaResult string
// events contains a log of important events relating to this contact.
events []Event
// Members for the old ratchet.
lastDHPrivate [32]byte
currentDHPrivate [32]byte
theirLastDHPublic [32]byte
theirCurrentDHPublic [32]byte
// New ratchet support.
ratchet *ratchet.Ratchet
cliId cliId
}
// Event represents a log entry. This does not apply to the global log, which
// is quite chatty, but rather to significant events related to a given
// contact. These events are surfaced in the UI and recorded in the statefile.
type Event struct {
t time.Time
msg string
}
// contactList is a sortable slice of Contacts.
type contactList []*Contact
func (cl contactList) Len() int {
return len(cl)
}
func (cl contactList) Less(i, j int) bool {
return cl[i].name < cl[j].name
}
func (cl contactList) Swap(i, j int) {
cl[i], cl[j] = cl[j], cl[i]
}
func (c *client) contactsSorted() []*Contact {
contacts := contactList(make([]*Contact, 0, len(c.contacts)))
for _, contact := range c.contacts {
contacts = append(contacts, contact)
}
sort.Sort(contacts)
return contacts
}
// previousTagLifetime contains the amount of time that we'll store a previous
// tag (or previous group private key) for.
const previousTagLifetime = 14 * 24 * time.Hour
// previousTag represents a group signature tag that was previously assigned to
// a contact. In the event of a revocation, all the tags change but we need to
// know the previous tags for a certain amount of time because messages may
// have been created before the contact saw the revocation update.
type previousTag struct {
tag []byte
// expired contains the time at which this tag was expired - i.e. the
// timestamp when the revocation occured.
expired time.Time
}
// previousGroupPrivateKey represents a group private key that has been
// revoked. These are retained for the same reason as previous tags.
type previousGroupPrivateKey struct {
priv *bbssig.PrivateKey
// expired contains the time at which this tag was expired - i.e. the
// timestamp when the revocation occured.
expired time.Time
}
// pendingDetachment represents a detachment conversion/upload operation that's
// in progress. These are not saved to disk.
type pendingDetachment struct {
size int64
path string
cancel func()
}
type Draft struct {
id uint64
created time.Time
to uint64
body string
inReplyTo uint64
attachments []*pond.Message_Attachment
detachments []*pond.Message_Detachment
// cliId is a number, assigned by the command-line interface, to
// identity this message for the duration of the session. It's not
// saved to disk.
cliId cliId
// pendingDetachments is only used by the GTK UI.
pendingDetachments map[uint64]*pendingDetachment
}
// prettyNumber formats n in base 10 and puts commas between groups of
// thousands.
func prettyNumber(n uint64) string {
s := strconv.FormatUint(n, 10)
ret := make([]rune, 0, len(s)*2)
phase := len(s) % 3
for i, r := range s {
if phase == 0 && i > 0 {
ret = append(ret, ',')
}
ret = append(ret, r)
phase--
if phase < 0 {
phase += 3
}
}
return string(ret)
}
// usageString returns a description of the amount of space taken up by a body
// with the given contents and a bool indicating overflow.
func (draft *Draft) usageString() (string, bool) {
var replyToId *uint64
if draft.inReplyTo != 0 {
replyToId = proto.Uint64(1)
}
var dhPub [32]byte
msg := &pond.Message{
Id: proto.Uint64(0),
Time: proto.Int64(1 << 62),
Body: []byte(draft.body),
BodyEncoding: pond.Message_RAW.Enum(),
InReplyTo: replyToId,
MyNextDh: dhPub[:],
Files: draft.attachments,
DetachedFiles: draft.detachments,
SupportedVersion: proto.Int32(protoVersion),
}
serialized, err := proto.Marshal(msg)
if err != nil {
panic("error while serialising candidate Message: " + err.Error())
}
s := fmt.Sprintf("%s of %s bytes", prettyNumber(uint64(len(serialized))), prettyNumber(pond.MaxSerializedMessage))
return s, len(serialized) > pond.MaxSerializedMessage
}
type queuedMessage struct {
request *pond.Request
id uint64
to uint64
server string
created time.Time
sent time.Time
acked time.Time
revocation bool
message *pond.Message
// sending is true if the transact goroutine is currently sending this
// message. This is protected by the queueMutex.
sending bool
// cliId is a number, assigned by the command-line interface, to
// identity this message for the duration of the session. It's not
// saved to disk.
cliId cliId
}
func (qm *queuedMessage) indicator(contact *Contact) Indicator {
switch {
case !qm.acked.IsZero():
return indicatorGreen
case !qm.sent.IsZero():
if qm.revocation {
// Revocations are never acked so they are green as
// soon as they are sent.
return indicatorGreen
}
return indicatorYellow
case contact != nil && contact.revokedUs:
return indicatorBlack
}
return indicatorRed
}
// outboxToDraft converts an outbox message back to a Draft. This is used when
// the user aborts the sending of a message.
func (c *client) outboxToDraft(msg *queuedMessage) *Draft {
draft := &Draft{
id: msg.id,
created: msg.created,
to: msg.to,
body: string(msg.message.Body),
attachments: msg.message.Files,
detachments: msg.message.DetachedFiles,
}
if irt := msg.message.GetInReplyTo(); irt != 0 {
// The inReplyTo value of a draft references *our* id for the
// inbox message. But the InReplyTo field of a pond.Message
// references's the contact's id for the message. So we need to
// enumerate the messages in the inbox from that contact and
// find the one with the matching id.
for _, inboxMsg := range c.inbox {
if inboxMsg.from == msg.to && inboxMsg.message != nil && inboxMsg.message.GetId() == irt {
draft.inReplyTo = inboxMsg.id
break
}
}
}
return draft
}
func (c *client) ContactName(id uint64) string {
if id == 0 {
return "Home Server"
}
return c.contacts[id].name
}
// detectTor sets c.torAddress, either from the POND_TOR_ADDRESS environment
// variable if it is set or by attempting to connect to port 9050 and 9150 on
// the local host and assuming that Tor is running on the first port that it
// finds to be open.
func (c *client) detectTor() bool {
c.torAddress = "127.0.0.1:9050" // default for dev mode.
if addr := os.Getenv("POND_TOR_ADDRESS"); len(addr) != 0 {
if _, _, err := net.SplitHostPort(addr); err != nil {
c.log.Printf("Ignoring POND_TOR_ADDRESS because of parse error: %s", err)
} else {
c.torAddress = addr
c.log.Printf("Using POND_TOR_ADDRESS=%s", addr)
return true
}
}
ports := []int{9050, 9150}
for _, port := range ports {
addr := fmt.Sprintf("127.0.0.1:%d", port)
conn, err := net.Dial("tcp", addr)
if err != nil {
continue
}
c.torAddress = addr
conn.Close()
return true
}
return false
}
var knownServers = []struct {
nickname string
description string
uri string
}{
{"wau", "Wau Holland Foundation", "pondserver://25WHHEVD3565FGIOXJZWV7LGQFR4BTO3HF3FWHEW7PCYPFMFPVOQ@vx652n4utsodj5c6.onion"},
{"hoi", "Hoi Polloi (https://hoi-polloi.org)", "pondserver://4V6Q5M2AFLBW6UIYL2B5LMKDHEBA6HRHR6UIUU3VDQFNI3BHZAEQ@oum7argqrnlzpcro.onion"},
}
func (c *client) enqueue(m *queuedMessage) {
c.queueMutex.Lock()
defer c.queueMutex.Unlock()
c.queue = append(c.queue, m)
}
func maybeTruncate(s string) string {
if runes := []rune(s); len(runes) > 30 {
runes = runes[:30]
runes = append(runes, 0x2026 /* ellipsis */)
return string(runes)
}
return s
}
func formatTime(t time.Time) string {
if t.IsZero() {
return "(not yet)"
}
return t.Format(time.RFC1123)
}
var errInterrupted = errors.New("cli: interrupt signal")
func (c *client) loadUI() error {
c.ui.initUI()
if !c.detectTor() && !c.dev {
if err := c.ui.torPromptUI(); err != nil {
return err
}
}
c.receiveHookCommand = os.Getenv("POND_HOOK_RECEIVE")
c.ui.loadingUI()
stateFile := &disk.StateFile{
Path: c.stateFilename,
Rand: c.rand,
Log: func(format string, args ...interface{}) {
c.log.Printf(format, args...)
},
}
var newAccount, imported bool
var err error
if c.stateLock, err = stateFile.Lock(false /* don't create */); err == nil && c.stateLock == nil {
c.ui.errorUI("State file locked by another process. Waiting for lock.", false)
c.log.Errorf("Waiting for locked state file")
for {
if c.stateLock, err = stateFile.Lock(false /* don't create */); c.stateLock != nil {
break
}
if err := c.ui.sleepUI(1 * time.Second); err != nil {
return err
}
}
} else if err == nil {
} else if os.IsNotExist(err) {
newAccount = true
} else {
c.ui.errorUI(err.Error(), true)
if err := c.ui.ShutdownAndSuspend(); err != nil {
return err
}
}
if newAccount {
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
panic(err)
}
copy(c.priv[:], priv[:])
copy(c.pub[:], pub[:])
if c.disableV2Ratchet {
c.randBytes(c.identity[:])
} else {
extra25519.PrivateKeyToCurve25519(&c.identity, priv)
}
curve25519.ScalarBaseMult(&c.identityPublic, &c.identity)
c.groupPriv, err = bbssig.GenerateGroup(rand.Reader)
if err != nil {
panic(err)
}
pw, err := c.ui.createPassphraseUI()
if err != nil {
return err
}
c.ui.createErasureStorage(pw, stateFile)
imported, err = c.ui.createAccountUI(stateFile, pw)
if err != nil {
return err
}
} else {
// First try with zero key.
err := c.loadState(stateFile, "")
for err == disk.BadPasswordError {
// That didn't work, try prompting for a key.
err = c.ui.keyPromptUI(stateFile)
}
if err == errInterrupted {
return err
}
if err != nil {
// Fatal error loading state. Abort.
c.ui.errorUI(err.Error(), true)
if err := c.ui.ShutdownAndSuspend(); err != nil {
return err
}
}
}
if newAccount && !imported {
c.stateLock, err = stateFile.Lock(true /* create */)
if err != nil {
err = errors.New("Failed to create state file: " + err.Error())
} else if c.stateLock == nil {
err = errors.New("Failed to obtain lock on created state file")
}
if err != nil {
c.ui.errorUI(err.Error(), true)
if err := c.ui.ShutdownAndSuspend(); err != nil {
return err
}
}
c.lastErasureStorageTime = time.Now()
}
c.writerChan = make(chan disk.NewState)
c.writerDone = make(chan struct{})
c.fetchNowChan = make(chan chan bool, 1)
// Start disk and network workers.
go stateFile.StartWriter(c.writerChan, c.writerDone)
go c.transact()
if newAccount {
c.save()
}
// Start any pending key exchanges.
for _, contact := range c.contacts {
if len(contact.pandaKeyExchange) == 0 {
continue
}
c.pandaWaitGroup.Add(1)
contact.pandaShutdownChan = make(chan struct{})
go c.runPANDA(contact.pandaKeyExchange, contact.id, contact.name, contact.pandaShutdownChan)
}
c.ui.mainUI()
return nil
}
func (contact *Contact) subline() string {
switch {
case contact.revokedUs:
return "has revoked"
case contact.isPending:
return "pending"
case len(contact.pandaResult) > 0:
return "failed"
case !contact.isPending && contact.ratchet == nil:
return "old ratchet"
}
return ""
}
func (contact *Contact) indicator() Indicator {
switch {
case contact.revokedUs:
return indicatorBlack
case contact.isPending:
return indicatorYellow
}
return indicatorNone
}
func (contact *Contact) processKeyExchange(kxsBytes []byte, testing, simulateOldClient, disableV2Ratchet bool) error {
var kxs pond.SignedKeyExchange
if err := proto.Unmarshal(kxsBytes, &kxs); err != nil {
return err
}
var sig [64]byte
if len(kxs.Signature) != len(sig) {
return errors.New("invalid signature length")
}
copy(sig[:], kxs.Signature)
var kx pond.KeyExchange
if err := proto.Unmarshal(kxs.Signed, &kx); err != nil {
return err
}
if len(kx.PublicKey) != len(contact.theirPub) {
return errors.New("invalid public key")
}
copy(contact.theirPub[:], kx.PublicKey)
if !ed25519.Verify(&contact.theirPub, kxs.Signed, &sig) {
return errors.New("invalid signature")
}
contact.theirServer = *kx.Server
if _, _, err := parseServer(contact.theirServer, testing); err != nil {
return err
}
group, ok := new(bbssig.Group).Unmarshal(kx.Group)
if !ok {
return errors.New("invalid group")
}
if contact.myGroupKey, ok = new(bbssig.MemberKey).Unmarshal(group, kx.GroupKey); !ok {
return errors.New("invalid group key")
}
if len(kx.IdentityPublic) != len(contact.theirIdentityPublic) {
return errors.New("invalid public identity")
}
copy(contact.theirIdentityPublic[:], kx.IdentityPublic)
if simulateOldClient {
kx.Dh1 = nil
}
if len(kx.Dh1) == 0 {
// They are using an old-style ratchet. We have to extract the
// private value from the Ratchet in order to use it with the
// old code.
contact.lastDHPrivate = contact.ratchet.GetKXPrivateForTransition()
if len(kx.Dh) != len(contact.theirCurrentDHPublic) {
return errors.New("invalid public DH value")
}
copy(contact.theirCurrentDHPublic[:], kx.Dh)
contact.ratchet = nil
} else {
// If the identity and ed25519 public keys are the same (modulo
// isomorphism) then the contact is using the v2 ratchet.
var ed25519Public, curve25519Public [32]byte
copy(ed25519Public[:], kx.PublicKey)
extra25519.PublicKeyToCurve25519(&curve25519Public, &ed25519Public)
v2 := !disableV2Ratchet && bytes.Equal(curve25519Public[:], kx.IdentityPublic[:])
if err := contact.ratchet.CompleteKeyExchange(&kx, v2); err != nil {
return err
}
}
contact.generation = *kx.Generation
return nil
}
// logEvent records an exceptional event relating to the given contact.
func (c *client) logEvent(contact *Contact, msg string) {
event := Event{
t: time.Now(),
msg: msg,
}
contact.events = append(contact.events, event)
c.log.Errorf("While processing message from %s: %s", contact.name, msg)
c.ui.logEventUI(contact, event)
}
func (c *client) randBytes(buf []byte) {
if _, err := io.ReadFull(c.rand, buf); err != nil {
panic(err)
}
}