-
Notifications
You must be signed in to change notification settings - Fork 8
/
nph-irc.cgi
executable file
·1444 lines (1223 loc) · 41.2 KB
/
nph-irc.cgi
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
# CGI:IRC - http://cgiirc.org/
# Copyright (C) 2000-2006 David Leadbeater <http://dgl.cx/>
# vim:set ts=3 expandtab shiftwidth=3 cindent:
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Uncomment this if the server doesn't chdir (Boa).
# BEGIN { (my $dir = $0) =~ s|[^/]+$||; chdir($dir) }
require 5.004;
use strict;
use lib qw{./modules ./interfaces};
use vars qw(
$VERSION @handles %inbuffer $select_bits @output
$unixfh $ircfh $cookie $ctcptime $intime $pingtime
$timer $event $config $cgi $irc $format $formatname $interface $ioptions
$regexpicon %regexpicon
$config_path $help_path
);
($VERSION =
'0.5.13 $Id$'
) =~ s/^.*?(\d\S+) .*?([0-9a-f]{4}).*/$1 . (index($1, "g") > 0 ? "$2" : "")/e;
use Socket;
use Symbol; # gensym
$|++;
# Check for IPV6. Bit yucky but avoids errors when module isn't present
BEGIN {
if (not exists $Socket::{AF_INET6}) {
# Legacy Socket6 module
eval('use Socket6; $::IPV6++ if defined $Socket6::VERSION');
unless(defined $::IPV6) {
$::IPV6 = 0;
eval('sub AF_INET6 {0};sub NI_NUMERICHOST {0};sub NI_NUMERICSERV {}');
}
} else {
Socket->import(":addrinfo");
$::IPV6++;
}
# then check for Encode
$::ENCODE = 0;
eval("use Encode;");
$::ENCODE = 1 unless $@;
}
# My own Modules
use Timer;
use Event;
use IRC;
use Command;
require 'parse.pl';
for('', '/etc/cgiirc/', '/etc/') {
last if -r ($config_path = $_) . 'cgiirc.config';
}
for('docs/', '/usr/share/doc/cgiirc/') {
last if -r ($help_path = $_) . 'help.html';
}
my $needtodie = 0;
# DEBUG
#use Carp;
#$SIG{__DIE__} = \&confess;
#### Network Functions
## Returns the address of a host (handles both IPv4 and IPv6)
## Return value: (ipv4,ipv6)
sub net_hostlookup {
my($host) = @_;
if($::IPV6) {
my($family,$socktype, $proto, $saddr, $canonname, @res) =
getaddrinfo($host, undef, AF_UNSPEC, SOCK_STREAM);
return undef unless $family;
my($addr, $port) = getnameinfo($saddr, NI_NUMERICHOST | NI_NUMERICSERV);
=pod
my $ip = config_set('prefer_v6')
? ($ipv6 ? $ipv6 : $ipv4)
: ($ipv4 ? $ipv4 : $ipv6);
=cut
return $addr;
}else{ # IPv4
my $ip = (gethostbyname($host))[4];
return $ip ? inet_ntoa($ip) : undef;
}
}
## Connects a tcp socket and returns the file handle
## inet_addr should be the output of net_gethostbyname
sub net_tcpconnect {
my($inet_addr, $port) = @_;
my $fh = Symbol::gensym;
my $family = ($inet_addr !~ /:/ ? AF_INET : AF_INET6);
socket($fh, $family, SOCK_STREAM,
getprotobyname('tcp')) or return(0, $!);
setsockopt($fh, SOL_SOCKET, SO_KEEPALIVE, pack("l", 1)) or return(0, $!);
my $saddr;
if($inet_addr !~ /:/) {
$saddr = sockaddr_in($port, inet_aton($inet_addr));
if(config_set('vhost')) {
(my $vhost) = $config->{vhost} =~ /(.*)/; # untaint
my @vhosts = split /,\s*/, $vhost;
bind($fh, pack_sockaddr_in(0, inet_aton($vhosts[rand @vhosts])));
}else{
bind($fh, pack_sockaddr_in(0, inet_aton('0.0.0.0')));
}
}else{
$saddr = sockaddr_in6($port, inet_pton(AF_INET6, $inet_addr));
if(config_set('vhost6')) {
# this needs testing...
(my $vhost) = $config->{vhost6} =~ /([^ ]+)/;
bind($fh, pack_sockaddr_in6(0, inet_pton(AF_INET6, $vhost)));
}
}
if($family == AF_INET) {
my($localport,$localip) = sockaddr_in(getsockname $fh);
irc_write_server(inet_ntoa($localip), $localport, $inet_addr, $port);
}else{
my($localport,$localip) = sockaddr_in6(getsockname $fh);
irc_write_server(inet_pton(AF_INET6, $localip), $localport, $inet_addr, $port);
}
$SIG{ALRM} = sub { die "xtimeout" };
eval {
local $SIG{__DIE__} = undef;
alarm 60;
connect($fh, $saddr) or die "$!\n";
};
alarm 0;
if($@ =~ /xtimeout/) {
return(0, "Connection timed out (60 seconds)");
}elsif($@) {
chomp(my $error = $@);
return(0, "$error connecting to $inet_addr:$port");
}
net_autoflush($fh);
return($fh);
}
## Opens a UNIX Domain Listening socket
## Passed just the filename, returns 1 on success, 0 on failure
sub net_unixconnect {
my($local) = @_;
my $fh = Symbol::gensym;
if(-e $local) {
return 0 unless unlink $local;
}
socket($fh, PF_UNIX, SOCK_STREAM, 0) or return (0, $!);
bind($fh, sockaddr_un($local)) or return (0, $!);
listen($fh, SOMAXCONN) or return (0, $!);
net_autoflush($fh);
return $fh;
}
sub net_autoflush {
my $fh = shift;
select $fh;
$| = 1;
select STDOUT;
}
## Send data to specific filehandle (and deal with encodings for irc)..
sub net_send {
my($fh,$data) = @_;
if($::ENCODE && $fh == $ircfh) {
my $output = Encode::encode($config->{'irc charset'}, $data);
$output = $data unless defined $output;
syswrite($fh, $output, length $output);
}elsif($::ENCODE) {
my $output = Encode::encode('utf8', $data);
$output = $data unless defined $output;
syswrite($fh, $output, length $output);
}else{
syswrite($fh, $data, length $data);
}
}
#### Select Helper Functions
## Code adapted from IO::Select.pm by Graham Barr
## Adds file handle into @handles and fileno into the bit vector
sub select_add {
my($fh) = @_;
my $fileno = select_fileno($fh);
$handles[$fileno] = $fh;
select_makebits();
}
## Deletes the filehandle and fileno
sub select_del {
my($fh) = @_;
my $fileno = select_fileno($fh);
if(!$fileno) {
for(0 .. $#handles) {
$fileno = $_, last if $handles[$_] == $fh;
}
}
return unless defined $handles[$fileno];
$handles[$fileno] = undef;
select_makebits();
}
## Returns a fileno
sub select_fileno {
fileno(shift);
}
sub select_makebits {
$select_bits = '';
for(2 .. $#handles) {
next unless defined $handles[$_] && ref $handles[$_];
vec($select_bits, select_fileno($handles[$_]), 1) = 1;
}
}
## Returns list of handles with input waiting
sub select_canread {
my($timeout) = @_;
my $read = $select_bits;
if(select($read, undef, undef, $timeout) > 0) {
my @out;
for(0 .. $#handles) {
push(@out, $handles[$_]) if vec($read, $_, 1);
}
return @out;
}
return ();
}
## Closes and deletes a filehandle
sub select_close {
my($fh) = @_;
return irc_close() if $ircfh == $fh;
select_del($fh);
close($fh);
}
#### Format Functions
## Loads the format given to it, or the default
sub load_format {
$formatname = $config->{format};
if($cgi->{format} && $cgi->{format} !~ /[^A-Za-z0-9]/) {
$formatname = $cgi->{format};
}
return parse_config($config_path . 'formats/' . $formatname);
}
## Prints a nicely formatted line
## the format is the format name to use, taken from the %format hash
## the params are passed to the format
sub format_out {
my($formatname, $info, $params) = @_;
return unless exists $format->{$formatname};
return unless $format->{$formatname};
my $line = format_parse($format->{$formatname}, $info, $params);
my $try = 0;
# If there is malformed UTF8 various regexes under here can die for odd
# reasons (which I don't fully understand) therefore wrap in an eval.
OUTPUT: eval {
$line = format_colourhtml($line);
interface_lineout($info, $line);
};
if($@) {
print STDERR "Output failed with: $@\n";
# Try again without UTF8 (treat as binary, probably only does something
# vaguely useful for latin characters?)
Encode::_utf8_off($line) if $::ENCODE;
goto OUTPUT unless $try++;
}
}
sub message {
my($formatname, @params) = @_;
my $info = { target => 'Status', activity => 1, type => $formatname };
format_out($formatname, $info, \@params);
}
## Formats IRC Colours and Styles into HTML and makes URLs clickable
sub format_colourhtml {
my($line) = @_;
# Used as a token for replaces
my $tok = "\004";
$line =~ s/$tok//g;
$line =~ s/\&/$tok\&$tok/g;
$line =~ s/</$tok\<$tok/g;
$line =~ s/>/$tok\>$tok/g;
$line =~ s/"/$tok\"$tok/g;
$line =~ s{((https?|ftp):\/\/[^$ ]+)(?![^<]*>)}{$interface->link(format_remove($1), format_linkshorten($1))}gie;
$line =~ s{(^|\s)(www\..*?)([\.,]?($|\s)|\)|\002)(?![^<]*>)}{"$1" . $interface->link(format_remove("http://$2"), $2) . $3}gie;
if(exists $ioptions->{smilies} && $ioptions->{smilies}) {
$line =~ s{(?<![^\.a-zA-Z_ ])$regexpicon(?![^<]*>)}{
my($sm, $tmp) = ($1, $1);
for(keys %regexpicon) {
next unless $sm =~ /^$_$/;
$tmp = $interface->smilie("$config->{image_path}/$regexpicon{$_}.gif", $regexpicon{$_}, $sm);
last;
}
$tmp
}ge;
}
$line =~ s/$tok//g;
$line =~ s/( {2,})/' ' x (length $1)/eg;
return format_remove($line) if $config->{removecolour};
if($line =~ /[\002\003\017\022\037]/) {
$line=~ s/\003(\d{1,2})(\,(\d{1,2})|)([^\003\017]*|.*?$)/
my $me = "<font ";
my $fg = sprintf("%0.2d",$1);
my $bg = (defined $3 && length $3) ? sprintf("%0.2d",$3) : '';
if(length $bg) {
$me .= "style=\"background: ".$format->{$bg}."\" "
}
$me .= "color=\"$format->{$fg}\">$4<\/font>";
$me
/eg;
$line =~ s/\002(.*?)(\002|\017|$)/<b>$1<\/b>/g;
$line =~ s/\022(.*?)(\022|\017|$)/<u>$1<\/u>/g;
$line =~ s/\037(.*?)(\037|\017|$)/<u>$1<\/u>/g;
}
return format_remove($line);
}
sub format_init_smilies {
if(config_set('smilies')) {
%regexpicon = %{parse_config($config_path . $config->{smilies})};
} else {
%regexpicon = (
'\;-?\)' => 'wink',
'\;-?D' => 'grin',
':\'\(?' => 'cry',
':-?/(?!\S)' => 'notsure',
':-?[xX]' => 'confused',
':-?\]' => 'embarassed',
':-?\*' => 'love',
':-?[pP]' => 'tongue',
':-?\)' => 'happy',
'\:-?D' => 'cheesy',
':-?\(' => 'unhappy',
':-[oO]' => 'surprised',
'8-?\)' => 'cool',
':-?\|' => 'flat',
':\'\)\)?' => 'happycry',
"\004\>\004:-?/" => 'hmmm',
"\004\>\004:-?\\(" => 'angry',
':-?\*\*' => 'kiss',
':-z' => 'sleep',
':-\.' => 'sorry',
'8-@' => 'what',
);
}
$regexpicon = '(' . join('|', sort { length $b <=> length $a } keys %regexpicon) . ')';
}
sub format_linkshorten {
my $link = shift;
if(config_set('linkshorten')) {
return substr($link, 0, $config->{linkshorten})
. (length $link > $config->{linkshorten} ? '...' : '');
}else{
return substr($link, 0, 120)
. (length $link > 120 ? '...' : '');
}
}
## Removes all IRC formating characters
sub format_remove {
my($line) = @_;
$line =~ s/\003(\d{1,2})(\,(\d{1,2})|)//g;
$line =~ s/[\x00-\x1f]//g;
return $line;
}
## Lowlevel code that deals with the format parsing
## No longer supports nested
sub format_parse {
my($line, $info, $params) = @_;
return unless defined $line;
my($match, $name, $param);
$line =~ s{
( # format
\{
([^\}\s]+)
\s?([^\}]+)?
\}
# variables
| (\$[A-Za-z0-9-]+)
| (\%(?:\d{1,2}|n|_|%))
)
}{
($match, $name, $param) = ($1, $2, $3);
if($match =~ /^[\$%]/) {
format_varexpand($match, $info, $params);
}elsif(!exists $format->{$name}) {
error("Invalid format ($name) called: $line");
}else{
format_parse($format->{$name}, $info,
[map {format_varexpand($_, $info, $params)} split / /,
defined $param ? $param : '']);
}
}egx;
return $line;
}
sub format_varexpand {
$_ = shift;
my($info, $params) = @_;
return '' unless defined;
if(s/^\$//) {
if(ref $params && /^(\d+)\-$/) {
return join(' ', @$params[$1 .. @$params - 1]);
}elsif(!/\D/) {
return $params->[$_] if ref $params && defined $params->[$_];
return '';
}elsif(/^VERSION$/) {
return $VERSION;
}elsif(/^T$/ && exists $info->{target}) {
return $info->{target};
}elsif(/^N$/) {
return $irc->{nick}
}elsif(/^S$/) {
return $irc->{server};
}
}elsif(s/^%//) {
if(/^_$/) {
return "\002";
}elsif(/^n$/) {
return "\003$format->{fg},$format->{bg}";
}elsif(/^%$/) {
return "%";
}elsif(/^\d+$/) {
return "\003$_";
}
return "\%$_";
}
return $_;
}
#### Interface Functions
## Loads the default interface.
sub load_interface {
my $name = defined $cgi->{interface} ? $cgi->{interface} : 'default';
($name) = $name =~ /([a-z0-9]+)/i;
require("./interfaces/$name.pm");
$ioptions = parse_interface_cookie();
for(keys %$config) {
next unless s/^interface //;
next if exists $ioptions->{$_};
$ioptions->{$_} = $config->{"interface $_"};
}
$interface = $name->new($event,$timer, $config, $ioptions);
my $bg = $format->{$format->{bg}};
my $fg = $format->{$format->{fg}};
$interface->header($config, $cgi, $bg, $fg);
return $interface;
}
sub interface_show {
my($show, $input) = @_;
return '' unless $interface->exists($show);
return $interface->$show($input, $irc, $config);
}
sub interface_keepalive {
$interface->keepalive($irc, $config);
}
sub interface_lineout {
my($type, $target, $html) = @_;
push(@output, $interface->makeline($type, $target, $html));
}
#### Unix Domain Socket Functions
## Opens the listening socket
sub load_socket {
error('Communication socket name is invalid')
if !$cgi->{R} or $cgi->{R} =~ /[^A-Za-z0-9]/;
($cgi->{R}) = $cgi->{R} =~ /([A-Za-z0-9]+)/;
error('Communication socket already exists')
if -e $config->{socket_prefix}.$cgi->{R};
mkdir($config->{socket_prefix}.$cgi->{R}, 0700) or error("Mkdir error: $!");
open(IP, ">$config->{socket_prefix}$cgi->{R}/ip") or error("Open error: $!");
print IP "$ENV{REMOTE_ADDR}\n";
my $client_ip = $ENV{HTTP_X_FORWARDED_FOR};
$client_ip = $ENV{HTTP_CLIENT_IP} unless defined $client_ip;
print IP "$client_ip\n" if defined $client_ip;
close(IP);
my($socket,$error) =
net_unixconnect($config->{socket_prefix}.$cgi->{R}.'/sock');
error("Error opening socket: $error") unless ref $socket;
select_add($socket);
return $socket;
}
sub unix_in {
my($fh, $line) = @_;
my $input = parse_query($line, ($line =~ /&xmlhttp/ ? 2 : 0));
if($cookie && (!defined $input->{COOKIE} || $input->{COOKIE} ne $cookie)) {
net_send($fh, "Content-type: text/html\r\n\r\nInvalid cookie\r\n");
select_close($fh);
return;
}
$pingtime = time;
$intime = $pingtime if $input->{cmd} eq 'say'
&& $input->{say} ne '/noop';
if($input->{cmd}) {
my $now = time;
utime($now, $now, "$config->{socket_prefix}$cgi->{R}/sock");
input_command($input->{cmd}, $input, $fh, $line);
}
net_send($fh, "Content-type: text/html\r\n\r\n");
if(defined $input->{item} && $input->{item} =~ /^\w+$/) {
net_send($fh, interface_show($input->{item}, $input));
}
select_close($fh);
}
sub input_command {
my($command, $params, $fh, $line) = @_;
if($command eq 'say') {
say_command($params->{say}, $params->{target});
}elsif($command eq 'paste') {
$params = parse_query($line, 1 + ($line =~ /&xmlhttp/ ? 2 : 0));
for(split /\n/, $params->{say}) {
s/\r$//;
next unless $_;
say_command($_, $params->{target});
}
}elsif($command eq 'quit') {
net_send($fh, "Content-type: text/html\r\n\r\nquit\r\n"); # avoid errors
irc_close("");
}elsif($command eq 'options' && length $params->{name} && length $params->{value}) {
$ioptions->{$params->{name}} = $params->{value};
$interface->setoption($params->{name}, $params->{value});
# write proper cookie code one day.
net_send($fh, "Set-Cookie: cgiirc$params->{name}=$params->{value}; path=/; expires=Fri, 01-Jan-2021 00:00:00 GMT\r\n");
}
}
sub say_command {
my($say, $target) = @_;
return unless length $say;
$say =~ s/(\n|\r|\0|\001)//sg;
$target =~ s/(\n|\r|\0|\001)//sg;
if(!config_set('disable_format_input')) {
$say =~ s/\%C/\003/g;
$say =~ s/\%B/\002/g;
$say =~ s/\%U/\037/g;
}
if($say =~ m!^/!) {
if($say =~ s!^/ /!/!) {
irc_send_message($target, $say);
}else{
(my $command, my $params) = $say =~ m|^/([^ ]+)(?: (.+))?$|;
unless(defined $command && length $command) {
return;
}
$command = Command->expand($command);
unless(access_command($command)) {
message('command denied', $command);
return;
}
my $error = Command->run($event, $irc, $command, $target, defined $params ? $params : '', $config, $interface);
return 1 if $error == 100;
if($error == 2) {
message('command notparams', $error);
}else{
message('command error', $error);
}
return 0;
}
}else{
irc_send_message($target, $say);
}
}
#### Access Checking Functions
sub config_set {
my($option) = @_;
return 1 if defined $config->{$option} && $config->{$option};
0;
}
sub access_ipcheck {
return unless config_set('ip_access_file') || config_set("max_users");
my($ip, $hostname) = @_;
my($ipn) = inet_aton($ip);
my($ipaccess_match) = 0;
my($limit) = undef;
my %ips = list_connected_ips();
my $total = 0;
$total += $ips{$_} for keys %ips;
if(config_set("max_users") && $total > $config->{max_users}) {
message('access denied', 'Too many connections (global)');
irc_close();
}
return unless config_set('ip_access_file');
for my $ipaccess_file (split(',', $config->{ip_access_file})) {
# If any of the files don't exist, we just skip them.
open(IP, "<" . ($ipaccess_file =~ m!^/! ? '' : $config_path)
. $ipaccess_file) or next;
while(<IP>) {
chomp;
next if /^\s*(#|$)/;
s/\s+#.*$//g;
my($check);
($check, $limit) = split(' ', $_, 2);
if ($check =~ /\//) {
# IP address with subnet mask
my($addr,$mask) = split('/', $check, 2);
$mask = "1" x $mask . "0" x (32-$mask);
$mask = pack ("B32", $mask);
$mask = inet_ntoa($mask & $ipn);
if($addr eq $mask) {
$ipaccess_match = 1;
}
} else {
# IP or hostname (we check both)
# XXX: someone could make their hostname resolve to
# 127.0.0.1.foobar.com and it would match eg 127.*.*.*
# I don't think it's that serious and if it really is a
# problem, 127.0.0.0/8 wouldn't match.
$check =~ s/\./\\./g;
$check =~ s/\?/./g;
my $ipcheck = $check;
$ipcheck =~ s/\*/\\d+/g;
$check =~ s/\*/.*/g;
if($ip =~ /^$ipcheck$/) {
$ipaccess_match = 1;
} elsif($hostname =~ /^$check$/i) {
$ipaccess_match = 1;
}
}
# We stop parsing, if this line matched.
last if $ipaccess_match;
}
close(IP);
# We don't parse more files, if a line in the last file matched.
last if $ipaccess_match;
}
# If we got a matching line...
if($ipaccess_match) {
# We just accept the client, if there is no limit defined.
return unless defined $limit;
if($limit == 0) {
message('access denied', "No connections allowed from your hostname $hostname or your IP address $ip");
} elsif($ips{$ip} >= $limit) {
message('access denied', 'Too many connections');
} else {
return;
}
} else {
message('access denied', 'No connections allowed');
}
irc_close();
}
sub access_dnsbl {
my $ip = shift;
return unless config_set('dnsbl');
my $arpa = join '.', reverse split /\./, $ip;
for my $zone(split ' ', $config->{dnsbl}) {
my $res = net_hostlookup("$arpa.$zone.");
if(defined $res) {
message('access denied', "Found in DNS black list $zone (your IP is $ip, result: $res)");
irc_close();
}
}
}
sub list_connected_ips {
my %ips = ();
(my $dir, my $prefix) = $config->{socket_prefix} =~ /^(.*\/)([^\/]+)$/;
opendir(TMPDIR, "$dir") or return ();
for(readdir TMPDIR) {
next unless /^\Q$prefix\E/;
next unless -o $dir . $_ && -d $dir . $_;
next unless -f "$dir$_/server";
open(TMP, "<$dir$_/ip") or next;
chomp(my $tmp = <TMP>);
$ips{$tmp}++;
close(TMP);
}
closedir(TMPDIR);
return %ips;
}
sub access_configcheck {
my($type, $check) = @_;
if(config_set("default_$type")) {
my %tmp;
@tmp{split /,\s*/, lc $config->{"default_$type"}} = 1;
return 1 if exists $tmp{lc $check};
}
return 0 unless config_set('allow_non_default') && config_set("access_$type");
return 1 if $check =~ /^$config->{"access_$type"}$/i;
0;
}
sub access_command {
my($command) = @_;
return 1 unless config_set('access_command');
for(split / /, $config->{access_command}) {
if(/^!(.*)/) {
return 0 if $command =~ /^$1/i;
}else{
return 1 if $command =~ /^$_/i;
}
}
return 1;
}
sub encode_ip {
return join('',map(sprintf("%0.2x", $_), split(/\./,shift)));
}
# Resolve host *and* do checks against hosts that are allowed to connect.
# Note: this follows proxies (via X-Forwarded-For header - but only if the
# proxy is listed in the trusted-proxy file).
sub access_check_host {
my $ip = defined $_[0] ? $_[0] : $ENV{REMOTE_ADDR};
$ip =~ s/^::ffff://; # Treat as plain IPv4 if listening on IPv6.
if($ip =~ /:/) { # IPv6
$ip =~ s/^:/0:/;
# Hack: No access checking for IPv6 yet.
# We just make sure that connections are allowed in general by checking
# against 0.0.0.0.
access_ipcheck("0.0.0.0", "0.0.0.0");
return($ip, $ip);
}
my $ipn = inet_aton($ip);
access_dnsbl($ip);
my($hostname) = gethostbyaddr($ipn, AF_INET);
unless(defined $hostname && $hostname) {
access_ipcheck($ip, $ip);
return($ip, $ip);
}
# Check reverse == forward
my(undef,undef,undef,undef,@ips) = gethostbyname($hostname);
my $ok = 0;
for(@ips) {
$ok = 1 if $_ eq $ipn;
}
if(!$ok) {
access_ipcheck($ip, $ip);
return($ip, $ip);
}
access_ipcheck($ip, $hostname);
my $client_ip = $ENV{HTTP_X_FORWARDED_FOR};
$client_ip = $ENV{HTTP_CLIENT_IP} unless defined $client_ip;
if(defined $client_ip
&& $client_ip =~ /((\d{1,3}\.){3}\d{1,3})$/
&& !defined $_[1]) { # check proxy but only once
my $proxyip = $1;
return($hostname, $ip) if $proxyip =~ /^(192\.168|127|10|172\.(1[6789]|2\d|3[01]))\./;
open(TRUST, "<${config_path}trusted-proxy") or return($hostname, $ip);
while(<TRUST>) {
chomp;
s/\*/.*/g;
s/\?/./g;
return access_check_host($proxyip, 1) if $hostname =~ /^$_$/i;
}
close TRUST;
}
return($hostname, $ip);
}
sub session_timeout {
return unless defined $intime;
if(config_set('session_timeout') &&
(time - $config->{session_timeout}) > $intime) {
message('session timeout');
irc_close('Session timeout');
}elsif($interface->ping && $pingtime < time - 300) {
irc_close('Ping timeout');
}elsif($interface->ping && $pingtime < time - 240) {
$interface->sendping;
}
}
#### IRC Functions
## Opens the connection to IRC
sub irc_connect {
my($server, $port) = @_;
error("No server specified") unless $server;
message('looking up', $server);
flushoutput(); # this stuff can block - keep the user informed
my $ip = net_hostlookup($server);
unless(defined $ip) {
error("Looking up address: $! ($?)");
}
message('connecting', $server, $ip, $port);
flushoutput();
my($fh, $error) = net_tcpconnect($ip, $port);
error("Connecting to IRC: $error") unless ref $fh;
select_add($fh);
return $fh;
}
sub irc_write_server {
my($lip, $lport, $rip, $rport) = @_;
open(S, ">$config->{socket_prefix}$cgi->{R}/server")
or error("Opening server file: $!");
print S "$rip:$rport\n$lip:$lport\n";
close(S);
}
## Sends data to the irc connection
sub irc_out {
my($event,$fh,$data) = @_;
$data = $fh, $fh = $event if !$data;
net_send($fh, $data . "\r\n");
}
sub irc_close {
my $message = shift;
$message = 'EOF' unless defined $message;
$message = (config_set('quit_prefix') ? $config->{quit_prefix} : "CGI:IRC") .
($message ? " ($message)" : '');
flushoutput();
exit unless ref $unixfh;
close($unixfh);
my $t = $config->{socket_prefix} . $cgi->{R};
unlink("$t/sock", "$t/ip", "$t/server", "$t/ident");
exit unless rmdir($t);
exit unless ref $ircfh;
net_send($ircfh, "QUIT :$message\r\n");
my $info = { target => '-all', activity => 1 };
my $close = format_colourhtml(format_parse($format->{'irc close'}, $info));
my $url = defined $config->{form_redirect} ? $config->{form_redirect} : $config->{script_login};
$close =~ s/\((.*?)\)/"(" . $interface->reconnect($url, $1) . ")"/e;
interface_lineout($info, $close);
flushoutput();
$interface->end if ref $interface;
sleep 1;
close($ircfh);
exit;
}
sub irc_connected {
my($event, $self, $server, $nick) = @_;
open(SERVER, ">>$config->{socket_prefix}$cgi->{R}/server")
or error("Writing to server file; $!");
print SERVER "$server\n$nick\n";
close(SERVER);
my $key;
$key = $1 if $cgi->{chan} =~ s/ (.+)$//;
unless(access_configcheck('channel', $cgi->{chan})) {
message('access channel denied', $cgi->{chan});
$cgi->{chan} = (split /,/, $config->{default_channel})[0];
}
$irc->join($cgi->{chan} . (defined $key ? ' ' . $key : ''));
say_command($_, 'Status') for split(/;/, $config->{perform});
}
sub irc_send_message {
my($target, $text) = @_;
$event->handle('message ' .
(
$irc->is_channel($target) ? 'public'
: 'private' .
($interface->query ? ' window' : '')
) . ' own',
{ target => $target, create => 1 },
$irc->{nick}, $irc->{myhost}, $text);
$irc->msg($target,$text);
}
sub irc_event {
my($event, $name, $info, @params) = @_;
return if $name =~ /^user /;
$info->{type} = $name;
if($name =~ /^raw/) {
#message('default', "Unhandled numeric: $name");
my $params = $params[0];
$info->{activity} = 1;
$info->{target} = defined $params->{params}->[2] ? $params->{params}->[2] : 'Status';
@params = (join(' ', defined $params->{params}->[2]
? @{$params->{params}}[2 .. @{$params->{params}} - 1]
: ''),
defined $params->{text}
? $params->{text}
: '');
}elsif($name =~ /^ctcp/) {
return irc_ctcp($name, $info, @params);
}elsif($name eq 'message public' && $params[2] =~ /^\Q$irc->{nick}\E\W/i) {
$info->{activity} = 3;