-
Notifications
You must be signed in to change notification settings - Fork 3
/
mozbot.pl
2773 lines (2523 loc) · 98 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 -wT
# -*- 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 <harrison@netscape.com>
# Terry Weissman <terry@mozilla.org>
# Risto Kotalampi <risto@kotalampi.com>
# Josh Soref <timeless@bemail.org>
# Ian Hickson <mozbot@hixie.ch>
#
# mozbot.pl harrison@netscape.com 1998-10-14
# "irc bot for the gang on #mozilla"
#
# mozbot.pl mozbot@hixie.ch 2000-07-04
# "irc bot engine for anyone" :-)
#
# hack on me! required reading:
#
# Net::IRC web page:
# http://netirc.betterbox.net/
# (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'. http://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)
################################
# 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'); };
$SIG{'CHLD'} = sub { wait(); }; # reap children
# 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;
# 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 IO::Select;
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.
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;
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 = 'see http://www.mozilla.org/projects/mozbot/'; # used in IRC name and in help
my @modulenames = ('General');
# - 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'],
[\$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],
['Password?', \$password],
['What channels should I join?', \@channels],
['What is the e-mail address of my owner?', \$owner],
['What is your SMTP host?', \$Mails::smtphost],
]);
# - 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 #
################################
# setup connection
sub connect {
$uptime = time();
&debug("connecting to $server:$port...");
my ($bot, $mailed);
until ($bot = $irc->newconn(
Server => $server,
Port => $port,
Password => $password,
Nick => $nicks[$nick],
Ircname => "[mozbot] $helpline",
Username => $USERNAME,
LocalAddr => $localAddr,
)) {
&debug("Could not connect. Are you sure '$server:$port' is a valid host?");
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.");
}
$mailed = &Mails::ServerDown($server, $port, $localAddr, $nicks[$nick], "[mozbot] $helpline", $nicks[0]) unless $mailed;
sleep($sleepdelay);
&Configuration::Get($cfgfile, &configStructure(\$server, \$port, \@nicks, \$nick, \$owner, \$sleepdelay));
&debug("connecting to $server:$port...");
}
&debug("connected! woohoo!");
# add the handlers
&debug("adding IRC handlers");
# $bot->debug(1); # this can help when debugging API stuff
&debug(" + informational ");
$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
409, # noorigin
405, # toomanychannels XXX should do something about this!
404, # cannot sent to channel
403, # no such channel
401, # no such server
402, # no such nick
407, # too many targets
], \&on_notice);
&debug(" + end of startup ");
$bot->add_global_handler([ # should only be one command here - when to join channels
376, # RPL_ENDOFMOTD
422, # nomotd
], \&on_connect);
&debug(" + nick management ");
$bot->add_global_handler([ # when to change nick name
433, # ERR_NICKNAMEINUSE
436, # nick collision
], \&on_nick_taken);
&debug(" + connection management ");
$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.
&debug(" + channel handlers");
$bot->add_handler('msg', \&on_private); # /msg bot hello
$bot->add_handler('public', \&on_public); # hello
$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('nick', \&on_nick); # when someone changes nick
$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
&debug(" + whois messages");
$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);
&debug(" + CTCP handlers");
$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
&debug("handlers added");
$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 ($nickHadProblem, $nickProblemEscalated, $nickOriginal) = (0, 0, 0);
sub on_nick_taken {
my ($self, $event, $nickSlept) = @_, 0;
return unless $self->connected();
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
$nickOriginal = $nick;
} else {
if (!$nickHadProblem) {
&debug("preferred nick ($nicks[$nick]) in use, searching for another...");
$nickOriginal = $nick;
$nickHadProblem++;
} # else we are currently looping
$nick++;
$nick = 0 if $nick > $#nicks;
if ($nick == $nickOriginal) {
# looped!
local $" = ", ";
&debug("could not find an unused nick");
&debug("nicks tried: @nicks");
if (-t) {
print "Please suggest a nick (blank to abort): ";
my $new = <>;
chomp($new);
if ($new) {
@nicks = (@nicks[0..$nickOriginal], $new, @nicks[$nickOriginal+1..$#nicks]);
&debug("saving nicks: @nicks");
&Configuration::Save($cfgfile, &configStructure(\@nicks));
} else {
&debug("Could not find an unused nick");
exit(1);
}
} else {
&debug("edit $cfgfile to add more nicks *hint* *hint*");
$nickProblemEscalated = Mails::NickShortage($cfgfile, $self->server, $self->port,
$self->username, $self->ircname, @nicks) unless $nickProblemEscalated;
$nickProblemEscalated++;
&debug("going to wait $sleepdelay seconds so as not to overload ourselves.");
$self->schedule($sleepdelay, \&on_nick_taken, $event, 1); # try again, this time don't mail if it goes wrong
return; # otherwise we no longer respond to pings.
}
}
}
&debug("now going to try nick $nicks[$nick]");
$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...');
return;
}
&debug("using nick '$nicks[$nick]'");
if ($nickHadProblem) {
# Remember which nick we are using
&Configuration::Save($cfgfile, &configStructure(\$nick));
Mails::NickOk($nicks[$nick]) if $nickProblemEscalated;
}
# -- #mozwebtools was here --
# *** oopsbot (oopsbot@129.59.231.42) has joined channel #mozwebtools
# *** Mode change [+o oopsbot] on channel #mozwebtools by timeless
# <timeless> wow an oopsbot!
# *** Signoff: oopsbot (oopsbot@129.59.231.42) 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
foreach my $module (@modules) { $module->JoinedIRC({'bot'=>$self}); }
# 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 = ();
# try to get our hostname
$self->whois($self->nick);
# tell the modules to set up the scheduled commands
&debug('setting up scheduler...');
foreach my $module (@modules) { $module->Schedule({'bot'=>$self}); }
# enable the drainmsgqueue
&drainmsgqueue($self);
# 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");
foreach (@modules) { $_->unload(); }
@modules = ();
$self->quit('connection timed out -- trying to reconnect');
&connect();
}
# if something nasty happens
sub on_disconnected {
my $self = shift;
return if defined($self->{'__mozbot__shutdown'}); # HACK HACK HACK
$self->{'__mozbot__shutdown'} = 1; # HACK HACK HACK
&debug("eek! disconnected from network");
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({'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) = @_;
return $data =~ /^(\s*$nick(?:[\s,:;.!?]+|\s*:-\s*|\s*--+\s*|\s*-+>?\s+))(.+)$/is ?
(defined $2 ? $2 : '') : undef;
}
# on_public: messages received on channels
sub on_public {
my ($self, $event) = @_;
my $data = join(' ', $event->args);
if (defined($_ = targetted($data, quotemeta($self->nick)))) {
if ($_ ne '') {
$event->args([$_]);
$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');
}
}
sub on_private {
my ($self, $event) = @_;
my $data = join(' ', $event->args);
my $nick = quotemeta($self->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).
$event->args([$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);
$event->args([$data]);
my $nick = quotemeta($self->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;
$event->args([$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) {
$event->args([$_]);
if ($_ eq $self->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, 'neuter');
} # well, close enough...
# 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_nick { &do(@_, 'SpottedNickChange'); }
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 toToChannel {
my $self = shift;
my $channel;
foreach (@_) {
if (/^[#&+\$]/os) {
if (defined($channel)) {
return '';
} else {
$channel = $_;
}
} elsif ($_ eq $self->nick) {
return '';
}
}
return lc($channel); # if message was sent to one person only, this is it
}
sub do {
my $self = shift @_;
my $event = shift @_;
my $to = $event->to;
my $channel = &toToChannel($self, @$to);
my $e = {
'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' => $self->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 (@modulesInNextLoop);
} while ($continue and scalar(@_));
} else {
&debug('Ignored (from \'' . $event->userhost . "'): $channel <".$event->nick.'> '.join(' ', $event->args));
}
&doLog($e);
}
sub doLog {
my $e = shift;
foreach my $module (@modules) {
eval {
$module->Log($e);
};
if ($@) {
# $@ contains the error
&debug("ERROR!!!", $@);
}
}
}
################################
# internal utilities #
################################
my @msgqueue;
my $timeLastSetAway = 0; # the time since the away flag was last set, so that we don't set it repeatedly.
# Use this routine, always, instead of the standard "privmsg" routine. This
# one makes sure we don't send more than one message every two seconds or so,
# which will make servers not whine about us flooding the channel.
# messages aren't the only type of flood :-( away is included
sub sendmsg {
my ($self, $who, $msg, $do) = (@_, 'msg');
unless ((defined($do) and defined($msg) and defined($who) and ($who ne '')) and
((($do eq 'msg') and (not ref($msg))) or
(($do eq 'me') and (not ref($msg))) or
(($do eq 'notice') and (not ref($msg))) or
(($do eq 'ctcpSend') and (ref($msg) eq 'ARRAY') and (@$msg >= 2)) or
(($do eq 'ctcpReply') and (not ref($msg))))) {
cluck('Wrong arguments passed to sendmsg() - ignored');
} else {
$self->schedule($delaytime / 2, \&drainmsgqueue) unless @msgqueue;
if ($do eq 'msg' or $do eq 'me' or $do eq 'notice') {
foreach (splitMessageAcrossLines($msg)) {
push(@msgqueue, [$who, $_, $do]);
}
} else {
push(@msgqueue, [$who, $msg, $do]);
}
}
}
# send any pending messages
sub drainmsgqueue {
my $self = shift;
return unless $self->connected;
my $qln = @msgqueue;
if (@msgqueue > 0) {
my ($who, $msg, $do) = getnextmsg();
my $type;
if ($do eq 'msg') {
&debug("->$who: $msg"); # XXX this makes logfiles large quickly...
$self->privmsg($who, $msg); # it seems 'who' can be an arrayref and it works
$type = 'Heard';
} elsif ($do eq 'me') {
&debug("->$who * $msg"); # XXX
$self->me($who, $msg);
$type = 'Saw';
} elsif ($do eq 'notice') {
&debug("=notice=>$who: $msg");
$self->notice($who, $msg);
# $type = 'XXX';
} elsif ($do eq 'ctcpSend') {
{ local $" = ' '; &debug("->$who CTCP PRIVMSG @$msg"); }
my $type = shift @$msg; # @$msg contains (type, args)
$self->ctcp($type, $who, @$msg);
# $type = 'XXX';
} elsif ($do eq 'ctcpReply') {
{ local $" = ' '; &debug("->$who CTCP NOTICE $msg"); }
$self->ctcp_reply($who, $msg);
# $type = 'XXX';
} else {
&debug("Unknown action '$do' intended for '$who' (content: '$msg') ignored.");
}
if (defined($type)) {
&doLog({
'bot' => $self,
'_event' => undef,
'channel' => &toToChannel($self, $who),
'from' => $self->nick,
'target' => $who,
'user' => undef, # XXX
'data' => $msg,
'fulldata' => $msg,
'to' => $who,
'subtype' => undef,
'firsttype' => $type,
'nick' => $self->nick,
'level' => 0,
'type' => $type,
});
}
if (@msgqueue > 0) {
if ((@msgqueue % 10 == 0) and (time() - $timeLastSetAway > 5 * $delaytime)) {
&bot_longprocess($self, "Long send queue. There were $qln, and I just sent one to $who.");
$timeLastSetAway = time();
$self->schedule($delaytime * 4, # because previous one counts as message, plus you want to delay an extra bit regularly
\&drainmsgqueue);
} else {
$self->schedule($delaytime, \&drainmsgqueue);
}
} else {
&bot_back($self); # clear away state
}
}
}
# wrap long lines at spaces and hard returns (\n)
# this is for IRC, not for the console -- long can be up to 255
sub splitMessageAcrossLines {
my ($str) = @_;
my $MAXPROTOCOLLENGTH = 255;
my @output;
# $str could be several lines split with \n, so split it first:
foreach my $line (split(/\n/, $str)) {
while (length($line) > $MAXPROTOCOLLENGTH) {
# position is zero-based index
my $pos = rindex($line, ' ', $MAXPROTOCOLLENGTH - 1);
if ($pos < 0) {
$pos = $MAXPROTOCOLLENGTH - 1;
}
push(@output, substr($line, 0, $pos));
$line = substr($line, $pos);
$line =~ s/^\s+//gos;
}
push(@output, $line) if length($line);
}
return @output;
}
# equivalent of shift or pop, but for the middle of the array.
# used by getnextmsg() below to pull the messages out of the
# msgqueue stack and shove them at the end.
sub yank {
my ($index, $list) = @_;
my $result = @{$list}[$index];
@{$list} = (@{$list}[0..$index-1], @{$list}[$index+1..$#{$list}]);
return $result;
}
# looks at the msgqueue stack and decides which message to send next.
sub getnextmsg {
my ($who, $msg, $do) = @{shift(@msgqueue)};
my @newmsgqueue;
my $index = 0;
while ($index < @msgqueue) {
if ($msgqueue[$index]->[0] eq $who) {
push(@newmsgqueue, &yank($index, \@msgqueue));
} else {
$index++;
}
}
push(@msgqueue, @newmsgqueue);
return ($who, $msg, $do);
}
my $markedaway = 0;
# mark bot as being away
sub bot_longprocess {
my $self = shift;
&debug('[away: '.join(' ',@_).']');
$self->away(join(' ',@_));
$markedaway = @_;
}
# mark bot as not being away anymore
sub bot_back {
my $self = shift;
$self->away('') if $markedaway;
$markedaway = 0;
}
# internal routines for IO::Select handling
sub bot_select {
my ($pipe) = @_;
$irc->removefh($pipe);
# enable slurp mode for this function (see man perlvar for $/ documentation)