-
Notifications
You must be signed in to change notification settings - Fork 0
/
erc-backend.el
2854 lines (2529 loc) · 119 KB
/
erc-backend.el
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
;;; erc-backend.el --- Backend network communication for ERC -*- lexical-binding:t -*-
;; Copyright (C) 2004-2024 Free Software Foundation, Inc.
;; Author: Lawrence Mitchell <wence@gmx.li>
;; Maintainer: Amin Bandali <bandali@gnu.org>, F. Jason Park <jp@neverwas.me>
;; Created: 2004-05-7
;; Keywords: comm, IRC, chat, client, internet
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This file defines backend network communication handlers for ERC.
;;
;; How things work:
;;
;; You define a new handler with `define-erc-response-handler'. This
;; defines a function, a corresponding hook variable, and populates a
;; global hash table `erc-server-responses' with a map from response
;; to hook variable. See the function documentation for more
;; information.
;;
;; Upon receiving a line from the server, `erc-parse-server-response'
;; is called on it.
;;
;; A line generally looks like:
;;
;; LINE := ':' SENDER ' ' COMMAND ' ' (COMMAND-ARGS ' ')* ':' CONTENTS
;; SENDER := Not ':' | ' '
;; COMMAND := Not ':' | ' '
;; COMMAND-ARGS := Not ':' | ' '
;;
;; This gets parsed and stuffed into an `erc-response' struct. You
;; can access the fields of the struct with:
;;
;; COMMAND --- `erc-response.command'
;; COMMAND-ARGS --- `erc-response.command-args'
;; CONTENTS --- `erc-response.contents'
;; SENDER --- `erc-response.sender'
;; LINE --- `erc-response.unparsed'
;; TAGS --- `erc-response.tags'
;;
;; WARNING, WARNING!!
;; It's probably not a good idea to destructively modify the list
;; of command-args in your handlers, since other functions down the
;; line may well need to access the arguments too.
;;
;; That is, unless you're /absolutely/ sure that your handler doesn't
;; invoke some other function that needs to use COMMAND-ARGS, don't do
;; something like
;;
;; (while (erc-response.command-args parsed)
;; (let ((a (pop (erc-response.command-args parsed))))
;; ...))
;;
;; The parsed response is handed over to
;; `erc-handle-parsed-server-response', which checks whether it should
;; carry out duplicate suppression, and then runs `erc-call-hooks'.
;; `erc-call-hooks' retrieves the relevant hook variable from
;; `erc-server-responses' and runs it.
;;
;; Most handlers then destructure the parsed response in some way
;; (depending on what the handler is, the arguments have different
;; meanings), and generally display something, usually using
;; `erc-display-message'.
;;; TODO:
;; o Generalize the display-line code so that we can use it to
;; display the stuff we send, as well as the stuff we receive.
;; Then, move all display-related code into another backend-like
;; file, erc-display.el, say.
;;
;; o Clean up the handlers using new display code (has to be written
;; first).
;;; History:
;; 2004/05/10 -- Handler bodies taken out of erc.el and ported to new
;; interface.
;; 2005-08-13 -- Moved sending commands from erc.el.
;;; Code:
(eval-when-compile (require 'cl-lib))
(require 'erc-common)
(defvar erc--display-context)
(defvar erc--msg-prop-overrides)
(defvar erc--target)
(defvar erc-channel-list)
(defvar erc-channel-members)
(defvar erc-default-nicks)
(defvar erc-default-recipients)
(defvar erc-ensure-target-buffer-on-privmsg)
(defvar erc-hide-prompt)
(defvar erc-input-marker)
(defvar erc-insert-marker)
(defvar erc-join-buffer)
(defvar erc-networks--id)
(defvar erc-nick)
(defvar erc-nick-change-attempt-count)
(defvar erc-verbose-server-ping)
(declare-function erc--ensure-query-member "erc" (name))
(declare-function erc--ensure-query-members "erc" ())
(declare-function erc--init-channel-modes "erc" (channel raw-args))
(declare-function erc--open-target "erc" (target))
(declare-function erc--parse-nuh "erc" (string))
(declare-function erc--query-list "erc" ())
(declare-function erc--remove-channel-users-but "erc" (nick))
(declare-function erc--target-from-string "erc" (string))
(declare-function erc--update-modes "erc" (raw-args))
(declare-function erc-active-buffer "erc" nil)
(declare-function erc-add-default-channel "erc" (channel))
(declare-function erc-banlist-update "erc" (proc parsed))
(declare-function erc-buffer-filter "erc" (predicate &optional proc))
(declare-function erc-buffer-list-with-nick "erc" (nick proc))
(declare-function erc-channel-begin-receiving-names "erc" nil)
(declare-function erc-channel-end-receiving-names "erc" nil)
(declare-function erc-channel-p "erc" (channel))
(declare-function erc-channel-receive-names "erc" (names-string))
(declare-function erc-cmd-JOIN "erc" (channel &optional key))
(declare-function erc-connection-established "erc" (proc parsed))
(declare-function erc-current-nick "erc" nil)
(declare-function erc-current-nick-p "erc" (nick))
(declare-function erc-current-time "erc" (&optional specified-time))
(declare-function erc-default-target "erc" nil)
(declare-function erc-delete-default-channel "erc" (channel &optional buffer))
(declare-function erc-display-error-notice "erc" (parsed string))
(declare-function erc-display-server-message "erc" (_proc parsed))
(declare-function erc-emacs-time-to-erc-time "erc" (&optional specified-time))
(declare-function erc-format-message "erc" (msg &rest args))
(declare-function erc-get-buffer "erc" (target &optional proc))
(declare-function erc-handle-login "erc" nil)
(declare-function erc-handle-user-status-change "erc" (type nlh &optional l))
(declare-function erc-ignored-reply-p "erc" (msg tgt proc))
(declare-function erc-ignored-user-p "erc" (spec))
(declare-function erc-is-message-ctcp-and-not-action-p "erc" (message))
(declare-function erc-is-message-ctcp-p "erc" (message))
(declare-function erc-log-irc-protocol "erc" (string &optional outbound))
(declare-function erc-login "erc" nil)
(declare-function erc-network "erc-networks" nil)
(declare-function erc-networks--id-given "erc-networks" (arg &rest args))
(declare-function erc-networks--id-reload "erc-networks" (arg &rest args))
(declare-function erc-nickname-in-use "erc" (nick reason))
(declare-function erc-parse-user "erc" (string))
(declare-function erc-process-away "erc" (proc away-p))
(declare-function erc-process-ctcp-query "erc" (proc parsed nick login host))
(declare-function erc-remove-channel-member "erc" (channel nick))
(declare-function erc-remove-channel-users "erc" nil)
(declare-function erc-remove-user "erc" (nick))
(declare-function erc-sec-to-time "erc" (ns))
(declare-function erc-server-buffer "erc" nil)
(declare-function erc-set-active-buffer "erc" (buffer))
(declare-function erc-set-current-nick "erc" (nick))
(declare-function erc-time-diff "erc" (t1 t2))
(declare-function erc-trim-string "erc" (s))
(declare-function erc-update-mode-line "erc" (&optional buffer))
(declare-function erc-update-mode-line-buffer "erc" (buffer))
(declare-function erc-wash-quit-reason "erc" (reason nick login host))
(declare-function erc--determine-speaker-message-format-args "erc"
(nick target message queryp privmsgp statusmsgp inputp
&optional prefix disp-nick))
(declare-function erc-display-message "erc"
(parsed type buffer msg &rest args))
(declare-function erc-get-buffer-create "erc"
(server port target &optional tgt-info id))
(declare-function erc-process-ctcp-reply "erc"
(proc parsed nick login host msg))
(declare-function erc-update-channel-topic "erc"
(channel topic &optional modify))
(declare-function erc-update-user-nick "erc"
(nick &optional new-nick host login full-name info))
(declare-function erc-open "erc"
(&optional server port nick full-name connect passwd tgt-list
channel process client-certificate user id))
(declare-function erc-update-channel-member "erc"
(channel nick new-nick
&optional add voice halfop op admin owner host
login full-name info update-message-time))
;;;; Variables and options
(defvar-local erc-session-password nil
"The password used for the current session.
This should be a string or a function returning a string.")
(defvar erc-server-responses (make-hash-table :test #'equal)
"Hash table mapping server responses to their handler hooks.")
;;; User data
(defvar-local erc-server-current-nick nil
"Nickname on the current server.
Use `erc-current-nick' to access this.")
(defvar-local erc-session-user-full-name nil
"Real name used for the current session.
Sent as the last argument to the USER command.")
(defvar-local erc-session-username nil
"Username used for the current session.
Sent as the first argument of the USER command.")
;;; Server attributes
(defvar-local erc-server-process nil
"The process object of the corresponding server connection.")
(defvar-local erc-session-server nil
"The server name used to connect to for this session.")
(defvar-local erc-session-connector nil
"The function used to connect to this session (nil for the default).")
(defvar-local erc-session-port nil
"The port used to connect to.")
(defvar-local erc-session-client-certificate nil
"TLS client certificate used when connecting over TLS.
If non-nil, should either be a list where the first element is
the certificate key file name, and the second element is the
certificate file name itself, or t, which means that
`auth-source' will be queried for the key and the certificate.")
(defvar-local erc-server-announced-name nil
"The name the server announced to use.")
(defvar-local erc-server-version nil
"The name and version of the server's ircd.")
(defvar-local erc-server-parameters nil
"Alist listing the supported server parameters.
This is only set if the server sends 005 messages saying what is
supported on the server.
Entries are of the form:
(PARAMETER . VALUE)
or
(PARAMETER) if no value is provided.
where PARAMETER is a string and VALUE is a string or nil. For
compatibility, a raw parameter of the form \"FOO=\" becomes
(\"FOO\" . \"\") even though it's equivalent to the preferred
canonical form \"FOO\" and its lisp representation (\"FOO\").
Some examples of possible parameters sent by servers:
CHANMODES=b,k,l,imnpst - list of supported channel modes
CHANNELLEN=50 - maximum length of channel names
CHANTYPES=#&!+ - supported channel prefixes
CHARMAPPING=rfc1459 - character mapping used for nickname and channels
KICKLEN=160 - maximum allowed kick message length
MAXBANS=30 - maximum number of bans per channel
MAXCHANNELS=10 - maximum number of channels allowed to join
NETWORK=EFnet - the network identifier
NICKLEN=9 - maximum allowed length of nicknames
PREFIX=(ov)@+ - list of channel modes and the user prefixes if user has mode
RFC2812 - server supports RFC 2812 features
SILENCE=10 - supports the SILENCE command, maximum allowed number of entries
TOPICLEN=160 - maximum allowed topic length
WALLCHOPS - supports sending messages to all operators in a channel")
(defvar-local erc--isupport-params nil
"Hash map of \"ISUPPORT\" params.
Keys are symbols. Values are lists of zero or more strings with hex
escapes removed. ERC normalizes incoming parameters of the form
\"FOO=\" to (FOO).")
;;; Server and connection state
(defvar erc-server-ping-timer-alist nil
"Mapping of server buffers to their specific ping timer.")
(defvar-local erc-server-connected nil
"Non-nil if the current buffer belongs to an active IRC connection.
To determine whether an underlying transport is connected, use the
function `erc-server-process-alive' instead.")
(defvar-local erc-server-reconnect-count 0
"Number of times we have failed to reconnect to the current server.")
(defvar-local erc--server-reconnect-display-timer nil
"Timer that resets `erc--server-last-reconnect-count' to zero.
Becomes non-nil in all server buffers when an IRC connection is
first \"established\" and carries out its duties
`erc-auto-reconnect-display-timeout' seconds later.")
(defvar-local erc--server-last-reconnect-count 0
"Snapshot of reconnect count when the connection was established.")
(defvar-local erc--server-reconnect-timer nil
"Auto-reconnect timer for a network context.")
(defvar-local erc-server-quitting nil
"Non-nil if the user requests a quit.")
(defvar-local erc-server-reconnecting nil
"Non-nil if the user requests an explicit reconnect, and the
current IRC process is still alive.")
(make-obsolete-variable 'erc-server-reconnecting
"see `erc--server-reconnecting'" "29.1")
(defvar erc--server-reconnecting nil
"An alist of buffer-local vars and their values when reconnecting.
This is for the benefit of local modules and `erc-mode-hook'
members so they can access buffer-local data from the previous
session when reconnecting. Once `erc-reuse-buffers' is retired
and fully removed, modules can switch to leveraging the
`permanent-local' property instead.")
(defvar erc--server-post-connect-hook '(erc-networks--warn-on-connect)
"Functions to run when a network connection is successfully opened.
Though internal, this complements `erc-connect-pre-hook' in that
it bookends the process rather than the logical connection, which
is the domain of `erc-before-connect' and `erc-after-connect'.
Note that unlike `erc-connect-pre-hook', this only runs in server
buffers, and it does so immediately before the first protocol
exchange.")
(defvar-local erc-server-timed-out nil
"Non-nil if the IRC server failed to respond to a ping.")
(defvar-local erc-server-banned nil
"Non-nil if the user is denied access because of a server ban.")
(defvar-local erc-server-error-occurred nil
"Non-nil if the user triggers some server error.")
(defvar-local erc-server-lines-sent nil
"Line counter.")
(defvar-local erc-server-last-peers nil
"Last peers used, both sender and receiver.
Those are used for /MSG destination shortcuts.")
(defvar-local erc-server-last-sent-time nil
"Time the message was sent.
This is useful for flood protection.")
(defvar-local erc-server-last-ping-time nil
"Time the last ping was sent.
This is useful for flood protection.")
(defvar-local erc-server-last-received-time nil
"Time the last message was received from the server.
This is useful for detecting hung connections.")
(defvar-local erc-server-lag nil
"Calculated server lag time in seconds.
This variable is only set in a server buffer.")
(defvar-local erc-server-filter-data nil
"The data that arrived from the server but has not been processed yet.")
(defvar-local erc-server-duplicates (make-hash-table :test 'equal)
"Internal variable used to track duplicate messages.")
;; From Circe
(defvar-local erc-server-processing-p nil
"Non-nil when we're currently processing a message.
When ERC receives a private message, it sets up a new buffer for
this query. These in turn, though, do start flyspell. This
involves starting an external process, in which case Emacs will
wait - and when it waits, it does accept other stuff from, say,
network exceptions. So, if someone sends you two messages
quickly after each other, ispell is started for the first, but
might take long enough for the second message to be processed
first.")
(defvar-local erc-server-flood-last-message 0
"When we sent the last message.
See `erc-server-flood-margin' for an explanation of the flood
protection algorithm.")
(defvar-local erc-server-flood-queue nil
"The queue of messages waiting to be sent to the server.
See `erc-server-flood-margin' for an explanation of the flood
protection algorithm.")
(defvar-local erc-server-flood-timer nil
"The timer to resume sending.")
;;; IRC protocol and misc options
(defgroup erc-server nil
"Parameters for dealing with IRC servers."
:group 'erc)
(defcustom erc-server-auto-reconnect t
"Non-nil means that ERC will attempt to reestablish broken connections.
Reconnection will happen automatically for any unexpected disconnection."
:type 'boolean)
(defcustom erc-server-reconnect-attempts 2
"Number of times that ERC will attempt to reestablish a broken connection.
If t, always attempt to reconnect.
This only has an effect if `erc-server-auto-reconnect' is non-nil."
:type '(choice (const :tag "Always reconnect" t)
integer))
(defcustom erc-server-reconnect-timeout 1
"Number of seconds to wait between successive reconnect attempts.
If this value is too low, servers may reject your initial nick
request upon reconnecting because they haven't yet noticed that
your previous connection is dead. If this happens, try setting
this value to 120 or greater and/or exploring the option
`erc-services-regain-alist', which may provide a more proactive
means of handling this situation on some servers."
:type 'number)
(defcustom erc-server-reconnect-function 'erc-server-delayed-reconnect
"Function called by the reconnect timer to create a new connection.
Called with a server buffer as its only argument. Potential uses
include exponential backoff and probing for connectivity prior to
dialing. Use `erc-schedule-reconnect' to instead try again later
and optionally alter the attempts tally."
:package-version '(ERC . "5.5")
:type '(choice (function-item erc-server-delayed-reconnect)
(function-item erc-server-delayed-check-reconnect)
function))
(defcustom erc-split-line-length 440
"The maximum length of a single message.
ERC normally splits chat input submitted at its prompt into
multiple messages when the initial size exceeds this value in
bytes. Modules can tell ERC to forgo splitting entirely by
setting this to zero locally or, preferably, by binding it around
a remapped `erc-send-current-line' command.
IRC allows for lines up to 512 bytes. Two of them are CR LF.
And a typical message looks like this:
:nicky!uhuser@host212223.dialin.fnordisp.net PRIVMSG #lazybastards :Hello!
You can limit here the maximum length of the \"Hello!\" part.
Good luck."
:type 'integer)
(defcustom erc-coding-system-precedence '(utf-8 undecided)
"List of coding systems to be preferred when receiving a string from the server.
This will only be consulted if the coding system in
`erc-server-coding-system' is `undecided'."
:version "24.1"
:type '(repeat coding-system))
(defcustom erc-server-coding-system (if (and (coding-system-p 'undecided)
(coding-system-p 'utf-8))
'(utf-8 . undecided)
nil)
"The default coding system for incoming and outgoing text.
This is either a coding system, a cons, a function, or nil.
If a cons, the encoding system for outgoing text is in the car
and the decoding system for incoming text is in the cdr. The most
interesting use for this is to put `undecided' in the cdr. This
means that `erc-coding-system-precedence' will be consulted, and the
first match there will be used.
If a function, it is called with the argument `target' and should
return a coding system or a cons as described above.
If you need to send non-ASCII text to people not using a client that
does decoding on its own, you must tell ERC what encoding to use.
Emacs cannot guess it, since it does not know what the people on the
other end of the line are using."
:type '(choice (const :tag "None" nil)
coding-system
(cons (coding-system :tag "encoding" :value utf-8)
(coding-system :tag "decoding" :value undecided))
function))
(defcustom erc-encoding-coding-alist nil
"Alist of target regexp and coding-system pairs to use.
This overrides `erc-server-coding-system' depending on the
current target as returned by `erc-default-target'.
Example: If you know that the channel #linux-ru uses the coding-system
`cyrillic-koi8', then add (\"#linux-ru\" . cyrillic-koi8) to the
alist."
:type '(repeat (cons (regexp :tag "Target")
coding-system)))
(defcustom erc-server-connect-function #'erc-open-network-stream
"Function used to initiate a connection.
It should take same arguments as `open-network-stream' does."
:type 'function)
(defcustom erc-server-prevent-duplicates '("301")
"Either nil or a list of strings.
Each string is a IRC message type, like PRIVMSG or NOTICE.
All Message types in that list of subjected to duplicate prevention."
:type '(repeat string))
(defcustom erc-server-duplicate-timeout 60
"The time allowed in seconds between duplicate messages.
If two identical messages arrive within this value of one another, the second
isn't displayed."
:type 'integer)
(defcustom erc-server-timestamp-format "%Y-%m-%d %T"
"Timestamp format used with server response messages.
This string is processed using `format-time-string'."
:version "24.3"
:type 'string)
;;; Flood-related
;; Most of this is courtesy of Jorgen Schaefer and Circe
;; (https://www.nongnu.org/circe)
(defcustom erc-server-flood-margin 10
"A margin on how much excess data we send.
The flood protection algorithm of ERC works like the one
detailed in RFC 2813, section 5.8 \"Flood control of clients\".
* If `erc-server-flood-last-message' is less than the current
time, set it equal.
* While `erc-server-flood-last-message' is less than
`erc-server-flood-margin' seconds ahead of the current
time, send a message, and increase
`erc-server-flood-last-message' by
`erc-server-flood-penalty' for each message."
:type 'integer)
(defcustom erc-server-flood-penalty 3
"How much we penalize a message.
See `erc-server-flood-margin' for an explanation of the flood
protection algorithm."
:type 'integer)
;; Ping handling
(defcustom erc-server-send-ping-interval 30
"Interval of sending pings to the server, in seconds.
If this is set to nil, pinging the server is disabled."
:type '(choice (const :tag "Disabled" nil)
(integer :tag "Seconds")))
(defcustom erc-server-send-ping-timeout 120
"If the time between ping and response is greater than this, reconnect.
The time is in seconds.
This must be greater than or equal to the value for
`erc-server-send-ping-interval'.
If this is set to nil, never try to reconnect."
:type '(choice (const :tag "Disabled" nil)
(integer :tag "Seconds")))
(defvar-local erc-server-ping-handler nil
"This variable holds the periodic ping timer.")
;;;; Helper functions
(defvar erc--reject-unbreakable-lines nil
"Signal an error when a line exceeds `erc-split-line-length'.
Sending such lines and hoping for the best is no longer supported
in ERC 5.6. This internal var exists as a possibly temporary
escape hatch for inhibiting their transmission.")
(defun erc--split-line (longline)
(let* ((coding (erc-coding-system-for-target nil))
(original-window-buf (window-buffer (selected-window)))
out)
(when (consp coding)
(setq coding (car coding)))
(setq coding (coding-system-change-eol-conversion coding 'unix))
(unwind-protect
(with-temp-buffer
(set-window-buffer (selected-window) (current-buffer))
(insert longline)
(goto-char (point-min))
(while (not (eobp))
(let ((upper (filepos-to-bufferpos erc-split-line-length
'exact coding)))
(goto-char (or upper (point-max)))
(unless (eobp)
(skip-chars-backward "^ \t"))
(when (bobp)
(when erc--reject-unbreakable-lines
(user-error
(substitute-command-keys
(concat "Unbreakable line encountered "
"(Recover input with \\[erc-previous-command])"))))
(goto-char upper))
(when-let ((cmp (find-composition (point) (1+ (point)))))
(if (= (car cmp) (point-min))
(goto-char (nth 1 cmp))
(goto-char (car cmp)))))
(when (= (point-min) (point))
(goto-char (point-max)))
(push (buffer-substring-no-properties (point-min) (point)) out)
(delete-region (point-min) (point)))
(or (nreverse out) (list "")))
(set-window-buffer (selected-window) original-window-buf))))
;; From Circe
(defun erc-split-line (longline)
"Return a list of lines which are not too long for IRC.
The length is specified in `erc-split-line-length'.
Currently this is called by `erc-send-input'."
(let* ((coding (erc-coding-system-for-target nil))
(charset (if (consp coding) (car coding) coding)))
(with-temp-buffer
(insert longline)
;; The line lengths are in octets, not characters (because these
;; are server protocol limits), so we have to first make the
;; text into bytes, then fold the bytes on "word" boundaries,
;; and then make the bytes into text again.
(encode-coding-region (point-min) (point-max) charset)
(let ((fill-column erc-split-line-length))
(fill-region (point-min) (point-max)
nil t))
(decode-coding-region (point-min) (point-max) charset)
(split-string (buffer-string) "\n"))))
(defun erc-forward-word ()
"Move forward one word, ignoring any subword settings.
If no `subword-mode' is active, then this is (forward-word)."
(skip-syntax-forward "^w")
(> (skip-syntax-forward "w") 0))
(defun erc-word-at-arg-p (pos)
"Report whether the char after a given POS has word syntax.
If POS is out of range, the value is nil."
(let ((c (char-after pos)))
(if c
(eq ?w (char-syntax c))
nil)))
(defun erc-bounds-of-word-at-point ()
"Return the bounds of word at point, or nil if we're not at a word.
If no `subword-mode' is active, then this is
\(bounds-of-thing-at-point \\='word)."
(if (or (erc-word-at-arg-p (point))
(erc-word-at-arg-p (1- (point))))
(save-excursion
(let* ((start (progn (skip-syntax-backward "w") (point)))
(end (progn (skip-syntax-forward "w") (point))))
(cons start end)))
nil))
;; Used by CTCP functions
(defun erc-upcase-first-word (str)
"Upcase the first word in STR."
(with-temp-buffer
(insert str)
(goto-char (point-min))
(upcase-region (point) (progn (erc-forward-word) (point)))
(buffer-string)))
(defun erc-server-setup-periodical-ping (buffer)
"Set up a timer to periodically ping the current server.
The current buffer is given by BUFFER."
(with-current-buffer buffer
(when erc-server-ping-handler
(cancel-timer erc-server-ping-handler))
(when erc-server-send-ping-interval
(setq erc-server-ping-handler (run-with-timer
4 erc-server-send-ping-interval
#'erc-server-send-ping
buffer))
;; I check the timer alist for an existing timer. If one exists,
;; I get rid of it
(let ((timer-tuple (assq buffer erc-server-ping-timer-alist)))
(if timer-tuple
;; this buffer already has a timer. Cancel it and set the new one
(progn
(cancel-timer (cdr timer-tuple))
(setf (cdr (assq buffer erc-server-ping-timer-alist)) erc-server-ping-handler))
;; no existing timer for this buffer. Add new one
(add-to-list 'erc-server-ping-timer-alist
(cons buffer erc-server-ping-handler)))))))
(defun erc-server-process-alive (&optional buffer)
"Return non-nil when BUFFER has an `erc-server-process' open or running."
(with-current-buffer (or buffer (current-buffer))
(and erc-server-process
(processp erc-server-process)
(memq (process-status erc-server-process) '(run open)))))
;;;; Connecting to a server
(defun erc-open-network-stream (name buffer host service &rest parameters)
"Like `open-network-stream', but does non-blocking IO."
(let ((p (plist-put parameters :nowait t)))
(apply #'open-network-stream name buffer host service p)))
(cl-defmethod erc--register-connection ()
"Perform opening IRC protocol exchange with server."
(run-hooks 'erc--server-post-connect-hook)
(erc-login))
(defvar erc--server-connect-function #'erc--server-propagate-failed-connection
"Function called one second after creating a server process.
Called with the newly created process just before the opening IRC
protocol exchange.")
(defun erc--server-propagate-failed-connection (process)
"Ensure the PROCESS sentinel runs at least once on early failure.
Act as a watchdog timer to force `erc-process-sentinel' and its
finalizers, like `erc-disconnected-hook', to run when PROCESS has
a status of `failed' after one second. But only do so when its
error data is something ERC recognizes. Print an explanation to
the server buffer in any case."
(when (eq (process-status process) 'failed)
(erc-display-message
nil '(notice error) (process-buffer process)
(format "Process exit status: %S" (process-exit-status process)))
(pcase (process-exit-status process)
(111
(erc-process-sentinel process "failed with code 111\n"))
(`(file-error . ,_)
(erc-process-sentinel process "failed with code -523\n"))
((rx "tls" (+ nonl) "failed")
(erc-process-sentinel process "failed with code -525\n")))))
(defvar erc--server-connect-dumb-ipv6-regexp
;; Not for validation (gives false positives).
(rx bot "[" (group (+ (any xdigit digit ":.")) (? "%" (+ alnum))) "]" eot))
(defun erc-server-connect (server port buffer &optional client-certificate)
"Perform the connection and login using the specified SERVER and PORT.
We will store server variables in the buffer given by BUFFER.
CLIENT-CERTIFICATE may optionally be used to specify a TLS client
certificate to use for authentication when connecting over
TLS (see `erc-session-client-certificate' for more details)."
(when (string-match erc--server-connect-dumb-ipv6-regexp server)
(setq server (match-string 1 server)))
(let ((msg (erc-format-message 'connect ?S server ?p port)) process
(args `(,(format "erc-%s-%s" server port) nil ,server ,port)))
(when client-certificate
(setq args `(,@args :client-certificate ,client-certificate)))
(message "%s" msg)
(setq process (apply erc-server-connect-function args))
(unless (processp process)
(error "Connection attempt failed"))
;; Misc server variables
(with-current-buffer buffer
(setq erc-server-filter-data nil)
(setq erc-server-process process)
(setq erc-server-quitting nil)
(setq erc-server-reconnecting nil
erc--server-reconnect-timer nil)
(setq erc-server-timed-out nil)
(setq erc-server-banned nil)
(setq erc-server-error-occurred nil)
(let ((time (erc-current-time)))
(setq erc-server-last-sent-time time)
(setq erc-server-last-ping-time time)
(setq erc-server-last-received-time time))
(setq erc-server-lines-sent 0)
;; last peers (sender and receiver)
(setq erc-server-last-peers (cons nil nil)))
;; we do our own encoding and decoding
(when (fboundp 'set-process-coding-system)
(set-process-coding-system process 'raw-text))
;; process handlers
(set-process-sentinel process #'erc-process-sentinel)
(set-process-filter process #'erc-server-filter-function)
(set-process-buffer process buffer)
(erc-log "\n\n\n********************************************\n")
(message "%s" (erc-format-message
'login ?n
(with-current-buffer buffer (erc-current-nick))))
;; wait with script loading until we receive a confirmation (first
;; MOTD line)
(if (eq (process-status process) 'connect)
;; waiting for a non-blocking connect - keep the user informed
(let ((erc--msg-prop-overrides `((erc--skip . (stamp))
,@erc--msg-prop-overrides)))
(erc-display-message nil nil buffer "Opening connection..\n")
(run-at-time 1 nil erc--server-connect-function process))
(message "%s...done" msg)
(erc--register-connection))))
(defun erc-server-reconnect ()
"Reestablish the current IRC connection.
Make sure you are in an ERC buffer when running this."
(let ((buffer (erc-server-buffer)))
(unless (buffer-live-p buffer)
(if (eq major-mode 'erc-mode)
(setq buffer (current-buffer))
(error "Reconnect must be run from an ERC buffer")))
(with-current-buffer buffer
(erc-update-mode-line)
(erc-set-active-buffer (current-buffer))
(setq erc-server-last-sent-time 0)
(setq erc-server-lines-sent 0)
(let ((erc-server-connect-function (or erc-session-connector
#'erc-open-network-stream))
(erc--server-reconnecting (buffer-local-variables)))
(erc-open erc-session-server erc-session-port erc-server-current-nick
erc-session-user-full-name t erc-session-password
nil nil nil erc-session-client-certificate
erc-session-username
(erc-networks--id-given erc-networks--id))
(defvar erc-reuse-buffers)
(unless (with-suppressed-warnings ((obsolete erc-reuse-buffers))
erc-reuse-buffers)
(cl-assert (not (eq buffer (current-buffer)))))))))
(defun erc-server-delayed-reconnect (buffer)
(if (buffer-live-p buffer)
(with-current-buffer buffer
(erc-server-reconnect))))
(defvar-local erc--server-reconnect-timeout nil)
(defvar-local erc--server-reconnect-timeout-check 10)
(defvar-local erc--server-reconnect-timeout-scale-function
#'erc--server-reconnect-timeout-double)
(defun erc--server-reconnect-timeout-double (existing)
"Double EXISTING timeout, but cap it at 5 minutes."
(min 300 (* existing 2)))
;; This may appear to hang at various places. It's assumed that when
;; *Messages* contains "Waiting for socket ..." or similar, progress
;; will be made eventually.
(defun erc-server-delayed-check-reconnect (buffer)
"Wait for internet connectivity before trying to reconnect.
Expect BUFFER to be the server buffer for the current connection."
(when (buffer-live-p buffer)
(with-current-buffer buffer
(setq erc--server-reconnect-timeout
(funcall erc--server-reconnect-timeout-scale-function
(or erc--server-reconnect-timeout
erc-server-reconnect-timeout)))
(let* ((reschedule (lambda (proc)
(when (buffer-live-p buffer)
(with-current-buffer buffer
(let ((erc-server-reconnect-timeout
erc--server-reconnect-timeout))
(delete-process proc)
(erc-display-message nil 'error buffer
"Nobody home...")
(erc-schedule-reconnect buffer 0))))))
(conchk-exp (time-add erc--server-reconnect-timeout-check
(current-time)))
(conchk-timer nil)
(conchk (lambda (proc)
(let ((status (process-status proc))
(xprdp (time-less-p conchk-exp (current-time))))
(when (or (not (eq 'connect status)) xprdp)
(cancel-timer conchk-timer))
(when (buffer-live-p buffer)
(cond (xprdp (erc-display-message
nil 'error buffer
"Timed out while dialing...")
(delete-process proc)
(funcall reschedule proc))
((eq 'failed status)
(funcall reschedule proc)))))))
(sentinel (lambda (proc event)
(pcase event
("open\n"
(run-at-time nil nil #'send-string proc
(format "PING %d\r\n"
(time-convert nil 'integer))))
((or "connection broken by remote peer\n"
(rx bot "failed"))
(run-at-time nil nil reschedule proc)))))
(filter (lambda (proc _)
(delete-process proc)
(with-current-buffer buffer
(setq erc--server-reconnect-timeout nil))
(run-at-time nil nil #'erc-server-delayed-reconnect
buffer))))
(condition-case _
(let ((proc (funcall erc-session-connector
"*erc-connectivity-check*" nil
erc-session-server erc-session-port
:nowait t)))
(setq conchk-timer (run-at-time 1 1 conchk proc))
(set-process-filter proc filter)
(set-process-sentinel proc sentinel))
(file-error (funcall reschedule nil)))))))
(defun erc-server-filter-function (process string)
"The process filter for the ERC server."
(with-current-buffer (process-buffer process)
(setq erc-server-last-received-time (erc-current-time))
;; If you think this is written in a weird way - please refer to the
;; docstring of `erc-server-processing-p'
(if erc-server-processing-p
(setq erc-server-filter-data
(if erc-server-filter-data
(concat erc-server-filter-data string)
string))
;; This will be true even if another process is spawned!
(let ((erc-server-processing-p t))
(setq erc-server-filter-data (if erc-server-filter-data
(concat erc-server-filter-data
string)
string))
(while (and erc-server-filter-data
(string-match "[\n\r]+" erc-server-filter-data))
(let ((line (substring erc-server-filter-data
0 (match-beginning 0))))
(setq erc-server-filter-data
(if (= (match-end 0)
(length erc-server-filter-data))
nil
(substring erc-server-filter-data
(match-end 0))))
(erc-log-irc-protocol line nil)
(erc-parse-server-response process line)))))))
(defun erc--server-reconnect-p (event)
"Return non-nil when ERC should attempt to reconnect.
EVENT is the message received from the closed connection process."
(and erc-server-auto-reconnect
(not erc-server-banned)
;; make sure we don't infinitely try to reconnect, unless the
;; user wants that
(or (eq erc-server-reconnect-attempts t)
(and (integerp erc-server-reconnect-attempts)
(< erc-server-reconnect-count
erc-server-reconnect-attempts)))
(or erc-server-timed-out
(not (string-match "^deleted" event)))
;; open-network-stream-nowait error for connection refused
(if (string-match "^failed with code 111" event) 'nonblocking t)))
(defun erc-server-reconnect-p (event)
"Return non-nil if ERC should attempt to reconnect automatically.
EVENT is the message received from the closed connection process."
(declare (obsolete "see `erc--server-reconnect-p'" "29.1"))
(or (with-suppressed-warnings ((obsolete erc-server-reconnecting))
erc-server-reconnecting)
(erc--server-reconnect-p event)))
(defun erc--server-last-reconnect-on-disconnect (&rest _)
(remove-hook 'erc-disconnected-hook
#'erc--server-last-reconnect-on-disconnect t)
(erc--server-last-reconnect-display-reset (current-buffer)))
(defun erc--server-last-reconnect-display-reset (buffer)
"Deactivate `erc-auto-reconnect-display'."
(when (buffer-live-p buffer)
(with-current-buffer buffer
(when erc--server-reconnect-display-timer
(cancel-timer erc--server-reconnect-display-timer)
(remove-hook 'erc-disconnected-hook
#'erc--server-last-reconnect-display-reset t)
(setq erc--server-reconnect-display-timer nil
erc--server-last-reconnect-count 0)))))
(defconst erc--mode-line-process-reconnecting
'(:eval (erc-with-server-buffer
(and erc--server-reconnect-timer
(format ": reconnecting in %.1fs"
(- (timer-until erc--server-reconnect-timer
(current-time)))))))
"Mode-line construct showing seconds until next reconnect attempt.
Move point around to refresh.")
(defun erc--cancel-auto-reconnect-timer ()
(when erc--server-reconnect-timer
(cancel-timer erc--server-reconnect-timer)
(erc-display-message nil 'notice nil 'reconnect-canceled
?u (buffer-name)
?c (- (timer-until erc--server-reconnect-timer
(current-time))))
(setq erc--server-reconnect-timer nil)
(erc-update-mode-line)))
(defun erc-schedule-reconnect (buffer &optional incr)
"Create and return a reconnect timer for BUFFER.
When `erc-server-reconnect-attempts' is a number, increment
`erc-server-reconnect-count' by INCR unconditionally."
(let ((count (and (integerp erc-server-reconnect-attempts)
(- erc-server-reconnect-attempts
(cl-incf erc-server-reconnect-count (or incr 1)))))
(proc (buffer-local-value 'erc-server-process buffer)))