-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
2034 lines (1867 loc) · 53.5 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
// Copyright (C) 2020 Christopher E. Miller
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
package irc
import (
"bufio"
"context"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"log"
"math/rand"
"net"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/go-irc/irc"
"golang.org/x/net/publicsuffix"
"golang.org/x/time/rate"
"stdchat.org"
"stdchat.org/service"
)
const Protocol = "irc"
type Client struct {
sendLine chan<- string
mx sync.RWMutex
support isupport // locked by mx
strToLower func(string) string // locked by mx
tp service.Transporter
conn net.Conn
svc *service.Service
lim *rate.Limiter
lastRecvTime time.Time // locked by mx
addrs []string
nicks []string
realName string
user string // user/ident
pass string // server pass
version string
tlsConfig *tls.Config
requestCaps []string
channels []*Channel // locked by mx
nick string // locked by mx. current nick, empty before 001.
fixNick chan struct{} // locked by mx
netID string
recvLoopCh chan cconn
sendLoopCh chan cconn
done chan struct{}
disconnA atomic.Value // atomic: chan struct{}, closed on single disconnect.
connID string // locked by mx
connState int32 // atomic: connState*
state int32 // atomic: state*
inick int32 // atomic: nicks[inick%len] or -1
Verbose bool // verbose output to log.Print/Printf
forceTLS int8 // 0 = default, 1 = force TLS, -1 = force not TLS.
}
const (
stateInit = iota
stateStarted
stateReady // started+ready
stateClosed // Close was called.
)
func (client *Client) getState() int32 {
return atomic.LoadInt32(&client.state)
}
func (client *Client) disconn() chan struct{} {
ch, _ := client.disconnA.Load().(chan struct{})
return ch
}
type cconn struct {
conn net.Conn
disconn chan struct{}
}
type isupport map[string]string
func (support isupport) Int(key string) int {
x, _ := strconv.ParseInt(key, 10, 64)
return int(x)
}
func (support isupport) IsSet(key string) bool {
_, ok := support[key]
return ok
}
func (support isupport) clone() isupport {
x := isupport{}
for k, v := range support {
x[k] = v
}
return x
}
var defaultSupport = isupport{
"PREFIX": "(ov)@+",
"CHANTYPES": "#&",
"CHANMODES": "be,k,l,imnpst",
"CASEMAPPING": "rfc1459",
"MODES": "3",
"NICKLEN": "9",
}
// ServerTimeFormat is the time format of the server-time CAP.
// The time must be in UTC.
// ISO 8601: YYYY-MM-DDThh:mm:ss.sssZ
const ServerTimeFormat = "2006-01-02T15:04:05.999Z07:00"
func split(s string) []string {
return strings.FieldsFunc(s, func(r rune) bool {
return unicode.IsSpace(r) || r == ';'
})
}
func NewClient(svc *service.Service, addr, nick, pass string, values stdchat.ValuesInfo) (service.Networker, error) {
if svc.Closed() {
return nil, errors.New("service is closed")
}
addrs := split(addr)
if len(addrs) == 0 {
return nil, errors.New("address expected")
}
nicks := split(nick)
if len(nicks) == 0 {
return nil, errors.New("nickname expected")
}
user := values.Get("irc.user")
if user == "" {
user = nicks[0]
}
realName := values.Get("irc.real-name")
if realName == "" {
realName = user
}
sendLine := make(chan string, 32)
client := &Client{
sendLine: sendLine,
Verbose: svc.Verbose,
support: defaultSupport,
tp: svc.Transporter(),
svc: svc,
lim: rate.NewLimiter(0.5, 4),
recvLoopCh: make(chan cconn, 1),
sendLoopCh: make(chan cconn, 1),
done: make(chan struct{}),
addrs: addrs,
nicks: nicks,
realName: realName,
user: user,
pass: pass,
}
client.changedAllSupportUnlocked() // lock not needed in New
err := client.setNetID()
if err != nil {
return nil, err
}
client.version = "irc 3000"
client.tlsConfig = &tls.Config{}
// ircs:// use TLS...
acceptInvalidCert := values.Get("accept-invalid-cert") == "1"
client.tlsConfig.InsecureSkipVerify = acceptInvalidCert
client.requestCaps = append(client.requestCaps,
"multi-prefix", "extended-join", "account-tag", "account-notify",
"away-notify", "message-tags", "server-time", "echo-message",
"draft/labeled-response", "batch", "invite-notify", "chghost",
"userhost-in-names", "draft/setname")
client.requestCaps = append(client.requestCaps,
split(values.Get("irc.cap.request"))...)
if clientCert := values.Get("irc.tls.client-cert"); clientCert != "" {
var certificate tls.Certificate
for data := []byte(clientCert); ; {
var block *pem.Block
block, data = pem.Decode(data)
if block == nil {
break
}
switch block.Type {
case "RSA PRIVATE KEY":
if certificate.PrivateKey != nil {
return nil, errors.New("multiple private keys found in client cert")
}
var err error
certificate.PrivateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
log.Printf("ERROR with TLS client cert PKCS1PrivateKey: %v", err)
}
case "PRIVATE KEY":
if certificate.PrivateKey != nil {
return nil, errors.New("multiple private keys found in client cert")
}
privKeyX, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
log.Printf("ERROR with TLS client cert PKCS8PrivateKey: %v", err)
}
if privKey, _ := privKeyX.(*rsa.PrivateKey); privKey == nil {
log.Printf("ERROR with TLS client cert: not RSA private key")
} else {
certificate.PrivateKey = privKey
}
case "CERTIFICATE":
certificate.Certificate = append(certificate.Certificate, block.Bytes)
if certificate.Leaf == nil { // The first one is the leaf.
if cert, err := x509.ParseCertificate(block.Bytes); err != nil {
log.Printf("ERROR with TLS client cert Certificate: %v", err)
} else {
certificate.Leaf = cert
}
}
default:
log.Printf("INFO unknown block in TLS client cert: %s", block.Type)
}
}
if certificate.PrivateKey == nil {
log.Println("INFO TLS client cert private key not found")
}
if len(certificate.Certificate) == 0 {
log.Println("INFO TLS client cert certificate not found")
}
if certificate.PrivateKey == nil || len(certificate.Certificate) == 0 {
return nil, errors.New("incomplete TLS client cert")
}
client.tlsConfig.Certificates = append(
client.tlsConfig.Certificates, certificate)
log.Println("Using TLS client cert")
}
if useTLS := values.Get("irc.use-tls"); useTLS == "1" {
client.forceTLS = 1
} else if useTLS == "0" {
client.forceTLS = -1
}
go client.recvLoop()
go client.sendLoop(sendLine)
return client, nil
}
const (
connStateInit = iota
connStateConnecting
connStateConnected
connStateDisconnected
)
func (client *Client) getConnState() int32 {
return atomic.LoadInt32(&client.connState)
}
// Connected returns true if a connection is established to the server.
func (client *Client) Connected() bool {
return client.getConnState() == connStateConnected
}
// Closed returns true if Close() was called.
func (client *Client) Closed() bool {
return client.getState() == stateClosed
}
// Ready returns true if we are logged onto the server and have a nickname.
func (client *Client) Ready() bool {
return client.getState() == stateReady
}
func (client *Client) NetworkID() string {
return client.netID
}
func (client *Client) ConnID() string {
client.mx.RLock()
connID := client.connID
client.mx.RUnlock()
return connID
}
// Nick gets your current nickname,
// which can be empty before or during a connection.
// Note that reading the Nick() may return the old nickname until updated by the server.
func (client *Client) Nick() string {
client.mx.RLock()
nick := client.nick
client.mx.RUnlock()
return nick
}
// NickID gets the ID of Nick()
func (client *Client) NickID() string {
client.mx.RLock()
defer client.mx.RUnlock()
return client.strToLower(client.nick)
}
// SetNick sets your nickname. Also see Nick()
func (client *Client) SetNick(nick string) {
atomic.StoreInt32(&client.inick, -1) // Custom nick; used by myNickChanged
client.setNick(nick)
}
// SendLine queues up the line to be sent eventually, after considering rate limiting.
// Note that if the queue fills up, the call blocks; use TrySendLine to avoid this.
// An error can be returned when the connection is closed.
func (client *Client) SendLine(line string) error {
select {
case client.sendLine <- line:
return nil
case <-client.disconn():
return errors.New("connection closed")
}
}
var ErrSendQueueFull = errors.New("send queue full")
// TrySendLine is similar to SendLine,
// but will return ErrSendQueueFull immediately if the send queue is full.
func (client *Client) TrySendLine(line string) error {
select {
case client.sendLine <- line:
return nil
case <-client.disconn():
return errors.New("connection closed")
default:
return ErrSendQueueFull
}
}
func (client *Client) setNick(nick string) error {
return client.SendLine("NICK :" + nick)
}
// Join IRC channels; joinArgs can have comma-separated names, and keys.
func (client *Client) Join(joinArgs string) error {
return client.SendLine("JOIN " + joinArgs)
}
func (client *Client) SendMsg(dest, msg string) error {
return client.SendLine("PRIVMSG " + dest + " :" + msg)
}
func (client *Client) SendAction(dest, msg string) error {
return client.SendLine("PRIVMSG " + dest + " :\x01ACTION " + msg + "\x01")
}
func (client *Client) SendCTCP(dest, ctcp, args string) error {
if args != "" {
return client.SendMsg(dest, "\x01"+ctcp+" "+args+"\x01")
} else {
return client.SendMsg(dest, "\x01"+ctcp+"\x01")
}
}
func (client *Client) SendNotice(dest, notice string) error {
return client.SendLine("NOTICE " + dest + " :" + notice)
}
func (client *Client) SendCTCPReply(dest, ctcp, args string) error {
if args != "" {
return client.SendNotice(dest, "\x01"+ctcp+" "+args+"\x01")
} else {
return client.SendNotice(dest, "\x01"+ctcp+"\x01")
}
}
func (client *Client) setNetID() error {
for _, addr := range client.addrs {
serverName, _, _, _, _ := parseAddr(addr)
if serverName != "" {
netID, err := publicsuffix.EffectiveTLDPlusOne(serverName)
if err != nil {
hostparts := strings.FieldsFunc(serverName,
func(r rune) bool { return r == '.' })
if len(hostparts) > 0 {
netID := hostparts[len(hostparts)-1]
n := len(netID)
for i := len(hostparts) - 2; i >= 0; i-- {
netID = hostparts[i] + "." + netID
n += len(hostparts[i])
if n > 5 {
break
}
}
}
}
if netID != "" {
for i := 1; ; i++ {
tryNetID := netID
if i > 1 {
//tryNetID += fmt.Sprintf(".%d", i)
return errors.New("network already connected")
}
if client.svc.GetClientByNetwork(tryNetID) == nil {
client.netID = tryNetID
return nil
}
}
}
}
}
// Couldn't make a netID, so invent one.
client.netID = service.MakeID("")
return nil
}
func (client *Client) changedSupportUnlocked(key string) {
switch key {
case "CASEMAPPING":
client.strToLower = GetToLowerFunc(client.support["CASEMAPPING"])
}
}
func (client *Client) changedAllSupportUnlocked() {
for k := range client.support {
client.changedSupportUnlocked(k)
}
}
// StringToLower converts s to lowercase per the server's casemapping.
func (client *Client) StringToLower(s string) string {
client.mx.RLock()
defer client.mx.RUnlock()
return client.strToLower(s)
}
type chanMode byte
const (
chanModeNone chanMode = iota
chanModeList // A
chanModeAlwaysParam // B
chanModeSetParam // C
chanModeSetting // D
)
func (x chanMode) Valid() bool {
return x != 0
}
// isSet should be true if the arg is being set (+)
func (x chanMode) HasArg(isSet bool) bool {
switch x {
case chanModeList:
return true
case chanModeAlwaysParam:
return true
case chanModeSetParam:
return isSet
default:
return false
}
}
// Returns one of the chanMode* values above, chanModeNone (0) means not a chan mode.
func (client *Client) chanModeTypeUnlocked(mode byte) chanMode {
itype := chanModeList
chanmodes := client.support["CHANMODES"]
for i := 0; i < len(chanmodes); i++ {
ch := chanmodes[i]
if ch == ',' {
itype++
} else if ch == mode {
return itype
}
}
// Now check PREFIX:
prefix := client.support["PREFIX"]
for i := 0; i < len(prefix); i++ {
ch := prefix[i]
if ch == ')' {
break
}
if ch != '(' && ch == mode {
return chanModeAlwaysParam
}
}
return chanModeNone
}
func (client *Client) chanModeType(mode byte) chanMode {
client.mx.RLock()
defer client.mx.RUnlock()
return client.chanModeTypeUnlocked(mode)
}
func (client *Client) NetworkName() string {
client.mx.RLock()
defer client.mx.RUnlock()
netw := client.support["NETWORK"]
if netw == "" {
netw = client.netID
}
return netw
}
func (client *Client) GetStateInfo() service.ClientStateInfo {
msg := stdchat.NetworkStateInfo{}
msg.Type = "network-state"
msg.Ready = client.Ready()
msg.Network.Init(client.NetworkID(), "net")
msg.Network.SetName(client.NetworkName(), "")
msg.Connection.Init(client.ConnID(), "conn")
msg.Myself.Init(client.NickID(), "user")
msg.Myself.SetName(client.Nick(), "")
msg.Protocol = Protocol
if msg.Ready {
client.setFeatures(&msg.Values)
}
client.mx.RLock()
defer client.mx.RUnlock()
var subs []stdchat.SubscriptionStateInfo
for _, channel := range client.channels {
if channel.joinedUnlocked() {
subs = append(subs, channel.getStateInfoUnlocked(msg.Network))
}
}
return service.ClientStateInfo{Network: msg, Subscriptions: subs}
}
func (client *Client) IsChanType(ch byte) bool {
client.mx.RLock()
defer client.mx.RUnlock()
return strings.IndexByte(client.support["CHANTYPES"], ch) != -1
}
func (client *Client) IsNickPrefix(ch byte) bool {
client.mx.RLock()
defer client.mx.RUnlock()
prefix := client.support["PREFIX"]
iclose := strings.IndexByte(prefix, ')')
if iclose != -1 {
return strings.IndexByte(prefix[iclose+1:], ch) != -1
}
return false
}
func (client *Client) removeNickPrefixes(nick string) string {
for len(nick) > 0 {
if !client.IsNickPrefix(nick[0]) {
break
}
nick = nick[1:]
}
return nick
}
func (client *Client) GetPrefix() (modes string, chars string) {
client.mx.RLock()
defer client.mx.RUnlock()
prefix := client.support["PREFIX"]
if len(prefix) > 0 && prefix[0] == '(' {
x := prefix[1:]
ix := strings.IndexByte(x, ')')
if ix != -1 {
modes = x[:ix]
chars = x[ix+1:]
return
}
}
return
}
// Returns 0 if ch is not a channel nick prefix mode.
func (client *Client) GetNickPrefix(ch byte) byte {
modes, chars := client.GetPrefix()
ich := strings.IndexByte(modes, ch)
if ich != -1 && ich < len(chars) {
return chars[ich]
}
return 0
}
// get channel name, or empty if not.
func (client *Client) chanFromTarget(s string) string {
s = client.removeNickPrefixes(s)
if len(s) > 0 && client.IsChanType(s[0]) {
return s
}
return ""
}
// Logout and Close.
// This is needed to release resources,
// stop goroutines, and remove from the service clients list.
func (client *Client) Logout(reason string) error {
if !atomic.CompareAndSwapInt32(&client.state, stateStarted, stateClosed) &&
!atomic.CompareAndSwapInt32(&client.state, stateReady, stateClosed) {
if client.getState() == stateInit {
return errors.New("not started")
}
return errors.New("already closed")
}
if client.Connected() {
disconn := client.disconn()
// Not closing the connection yet,
// let the QUIT handle disconnect.
if client.TrySendLine("QUIT :"+reason) != nil {
client.disconnect("client closed")
} else {
// Not very patient...
// TODO: use Shutdown context??
select {
case <-disconn:
case <-time.After(5 * time.Second):
client.disconnect("client closed")
}
}
}
client.svc.OnClientClosed(client)
close(client.recvLoopCh)
close(client.sendLoopCh)
<-client.done
return nil
}
// Close the client.
func (client *Client) Close() error {
return client.Logout("Close")
}
// BreakConnection will force break the connection, as if there was a network error.
// A broken connection will auto-reconnect; use Close() for proper connection close.
func (client *Client) BreakConnection() error {
client.mx.RLock()
conn := client.conn
client.mx.RUnlock()
return conn.Close()
}
type doneCtx struct {
context.Context
done <-chan struct{}
}
func (ctx *doneCtx) Done() <-chan struct{} {
return ctx.done
}
func (ctx *doneCtx) Err() error {
select {
case <-ctx.done:
return errors.New("Client is done")
default:
return nil
}
}
func (ctx *doneCtx) String() string {
return "Client context: " + Protocol
}
func (client *Client) Context() context.Context {
return &doneCtx{context.Background(), client.done}
}
// The returned context is "done" when the current connection is closed,
// including on disconnection with auto-reconnect or client Close.
func (client *Client) connContext() context.Context {
return &doneCtx{context.Background(), client.disconn()}
}
func (client *Client) maybeUnsubscribeAll(msgType string, m stdchat.MessageInfo) bool {
// Clear channel members, send unsubscribe for all that had members.
for _, channel := range client.GetChannels() {
if channel.clearMembers() > 0 {
client.publishUnsubscribe(channel, msgType, m, nil)
}
}
return true
}
// This disconnect allows auto-reconnect; use Close to avoid reconnecting.
// Note: during disconnection, this can get called several times,
// only the first gets through, and thus only the first cause counts.
func (client *Client) disconnect(cause string) {
if !atomic.CompareAndSwapInt32(&client.connState,
connStateConnected, connStateDisconnected) {
return
}
if cause == "" {
cause = "disconnect"
}
// Not ready, but also not Close'd.
atomic.CompareAndSwapInt32(&client.state, stateReady, stateStarted)
var conn net.Conn
func() {
client.mx.Lock()
defer client.mx.Unlock()
// Do some lock things.
conn = client.conn
if client.fixNick != nil { // Don't try to fix nick.
close(client.fixNick)
client.fixNick = nil
}
}()
close(client.disconn())
conn.Close()
{
m := stdchat.MessageInfo{}
m.SetText(cause)
client.maybeUnsubscribeAll("unsubscribe", m)
}
{
msg := &stdchat.NetMsg{}
msg.Init(service.MakeID(""), "offline", Protocol,
client.NetworkID())
msg.Network.SetName(client.NetworkName(), "")
client.tp.Publish(msg.Network.ID, "", "network", msg)
}
{
msg := &stdchat.ConnMsg{}
msg.Init(service.MakeID(""), "conn-state", Protocol,
client.NetworkID(), client.ConnID(), stdchat.Disconnected)
msg.Network.SetName(client.NetworkName(), "")
msg.Cause = cause
client.tp.Publish("", "", "conn", msg)
}
if !client.Closed() {
// If not closed, it means we want to reconnect.
go client.reconnect(client.Context(), "")
}
}
func fixEncoding(e *irc.Message) {
// Not bothering with Tags or Command.
// Consciously decoding each parameter separately.
for i := 0; i < len(e.Params); i++ {
e.Params[i] = ircToString(e.Params[i])
}
}
func (client *Client) recvLoop() {
defer close(client.done)
for {
select {
case cc, ok := <-client.recvLoopCh:
if !ok {
return
}
reader := bufio.NewReaderSize(cc.conn, 1024)
for {
// Loop quits when conn closed.
line, err := reader.ReadString('\n')
if err != nil {
select {
case <-cc.disconn:
log.Printf("connection %s closed (recvLoop)", client.ConnID())
//client.disconnect("connection closed")
default:
client.disconnect("read error")
}
break
}
e, err := irc.ParseMessage(line)
if err != nil {
//
continue
}
fixEncoding(e)
client.ircEvent(e)
}
}
}
}
func (client *Client) sendLoop(sendLine <-chan string) {
ctx := client.connContext()
ticker := time.NewTicker(20 * time.Second)
defer ticker.Stop()
loop:
for {
drain: // Drain sendLine.
for {
select {
case <-sendLine:
default:
break drain
}
}
cc, ok := <-client.sendLoopCh
if !ok {
return
}
writer := cc.conn
for {
select {
case <-cc.disconn:
continue loop
case line := <-sendLine:
select { // Check again in case disconn is also ready.
case <-cc.disconn:
continue loop
default:
}
line = cleanReplacer.Replace(line) // a "line" can't have newlines
// As long as this wait is short, the ticker should be fine.
if client.lim.Wait(ctx) == nil {
if client.Verbose {
log.Printf("-> %s", line)
}
_, err := writer.Write([]byte(line + "\r\n"))
if err != nil {
select {
case <-cc.disconn:
log.Printf("connection %s closed (sendLoop)", client.ConnID())
//client.disconnect("connection closed")
default:
// This delay allows recvLoop potentially to do things first.
// Note: this sleep plus client.lim.Wait need to be
// less than the initial reconnect delay.
// TODO: find a better way to do this.
time.Sleep(100 * time.Millisecond)
//client.tp.PublishError(service.MakeID(""), client.NetworkID(), err)
// Not sending this error for reasons:
// 1) After lim.Wait this error can surface way too late.
// 2) On connection error, receive will find the problem.
// For now, just log the error locally:
log.Printf("Write error: %v", err)
client.disconnect("write error")
}
continue loop
}
// Handle some outgoing commands:
if strings.HasPrefix(line, "PRIVMSG ") ||
strings.HasPrefix(line, "TAGMSG ") ||
strings.HasPrefix(line, "NOTICE ") {
// TODO: check for echo-message CAP...
// If no echo-message CAP, feed our own through:
if e, err := irc.ParseMessage(line); err != nil {
log.Printf("WARN outgoing message failed to parse: %v", err)
} else {
e.Prefix.Name = client.Nick()
msgid, _ := e.Tags.GetTag("msgid")
if msgid == "" {
msgid = service.MakeID("")
e.Tags["msgid"] = irc.TagValue(msgid)
}
targets := strings.FieldsFunc(earg(e, 0), func(r rune) bool {
return r == ','
})
if len(targets) < 2 {
client.ircEvent(e)
} else { // Split up the targets.
for i, target := range targets {
e2 := e.Copy()
e2.Params[0] = target // Set single target.
// Update the msgid to msgid@n:
msgid2 := fmt.Sprintf("%s@%d", msgid, i+1)
e2.Tags["msgid"] = irc.TagValue(msgid2)
client.ircEvent(e2)
}
}
}
} else if line == "QUIT" || strings.HasPrefix(line, "QUIT ") {
connID := client.ConnID()
go func() {
// Wait a short time for the server to respond.
time.Sleep(time.Second)
if connID == client.ConnID() { // Not if already reconnecting.
client.disconnect("client quit")
}
}()
continue loop
}
}
case <-ticker.C:
client.mx.RLock()
lastRecvTime := client.lastRecvTime
client.mx.RUnlock()
if lastRecvTime.Add(1 * time.Minute).Before(time.Now()) {
if lastRecvTime.Add(2 * time.Minute).Before(time.Now()) {
client.disconnect("local ping timeout")
} else {
line := "PING :ping@" + client.ConnID()
select {
case client.sendLine <- line:
default:
// Ignore sending PING if the send queue is full,
// it's already sending stuff and likely to get a response.
}
}
}
}
}
}
}
func (client *Client) Start(ctx context.Context, id string) error {
if !atomic.CompareAndSwapInt32(&client.state, stateInit, stateStarted) {
return errors.New("already started")
}
if !client.connect(client.Context(), id) {
client.Close()
return errors.New("too many failed attempts to connect")
}
return nil
}
func (client *Client) connect(ctx context.Context, id string) bool {
if client.Closed() {
return false
}
if !atomic.CompareAndSwapInt32(&client.connState,
connStateInit, connStateConnecting) &&
!atomic.CompareAndSwapInt32(&client.connState,
connStateDisconnected, connStateConnecting) {
return false
}
connID := "irc/" + service.MakeID("")
client.mx.Lock()
client.connID = connID
client.nick = "" // Don't have a nick yet; leave blank so that nextNick() works.
client.mx.Unlock()
atomic.StoreInt32(&client.inick, 0) // Back at trying the first nick.
{
// Publish msg about the pending connection,
// and allow it to tie the caller's ID to the new connID.
msg := &stdchat.ConnMsg{}
msg.Init(service.MakeID(id), "conn-state", Protocol,
client.NetworkID(), connID, stdchat.Connecting)
msg.Cause = "login"
client.tp.Publish("", "", "conn", msg)
}
for j := 0; j < 3; j++ {
for _, addr := range client.addrs {
select {
case <-ctx.Done():
return false
case <-client.done:
return false
default:
}
serverName, serverPort, join, wantTLS, err := parseAddr(addr)
if err != nil {
{
msg := &stdchat.ConnMsg{}
msg.Init(service.MakeID(id), "conn-state", Protocol,
client.NetworkID(), connID, stdchat.ConnectFailed)
msg.Cause = "parse address" // ???
msg.Message.SetText("Error: " + err.Error())
client.tp.Publish("", "", "conn", msg)
}
continue
}
endpoint := serverName + ":" + serverPort
useTLS := wantTLS && client.forceTLS != -1 || client.forceTLS == 1
dialer := &net.Dialer{Timeout: time.Minute}
var conn net.Conn
if useTLS {
// TODO: DialContextWithDialer ...
// Not merged: https://go-review.googlesource.com/c/go/+/93255/
conn, err = tls.DialWithDialer(dialer, "tcp", endpoint, client.tlsConfig)
} else {
conn, err = dialer.DialContext(ctx, "tcp", endpoint)
}
if err != nil {
{
msg := &stdchat.ConnMsg{}
msg.Init(service.MakeID(id), "conn-state", Protocol,
client.NetworkID(), connID, stdchat.ConnectFailed)
msg.Cause = "connection setup" // ???
msg.Message.SetText("Error: " + err.Error())
client.tp.Publish("", "", "conn", msg)
}
time.Sleep(15 * time.Second)
continue
}