]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Irc.pl
explicit $chan for getChanConfDefault
[infobot.git] / src / IRC / Irc.pl
1 #
2 #    Irc.pl: IRC core stuff.
3 #    Author: dms
4 #   Version: 20000126
5 #      NOTE: Based on code by Kevin Lenzo & Patrick Cole  (c) 1997
6 #
7
8 use strict;
9
10 no strict 'refs';
11 no strict 'subs'; # IN/STDIN
12
13 use vars qw(%floodjoin %nuh %dcc %cache %conns %channels %param %mask
14         %chanconf %orig %ircPort %ircstats %last %netsplit);
15 use vars qw($irc $nickserv $conn $msgType $who $talkchannel
16         $addressed $postprocess);
17 use vars qw($notcount $nottime $notsize $msgcount $msgtime $msgsize
18                 $pubcount $pubtime $pubsize);
19 use vars qw($b_blue $ob);
20 use vars qw(@ircServers);
21
22 #use open ':utf8';
23 #use open ':std';
24
25 $nickserv       = 0;
26 my $maxlinelen  = 400;
27
28 sub ircloop {
29     my $error   = 0;
30     my $lastrun = 0;
31
32 loop:;
33     while (my $host = shift @ircServers) {
34         # JUST IN CASE. irq was complaining about this.
35         if ($lastrun == time()) {
36             &DEBUG("ircloop: hrm... lastrun == time()");
37             $error++;
38             sleep 10;
39             next;
40         }
41
42         if (!defined $host) {
43             &DEBUG("ircloop: ircServers[x] = NULL.");
44             $lastrun = time();
45             next;
46         }
47         next unless (exists $ircPort{$host});
48
49         my $retval      = &irc($host, $ircPort{$host});
50         next unless (defined $retval and $retval == 0);
51         $error++;
52
53         if ($error % 3 == 0 and $error != 0) {
54             &status("IRC: Could not connect.");
55             &status("IRC: ");
56             next;
57         }
58
59         if ($error >= 3*2) {
60             &status("IRC: cannot connect to any IRC servers; stopping.");
61             &shutdown();
62             exit 1;
63         }
64     }
65
66     &status("IRC: ok, done one cycle of IRC servers; trying again.");
67
68     &loadIRCServers();
69     goto loop;
70 }
71
72 sub irc {
73     my ($server,$port) = @_;
74
75     $irc = new Net::IRC;
76
77     # TODO: move all this to an sql table
78     my $iaddr = inet_aton($server);
79     my $paddr = sockaddr_in($port, $iaddr);
80     my $proto = getprotobyname('tcp');
81
82     # why was this here?
83     #select STDOUT;
84
85     # host->ip.
86     my $resolve;
87     if ($server =~ /\D$/) {
88         my $packed = scalar(gethostbyname($server));
89
90         if (!defined $packed) {
91             &status("  cannot resolve $server.");
92             return 0;
93         }
94
95         $resolve = inet_ntoa($packed);
96         ### warning in Sys/Hostname line 78???
97         ### caused inside Net::IRC?
98     }
99
100     my %args = (
101                 Nick    => $param{'ircNick'},
102                 Server  => $server,
103                 Port    => $port,
104                 Ircname => $param{'ircName'},
105     );
106     $args{'LocalAddr'} = $param{'ircHost'} if ($param{'ircHost'});
107     $args{'Password'} = $param{'ircPasswd'} if ($param{'ircPasswd'});
108
109     foreach my $mynick (split ',', $param{'ircNick'}) {
110         &status("Connecting to port $port of server $server ($resolve) as $mynick ...");
111         $args{'Nick'} = $mynick;
112         $conns{$mynick} = $irc->newconn(%args);
113         if (!defined $conns{$mynick}) {
114             &ERROR("IRC: connection failed.");
115             &ERROR("add \"set ircHost 0.0.0.0\" to your config. If that does not work");
116             &ERROR("Please check /etc/hosts to see if you have a localhost line like:");
117             &ERROR("127.0.0.1   localhost    localhost");
118             &ERROR("If this is still a problem, please contact the maintainer.");
119         }
120         $conns{$mynick}->maxlinelen($maxlinelen);
121         # handler stuff.
122         $conns{$mynick}->add_global_handler('caction',  \&on_action);
123         $conns{$mynick}->add_global_handler('cdcc',     \&on_dcc);
124         $conns{$mynick}->add_global_handler('cping',    \&on_ping);
125         $conns{$mynick}->add_global_handler('crping',   \&on_ping_reply);
126         $conns{$mynick}->add_global_handler('cversion', \&on_version);
127         $conns{$mynick}->add_global_handler('crversion',        \&on_crversion);
128         $conns{$mynick}->add_global_handler('dcc_open', \&on_dcc_open);
129         $conns{$mynick}->add_global_handler('dcc_close',        \&on_dcc_close);
130         $conns{$mynick}->add_global_handler('chat',     \&on_chat);
131         $conns{$mynick}->add_global_handler('msg',      \&on_msg);
132         $conns{$mynick}->add_global_handler('public',   \&on_public);
133         $conns{$mynick}->add_global_handler('join',     \&on_join);
134         $conns{$mynick}->add_global_handler('part',     \&on_part);
135         $conns{$mynick}->add_global_handler('topic',    \&on_topic);
136         $conns{$mynick}->add_global_handler('invite',   \&on_invite);
137         $conns{$mynick}->add_global_handler('kick',     \&on_kick);
138         $conns{$mynick}->add_global_handler('mode',     \&on_mode);
139         $conns{$mynick}->add_global_handler('nick',     \&on_nick);
140         $conns{$mynick}->add_global_handler('quit',     \&on_quit);
141         $conns{$mynick}->add_global_handler('notice',   \&on_notice);
142         $conns{$mynick}->add_global_handler('whoischannels', \&on_whoischannels);
143         $conns{$mynick}->add_global_handler('useronchannel', \&on_useronchannel);
144         $conns{$mynick}->add_global_handler('whois',    \&on_whois);
145         $conns{$mynick}->add_global_handler('other',    \&on_other);
146         $conns{$mynick}->add_global_handler('disconnect', \&on_disconnect);
147         $conns{$mynick}->add_global_handler([251,252,253,254,255], \&on_init);
148 #       $conns{$mynick}->add_global_handler(302, \&on_init); # userhost
149         $conns{$mynick}->add_global_handler(303, \&on_ison); # notify.
150         $conns{$mynick}->add_global_handler(315, \&on_endofwho);
151         $conns{$mynick}->add_global_handler(422, \&on_endofwho); # nomotd.
152         $conns{$mynick}->add_global_handler(324, \&on_modeis);
153         $conns{$mynick}->add_global_handler(333, \&on_topicinfo);
154         $conns{$mynick}->add_global_handler(352, \&on_who);
155         $conns{$mynick}->add_global_handler(353, \&on_names);
156         $conns{$mynick}->add_global_handler(366, \&on_endofnames);
157         $conns{$mynick}->add_global_handler(376, \&on_endofmotd); # on_connect.
158         $conns{$mynick}->add_global_handler(433, \&on_nick_taken);
159         $conns{$mynick}->add_global_handler(439, \&on_targettoofast);
160         # for proper joinnextChan behaviour
161         $conns{$mynick}->add_global_handler(471, \&on_chanfull);
162         $conns{$mynick}->add_global_handler(473, \&on_inviteonly);
163         $conns{$mynick}->add_global_handler(474, \&on_banned);
164         $conns{$mynick}->add_global_handler(475, \&on_badchankey);
165         $conns{$mynick}->add_global_handler(443, \&on_useronchan);
166         # end of handler stuff.
167     }
168
169     &clearIRCVars();
170
171     # change internal timeout value for scheduler.
172     $irc->{_timeout}    = 10;   # how about 60?
173     # Net::IRC debugging.
174     $irc->{_debug}      = 1;
175
176     $ircstats{'Server'} = "$server:$port";
177
178     # works? needs to actually do something
179     # should likely listen on a tcp port instead
180     #$irc->addfh(STDIN, \&on_stdin, "r");
181
182     &status("starting main loop");
183
184     $irc->start;
185 }
186
187 ######################################################################
188 ######## IRC ALIASES   IRC ALIASES   IRC ALIASES   IRC ALIASES #######
189 ######################################################################
190
191 sub rawout {
192     my ($buf) = @_;
193     $buf =~ s/\n//gi;
194
195     # slow down a bit if traffic is "high".
196     # need to take into account time of last message sent.
197     if ($last{buflen} > 256 and length($buf) > 256) {
198         sleep 1;
199     }
200
201     $conn->sl($buf) if (&whatInterface() =~ /IRC/);
202
203     $last{buflen} = length($buf);
204 }
205
206 sub say {
207     my ($msg) = @_;
208     my $mynick = $conn->nick();
209     if (!defined $msg) {
210         $msg ||= "NULL";
211         &WARN("say: msg == $msg.");
212         return;
213     }
214
215     if ( $postprocess ) {
216         undef $postprocess;
217     } elsif ($postprocess = &getChanConf('postprocess', $talkchannel)) {
218         &DEBUG("say: $postprocess $msg");
219         &parseCmdHook($postprocess . ' ' . $msg);
220         undef $postprocess;
221         return;
222     }
223
224     &status("<$mynick/$talkchannel> $msg");
225
226     return unless (&whatInterface() =~ /IRC/);
227
228     $msg = "zero" if ($msg =~ /^0+$/);
229
230     my $t = time();
231
232     if ($t == $pubtime) {
233         $pubcount++;
234         $pubsize += length $msg;
235
236         my $i = &getChanConfDefault("sendPublicLimitLines", 3, $chan);
237         my $j = &getChanConfDefault("sendPublicLimitBytes", 1000, $chan);
238
239         if ( ($pubcount % $i) == 0 and $pubcount) {
240             sleep 1;
241         } elsif ($pubsize > $j) {
242             sleep 1;
243             $pubsize -= $j;
244         }
245
246     } else {
247         $pubcount       = 0;
248         $pubtime        = $t;
249         $pubsize        = length $msg;
250     }
251
252     $conn->privmsg($talkchannel, $msg);
253 }
254
255 sub msg {
256     my ($nick, $msg) = @_;
257     if (!defined $nick) {
258         &ERROR("msg: nick == NULL.");
259         return;
260     }
261
262     if (!defined $msg) {
263         $msg ||= "NULL";
264         &WARN("msg: msg == $msg.");
265         return;
266     }
267
268     &status(">$nick< $msg");
269
270     return unless (&whatInterface() =~ /IRC/);
271     my $t = time();
272
273     if ($t == $msgtime) {
274         $msgcount++;
275         $msgsize += length $msg;
276
277         my $i = &getChanConfDefault("sendPrivateLimitLines", 3, $chan);
278         my $j = &getChanConfDefault("sendPrivateLimitBytes", 1000, $chan);
279         if ( ($msgcount % $i) == 0 and $msgcount) {
280             sleep 1;
281         } elsif ($msgsize > $j) {
282             sleep 1;
283             $msgsize -= $j;
284         }
285
286     } else {
287         $msgcount       = 0;
288         $msgtime        = $t;
289         $msgsize        = length $msg;
290     }
291
292     $conn->privmsg($nick, $msg);
293 }
294
295 # Usage: &action(nick || chan, txt);
296 sub action {
297     my $mynick = $conn->nick();
298     my ($target, $txt) = @_;
299     if (!defined $txt) {
300         &WARN("action: txt == NULL.");
301         return;
302     }
303
304     if (length $txt > 480) {
305         &status("action: txt too long; truncating.");
306         chop($txt) while (length $txt > 480);
307     }
308
309     &status("* $mynick/$target $txt");
310     $conn->me($target, $txt);
311 }
312
313 # Usage: &notice(nick || chan, txt);
314 sub notice {
315     my ($target, $txt) = @_;
316     if (!defined $txt) {
317         &WARN("notice: txt == NULL.");
318         return;
319     }
320
321     &status("-$target- $txt");
322
323     my $t       = time();
324
325     if ($t == $nottime) {
326         $notcount++;
327         $notsize += length $txt;
328
329         my $i = &getChanConfDefault("sendNoticeLimitLines", 3, $chan);
330         my $j = &getChanConfDefault("sendNoticeLimitBytes", 1000, $chan);
331
332         if ( ($notcount % $i) == 0 and $notcount) {
333             sleep 1;
334         } elsif ($notsize > $j) {
335             sleep 1;
336             $notsize -= $j;
337         }
338
339     } else {
340         $notcount       = 0;
341         $nottime        = $t;
342         $notsize        = length $txt;
343     }
344
345     $conn->notice($target, $txt);
346 }
347
348 sub DCCBroadcast {
349     my ($txt,$flag) = @_;
350
351     ### FIXME: flag not supported yet.
352
353     foreach (keys %{ $dcc{'CHAT'} }) {
354         $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
355     }
356 }
357
358 ##########
359 ### perform commands.
360 ###
361
362 # Usage: &performReply($reply);
363 sub performReply {
364     my ($reply) = @_;
365
366     if (!defined $reply or $reply =~ /^\s*$/) {
367         &DEBUG("performReply: reply == NULL.");
368         return;
369     }
370
371     $reply =~ /([\.\?\s]+)$/;
372
373     # FIXME need real throttling....
374     if (length($reply) > $maxlinelen - 30) {
375         $reply = substr($reply, 0, $maxlinelen - 33);
376         $reply =~ s/ [^ ]*?$/ .../;
377     }
378     &checkMsgType($reply);
379
380     if ($msgType eq 'public') {
381         if (rand() < 0.5 or $reply =~ /[\.\?]$/) {
382             $reply = "$orig{who}: ".$reply;
383         } else {
384             $reply = "$reply, ".$orig{who};
385         }
386         &say($reply);
387
388     } elsif ($msgType eq 'private') {
389         if (rand() > 0.5) {
390             $reply = "$reply, ".$orig{who};
391         }
392         &msg($who, $reply);
393
394     } elsif ($msgType eq 'chat') {
395         if (!exists $dcc{'CHAT'}{$who}) {
396             &VERB("pSR: dcc{'CHAT'}{$who} does not exist.",2);
397             return;
398         }
399         $conn->privmsg($dcc{'CHAT'}{$who}, $reply);
400
401     } else {
402         &ERROR("PR: msgType invalid? ($msgType).");
403     }
404 }
405
406 # ...
407 sub performAddressedReply {
408     return unless ($addressed);
409     &performReply(@_);
410 }
411
412 # Usage: &performStrictReply($reply);
413 sub performStrictReply {
414     my ($reply) = @_;
415
416     # FIXME need real throttling....
417     if (length($reply) > $maxlinelen - 30) {
418         $reply = substr($reply, 0, $maxlinelen - 33);
419         $reply =~ s/ [^ ]*?$/ .../;
420     }
421     &checkMsgType($reply);
422
423     if ($msgType eq 'private') {
424         &msg($who, $reply);
425     } elsif ($msgType eq 'public') {
426         &say($reply);
427     } elsif ($msgType eq 'chat') {
428         &dccsay(lc $who, $reply);
429     } else {
430         &ERROR("pSR: msgType invalid? ($msgType).");
431     }
432 }
433
434 sub dccsay {
435     my($who, $reply) = @_;
436
437     if (!defined $reply or $reply =~ /^\s*$/) {
438         &WARN("dccsay: reply == NULL.");
439         return;
440     }
441
442     if (!exists $dcc{'CHAT'}{$who}) {
443         &VERB("pSR: dcc{'CHAT'}{$who} does not exist. (2)",2);
444         return;
445     }
446
447     &status("=>$who<= $reply");         # dcc chat.
448     $conn->privmsg($dcc{'CHAT'}{$who}, $reply);
449 }
450
451 sub dcc_close {
452     my($who) = @_;
453     my $type;
454
455     foreach $type (keys %dcc) {
456         &FIXME("dcc_close: $who");
457         my @who = grep /^\Q$who\E$/i, keys %{ $dcc{$type} };
458         next unless (scalar @who);
459         $who = $who[0];
460         &DEBUG("dcc_close... close $who!");
461     }
462 }
463
464 sub joinchan {
465     my ($chan, $key) = @_;
466     $key ||= &getChanConf("chankey", $chan);
467     $key ||= "";
468
469     # forgot for about 2 years to implement channel keys when moving
470     # over to Net::IRC...
471
472     # hopefully validChan is right.
473     if (&validChan($chan)) {
474         &status("join: already on $chan?");
475     }
476     #} else {
477         &status("joining $b_blue$chan $key$ob");
478
479         return if ($conn->join($chan, $key));
480         return if (&validChan($chan));
481
482         &DEBUG("joinchan: join failed. trying connect!");
483         &clearIRCVars();
484         $conn->connect();
485     #}
486 }
487
488 sub part {
489     my $chan;
490
491     foreach $chan (@_) {
492         next if ($chan eq "");
493         $chan =~ tr/A-Z/a-z/;   # lowercase.
494
495         if ($chan !~ /^$mask{chan}$/) {
496             &WARN("part: chan is invalid ($chan)");
497             next;
498         }
499
500         &status("parting $chan");
501         if (!&validChan($chan)) {
502             &WARN("part: not on $chan; doing anyway");
503 #           next;
504         }
505
506         $conn->part($chan);
507         # deletion of $channels{chan} is done in &entryEvt().
508     }
509 }
510
511 sub mode {
512     my ($chan, @modes) = @_;
513     my $modes = join(" ", @modes);
514
515     if (&validChan($chan) == 0) {
516         &ERROR("mode: invalid chan => '$chan'.");
517         return;
518     }
519
520     &DEBUG("mode: MODE $chan $modes");
521
522     # should move to use Net::IRC's $conn->mode()... but too lazy.
523     rawout("MODE $chan $modes");
524 }
525
526 sub op {
527     my ($chan, @who) = @_;
528     my $os      = "o" x scalar(@who);
529
530     &mode($chan, "+$os @who");
531 }
532
533 sub deop {
534     my ($chan, @who) = @_;
535     my $os = "o" x scalar(@who);
536
537     &mode($chan, "-$os ".@who);
538 }
539
540 sub kick {
541     my ($nick,$chan,$msg) = @_;
542     my (@chans) = ($chan eq "") ? (keys %channels) : lc($chan);
543     my $mynick = $conn->nick();
544
545     if ($chan ne "" and &validChan($chan) == 0) {
546         &ERROR("kick: invalid channel $chan.");
547         return;
548     }
549
550     $nick =~ tr/A-Z/a-z/;
551
552     foreach $chan (@chans) {
553         if (!&IsNickInChan($nick,$chan)) {
554             &status("kick: $nick is not on $chan.") if (scalar @chans == 1);
555             next;
556         }
557
558         if (!exists $channels{$chan}{o}{$mynick}) {
559             &status("kick: do not have ops on $chan :(");
560             next;
561         }
562
563         &status("Kicking $nick from $chan.");
564         $conn->kick($chan, $nick, $msg);
565     }
566 }
567
568 sub ban {
569     my ($mask,$chan) = @_;
570     my (@chans) = ($chan =~ /^\*?$/) ? (keys %channels) : lc($chan);
571     my $mynick = $conn->nick();
572     my $ban     = 0;
573
574     if ($chan !~ /^\*?$/ and &validChan($chan) == 0) {
575         &ERROR("ban: invalid channel $chan.");
576         return;
577     }
578
579     foreach $chan (@chans) {
580         if (!exists $channels{$chan}{o}{$mynick}) {
581             &status("ban: do not have ops on $chan :(");
582             next;
583         }
584
585         &status("Banning $mask from $chan.");
586         &rawout("MODE $chan +b $mask");
587         $ban++;
588     }
589
590     return $ban;
591 }
592
593 sub unban {
594     my ($mask,$chan) = @_;
595     my (@chans) = ($chan =~ /^\*?$/) ? (keys %channels) : lc($chan);
596     my $mynick = $conn->nick();
597     my $ban     = 0;
598
599     &DEBUG("unban: mask = $mask, chan = @chans");
600
601     foreach $chan (@chans) {
602         if (!exists $channels{$chan}{o}{$mynick}) {
603             &status("unBan: do not have ops on $chan :(");
604             next;
605         }
606
607         &status("Removed ban $mask from $chan.");
608         &rawout("MODE $chan -b $mask");
609         $ban++;
610     }
611
612     return $ban;
613 }
614
615 sub quit {
616     my ($quitmsg) = @_;
617     if (defined $conn) {
618         &status("QUIT " . $conn->nick() . " has quit IRC ($quitmsg)");
619         $conn->quit($quitmsg);
620     } else {
621         &WARN("quit: could not quit!");
622     }
623 }
624
625 sub nick {
626     my ($newnick) = @_;
627     my $mynick = $conn->nick();
628
629     if (!defined $newnick) {
630         &ERROR("nick: nick == NULL.");
631         return;
632     }
633
634     if (!defined $mynick) {
635         &WARN("nick: mynick == NULL.");
636         return;
637     }
638
639     my $bad = 0;
640     $bad++ if (exists $nuh{$newnick});
641     $bad++ if (&IsNickInAnyChan($newnick));
642
643     if ($bad) {
644         &WARN("Nick: not going to try to change from $mynick to $newnick. [". scalar(gmtime). "]");
645         # hrm... over time we lose track of our own nick.
646         #return;
647     }
648
649     if ($newnick =~ /^$mask{nick}$/) {
650         &status("nick: Changing nick from $mynick to $newnick");
651         # ->nick() will NOT change cause we are using rawout?
652         &rawout("NICK $newnick");
653         return 1;
654     }
655     &DEBUG("nick: failed... why oh why (mynick=$mynick, newnick=$newnick)");
656     return 0;
657 }
658
659 sub invite {
660     my($who, $chan) = @_;
661     # TODO: check if $who or $chan are invalid.
662
663     $conn->invite($who, $chan);
664 }
665
666 ##########
667 # Channel related functions...
668 #
669
670 # Usage: &joinNextChan();
671 sub joinNextChan {
672     my $joined = 0;
673     foreach (sort keys %conns) {
674         $conn = $conns{$_};
675         my $mynick = $conn->nick();
676         my @join = getJoinChans(1);
677
678         if (scalar @join) {
679             my $chan = shift @join;
680             &joinchan($chan);
681
682             if (my $i = scalar @join) {
683                 &status("joinNextChan: $mynick $i chans to join.");
684             }
685             $joined = 1;
686         }
687     }
688     return if $joined;
689
690     if (exists $cache{joinTime}) {
691         my $delta       = time() - $cache{joinTime} - 5;
692         my $timestr     = &Time2String($delta);
693         # FIXME: @join should be @in instead (hacked to 10)
694         #my $rate       = sprintf("%.1f", $delta / @in);
695         my $rate        = sprintf("%.1f", $delta / 10);
696         delete $cache{joinTime};
697
698         &status("time taken to join all chans: $timestr; rate: $rate sec/join");
699     }
700
701     # chanserv check: global channels, in case we missed one.
702     foreach ( &ChanConfList("chanServ_ops") ) {
703         &chanServCheck($_);
704     }
705 }
706
707 # Usage: &getNickInChans($nick);
708 sub getNickInChans {
709     my ($nick) = @_;
710     my @array;
711
712     foreach (keys %channels) {
713         next unless (grep /^\Q$nick\E$/i, keys %{ $channels{$_}{''} });
714         push(@array, $_);
715     }
716
717     return @array;
718 }
719
720 # Usage: &getNicksInChan($chan);
721 sub getNicksInChan {
722     my ($chan) = @_;
723     my @array;
724
725     return keys %{ $channels{$chan}{''} };
726 }
727
728 sub IsNickInChan {
729     my ($nick,$chan) = @_;
730
731     $chan =~ tr/A-Z/a-z/;       # not lowercase unfortunately.
732
733     if ($chan =~ /^$/) {
734         &DEBUG("INIC: chan == NULL.");
735         return 0;
736     }
737
738     if (&validChan($chan) == 0) {
739         &ERROR("INIC: invalid channel $chan.");
740         return 0;
741     }
742
743     if (grep /^\Q$nick\E$/i, keys %{ $channels{$chan}{''} }) {
744         return 1;
745     } else {
746         foreach (keys %channels) {
747             next unless (/[A-Z]/);
748             &DEBUG("iNIC: hash channels contains mixed cased chan!!!");
749         }
750         return 0;
751     }
752 }
753
754 sub IsNickInAnyChan {
755     my ($nick) = @_;
756     my $chan;
757
758     foreach $chan (keys %channels) {
759         next unless (grep /^\Q$nick\E$/i, keys %{ $channels{$chan}{''}  });
760         return 1;
761     }
762     return 0;
763 }
764
765 # Usage: &validChan($chan);
766 sub validChan {
767     # TODO: use $c instead?
768     my ($chan) = @_;
769
770     if (!defined $chan or $chan =~ /^\s*$/) {
771         return 0;
772     }
773
774     if (lc $chan ne $chan) {
775         &WARN("validChan: lc chan != chan. ($chan); fixing.");
776         $chan =~ tr/A-Z/a-z/;
777     }
778
779     # it's possible that this check creates the hash if empty.
780     if (defined $channels{$chan} or exists $channels{$chan}) {
781         if ($chan =~ /^_?default$/) {
782 #           &WARN("validC: chan cannot be _default! returning 0!");
783             return 0;
784         }
785
786         return 1;
787     } else {
788         return 0;
789     }
790 }
791
792 ###
793 # Usage: &delUserInfo($nick,@chans);
794 sub delUserInfo {
795     my ($nick,@chans) = @_;
796     my ($mode,$chan);
797
798     foreach $chan (@chans) {
799         foreach $mode (keys %{ $channels{$chan} }) {
800             # use grep here?
801             next unless (exists $channels{$chan}{$mode}{$nick});
802
803             delete $channels{$chan}{$mode}{$nick};
804         }
805     }
806 }
807
808 sub clearChanVars {
809     my ($chan) = @_;
810
811     delete $channels{$chan};
812 }
813
814 sub clearIRCVars {
815     undef %channels;
816     undef %floodjoin;
817
818     $cache{joinTime}    = time();
819 }
820
821 sub getJoinChans {
822     my($show)   = @_;
823
824     my @in;
825     my @skip;
826     my @join;
827
828     # can't join any if not connected
829     return @join if (!$conn);
830
831     my $nick = $conn->nick();
832
833     foreach (keys %chanconf) {
834         next if ($_ eq "_default");
835
836         my $skip = 0;
837         my $val = $chanconf{$_}{autojoin};
838
839         if (defined $val) {
840             $skip++ if ($val eq "0");
841             if ($val eq "1") {
842                 # convert old +autojoin to autojoin <nick>
843                 $val = $nick;
844                 $chanconf{$_}{autojoin} = $val;
845             }
846             $skip++ if ($val ne $nick);
847         } else {
848             $skip++;
849         }
850
851         if ($skip) {
852             push(@skip, $_);
853         } else {
854             if (defined $channels{$_} or exists $channels{$_}) {
855                 push(@in, $_);
856             } else {
857                 push(@join, $_);
858             }
859         }
860     }
861
862     my $str;
863     #$str .= ' in:' . join(',', sort @in) if scalar @in;
864     #$str .= ' skip:' . join(',', sort @skip) if scalar @skip;
865     $str .= ' join:' . join(',', sort @join) if scalar @join;
866
867     &status("Chans: ($nick)$str") if ($show);
868
869     return sort @join;
870 }
871
872 sub closeDCC {
873 #    &DEBUG("closeDCC called.");
874     my $type;
875
876     foreach $type (keys %dcc) {
877         next if ($type ne uc($type));
878
879         my $nick;
880         foreach $nick (keys %{ $dcc{$type} }) {
881             next unless (defined $nick);
882             &status("DCC CHAT: closing DCC $type to $nick.");
883             next unless (defined $dcc{$type}{$nick});
884
885             my $ref = $dcc{$type}{$nick};
886             &dccsay($nick, "bye bye, $nick") if ($type =~ /^chat$/i);
887             $dcc{$type}{$nick}->close();
888             delete $dcc{$type}{$nick};
889             &DEBUG("after close for $nick");
890         }
891         delete $dcc{$type};
892     }
893 }
894
895 sub joinfloodCheck {
896     my($who,$chan,$userhost) = @_;
897
898     return unless (&IsChanConf("joinfloodCheck"));
899
900     if (exists $netsplit{lc $who}) {    # netsplit join.
901         &DEBUG("joinfloodCheck: $who was in netsplit; not checking.");
902     }
903
904     if (exists $floodjoin{$chan}{$who}{Time}) {
905         &WARN("floodjoin{$chan}{$who} already exists?");
906     }
907
908     $floodjoin{$chan}{$who}{Time} = time();
909     $floodjoin{$chan}{$who}{Host} = $userhost;
910
911     ### Check...
912     foreach (keys %floodjoin) {
913         my $c = $_;
914         my $count = scalar keys %{ $floodjoin{$c} };
915         next unless ($count > 5);
916         &DEBUG("joinflood: count => $count");
917
918         my $time;
919         foreach (keys %{ $floodjoin{$c} }) {
920             my $t = $floodjoin{$c}{$_}{Time};
921             next unless (defined $t);
922
923             $time += $t;
924         }
925         &DEBUG("joinflood: time => $time");
926         $time /= $count;
927
928         &DEBUG("joinflood: new time => $time");
929     }
930
931     ### Clean it up.
932     my $delete = 0;
933     my $time = time();
934     foreach $chan (keys %floodjoin) {
935         foreach $who (keys %{ $floodjoin{$chan} }) {
936             my $t       = $floodjoin{$chan}{$who}{Time};
937             next unless (defined $t);
938
939             my $delta   = $time - $t;
940             next unless ($delta > 10);
941
942             delete $floodjoin{$chan}{$who};
943             $delete++;
944         }
945     }
946
947     &DEBUG("joinfloodCheck: $delete deleted.") if ($delete);
948 }
949
950 sub getHostMask {
951     my($n) = @_;
952
953     if (exists $nuh{$n}) {
954         return &makeHostMask($nuh{$n});
955     } else {
956         $cache{on_who_Hack} = 1;
957         $conn->who($n);
958     }
959 }
960
961 1;