-
Notifications
You must be signed in to change notification settings - Fork 0
/
mozbot.pl
executable file
·3201 lines (2923 loc) · 115 KB
/
mozbot.pl
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/perl -w -I ~/perl5/lib/perl5
# -*- Mode: perl; indent-tabs-mode: nil -*-
# DO NOT REMOVE THE -T ON THE FIRST LINE!!!
#
# _ _
# m o z i l l a |.| o r g | |
# _ __ ___ ___ ___| |__ ___ | |_
# | '_ ` _ \ / _ \_ / '_ \ / _ \| __|
# | | | | | | (_) / /| |_) | (_) | |_
# |_| |_| |_|\___/___|_.__/ \___/ \__|
# ====================================
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Harrison Page <[email protected]>
# Terry Weissman <[email protected]>
# Risto Kotalampi <[email protected]>
# Josh Soref <[email protected]>
# Ian Hickson <[email protected]>
# Ken Coar <[email protected]>
# Adam Di Carlo <[email protected]>
#
# mozbot.pl [email protected] 1998-10-14
# "irc bot for the gang on #mozilla"
#
# mozbot.pl [email protected] 2000-07-04
# "irc bot engine for anyone" :-)
#
# hack on me! required reading:
#
# Net::IRC web page:
# http://sourceforge.net/projects/net-irc/
# (free software)
# or get it from CPAN @ http://www.perl.com/CPAN
#
# RFC 1459 (Internet Relay Chat Protocol):
# http://sunsite.cnlab-switch.ch/ftp/doc/standard/rfc/14xx/1459
#
# Please file bugs in Bugzilla, under the 'Webtools' product,
# component 'Mozbot'. https://bugzilla.mozilla.org/
# TO DO LIST
# XXX Something that checks modules that failed to compile and then
# reloads them when possible
# XXX an HTML entity convertor for things that speak web page contents
# XXX UModeChange
# XXX minor checks
# XXX throttle nick changing and away setting (from module API)
# XXX compile self before run
# XXX parse mode (+o, etc)
# XXX customise gender
# XXX optimisations
# XXX maybe should catch hangup signal and go to background?
# XXX protect the bot from DOS attacks causing server overload
# XXX protect the server from an overflowing log (add log size limitter
# or rotation)
# XXX fix the "hack hack hack" bits to be better.
################################
# Initialisation #
################################
# -- #mozwebtools was here --
# <Hixie> syntax error at oopsbot.pl line 48, near "; }"
# <Hixie> Execution of oopsbot.pl aborted due to compilation errors.
# <Hixie> DOH!
# <endico> hee hee. nice smily in the error message
# catch nasty occurances
$SIG{'INT'} = sub { &killed('INT'); };
$SIG{'KILL'} = sub { &killed('KILL'); };
$SIG{'TERM'} = sub { &killed('TERM'); };
# this allows us to exit() without shutting down (by exec($0)ing)
BEGIN { exit() if ((defined($ARGV[0])) and ($ARGV[0] eq '--abort')); }
# pragmas
use strict;
use diagnostics;
use local::lib;
#use utf8::all;
# chroot if requested
my $CHROOT = 0;
if ((defined($ARGV[0])) and ($ARGV[0] eq '--chroot')) {
# chroot
chroot('.') or die "chroot failed: $!\nAborted";
# setuid
# This is hardcoded to use user ids and group ids 60001.
# You'll want to change this on your system.
$> = 60001; # setuid nobody
$) = 60001; # setgid nobody
shift(@ARGV);
use lib '/lib';
$CHROOT = 1;
} elsif ((defined($ARGV[0])) and ($ARGV[0] eq '--assume-chrooted')) {
shift(@ARGV);
use lib '/lib';
$CHROOT = 1;
} else {
use lib 'lib';
}
# important modules
use Net::IRC 0.7; # 0.7 is not backwards compatible with 0.63 for CTCP responses
use IO::SecurePipe; # internal based on IO::Pipe
use Socket;
use POSIX ":sys_wait_h";
use Carp qw(cluck confess);
use Configuration; # internal
use Mails; # internal
# Note: Net::SMTP is also used, see the sendmail function in Mails.
# force flushing
$|++;
# internal 'constants'
my $USERNAME = "pid-$$";
my $LOGFILEPREFIX;
# variables that should only be changed if you know what you are doing
my $LOGGING = 1; # set to '0' to disable logging
my $LOGFILEDIR; # set this to override the logging output directory
if ($LOGGING) {
# set up the log directory
unless (defined($LOGFILEDIR)) {
if ($CHROOT) {
$LOGFILEDIR = '/log';
} else {
# setpwent doesn't work on Windows, we should wrap this in some OS test
setpwent; # reset the search settings for the getpwuid call below
$LOGFILEDIR = (getpwuid($<))[7].'/log';
}
}
"$LOGFILEDIR/$0" =~ /^(.*)$/os; # untaints the evil $0.
$LOGFILEPREFIX = $1; # for some reason, $0 is considered tainted here, but not in other cases...
mkdir($LOGFILEDIR, 0700); # if this fails for a bad reason, we'll find out during the next line
}
# begin session log...
&debug('-'x80);
&debug('mozbot starting up');
&debug('compilation took '.&days($^T).'.');
if ($CHROOT) {
&debug('mozbot chroot()ed successfully');
}
# secure the environment
#
# XXX could automatically remove the current directory here but I am
# more comfortable with people knowing it is not allowed -- see the
# README file.
$ENV{'PATH'} = join ':', qw(/bin /sbin /usr/bin /usr/sbin);
if ($ENV{'PATH'} =~ /^(?:.*:)?\.?(?::.*)?$/os) {
die 'SECURITY RISK. You cannot have \'.\' in the path. See the README. Aborted';
}
$ENV{'PATH'} =~ /^(.*)$/os;
$ENV{'PATH'} = $1; # we have to assume their path is otherwise safe, they called us!
delete (@ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'});
# read the configuration file
my $cfgfile = shift || "$0.cfg";
$cfgfile =~ /^(.*)$/os;
$cfgfile = $1; # untaint it -- we trust this, it comes from the admin.
&debug("reading configuration from '$cfgfile'...");
# - setup variables
# note: owner is only used by the Mails module
my ($server, $port, $password, $localAddr, @nicks, @channels, %channelKeys, $owner,
@ignoredUsers, @ignoredTargets);
my $nick = 0;
my $sleepdelay = 60;
my $connectTimeout = 120;
my $delaytime = 1.3; # amount of time to wait between outputs
my $recentMessageCountThreshold = 3; # threshold before we stop outputting
my $recentMessageCountPenalty = 10; # if we hit the threshold, bump it up by this much
my $recentMessageCountLimit = 20; # limit above which the count won't go
my $recentMessageCountDecrementRate = 0.1; # how much to take off per $delaytime
my $variablepattern = '[-_:a-zA-Z0-9]+';
my %users = ('admin' => &newPassword('password')); # default password for admin
my %userFlags = ('admin' => 3); # bitmask; 0x1 = admin, 0x2 = delete user a soon as other admin authenticates
my $helpline = 'http://www.mozilla.org/projects/mozbot/'; # used in IRC name and in help
my $serverRestrictsIRCNames = '';
my $serverExpectsValidUsername = '';
my $username = 0; # makes the username default to the pid ($USERNAME)
my @modulenames = ('General', 'Greeting', 'Infobot', 'Parrot');
# - which variables can be saved.
®isterConfigVariables(
[\$server, 'server'],
[\$port, 'port'],
[\$password, 'password'],
[\$localAddr, 'localAddr'],
[\@nicks, 'nicks'],
[\$nick, 'currentnick'], # pointer into @nicks
[\@channels, 'channels'],
[\%channelKeys, 'channelKeys'],
[\@ignoredUsers, 'ignoredUsers'],
[\@ignoredTargets, 'ignoredTargets'],
[\@modulenames, 'modules'],
[\$owner, 'owner'],
[\$sleepdelay, 'sleep'],
[\$connectTimeout, 'connectTimeout'],
[\$delaytime, 'throttleTime'],
[\%users, 'users'], # usernames => &newPassword(passwords)
[\%userFlags, 'userFlags'], # usernames => bits
[\$variablepattern, 'variablepattern'],
[\$helpline, 'helpline'],
[\$username, 'username'],
[\$serverRestrictsIRCNames, 'simpleIRCNameServer'],
[\$serverExpectsValidUsername, 'validUsernameServer'],
[\$Mails::smtphost, 'smtphost'],
);
# - read file
&Configuration::Get($cfgfile, &configStructure()); # empty gets entire structure
# - check variables are ok
# note. Ensure only works on an interactive terminal (-t).
# It will abort otherwise.
{ my $changed; # scope this variable
$changed = &Configuration::Ensure([
['Connect to which server?', \$server],
['To which port should I connect?', \$port],
## disabled because check suddenly feels a need to ask this every time (he
## didn't before), even though there is no password, and it blocks him from
## starting until I answer - jvdmr
# ['What is the server\'s password? (Leave blank if there isn\'t one.)', \$password],
['What channels should I join?', \@channels],
['What is the e-mail address of my owner?', \$owner],
['What is your SMTP host?', \$Mails::smtphost],
]);
## See above - jvdmr
$password = '';
# - check we have some nicks
until (@nicks) {
$changed = &Configuration::Ensure([['What nicks should I use? (I need at least one.)', \@nicks]]) || $changed;
# the original 'mozbot 2.0' development codename (and thus nick) was oopsbot.
}
# - check current nick pointer is valid
# (we assume that no sillyness has happened with $[ as,
# according to man perlvar, "Its use is highly discouraged".)
$nick = 0 if (($nick > $#nicks) or ($nick < 0));
# - check channel names are all lowercase
foreach (@channels) { $_ = lc; }
# save configuration straight away, to make sure it is possible and to save
# any initial settings on the first run, if anything changed.
if ($changed) {
&debug("saving configuration to '$cfgfile'...");
&Configuration::Save($cfgfile, &configStructure());
}
} # close the scope for the $changed variable
# ensure Mails is ready
&debug("setting up Mails module...");
$Mails::debug = \&debug;
$Mails::owner = \$owner;
# setup the IRC variables
&debug("setting up IRC variables...");
my $uptime;
my $irc = new Net::IRC or confess("Could not create a new Net::IRC object. Aborting");
# connect
&debug("attempting initial connection...");
&connect(); # hmm.
# setup the modules array
my @modules; # we initialize it lower down (at the bottom in fact)
my $lastadmin; # nick of last admin to be seen
my %authenticatedUsers; # hash of user@hostname=>users who have authenticated
################################
# Net::IRC handler subroutines #
################################
sub setEventArgs {
my $event = shift;
# &debug($Net::IRC::VERSION);
if ($Net::IRC::VERSION == 0.75 || $Net::IRC::VERSION == 0.79) {
# curses. This version of Net::IRC is broken. Work around
# it here.
return $event->args(\@_);
} else {
return $event->args(@_);
}
}
my $lastNick;
# setup connection
sub connect {
$uptime = time();
&debug("connecting to $server:$port using nick '$nicks[$nick]'...");
my ($bot, $mailed);
$lastNick = undef;
my $ircname = 'mozbot';
if ($serverRestrictsIRCNames ne $server) {
$ircname = "[$ircname] $helpline";
}
my $identd = getpwuid($<);
if ($serverExpectsValidUsername ne $server) {
$identd = $username || $USERNAME;
}
until (inet_aton($server) and # we check this first because Net::IRC::Connection doesn't
$bot = $irc->newconn(
Server => $server,
Port => $port,
Password => $password ne '' ? $password : undef, # '' will cause PASS to be sent
Nick => $nicks[$nick],
Ircname => $ircname,
Username => $identd,
LocalAddr => $localAddr,
)) {
&debug("Could not connect. Are you sure '$server:$port' is a valid host?");
unless (inet_aton($server)) {
&debug('I couldn\'t resolve it.');
}
if (defined($localAddr)) {
&debug("Is '$localAddr' the correct address of the interface to use?");
} else {
&debug("Try editing '$cfgfile' to set 'localAddr' to the address of the interface to use.");
}
if ($Net::IRC::VERSION < 0.73) {
&debug("Note that to use 'localAddr' you need Net::IRC version 0.73 or higher (you have $Net::IRC::VERSION)");
}
$mailed = &Mails::ServerDown($server, $port, $localAddr, $nicks[$nick], $ircname, $identd) unless $mailed;
sleep($sleepdelay);
&Configuration::Get($cfgfile, &configStructure(\$server, \$port, \$password, \@nicks, \$nick, \$owner, \$sleepdelay));
&debug("connecting to $server:$port again...");
}
&debug("connected! woohoo!");
# add the handlers
&debug("adding event handlers");
# $bot->debug(1); # this can help when debugging API stuff
$bot->add_global_handler([ # Informational messages -- print these to the console
251, # RPL_LUSERCLIENT
252, # RPL_LUSEROP
253, # RPL_LUSERUNKNOWN
254, # RPL_LUSERCHANNELS
255, # RPL_LUSERME
302, # RPL_USERHOST
375, # RPL_MOTDSTART
372, # RPL_MOTD
], \&on_startup);
$bot->add_global_handler([ # Informational messages -- print these to the console
'snotice', # server notices
461, # need more arguments for PASS command
409, # noorigin
405, # toomanychannels XXX should do something about this!
404, # cannot send to channel
403, # no such channel
401, # no such server
402, # no such nick
407, # too many targets
], \&on_notice);
$bot->add_global_handler([ # should only be one command here - when to join channels
376, # RPL_ENDOFMOTD
422, # nomotd
], \&on_connect);
$bot->add_handler('welcome', \&on_set_nick); # when we connect, to get our nick
$bot->add_global_handler([ # when to change nick name
'erroneusnickname',
433, # ERR_NICKNAMEINUSE
436, # nick collision
], \&on_nick_taken);
$bot->add_handler('nick', \&on_nick); # when someone changes nick
$bot->add_global_handler([ # when to give up and go home
'disconnect', 'kill', # bad connection, booted offline
465, # ERR_YOUREBANNEDCREEP
], \&on_disconnected);
$bot->add_handler('destroy', \&on_destroy); # when object is GCed.
$bot->add_handler('msg', \&on_private); # /msg bot hello
$bot->add_handler('public', \&on_public); # hello
$bot->add_handler('notice', \&on_noticemsg); # notice messages
$bot->add_handler('join', \&on_join); # when someone else joins
$bot->add_handler('part', \&on_part); # when someone else leaves
$bot->add_handler('topic', \&on_topic); # when topic changes in a channel
$bot->add_handler('notopic', \&on_topic); # when topic in a channel is cleared
$bot->add_handler('invite', \&on_invite); # when someone invites us
$bot->add_handler('quit', \&on_quit); # when someone quits IRC
$bot->add_handler('kick', \&on_kick); # when someone (or us) is kicked
$bot->add_handler('mode', \&on_mode); # when modes change
$bot->add_handler('umode', \&on_umode); # when modes of user change (by IRCop or ourselves)
# XXX could add handler for 474, # ERR_BANNEDFROMCHAN
$bot->add_handler([ # ones we handle to get our hostmask
311, # whoisuser
], \&on_whois);
$bot->add_handler([ # ones we handle just by outputting to the console
312, # whoisserver
313, # whoisoperator
314, # whowasuser
315, # endofwho
316, # whoischanop
317, # whoisidle
318, # endofwhois
319, # whoischannels
], \&on_notice);
$bot->add_handler([ # names (currently just ignored)
353, # RPL_NAMREPLY "<channel> :[[@|+]<nick> [[@|+]<nick> [...]]]"
], \&on_notice);
$bot->add_handler([ # end of names (we use this to establish that we have entered a channel)
366, # RPL_ENDOFNAMES "<channel> :End of /NAMES list"
], \&on_join_channel);
$bot->add_handler('cping', \&on_cping); # client to client ping
$bot->add_handler('crping', \&on_cpong); # client to client ping (response)
$bot->add_handler('cversion', \&on_version); # version info of mozbot.pl
$bot->add_handler('csource', \&on_source); # where is mozbot.pl's source
$bot->add_handler('caction', \&on_me); # when someone says /me
$bot->add_handler('cgender', \&on_gender); # guess
$bot->schedule($connectTimeout, \&on_check_connect);
# and done.
&Mails::ServerUp($server) if $mailed;
}
# called when the client receives a startup-related message
sub on_startup {
my ($self, $event) = @_;
my (@args) = $event->args;
shift(@args);
&debug(join(' ', @args));
}
# called when the client receives a server notice
sub on_notice {
my ($self, $event) = @_;
&debug($event->type.': '.join(' ', $event->args));
}
# called when the client receives whois data
sub on_whois {
my ($self, $event) = @_;
&debug('collecting whois information: '.join('|', $event->args));
# XXX could cache this information and then autoop people from
# the bot's host, or whatever
}
my ($nickFirstTried, $nickHadProblem, $nickProblemEscalated) = (0, 0, 0);
# this is called both for the welcome message (001) and by the on_nick handler
sub on_set_nick {
my ($self, $event) = @_;
($lastNick) = $event->args; # (args can be either array or scalar, we want the first value)
# Find nick's index.
my $newnick = 0;
$newnick++ while (($newnick < @nicks) and ($lastNick ne $nicks[$newnick]));
# If nick isn't there, add it.
if ($newnick >= @nicks) {
push(@nicks, $lastNick);
}
# set variable
$nick = $newnick;
&debug("using nick '$nicks[$nick]'");
# try to get our hostname
$self->whois($nicks[$nick]);
if ($nickHadProblem) {
Mails::NickOk($nicks[$nick]) if $nickProblemEscalated;
$nickHadProblem = 0;
}
# save
&Configuration::Save($cfgfile, &::configStructure(\$nick, \@nicks));
}
sub on_nick_taken {
my ($self, $event, $nickSlept) = @_, 0;
return unless $self->connected();
if ($event->type eq 'erroneusnickname') {
my ($currentNick, $triedNick, $err) = $event->args; # current, tried, errmsg
&debug("requested nick ('$triedNick') refused by server ('$err')");
} elsif ($event->type eq 'nicknameinuse') {
my ($currentNick, $triedNick, $err) = $event->args; # current, tried, errmsg
&debug("requested nick ('$triedNick') already in use ('$err')");
} else {
my $type = $event->type;
my $args = join(' ', $event->args);
&debug("message $type from server: $args");
}
if (defined $lastNick) {
&debug("silently abandoning nick change idea :-)");
return;
}
# at this point, we don't yet have a nick, but we need one
if ($nickSlept) {
&debug("waited for a bit -- reading $cfgfile then searching for a nick...");
&Configuration::Get($cfgfile, &configStructure(\@nicks, \$nick));
$nick = 0 if ($nick > $#nicks) or ($nick < 0); # sanitise
$nickFirstTried = $nick;
} else {
if (not $nickHadProblem) {
$nickHadProblem = 1;
$nickFirstTried = $nick;
}
++$nick;
$nick = 0 if $nick > $#nicks; # sanitise
if ($nick == $nickFirstTried) {
# looped!
local $" = ", ";
&debug("could not find an acceptable nick");
&debug("nicks tried: @nicks");
if (not -t) {
&debug("edit $cfgfile to add more nicks *hint* *hint*");
$nickProblemEscalated ||= # only e-mail once (returns 0 on failure)
Mails::NickShortage($cfgfile, $self->server, $self->port,
$self->username, $self->ircname, @nicks)
&debug("going to wait $sleepdelay seconds so as not to overload ourselves.");
$self->schedule($sleepdelay, \&on_nick_taken, $event, 1); # try again
return; # otherwise we no longer respond to pings.
}
# else, we're terminal bound, ask user for nick
print "Please suggest a nick (blank to abort): ";
my $new = <>;
chomp($new);
if (not $new) {
&debug("Could not find an acceptable nick");
exit(1);
}
# XXX this could introduce duplicates
@nicks = (@nicks[0..$nickFirstTried], $new, @nicks[$nickFirstTried+1..$#nicks]);
$nick += 1; # try the new nick now
$nickFirstTried = $nick;
}
}
&debug("now going to try nick '$nicks[$nick]'");
&Configuration::Save($cfgfile, &configStructure(\$nick, \@nicks));
$self->nick($nicks[$nick]);
}
# called when we connect.
sub on_connect {
my $self = shift;
if (defined($self->{'__mozbot__shutdown'})) { # HACK HACK HACK
&debug('Uh oh. I connected anyway, even though I thought I had timed out.');
&debug('I\'m going to increase the timeout time by 20%.');
$connectTimeout = $connectTimeout * 1.2;
&Configuration::Save($cfgfile, &configStructure(\$connectTimeout));
$self->quit('having trouble connecting, brb...');
# XXX we don't call the SpottedQuit handlers here
return;
}
# -- #mozwebtools was here --
# *** oopsbot ([email protected]) has joined channel #mozwebtools
# *** Mode change [+o oopsbot] on channel #mozwebtools by timeless
# <timeless> wow an oopsbot!
# *** Signoff: oopsbot ([email protected]) has left IRC [Leaving]
# <timeless> um
# <timeless> not very stable.
# now load all modules
my @modulesToLoad = @modulenames;
@modules = (BotModules::Admin->create('Admin', '')); # admin commands
@modulenames = ('Admin');
foreach (@modulesToLoad) {
next if $_ eq 'Admin'; # Admin is static and is installed manually above
my $result = LoadModule($_);
if (ref($result)) {
&debug("loaded $_");
} else {
&debug("failed to load $_", $result);
}
}
# mass-configure the modules
&debug("loading module configurations...");
{ my %struct; # scope this variable
foreach my $module (@modules) { %struct = (%struct, %{$module->configStructure()}); }
&Configuration::Get($cfgfile, \%struct);
} # close the scope for the %struct variable
# tell the modules they have joined IRC
my $event = newEvent({
'bot' => $self,
});
foreach my $module (@modules) {
$module->JoinedIRC($event);
}
# join the channels
&debug('going to join: '.join(',', @channels));
foreach my $channel (@channels) {
if (defined($channelKeys{$channel})) {
$self->join($channel, $channelKeys{$channel});
} else {
$self->join($channel);
}
}
@channels = ();
# tell the modules to set up the scheduled commands
&debug('setting up scheduler...');
foreach my $module (@modules) {
eval {
$module->Schedule($event);
};
if ($@) {
&debug("Warning: An error occured while loading the module:\n$@");
}
}
# enable the drainmsgqueue
&drainmsgqueue($self);
$self->schedule($delaytime, \&lowerRecentMessageCount);
# signal that we are connected (see next two functions)
$self->{'__mozbot__active'} = 1; # HACK HACK HACK
# all done!
&debug('initialisation took '.&days($uptime).'.');
$uptime = time();
}
sub on_check_connect {
my $self = shift;
return if (defined($self->{'__mozbot__shutdown'}) or defined($self->{'__mozbot__active'})); # HACK HACK HACK
$self->{'__mozbot__shutdown'} = 1; # HACK HACK HACK
&debug("connection timed out -- trying again");
# XXX we don't call the SpottedQuit handlers here
foreach (@modules) { $_->unload(); }
@modules = ();
$self->quit('connection timed out -- trying to reconnect');
&connect();
}
# if something nasty happens
sub on_disconnected {
my ($self, $event) = @_;
return if defined($self->{'__mozbot__shutdown'}); # HACK HACK HACK
$self->{'__mozbot__shutdown'} = 1; # HACK HACK HACK
# &do(@_, 'SpottedQuit'); # XXX do we want to do this?
my($reason) = $event->args;
if ($reason =~ /Connection timed out/osi
and ($serverRestrictsIRCNames ne $server
or $serverExpectsValidUsername ne $server)) {
# try to set everything up as simple as possible
$serverRestrictsIRCNames = $server;
$serverExpectsValidUsername = $server;
&Configuration::Save($cfgfile, &configStructure(\$serverRestrictsIRCNames));
&debug("Hrm, $server is having issues.");
&debug("We're gonna try again with different settings, hold on.");
&debug("The full message from the server was: '$reason'");
} elsif ($reason =~ /Bad user info/osi and $serverRestrictsIRCNames ne $server) {
# change our IRC name to something simpler by setting the flag
$serverRestrictsIRCNames = $server;
&Configuration::Save($cfgfile, &configStructure(\$serverRestrictsIRCNames));
&debug("Hrm, $server didn't like our IRC name.");
&debug("Trying again with a simpler one, hold on.");
&debug("The full message from the server was: '$reason'");
} elsif ($reason =~ /identd/osi and $serverExpectsValidUsername ne $server) {
# try setting our username to the actual username
$serverExpectsValidUsername = $server;
&Configuration::Save($cfgfile, &configStructure(\$delaytime));
&debug("Hrm, $server said something about an identd problem.");
&debug("Trying again with our real username, hold on.");
&debug("The full message from the server was: '$reason'");
} elsif ($reason =~ /Excess Flood/osi) {
# increase the delay by 20%
$delaytime = $delaytime * 1.2;
&Configuration::Save($cfgfile, &configStructure(\$delaytime));
&debug('Hrm, we it seems flooded the server. Trying again with a delay 20% longer.');
&debug("The full message from the server was: '$reason'");
} elsif ($reason =~ /Bad Password/osi) {
&debug('Hrm, we don\'t seem to know the server password.');
&debug("The full message from the server was: '$reason'");
if (-t) {
print "Please enter the server password: ";
$password = <>;
chomp($password);
&Configuration::Save($cfgfile, &configStructure(\$password));
} else {
&debug("edit $cfgfile to set the password *hint* *hint*");
&debug("going to wait $sleepdelay seconds so as not to overload ourselves.");
sleep $sleepdelay;
}
} else {
&debug("eek! disconnected from network: '$reason'");
}
foreach (@modules) { $_->unload(); }
@modules = ();
&connect();
}
# on_join_channel: called when we join a channel
sub on_join_channel {
my ($self, $event) = @_;
my ($nick, $channel) = $event->args;
$channel = lc($channel);
push(@channels, $channel);
&Configuration::Save($cfgfile, &configStructure(\@channels));
&debug("joined $channel, about to autojoin modules...");
foreach (@modules) {
$_->JoinedChannel(newEvent({
'bot' => $self,
'channel' => $channel,
'target' => $channel,
'nick' => $nick
}), $channel);
}
}
# if something nasty happens
sub on_destroy {
&debug("Connection: garbage collected");
}
sub targetted {
my ($data, $nick) = @_;
if ($data =~ /^ (?: \s* $nick (?: [\s,:;.!?]+ | \s* :-\s* | \s* --+ \s* | \s* -+ >? \s+ ) ) ( .+ ) $/isx) {
return (defined $1 ? $1 : '');
} elsif ($data =~ /^ ( .+? ) (?: [,.;!?\s]+ $nick [!?.\s]* ) $/isx) {
return (defined $1 ? $1 : '');
} else {
return undef;
}
}
# on_public: messages received on channels
sub on_public {
my ($self, $event) = @_;
my $data = join(' ', $event->args);
if (defined($_ = targetted($data, quotemeta($nicks[$nick])))) {
if ($_ ne '') {
setEventArgs($event, $_);
$event->{'__mozbot__fulldata'} = $data;
&do($self, $event, 'Told', 'Baffled');
} else {
&do($self, $event, 'Heard');
}
} else {
foreach my $nick (@ignoredTargets) {
if (defined targetted($data, $nick)) {
my $channel = &toToChannel($self, @{$event->to});
&debug("Ignored (target matched /$nick/): $channel <".$event->nick.'> '.join(' ', $event->args));
return;
}
}
&do($self, $event, 'Heard');
}
}
# on_noticemsg: notice messages from the server, some service, or another
# user. beware! it's generally Bad Juju to respond to these, but for
# some things (like opn's NickServ) it's appropriate.
sub on_noticemsg {
my ($self, $event) = @_;
&do($self, $event, 'Noticed');
}
sub on_private {
my ($self, $event) = @_;
my $data = join(' ', $event->args);
my $nick = quotemeta($nicks[$nick]);
if (($data =~ /^($nick(?:[-\s,:;.!?]|\s*-+>?\s+))(.+)$/is) and ($2)) {
# we do this so that you can say 'mozbot do this' in both channels
# and /query screens alike (otherwise, in /query screens you would
# have to remember to omit the bot name).
setEventArgs($event, $2);
}
&do($self, $event, 'Told', 'Baffled');
}
# on_me: /me actions (CTCP actually)
sub on_me {
my ($self, $event) = @_;
my @data = $event->args;
my $data = join(' ', @data);
setEventArgs($event, $data);
my $nick = quotemeta($nicks[$nick]);
if ($data =~ /(?:^|[\s":<([])$nick(?:[])>.,?!\s'&":]|$)/is) {
&do($self, $event, 'Felt');
} else {
&do($self, $event, 'Saw');
}
}
# on_topic: for when someone changes the topic
# also for when the server notifies us of the topic
# ...so we have to parse it carefully.
sub on_topic {
my ($self, $event) = @_;
if ($event->userhost eq '@') {
# server notification
# need to parse data
my (undef, $channel, $topic) = $event->args;
setEventArgs($event, $topic);
$event->to($channel);
}
&do(@_, 'SpottedTopicChange');
}
# on_kick: parse the kick event
sub on_kick {
my ($self, $event) = @_;
my ($channel, $from) = $event->args; # from is already set anyway
my $who = $event->to;
$event->to($channel);
foreach (@$who) {
setEventArgs($event, $_);
if ($_ eq $nicks[$nick]) {
&do(@_, 'Kicked');
} else {
&do(@_, 'SpottedKick');
}
}
}
# Gives lag results for outgoing PINGs.
sub on_cpong {
my ($self, $event) = @_;
&debug('completed CTCP PING with '.$event->nick.': '.days($event->args->[0]));
# XXX should be able to use this then... see also Greeting module
# in standard distribution
}
# -- #mozbot was here --
# <timeless> $conn->add_handler('gender',\&on_ctcp_gender);
# <timeless> sub on_ctcp_gender{
# <timeless> my (undef, $event)=@_;
# <timeless> my $nick=$event->nick;
# <Hixie> # timeless this suspense is killing me!
# <timeless> $bot->ctcp_reply($nick, 'neuter');
# <timeless> }
# on_gender: What gender are we?
sub on_gender {
my ($self, $event) = @_;
my $nick = $event->nick;
$self->ctcp_reply($nick, 'female'); # changed to female by special request
}
# on_nick: A nick changed -- was it ours?
sub on_nick {
my ($self, $event) = @_;
if ($event->nick eq $nicks[$nick]) {
on_set_nick($self, $event);
}
&do(@_, 'SpottedNickChange');
}
# simple handler for when users do various things and stuff
sub on_join { &do(@_, 'SpottedJoin'); }
sub on_part { &do(@_, 'SpottedPart'); }
sub on_quit { &do(@_, 'SpottedQuit'); }
sub on_invite { &do(@_, 'Invited'); }
sub on_mode { &do(@_, 'ModeChange'); } # XXX need to parse modes # XXX on key change, change %channelKeys hash
sub on_umode { &do(@_, 'UModeChange'); }
sub on_version { &do(@_, 'CTCPVersion'); }
sub on_source { &do(@_, 'CTCPSource'); }
sub on_cping { &do(@_, 'CTCPPing'); }
sub newEvent($) {
my $event = shift;
$event->{'time'} = time();
return $event;
}
sub toToChannel {
my $self = shift;
my $channel;
foreach (@_) {
if (/^[#&+\$]/os) {
if (defined($channel)) {
return '';
} else {
$channel = $_;
}
} elsif ($_ eq $nicks[$nick]) {
return '';
}
}
return lc($channel); # if message was sent to one person only, this is it
}
# XXX some code below calls this, on lines marked "hack hack hack". We
# should fix this so that those are supported calls.
sub do {
my $self = shift @_;
my $event = shift @_;
my $to = $event->to;
my $channel = &toToChannel($self, @$to);
my $e = newEvent({
'bot' => $self,
'_event' => $event, # internal internal internal do not use... ;-)
'channel' => $channel,
'from' => $event->nick,
'target' => $channel || $event->nick,
'user' => $event->userhost,
'data' => join(' ', $event->args),
'fulldata' => defined($event->{'__mozbot__fulldata'}) ? $event->{'__mozbot__fulldata'} : join(' ', $event->args),
'to' => $to,
'subtype' => $event->type,
'firsttype' => $_[0],
'nick' => $nicks[$nick],
# level (set below)
# type (set below)
});
# updated admin field if person is an admin
if ($authenticatedUsers{$event->userhost}) {
if (($userFlags{$authenticatedUsers{$event->userhost}} & 1) == 1) {
$lastadmin = $event->nick;
}
$e->{'userName'} = $authenticatedUsers{$event->userhost};
$e->{'userFlags'} = $userFlags{$authenticatedUsers{$event->userhost}};
} else {
$e->{'userName'} = 0;
}
unless (scalar(grep $e->{'user'} =~ /^$_$/gi, @ignoredUsers)) {
my $continue;
do {
my $type = shift @_;
my $level = 0;
my @modulesInNextLoop = @modules;
$continue = 1;
$e->{'type'} = $type;
&debug("$type: $channel <".$event->nick.'> '.join(' ', $event->args));
do {
$level++;
$e->{'level'} = $level;
my @modulesInThisLoop = @modulesInNextLoop;
@modulesInNextLoop = ();
foreach my $module (@modulesInThisLoop) {
my $currentResponse;
eval {
$currentResponse = $module->do($self, $event, $type, $e);
};
if ($@) {
# $@ contains the error
&debug("ERROR IN MODULE $module->{'_name'}!!!", $@);
} elsif (!defined($currentResponse)) {
&debug("ERROR IN MODULE $module->{'_name'}: invalid response code to event '$type'.");
} else {
if ($currentResponse > $level) {
push(@modulesInNextLoop, $module);
}
$continue = ($continue and $currentResponse);
}
}
} while ($continue and @modulesInNextLoop);
} while ($continue and scalar(@_));
} else {
&debug('Ignored (from \'' . $event->userhost . "'): $channel <".$event->nick.'> '.join(' ', $event->args));