-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathircbot.sh
executable file
·1544 lines (1429 loc) · 44.7 KB
/
ircbot.sh
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
#!/usr/bin/env bash
# Copyright 2018 Anthony DeDominic <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
VERSION="neo8ball: v2021.4.17"
echo1() {
printf '%s\n' "$*"
}
echo2() {
printf >&2 '%s\n' "$*"
}
# help info
usage() {
echo2 \
'usage: '"$0"' [-c config] [-o logfile] [-t]
-t --timestamp Timestamp logs using iso-8601.
-c --config=file A neo8ball config.sh
-o --log-out=file A file to log to instead of stdout.
-h --help This message.
If no configuration path is found or CONFIG_PATH is not set,
ircbot will assume the configuration is in the same directory
as the script.
For testing, you can set MOCK_CONN_TEST=<anything>'
exit 1
}
die() {
echo2 "*** CRITICAL *** $1"
exit 1
}
# parse args
while (( $# > 0 )); do
case "$1" in
-c|--config)
CONFIG_PATH="$2"
shift
;;
--config=*)
CONFIG_PATH="${1#*=}"
;;
-o|--log-out)
exec 1<>"$2"
exec 2>&1
shift
;;
--log-out=*)
exec 1<>"${1#*=}"
exec 2>&1
;;
-t|--timestamp)
LOG_TSTAMP_FORMAT='%(%Y-%m-%dT%H:%M:%S%z)T '
LOG_TSTAMP_ARG1=-1
;;
-h|--help)
usage
;;
*)
usage
;;
esac
shift
done
#################
# Configuration #
#################
# find default configuration path
# location script's directory
[[ -z "$CONFIG_PATH" ]] && {
CONFIG_PATH="${BASH_SOURCE[0]%/*}/config.sh"
}
# load configuration
if [[ -f "$CONFIG_PATH" ]]; then
# shellcheck disable=SC1090
. "$CONFIG_PATH"
else
echo2 '*** CRITICAL *** no configuration'
usage
fi
# set default temp dir path if not set
# should consider using /dev/shm unless your /tmp is a tmpfs
[[ -z "$temp_dir" ]] && temp_dir=/tmp
#######################
# Configuration Tests #
#######################
# check for ncat, use bash tcp otherwise
# fail hard if user wanted tls and ncat not found
if ! type ncat >/dev/null 2>&1; then
echo1 "*** NOTICE *** ncat not found; using bash tcp"
[[ -n "$TLS" ]] &&
die "TLS does not work with bash tcp"
BASH_TCP=a
fi
# use default nick if not set, should be set
if [[ -z "$NICK" ]]; then
echo1 "*** NOTICE *** nick was not specified; using ircbashbot"
NICK="ircbashbot"
fi
# fail if no server
if [[ -z "$SERVER" ]]; then
die "A server must be defined; check the configuration."
fi
###############
# Plugin Temp #
###############
# shellcheck disable=SC2154
APP_TMP="$temp_dir/bash-ircbot.$$"
mkdir -m 0770 "$APP_TMP" ||
die "failed to make temp directory, check your config"
# add temp dir for plugins
PLUGIN_TEMP="$APP_TMP/plugin"
mkdir "$PLUGIN_TEMP" ||
die "failed to create plugin temp dir"
# this is for plugins, so export it
export PLUGIN_TEMP
#########
# State #
#########
# describes modes of users on a per channel basis
declare -A user_modes
# populate invites array to prevent duplicate entries
declare -A invites
if [[ -f "$INVITE_FILE" ]]; then
while read -r channel; do
[[ -z "$channel" ]] && continue
invites[$channel]=1
done < "$INVITE_FILE"
fi
declare -Ag antispam_list
# IGNORE to a hash
declare -A ignore_hash
for ign in "${IGNORE[@]}"; do
ignore_hash[$ign]=1
done
# if REGEX_ORDERED not defined, build it here
if [[ "${#REGEX_ORDERED[@]}" == 0 ]]; then
REGEX_ORDERED=("${!REGEX[@]}")
fi
####################
# Signal Listeners #
####################
# handler to terminate bot on TERM | INT
exit_status=0
quit_prg() {
exec 3<&-
exec 4<&-
[[ -n "$ncat_pid" ]] &&
kill -- "$ncat_pid"
rm -rf -- "$APP_TMP"
exit "$exit_status"
}
trap 'quit_prg' SIGINT SIGTERM
# similar to above but with >0 exit code
exit_failure() {
exit_status=1
quit_prg
}
# helper for channel config reload
# determine if chan is in channel list
contains_chan() {
for chan in "${@:2}"; do
[[ "$chan" == "$1" ]] && return 0
done
return 1
}
# handle configuration reloading
# faster than restarting
# will: change nick (if applicable)
# reauth with nickserv
# join/part new or removed channels
# reload all other variables, like COMMANDS, etc
reload_config() {
send_log 'DEBUG' 'CONFIG RELOAD TRIGGERED'
local _nick="$NICK"
# shellcheck disable=SC2153
local _nickserv="$NICKSERV"
local _channels=("${CHANNELS[@]}")
# shellcheck disable=SC1090
. "$CONFIG_PATH"
# NICK changed
if [[ "$NICK" != "$_nick" ]]; then
send_msg "NICK $NICK"
fi
# pass change for nickserv
if [[ "$NICKSERV" != "$_nickserv" ]]; then
printf '%s\r\n' "NICKSERV IDENTIFY $NICKSERV" >&3
send_log "DEBUG" "SENT -> NICKSERV IDENTIFY <PASSWORD>"
fi
# persist channel invites
# shellcheck disable=SC2207
[[ -f "$INVITE_FILE" ]] &&
CHANNELS+=($(< "$INVITE_FILE"))
declare -A uniq_chans
for chan in "${_channels[@]}" "${CHANNELS[@]}"; do
uniq_chans[$chan]+='1'
done
declare -a leave_list=()
declare -a join_list=()
local jlist='' llist=''
for uniq_chan in "${!uniq_chans[@]}"; do
(( ${#uniq_chans[$uniq_chan]} > 1 )) && continue
if contains_chan "$uniq_chan" "${_channels[@]}"; then
leave_list+=("$uniq_chan")
else
join_list+=("$uniq_chan")
fi
done
if [[ "${#join_list[@]}" -gt 0 ]]; then
printf -v jlist ',%s' "${join_list[@]}"
send_large_join_part ':j' "${jlist:1}"
fi
if [[ "${#leave_list[@]}" -gt 0 ]]; then
printf -v llist ',%s' "${leave_list[@]}"
send_large_join_part ':l' "${llist:1}"
fi
unset ignore_hash
declare -Ag ignore_hash
for ign in "${IGNORE[@]}"; do
ignore_hash[$ign]=1
done
}
trap 'reload_config' SIGHUP SIGWINCH
####################
# Setup Connection #
####################
TLS_OPTS=()
if [[ -n "$TLS" ]]; then
TLS_OPTS+=('--ssl')
# default verify
[[ -n "${VERIFY_TLS-y}" ]] &&
TLS_OPTS+=('--ssl-verify')
[[ -n "$VERIFY_TLS_FILE" ]] &&
TLS_OPTS+=('--ssl-cert' "$VERIFY_TLS_FILE")
fi
# this mode should be used for testing only
if [[ -n "$MOCK_CONN_TEST" ]]; then
echo2 'IN MOCK'
# send irc communication to
exec 4>&0 # from server - stdin
exec 3<&1 # to server - stdout
exec 1>&-
exec 1<&2 # remap stdout to err for logs
# Connect to server otherwise
elif [[ -z "$BASH_TCP" ]]; then
coproc {
ncat "${TLS_OPTS[@]}" "${SERVER:-irc.rizon.net}" "${PORT:-6667}"
echo1 'ERROR :ncat has terminated'
}
ncat_pid="$COPROC_PID"
# coprocs are a bit weird
# subshells may not be able to r/w to these fd's normally
# without reopening them
exec 3<> "/dev/fd/${COPROC[1]}"
exec 4<> "/dev/fd/${COPROC[0]}"
else
exec 3<> "/dev/tcp/${SERVER}/${PORT}" ||
die "Cannot connect to ($SERVER) on port ($PORT)"
exec 4<&3
fi
########################
# IRC Helper Functions #
########################
all_control_characters=$'\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37'
## helper for iterating over a string using a given delimiter
##
## iter_tokenize/2:
## $1: 'init' - Initialize tokenizer.
## $2 - String to tokenize.
##
## iter_tokenize/1:
## $1 - Delimit string with this character,
## consumes and returns remaining string if no such delimiter found.
##
## iter_tokenize/0:
## Test if iterator is done. Returns _iter_remain.
##
## mutates _iter_remain - unprocessed parts of the string.
## mutates REPLY - The next token found, or the remainder of the string.
##
## returns: (0|1) - 1 if no more input, 0 otherwise.
iter_tokenize() {
if [[ "$1" == 'init' && -n "$2" ]]; then
_iter_remain="$2"
REPLY=
return 0
elif [[ -z "$_iter_remain" ]]; then
REPLY=
return 1
elif [[ -n "$1" ]]; then
REPLY="${_iter_remain%%"$1"*}"
if [[ "${_iter_remain#"$REPLY$1"}" == "$_iter_remain" ]]; then
_iter_remain=
else
_iter_remain="${_iter_remain#"$REPLY$1"}"
fi
return 0
else # Iterator is not done.
REPLY="$_iter_remain"
return 0
fi
}
# Parse a given IRC message.
# e.g. :some!message!host VERB param1 param2 param3
# into user=some
# host=host
# sender=some!message!host
# command=VERB
# params=(param1 param2 param3)
#
# $1 - the full message to parse. may include or disclude \r
#
# mutates: sender - the user who sent the message.
# mutates: command - the IRC verb associated with the msessage.
# mutates: params - The params associated with this message.
# mutates: user - actually the nickname of the sender.
# mutates: host - the "hostname" associated with the sender.
parse_irc() {
# TODO: enable IRCv3 tags
# local state=tags
# ttags=
local state='sender'
sender=
command=
params=()
iter_tokenize init "${1%$'\r'}"
while iter_tokenize ' '; do
# we only consume extra spaces in the trailing parameter.
[[ "$REPLY" == '' ]] && continue
case "$state" in
sender)
case "$REPLY" in
:*)
sender="${REPLY#:}"
state='command'
;;
*)
command="$REPLY"
state='params'
;;
esac
;;
command)
command="$REPLY"
state='params'
;;
params)
case "$REPLY" in
:*)
local t="$REPLY"
iter_tokenize
params+=("${t#:}${REPLY:+" $REPLY"}")
break
;;
*)
params+=("$REPLY")
;;
esac
;;
esac
done
# parser sender into pieces
iter_tokenize init "$sender"
iter_tokenize '!'
user="$REPLY"
iter_tokenize '@'
# ignored for now
# user="$REPLY"
iter_tokenize
host="$REPLY"
}
# Takes a user mode as stored in $user_modes and returns a single char
# representing the user's highest chan mode.
#
# Possible values of REPLY:
# q - OWNER
# a - ADMIN
# o - OPERATOR
# h - HALF-OP
# v - VOICED
# '' - nothing
#
# $1 - the modebits
# mutates: REPLY - empty if user has no modes or a single char.
modebit_to_char() {
local mode="$1"
if (( (mode & 2#10000) > 0 )); then
REPLY='q'
elif (( (mode & 2#01000) > 0 )); then
REPLY='a'
elif (( (mode & 2#00100) > 0 )); then
REPLY='o'
elif (( (mode & 2#00010) > 0 )); then
REPLY='h'
elif (( (mode & 2#00001) > 0 )); then
REPLY='v'
else
REPLY=
fi
}
# inverse of modebit_to_char
# $1 - get the value of this given char
# mutates: REPLY - value of $1 in modebits.
char_to_modebit() {
case "$1" in
'v'|'+') REPLY='2#00001' ;;
'h'|'%') REPLY='2#00010' ;;
'o'|'@') REPLY='2#00100' ;;
'a'|'&') REPLY='2#01000' ;;
'q'|'~') REPLY='2#10000' ;;
*) REPLY='0' ;;
esac
}
# Add a given mode to a user.
#
# $1 - channel where this happened
# $2 - user who is affected
# $3 - the mode bit converted by char_to_modebit()
add_user_mode() {
local channel="$1"
local user="$2"
local modebit="$3"
local chr_mode="${user_modes["$channel $user"]}"
send_log 'DEBUG' "$channel <$user> MODE bits BEFORE: $chr_mode"
if [[ -z "$chr_mode" ]]; then
user_modes["$channel $user"]="$modebit"
else
user_modes["$channel $user"]="$(( chr_mode | modebit ))"
fi
send_log 'DEBUG' "$channel <$user> MODE bits AFTER: $(( chr_mode | modebit ))"
}
# Remove a given mode to a user.
#
# $1 - channel where this happened
# $2 - user who is affected
# $3 - the mode bit converted by char_to_modebit()
clear_user_mode() {
local channel="$1"
local user="$2"
local modebit="$3"
local chr_mode="${user_modes["$channel $user"]}"
send_log 'DEBUG' "$channel <$user> MODE bits BEFORE: $chr_mode"
if [[ -z "$chr_mode" ]]; then
user_modes["$channel $user"]="0"
else
user_modes["$channel $user"]="$(( chr_mode & (~modebit) ))"
fi
send_log 'DEBUG' "$channel <$user> MODE bits AFTER: $(( chr_mode & (~modebit) ))"
}
# Parse the 353 NAMES / NAMESX reply message.
#
# $1 - channel
# $2 - the string from the irc server with all the usernames (\w mode)
mode_chars='+%@&~'
parse_353() {
local channel="$1"
iter_tokenize init "$2"
while iter_tokenize ' '; do
local user="$REPLY"
local mode_string="${user##*["$mode_chars"]}"
mode_string="${user%"$mode_string"}"
user="${user##*["$mode_chars"]}"
# make sure we zero out the user's mode.
user_modes["$channel $user"]='2#00000';
while [[ -n "$mode_string" ]]; do
local mode_chr="${mode_string:0:1}"
local mode_string="${mode_string:1}"
char_to_modebit "$mode_chr"
mode_chr="$REPLY"
add_user_mode "$channel" "$user" "$mode_chr"
done
done
}
# Parse only CHANMODES=A,B,C,D
# where A = 1 ALWAYS has a parameter (Address | nick)
# B = 2 ALWAYS has a parameter (channel setting)
# C = 3 parameter only when +. - has no parameter
# D = 4 NEVER has a parameter.
# Fill with *sane* defaults in case we never get 005
declare -A ISUPPORT_CHANMODES=(
[b]=1 # ban
[e]=1 # exempt (from ban)
[I]=1 # invite-exempt (from chan mode +i)
[k]=2 # key
[l]=3 # channel limit (-l has no param, +l does)
# Assume rest are 4. We don't care about 4.
)
# parse the ISUPPORT key value pairs
# params could go from 1 to ~13 key value pairs
#
# $@ - array of parameters from ISUPPORT, only CHANMODES= is used.
parse_005() {
for arg; do
local value="${arg#*=}"
local key="${arg%"$value"}"
case "$key" in
CHANMODES)
ISUPPORT_CHANMODES=()
iter_tokenize init "$value"
# 1(a),2(b),3(c),4(d)
# we can ignore type 4(d) completely as these
# are primarily user modes and they have no value
# to channel mode tracking we care about (as a bot).
local mode_type=1
while iter_tokenize ','; do
local modes="$REPLY"
while [[ -n "$modes" ]]; do
local mode_chr="${modes:0:1}"
local modes="${modes:1}"
ISUPPORT_CHANMODES["$mode_chr"]="$mode_type"
done
mode_type="$(( mode_type + 1 ))"
done
return 0
;;
*) ;;
esac
done
}
# checks ISUPPORT_CHANMODES, or if it is a user prefix (q,a,o,h,v),
# requires a parameter.
#
# $1 - the signedness of the mode (+|-)
# $2 - the mode
#
# returns: 0 if the given mode requires a parameter.
has_parameter_mode() {
case "$2" in
q|a|o|h|v) return 0 ;;
esac
local m="${ISUPPORT_CHANMODES[$2]}"
case "$m" in
1|2) return 0 ;;
3) [[ "$1" == '+' ]] && return 0 ;;
esac
return 1
}
# This command is difficult to understand.
# As far as I can tell based on reading the spec at least twice:
# MODE reply returns to the user something like #channel +|-somemodes param param2, etc...
# Where you must first pregather all the modes that take a parameter (see CHANMODES ISUPPORT 005)
# and then first in, first out, match them to the modes being set.
# If this is incorrect, please help me understand by opening an issue.
#
# e.g.
# +bv banned!user@param -o voiced_user deop_user
# +b -> banned!user@param
# +v -> voiced_user
# -o -> deop_user
#
# $1 - channel these modes manipulate.
# ${@:1} - the rest of the mode line.
# returns: 1 if failed to correctly parse the MODE command.
parse_mode() {
local channel="$1"
shift # rest are "mode strings"
local cmode_type=
local cmodes=()
local params=()
local mode_line=
for mode_line; do
case "$mode_line" in
'-'*|'+'*)
while [[ -n "$mode_line" ]]; do
local mode_chr="${mode_line:0:1}"
local mode_line="${mode_line:1}"
if [[ "$mode_chr" == "+" || "$mode_chr" == '-' ]]
then
cmode_type="$mode_chr"
elif has_parameter_mode "$cmode_type" "$mode_chr"
then
cmodes+=("${cmode_type}${mode_chr}")
fi
done
;;
'') continue ;;
*) params+=("$mode_line") ;;
esac
done
# assert
if [[ "${#cmodes[@]}" != "${#params[@]}" ]]; then
send_log 'ERROR' \
'Something is wrong with the MODE parser or the server.'
send_log 'ERROR' \
'Number of modes to apply do not match up with number of parameters.'
send_log 'INFO' \
'Using NAMES command to attempt to recover Channel Modes.'
send_msg "NAMES $channel"
return 1
fi
local len="${#cmodes[@]}"
for (( i=0; i<len; ++i )); do
local m="${cmodes[i]}"
case "$m" in
+q|+a|+o|+h|+v)
char_to_modebit "${m:1:1}"
send_log 'DEBUG' "$REPLY"
local mv="$REPLY"
local user="${params[i]}"
add_user_mode "$channel" "$user" "$mv"
;;
-q|-a|-o|-h|-v)
char_to_modebit "${m:1}"
send_log 'DEBUG' "$REPLY"
local mv="$REPLY"
local user="${params[i]}"
clear_user_mode "$channel" "$user" "$mv"
;;
esac
done
return 0
}
# parse all the capabilites we support.
#
# $1 - ACK or NAK of capability
# $2 - message body to parse, all the capabilites we requested.
#
# returns: 1 if we didn't get the capabilites we need.
parse_cap() {
local ack="$1"
local message="$2"
local defer_cap_end=
iter_tokenize init "$message"
while iter_tokenize ' '; do
case "$REPLY" in
sasl)
if [[ "$ack" == "ACK" ]]; then
send_msg 'AUTHENTICATE PLAIN'
defer_cap_end=1
else
send_log 'CRITICAL' \
'Server does not support SASL, but SASL_PASS was configured.'
return 1
fi
;;
# We need this for proper mode tracking
# NAMES reply will show *ALL* user-specific channel modes.
# this mode should only be REQd if TRACK_CHAN_MODE=1
multi-prefix)
if [[ "$ack" == "NAK" ]]; then
send_log 'CRITICAL' \
'Server does not support multi-prefix, but TRACK_CHAN_MODE was configured.'
return 1
fi
;;
*)
send_log 'WARNING' \
'We were told about '"$REPLY"' capability with status '"$ack"', but we never asked for it.'
;;
esac
done
if [[ -z "$defer_cap_end" ]]; then
send_msg 'CAP END'
fi
return 0
}
# long joins can be truncated and
# rapidly joining multiple channels at once generally triggers
# some server side antispam
#
# $1 part or join command (:l, :j)
# $2 a comma delimited string of channels
send_large_join_part() {
# assume all chars are 8bit
local LANG=C
local join_len="${#2}"
if (( join_len < 500 )); then
send_cmd <<< "$1 $2"
return
fi
local join_partial=
iter_tokenize init "$2"
while iter_tokenize ','; do
local channel="$REPLY"
if (( (${#join_partial} + ${#channel}) < 500 )); then
join_partial+=",$channel"
else
send_cmd <<< "$1 ${join_partial:1}"
join_partial=",$channel"
fi
done
[[ -n "$join_partial" ]] &&
send_cmd <<< "$1 ${join_partial:1}"
}
# After server "identifies" the bot
# joins all channels
# identifies with nickserv
# NOTE: ircd must implement NICKSERV command
# This command is not technically a standard
post_ident() {
# join chans
local _channels
# shellcheck disable=SC2207
[[ -f "$INVITE_FILE" ]] &&
CHANNELS+=($(< "$INVITE_FILE"))
printf -v _channels ",%s" "${CHANNELS[@]}"
# channels are repopulated on JOIN commands
# to better reflect joined channel realities
CHANNELS=()
# list join channels
send_large_join_part ':j' "${_channels:1}"
# ident with nickserv
if [[ -n "$NICKSERV" ]]; then
# bypass logged send_cmd/send_msg
printf '%s\r\n' "NICKSERV IDENTIFY $NICKSERV" >&3
fi
}
# logger function that outputs to stdout
# checks log level to determine
#
# if applicable to be written
# $1 - log level of message
# $2 - the message
send_log() {
declare -i log_lvl
local clean_log_msg="${2//["$all_control_characters"]/}"
case $1 in
STDOUT)
# shellcheck disable=2183
[[ -n "$LOG_STDOUT" ]] &&
printf '%(%Y-%m-%d %H:%M:%S%z)T %s\n' '-1' "$clean_log_msg"
return
;;
WARNING) log_lvl=3 ;;
INFO) log_lvl=2 ;;
DEBUG) log_lvl=1 ;;
*) log_lvl=4 ;;
esac
(( log_lvl >= LOG_LEVEL )) &&
printf "$LOG_TSTAMP_FORMAT"'*** %s *** %s\n' $LOG_TSTAMP_ARG1 "$1" "$clean_log_msg"
}
# Send arguments to irc server.
# Most servers don't allow for string longer than 510+2 bytes
#
# $* - multiple strings to be sent.
send_msg() {
printf '%s\r\n' "$*" >&3
send_log "DEBUG" "SENT -> $*"
}
# function which converts sic/ircii-like
# commands to IRC messages.
# must be piped or heredoc; no arguments
#
# $1 - OPTIONAL the user/channel to reply to when using the :reply :r command.
# <STDIN> - valid bash-ircbot command string
# SEE - README.md
send_cmd() {
local reply_to="$1"
while read -r; do
cmd="${REPLY%% *}"
if [[ "$REPLY" == "${REPLY#"$cmd"* }" ]]; then
cmd="$cmd"' - ERR_NO_ARGS'
arg="<NO ARG>"
else
arg="${REPLY#"$cmd"* }"
arg="${arg%% *}"
fi
# OTHER ARG must be exactly one space after ARG
if [[ "$REPLY" == "${REPLY#"$cmd"*' '"$arg"' '}" ]]; then
other=
else
other="${REPLY#"$cmd"*' '"$arg"' '}"
fi
case $cmd in
:j|:join)
send_msg "JOIN $arg"
;;
:jd|:delay-join)
sleep "$arg"
send_msg "JOIN $other"
;;
:l|:leave)
send_msg "PART $arg :$other"
;;
:m|:message)
send_msg "PRIVMSG $arg :$other"
;;
:md|:delay-message)
sleep "$arg"
send_msg "PRIVMSG ${other% *} :${other#* }"
;;
:mn|:notice)
send_msg "NOTICE $arg :$other"
;;
:nd|:delay-notice)
sleep "$arg"
send_msg "NOTICE ${other% *} :${other#* }"
;;
:c|:ctcp)
send_msg "PRIVMSG $arg :"$'\001'"$other"$'\001'
;;
:n|:nick)
send_msg "NICK $arg"
;;
:q|:quit)
send_msg "QUIT :$arg $other"
;;
:r|:reply)
if [[ -n "$reply_to" ]]; then
send_msg "PRIVMSG $reply_to :${arg}${other:+ "$other"}"
else
send_log "ERROR" \
"Plugin attempted to use the reply command but we don't have a reply_to."
fi
;;
:raw)
send_msg "$arg $other"
;;
:le|:loge)
send_log "ERROR" "$arg $other"
;;
:lw|:logw)
send_log "WARNING" "$arg $other"
;;
:li|:log)
send_log "INFO" "$arg $other"
;;
:ld|:logd)
send_log "DEBUG" "$arg $other"
;;
*)
send_log "ERROR" "Invalid command: ($cmd) args: ($arg $other)"
;;
esac
done
}
# Match a string to the list of configured regexps to check.
#
# $1 - String to try and match.
# mutates: REPLY - Which will contain any matching regexp.
# returns: - 0 if REPLY contains a regexp match.
check_regexp() {
local regex
for regex in "${REGEX_ORDERED[@]}"; do
if [[ "$1" =~ $regex ]]; then
[[ -x "$PLUGIN_PATH/${REGEX["$regex"]}" ]] || return 1
REPLY="$regex"
return 0
fi
done
return 1
}
# Determines if message qualifies for spam filtering.
# This algorithm uses a leaky-bucket-like mechanism
# to prevent abuse.
#
# $1 - Nickname to check.
# returns: - 1 if the user should be ignored for spamming.
# config: ANTISPAM - If we should time users out.
# config: ANTISPAM_TIMEOUT - Time in seconds a user must wait
# til they can issue another command.
# config: ANTISPAM_COUNT - Number of requests a user gets before
# they are blocked for spamming.
check_spam() {
[[ -z "$ANTISPAM" ]] && return 0
# Allowance is the number of commands a given user
# is allowed to invoke before they are considered abusive.
# the last_allowed counter indicates when they last invoked
# a given command.
#
# If the last_allowed was far enough in the past (ANTISPAM_TIMEOUT),
# the user is granted an allowance.
local allowance
local last_allowed
# counts down to 0
local max_allowance=$(( ${ANTISPAM_COUNT:-3} + 1 ))
if [[ -z "${antispam_list[$1]}" ]]; then
allowance="$max_allowance"
last_allowed="$SECONDS"
else
allowance="${antispam_list[$1]% *}"
last_allowed="${antispam_list[$1]#* }"
fi
if (( allowance > 0 )); then
allowance=$(( allowance - 1 ))
fi
local current_time="$SECONDS"
local time_between_req="${ANTISPAM_TIMEOUT:-10}"
granted_tokens=$(( ( current_time - last_allowed ) / time_between_req ))
if (( granted_tokens > 0 )); then
last_allowed="$current_time"
allowance=$(( allowance + granted_tokens ))
if (( allowance > max_allowance )); then
allowance="$max_allowance"
fi
fi
antispam_list[$1]="$allowance $last_allowed"
if (( allowance == 0 )); then
send_log "DEBUG" "SPAMMER -> $1"
return 1
else
return 0
fi
}
# check if nick is in ignore list
#
# $1 - nick to check
#
# returns: 1 if the user should be ignored.
# config: IGNORE - a list of nickanmes we ignore
# we transmute the list into a hashmap for speed.
check_ignore() {
if [[ -n "${ignore_hash[$1]}" ]]; then
send_log "DEBUG" "IGNORED -> $1"
return 1
fi