-
Notifications
You must be signed in to change notification settings - Fork 71
/
ui.go
1940 lines (1746 loc) · 58.8 KB
/
ui.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
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/xml"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/agl/xmpp-client/xmpp"
"golang.org/x/crypto/otr"
"golang.org/x/crypto/ssh/terminal"
"golang.org/x/net/html"
"golang.org/x/net/proxy"
)
var configFile *string = flag.String("config-file", "", "Location of the config file")
var createAccount *bool = flag.Bool("create", false, "If true, attempt to create account")
// OTRWhitespaceTagStart may be appended to plaintext messages to signal to the
// remote client that we support OTR. It should be followed by one of the
// version specific tags, below. See "Tagged plaintext messages" in
// http://www.cypherpunks.ca/otr/Protocol-v3-4.0.0.html.
var OTRWhitespaceTagStart = []byte("\x20\x09\x20\x20\x09\x09\x09\x09\x20\x09\x20\x09\x20\x09\x20\x20")
var OTRWhiteSpaceTagV1 = []byte("\x20\x09\x20\x09\x20\x20\x09\x20")
var OTRWhiteSpaceTagV2 = []byte("\x20\x20\x09\x09\x20\x20\x09\x20")
var OTRWhiteSpaceTagV3 = []byte("\x20\x20\x09\x09\x20\x20\x09\x09")
var OTRWhitespaceTag = append(OTRWhitespaceTagStart, OTRWhiteSpaceTagV2...)
// appendTerminalEscaped acts like append(), but breaks terminal escape
// sequences that may be in msg.
func appendTerminalEscaped(out, msg []byte) []byte {
for _, c := range msg {
if c == 127 || (c < 32 && c != '\t') {
out = append(out, '?')
} else {
out = append(out, c)
}
}
return out
}
func stripHTML(msg []byte) (out []byte) {
z := html.NewTokenizer(bytes.NewReader(msg))
loop:
for {
tt := z.Next()
switch tt {
case html.TextToken:
out = append(out, z.Text()...)
case html.ErrorToken:
if err := z.Err(); err != nil && err != io.EOF {
out = msg
return
}
break loop
}
}
return
}
func terminalMessage(term *terminal.Terminal, color []byte, msg string, critical bool) {
line := make([]byte, 0, len(msg)+16)
line = append(line, ' ')
line = append(line, color...)
line = append(line, '*')
line = append(line, term.Escape.Reset...)
line = append(line, []byte(fmt.Sprintf(" (%s) ", time.Now().Format(time.Kitchen)))...)
if critical {
line = append(line, term.Escape.Red...)
}
line = appendTerminalEscaped(line, []byte(msg))
if critical {
line = append(line, term.Escape.Reset...)
}
line = append(line, '\n')
term.Write(line)
}
func info(term *terminal.Terminal, msg string) {
terminalMessage(term, term.Escape.Blue, msg, false)
}
func warn(term *terminal.Terminal, msg string) {
terminalMessage(term, term.Escape.Magenta, msg, false)
}
func alert(term *terminal.Terminal, msg string) {
terminalMessage(term, term.Escape.Red, msg, false)
}
func critical(term *terminal.Terminal, msg string) {
terminalMessage(term, term.Escape.Red, msg, true)
}
type Session struct {
account string
conn *xmpp.Conn
term *terminal.Terminal
roster []xmpp.RosterEntry
input Input
// conversations maps from a JID (without the resource) to an OTR
// conversation. (Note that unencrypted conversations also pass through
// OTR.)
conversations map[string]*otr.Conversation
// knownStates maps from a JID (without the resource) to the last known
// presence state of that contact. It's used to deduping presence
// notifications.
knownStates map[string]string
privateKey *otr.PrivateKey
config *Config
// lastMessageFrom is the JID (without the resource) of the contact
// that we last received a message from.
lastMessageFrom string
// timeouts maps from Cookies (from outstanding requests) to the
// absolute time when that request should timeout.
timeouts map[xmpp.Cookie]time.Time
// pendingRosterEdit, if non-nil, contains information about a pending
// roster edit operation.
pendingRosterEdit *rosterEdit
// pendingRosterChan is the channel over which roster edit information
// is received.
pendingRosterChan chan *rosterEdit
// pendingSubscribes maps JID with pending subscription requests to the
// ID if the iq for the reply.
pendingSubscribes map[string]string
// lastActionTime is the time at which the user last entered a command,
// or was last notified.
lastActionTime time.Time
// ignored is a list of users from whom messages are currently being
// ignored, e.g. due to doing `/ignore soandso@jabber.foo`
ignored map[string]struct{}
}
// rosterEdit contains information about a pending roster edit. Roster edits
// occur by writing the roster to a file and inviting the user to edit the
// file.
type rosterEdit struct {
// fileName is the name of the file containing the roster information.
fileName string
// roster contains the state of the roster at the time of writing the
// file. It's what we diff against when reading the file.
roster []xmpp.RosterEntry
// isComplete is true if this is the result of reading an edited
// roster, rather than a report that the file has been written.
isComplete bool
// contents contains the edited roster, if isComplete is true.
contents []byte
}
func (s *Session) readMessages(stanzaChan chan<- xmpp.Stanza) {
defer close(stanzaChan)
for {
stanza, err := s.conn.Next()
if err != nil {
alert(s.term, err.Error())
return
}
stanzaChan <- stanza
}
}
func updateTerminalSize(term *terminal.Terminal) {
width, height, err := terminal.GetSize(0)
if err != nil {
return
}
term.SetSize(width, height)
}
func main() {
flag.Parse()
oldState, err := terminal.MakeRaw(0)
if err != nil {
panic(err.Error())
}
defer terminal.Restore(0, oldState)
term := terminal.NewTerminal(os.Stdin, "")
updateTerminalSize(term)
term.SetBracketedPasteMode(true)
defer term.SetBracketedPasteMode(false)
resizeChan := make(chan os.Signal)
go func() {
for _ = range resizeChan {
updateTerminalSize(term)
}
}()
signal.Notify(resizeChan, syscall.SIGWINCH)
if len(*configFile) == 0 {
homeDir := os.Getenv("HOME")
if len(homeDir) == 0 {
alert(term, "$HOME not set. Please either export $HOME or use the -config-file option.\n")
return
}
persistentDir := filepath.Join(homeDir, "Persistent")
if stat, err := os.Lstat(persistentDir); err == nil && stat.IsDir() {
// Looks like Tails.
homeDir = persistentDir
}
*configFile = filepath.Join(homeDir, ".xmpp-client")
}
config, err := ParseConfig(*configFile)
if err != nil {
alert(term, "Failed to parse config file: "+err.Error())
config = new(Config)
if !enroll(config, term) {
return
}
config.filename = *configFile
config.Save()
}
password := config.Password
if len(password) == 0 {
if password, err = term.ReadPassword(fmt.Sprintf("Password for %s (will not be saved to disk): ", config.Account)); err != nil {
alert(term, "Failed to read password: "+err.Error())
return
}
}
term.SetPrompt("> ")
parts := strings.SplitN(config.Account, "@", 2)
if len(parts) != 2 {
alert(term, "invalid username (want user@domain): "+config.Account)
return
}
user := parts[0]
domain := parts[1]
var addr string
addrTrusted := false
if len(config.Server) > 0 && config.Port > 0 {
addr = fmt.Sprintf("%s:%d", config.Server, config.Port)
addrTrusted = true
} else {
if len(config.Proxies) > 0 {
alert(term, "Cannot connect via a proxy without Server and Port being set in the config file as an SRV lookup would leak information.")
return
}
host, port, err := xmpp.Resolve(domain)
if err != nil {
alert(term, "Failed to resolve XMPP server: "+err.Error())
return
}
addr = fmt.Sprintf("%s:%d", host, port)
}
var dialer proxy.Dialer
for i := len(config.Proxies) - 1; i >= 0; i-- {
u, err := url.Parse(config.Proxies[i])
if err != nil {
alert(term, "Failed to parse "+config.Proxies[i]+" as a URL: "+err.Error())
return
}
if dialer == nil {
dialer = proxy.Direct
}
if dialer, err = proxy.FromURL(u, dialer); err != nil {
alert(term, "Failed to parse "+config.Proxies[i]+" as a proxy: "+err.Error())
return
}
}
var certSHA256 []byte
if len(config.ServerCertificateSHA256) > 0 {
certSHA256, err = hex.DecodeString(config.ServerCertificateSHA256)
if err != nil {
alert(term, "Failed to parse ServerCertificateSHA256 (should be hex string): "+err.Error())
return
}
if len(certSHA256) != 32 {
alert(term, "ServerCertificateSHA256 is not 32 bytes long")
return
}
}
var createCallback xmpp.FormCallback
if *createAccount {
createCallback = func(title, instructions string, fields []interface{}) error {
return promptForForm(term, user, password, title, instructions, fields)
}
}
xmppConfig := &xmpp.Config{
Log: &lineLogger{term, nil},
CreateCallback: createCallback,
TrustedAddress: addrTrusted,
Archive: false,
ServerCertificateSHA256: certSHA256,
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS10,
CipherSuites: []uint16{tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
},
},
}
if domain == "jabber.ccc.de" {
// jabber.ccc.de uses CACert but distros are removing that root
// certificate.
roots := x509.NewCertPool()
caCertRoot, err := x509.ParseCertificate(caCertRootDER)
if err == nil {
alert(term, "Temporarily trusting only CACert root for CCC Jabber server")
roots.AddCert(caCertRoot)
xmppConfig.TLSConfig.RootCAs = roots
} else {
alert(term, "Tried to add CACert root for jabber.ccc.de but failed: "+err.Error())
}
}
if len(config.RawLogFile) > 0 {
rawLog, err := os.OpenFile(config.RawLogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
alert(term, "Failed to open raw log file: "+err.Error())
return
}
lock := new(sync.Mutex)
in := rawLogger{
out: rawLog,
prefix: []byte("<- "),
lock: lock,
}
out := rawLogger{
out: rawLog,
prefix: []byte("-> "),
lock: lock,
}
in.other, out.other = &out, &in
xmppConfig.InLog = &in
xmppConfig.OutLog = &out
defer in.flush()
defer out.flush()
}
if dialer != nil {
info(term, "Making connection to "+addr+" via proxy")
if xmppConfig.Conn, err = dialer.Dial("tcp", addr); err != nil {
alert(term, "Failed to connect via proxy: "+err.Error())
return
}
}
conn, err := xmpp.Dial(addr, user, domain, config.Resource, password, xmppConfig)
if err != nil {
alert(term, "Failed to connect to XMPP server: "+err.Error())
return
}
s := Session{
account: config.Account,
conn: conn,
term: term,
conversations: make(map[string]*otr.Conversation),
knownStates: make(map[string]string),
privateKey: new(otr.PrivateKey),
config: config,
pendingRosterChan: make(chan *rosterEdit),
pendingSubscribes: make(map[string]string),
lastActionTime: time.Now(),
// ignored contains UIDs that are currently being ignored.
ignored: make(map[string]struct{}),
}
info(term, "Fetching roster")
//var rosterReply chan xmpp.Stanza
rosterReply, _, err := s.conn.RequestRoster()
if err != nil {
alert(term, "Failed to request roster: "+err.Error())
return
}
conn.SignalPresence("")
s.input = Input{
term: term,
uidComplete: new(priorityList),
}
commandChan := make(chan interface{})
go s.input.ProcessCommands(commandChan)
stanzaChan := make(chan xmpp.Stanza)
go s.readMessages(stanzaChan)
if _, ok := s.privateKey.Parse(config.PrivateKey); !ok {
alert(term, "Failed to parse private key from config")
return
}
s.timeouts = make(map[xmpp.Cookie]time.Time)
info(term, fmt.Sprintf("Your fingerprint is %x", s.privateKey.Fingerprint()))
ticker := time.NewTicker(1 * time.Second)
pingTicker := time.NewTicker(60 * time.Second)
MainLoop:
for {
select {
case <-pingTicker.C:
// Send periodic pings so that we can detect connection timeouts.
s.conn.Ping()
case now := <-ticker.C:
haveExpired := false
for _, expiry := range s.timeouts {
if now.After(expiry) {
haveExpired = true
break
}
}
if !haveExpired {
continue
}
newTimeouts := make(map[xmpp.Cookie]time.Time)
for cookie, expiry := range s.timeouts {
if now.After(expiry) {
s.conn.Cancel(cookie)
} else {
newTimeouts[cookie] = expiry
}
}
s.timeouts = newTimeouts
case edit := <-s.pendingRosterChan:
if !edit.isComplete {
info(s.term, "Please edit "+edit.fileName+" and run /rostereditdone when complete")
s.pendingRosterEdit = edit
continue
}
if s.processEditedRoster(edit) {
s.pendingRosterEdit = nil
} else {
alert(s.term, "Please reedit file and run /rostereditdone again")
}
case rosterStanza, ok := <-rosterReply:
if !ok {
alert(s.term, "Failed to read roster: "+err.Error())
return
}
if s.roster, err = xmpp.ParseRoster(rosterStanza); err != nil {
alert(s.term, "Failed to parse roster: "+err.Error())
return
}
for _, entry := range s.roster {
s.input.AddUser(entry.Jid)
}
info(s.term, "Roster received")
case cmd, ok := <-commandChan:
if !ok {
warn(term, "Exiting because command channel closed")
break MainLoop
}
s.lastActionTime = time.Now()
switch cmd := cmd.(type) {
case quitCommand:
for to, conversation := range s.conversations {
msgs := conversation.End()
for _, msg := range msgs {
s.conn.Send(to, string(msg))
}
}
break MainLoop
case versionCommand:
replyChan, cookie, err := s.conn.SendIQ(cmd.User, "get", xmpp.VersionQuery{})
if err != nil {
alert(s.term, "Error sending version request: "+err.Error())
continue
}
s.timeouts[cookie] = time.Now().Add(5 * time.Second)
go s.awaitVersionReply(replyChan, cmd.User)
case rosterCommand:
info(s.term, "Current roster:")
maxLen := 0
for _, item := range s.roster {
if maxLen < len(item.Jid) {
maxLen = len(item.Jid)
}
}
for _, item := range s.roster {
state, ok := s.knownStates[item.Jid]
line := ""
if ok {
line += "[*] "
} else if cmd.OnlineOnly {
continue
} else {
line += "[ ] "
}
line += item.Jid
numSpaces := 1 + (maxLen - len(item.Jid))
for i := 0; i < numSpaces; i++ {
line += " "
}
line += item.Subscription + "\t" + item.Name
if ok {
line += "\t" + state
}
info(s.term, line)
}
case rosterEditCommand:
if s.pendingRosterEdit != nil {
warn(s.term, "Aborting previous roster edit")
s.pendingRosterEdit = nil
}
rosterCopy := make([]xmpp.RosterEntry, len(s.roster))
copy(rosterCopy, s.roster)
go s.editRoster(rosterCopy)
case rosterEditDoneCommand:
if s.pendingRosterEdit == nil {
warn(s.term, "No roster edit in progress. Use /rosteredit to start one")
continue
}
go s.loadEditedRoster(*s.pendingRosterEdit)
case toggleStatusUpdatesCommand:
s.config.HideStatusUpdates = !s.config.HideStatusUpdates
s.config.Save()
// Tell the user the current state of the statuses
if s.config.HideStatusUpdates {
info(s.term, "Status updates disabled")
} else {
info(s.term, "Status updates enabled")
}
case confirmCommand:
s.handleConfirmOrDeny(cmd.User, true /* confirm */)
case denyCommand:
s.handleConfirmOrDeny(cmd.User, false /* deny */)
case addCommand:
s.conn.SendPresence(cmd.User, "subscribe", "" /* generate id */)
case msgCommand:
conversation, ok := s.conversations[cmd.to]
isEncrypted := ok && conversation.IsEncrypted()
if cmd.setPromptIsEncrypted != nil {
cmd.setPromptIsEncrypted <- isEncrypted
}
if !isEncrypted && config.ShouldEncryptTo(cmd.to) {
warn(s.term, fmt.Sprintf("Did not send: no encryption established with %s", cmd.to))
continue
}
var msgs [][]byte
message := []byte(cmd.msg)
// Automatically tag all outgoing plaintext
// messages with a whitespace tag that
// indicates that we support OTR.
if config.OTRAutoAppendTag &&
!bytes.Contains(message, []byte("?OTR")) &&
(!ok || !conversation.IsEncrypted()) {
message = append(message, OTRWhitespaceTag...)
}
if ok {
var err error
msgs, err = conversation.Send(message)
if err != nil {
alert(s.term, err.Error())
break
}
} else {
msgs = [][]byte{[]byte(message)}
}
for _, message := range msgs {
s.conn.Send(cmd.to, string(message))
}
case otrCommand:
s.conn.Send(string(cmd.User), otr.QueryMessage)
case otrInfoCommand:
info(term, fmt.Sprintf("Your OTR fingerprint is %x", s.privateKey.Fingerprint()))
for to, conversation := range s.conversations {
if conversation.IsEncrypted() {
info(s.term, fmt.Sprintf("Secure session with %s underway:", to))
printConversationInfo(&s, to, conversation)
}
}
case endOTRCommand:
to := string(cmd.User)
conversation, ok := s.conversations[to]
if !ok {
alert(s.term, "No secure session established")
break
}
msgs := conversation.End()
for _, msg := range msgs {
s.conn.Send(to, string(msg))
}
s.input.SetPromptForTarget(cmd.User, false)
warn(s.term, "OTR conversation ended with "+cmd.User)
case authQACommand:
to := string(cmd.User)
conversation, ok := s.conversations[to]
if !ok {
alert(s.term, "Can't authenticate without a secure conversation established")
break
}
msgs, err := conversation.Authenticate(cmd.Question, []byte(cmd.Secret))
if err != nil {
alert(s.term, "Error while starting authentication with "+to+": "+err.Error())
}
for _, msg := range msgs {
s.conn.Send(to, string(msg))
}
case authOobCommand:
fpr, err := hex.DecodeString(cmd.Fingerprint)
if err != nil {
alert(s.term, fmt.Sprintf("Invalid fingerprint %s - not authenticated", cmd.Fingerprint))
break
}
existing := s.config.UserIdForFingerprint(fpr)
if len(existing) != 0 {
alert(s.term, fmt.Sprintf("Fingerprint %s already belongs to %s", cmd.Fingerprint, existing))
break
}
s.config.KnownFingerprints = append(s.config.KnownFingerprints, KnownFingerprint{fingerprint: fpr, UserId: cmd.User})
s.config.Save()
info(s.term, fmt.Sprintf("Saved manually verified fingerprint %s for %s", cmd.Fingerprint, cmd.User))
case awayCommand:
s.conn.SignalPresence("away")
case chatCommand:
s.conn.SignalPresence("chat")
case dndCommand:
s.conn.SignalPresence("dnd")
case xaCommand:
s.conn.SignalPresence("xa")
case onlineCommand:
s.conn.SignalPresence("")
case ignoreCommand:
s.ignoreUser(cmd.User)
case unignoreCommand:
s.unignoreUser(cmd.User)
case ignoreListCommand:
s.ignoreList()
}
case rawStanza, ok := <-stanzaChan:
if !ok {
warn(term, "Exiting because channel to server closed")
break MainLoop
}
switch stanza := rawStanza.Value.(type) {
case *xmpp.ClientMessage:
s.processClientMessage(stanza)
case *xmpp.ClientPresence:
s.processPresence(stanza)
case *xmpp.ClientIQ:
if stanza.Type != "get" && stanza.Type != "set" {
continue
}
reply := s.processIQ(stanza)
if reply == nil {
reply = xmpp.ErrorReply{
Type: "cancel",
Error: xmpp.ErrorBadRequest{},
}
}
if err := s.conn.SendIQReply(stanza.From, "result", stanza.Id, reply); err != nil {
alert(term, "Failed to send IQ message: "+err.Error())
}
case *xmpp.StreamError:
var text string
if len(stanza.Text) > 0 {
text = stanza.Text
} else {
text = fmt.Sprintf("%s", stanza.Any)
}
alert(term, "Exiting in response to fatal error from server: "+text)
break MainLoop
default:
info(term, fmt.Sprintf("%s %s", rawStanza.Name, rawStanza.Value))
}
}
}
os.Stdout.Write([]byte("\n"))
}
func (s *Session) processIQ(stanza *xmpp.ClientIQ) interface{} {
buf := bytes.NewBuffer(stanza.Query)
parser := xml.NewDecoder(buf)
token, _ := parser.Token()
if token == nil {
return nil
}
startElem, ok := token.(xml.StartElement)
if !ok {
return nil
}
switch startElem.Name.Space + " " + startElem.Name.Local {
case "http://jabber.org/protocol/disco#info query":
return xmpp.DiscoveryReply{
Identities: []xmpp.DiscoveryIdentity{
{
Category: "client",
Type: "pc",
Name: s.config.Account,
},
},
}
case "jabber:iq:version query":
return xmpp.VersionReply{
Name: "testing",
Version: "version",
OS: "none",
}
case "jabber:iq:roster query":
if len(stanza.From) > 0 && stanza.From != s.account {
warn(s.term, "Ignoring roster IQ from bad address: "+stanza.From)
return nil
}
var roster xmpp.Roster
if err := xml.NewDecoder(bytes.NewBuffer(stanza.Query)).Decode(&roster); err != nil || len(roster.Item) == 0 {
warn(s.term, "Failed to parse roster push IQ")
return nil
}
entry := roster.Item[0]
if entry.Subscription == "remove" {
for i, rosterEntry := range s.roster {
if rosterEntry.Jid == entry.Jid {
copy(s.roster[i:], s.roster[i+1:])
s.roster = s.roster[:len(s.roster)-1]
}
}
return xmpp.EmptyReply{}
}
found := false
for i, rosterEntry := range s.roster {
if rosterEntry.Jid == entry.Jid {
s.roster[i] = entry
found = true
break
}
}
if !found {
s.roster = append(s.roster, entry)
s.input.AddUser(entry.Jid)
}
return xmpp.EmptyReply{}
default:
info(s.term, "Unknown IQ: "+startElem.Name.Space+" "+startElem.Name.Local)
}
return nil
}
func (s *Session) handleConfirmOrDeny(jid string, isConfirm bool) {
id, ok := s.pendingSubscribes[jid]
if !ok {
warn(s.term, "No pending subscription from "+jid)
return
}
delete(s.pendingSubscribes, id)
typ := "unsubscribed"
if isConfirm {
typ = "subscribed"
}
if err := s.conn.SendPresence(jid, typ, id); err != nil {
alert(s.term, "Error sending presence stanza: "+err.Error())
}
}
func (s *Session) ignoreUser(uid string) {
if _, ok := s.ignored[uid]; ok {
info(s.input.term, "Already ignoring "+uid)
return
}
s.input.lock.Lock()
defer s.input.lock.Unlock()
hasContact := false
for _, existingUid := range s.input.uids {
if existingUid == uid {
hasContact = true
}
}
if hasContact {
info(s.input.term, fmt.Sprintf("Ignoring messages from %s for the duration of this session", uid))
} else {
warn(s.input.term, fmt.Sprintf("%s isn't in your contact list... ignoring anyway for the duration of this session!", uid))
}
s.ignored[uid] = struct{}{}
info(s.input.term, fmt.Sprintf("Use '/unignore %s' to continue receiving messages from them.", uid))
}
func (s *Session) unignoreUser(uid string) {
if _, ok := s.ignored[uid]; !ok {
info(s.input.term, "No ignore registered for "+uid)
return
}
info(s.input.term, "No longer ignoring messages from "+uid)
delete(s.ignored, uid)
}
func (s *Session) ignoreList() {
var ignored []string
for ignoredUser, _ := range s.ignored {
ignored = append(ignored, ignoredUser)
}
sort.Strings(ignored)
info(s.input.term, "Ignoring messages from these users for the duration of the session:")
for _, ignoredUser := range ignored {
info(s.term, " "+ignoredUser)
}
}
func (s *Session) processClientMessage(stanza *xmpp.ClientMessage) {
from := xmpp.RemoveResourceFromJid(stanza.From)
if _, ok := s.ignored[from]; ok {
return
}
if stanza.Type == "error" {
alert(s.term, "Error reported from "+from+": "+stanza.Body)
return
}
conversation, ok := s.conversations[from]
if !ok {
conversation = new(otr.Conversation)
conversation.PrivateKey = s.privateKey
s.conversations[from] = conversation
}
out, encrypted, change, toSend, err := conversation.Receive([]byte(stanza.Body))
if err != nil {
alert(s.term, "While processing message from "+from+": "+err.Error())
s.conn.Send(stanza.From, otr.ErrorPrefix+"Error processing message")
}
for _, msg := range toSend {
s.conn.Send(stanza.From, string(msg))
}
switch change {
case otr.NewKeys:
s.input.SetPromptForTarget(from, true)
info(s.term, fmt.Sprintf("New OTR session with %s established", from))
printConversationInfo(s, from, conversation)
case otr.ConversationEnded:
s.input.SetPromptForTarget(from, false)
// This is probably unsafe without a policy that _forces_ crypto to
// _everyone_ by default and refuses plaintext. Users might not notice
// their buddy has ended a session, which they have also ended, and they
// might send a plain text message. So we should ensure they _want_ this
// feature and have set it as an explicit preference.
if s.config.OTRAutoTearDown {
if s.conversations[from] == nil {
alert(s.term, fmt.Sprintf("No secure session established; unable to automatically tear down OTR conversation with %s.", from))
break
} else {
info(s.term, fmt.Sprintf("%s has ended the secure conversation.", from))
msgs := conversation.End()
for _, msg := range msgs {
s.conn.Send(from, string(msg))
}
info(s.term, fmt.Sprintf("Secure session with %s has been automatically ended. Messages will be sent in the clear until another OTR session is established.", from))
}
} else {
info(s.term, fmt.Sprintf("%s has ended the secure conversation. You should do likewise with /otr-end %s", from, from))
}
case otr.SMPSecretNeeded:
info(s.term, fmt.Sprintf("%s is attempting to authenticate. Please supply mutual shared secret with /otr-auth user secret", from))
if question := conversation.SMPQuestion(); len(question) > 0 {
info(s.term, fmt.Sprintf("%s asks: %s", from, question))
}
case otr.SMPComplete:
info(s.term, fmt.Sprintf("Authentication with %s successful", from))
fpr := conversation.TheirPublicKey.Fingerprint()
if len(s.config.UserIdForFingerprint(fpr)) == 0 {
s.config.KnownFingerprints = append(s.config.KnownFingerprints, KnownFingerprint{fingerprint: fpr, UserId: from})
}
s.config.Save()
case otr.SMPFailed:
alert(s.term, fmt.Sprintf("Authentication with %s failed", from))
}
if len(out) == 0 {
return
}
detectedOTRVersion := 0
// We don't need to alert about tags encoded inside of messages that are
// already encrypted with OTR
whitespaceTagLength := len(OTRWhitespaceTagStart) + len(OTRWhiteSpaceTagV1)
if !encrypted && len(out) >= whitespaceTagLength {
whitespaceTag := out[len(out)-whitespaceTagLength:]
if bytes.Equal(whitespaceTag[:len(OTRWhitespaceTagStart)], OTRWhitespaceTagStart) {
if bytes.HasSuffix(whitespaceTag, OTRWhiteSpaceTagV1) {
info(s.term, fmt.Sprintf("%s appears to support OTRv1. You should encourage them to upgrade their OTR client!", from))
detectedOTRVersion = 1
}
if bytes.HasSuffix(whitespaceTag, OTRWhiteSpaceTagV2) {
detectedOTRVersion = 2
}
if bytes.HasSuffix(whitespaceTag, OTRWhiteSpaceTagV3) {
detectedOTRVersion = 3
}
}
}
if s.config.OTRAutoStartSession && detectedOTRVersion >= 2 {
info(s.term, fmt.Sprintf("%s appears to support OTRv%d. We are attempting to start an OTR session with them.", from, detectedOTRVersion))
s.conn.Send(from, otr.QueryMessage)
} else if s.config.OTRAutoStartSession && detectedOTRVersion == 1 {
info(s.term, fmt.Sprintf("%s appears to support OTRv%d. You should encourage them to upgrade their OTR client!", from, detectedOTRVersion))
}
var line []byte
if encrypted {
line = append(line, s.term.Escape.Green...)
} else {
line = append(line, s.term.Escape.Red...)
}
var timestamp string
var messageTime time.Time
if stanza.Delay != nil && len(stanza.Delay.Stamp) > 0 {
// An XEP-0203 Delayed Delivery <delay/> element exists for
// this message, meaning that someone sent it while we were
// offline. Let's show the timestamp for when the message was
// sent, rather than time.Now().
messageTime, err = time.Parse(time.RFC3339, stanza.Delay.Stamp)
if err != nil {
alert(s.term, "Can not parse Delayed Delivery timestamp, using quoted string instead.")
timestamp = fmt.Sprintf("%q", stanza.Delay.Stamp)
}
} else {
messageTime = time.Now()
}
if len(timestamp) == 0 {
timestamp = messageTime.Format(time.Stamp)
}
t := fmt.Sprintf("(%s) %s: ", timestamp, from)
line = append(line, []byte(t)...)
line = append(line, s.term.Escape.Reset...)
line = appendTerminalEscaped(line, stripHTML(out))
line = append(line, '\n')
if s.config.Bell {
line = append(line, '\a')
}
s.term.Write(line)
s.maybeNotify()
}
func (s *Session) maybeNotify() {
now := time.Now()
idleThreshold := s.config.IdleSecondsBeforeNotification
if idleThreshold == 0 {
idleThreshold = 60
}
notifyTime := s.lastActionTime.Add(time.Duration(idleThreshold) * time.Second)
if now.Before(notifyTime) {
return
}
s.lastActionTime = now
if len(s.config.NotifyCommand) == 0 {
return