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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
|
#!/usr/bin/perl
# CGI:IRC - http://cgiirc.sourceforge.net/
# Copyright (C) 2000-2006 David Leadbeater <http://contact.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 =
'$Name: rel_0_5_9 $ 0_5_CVS $Id: nph-irc.cgi,v 1.120 2006/06/06 18:50:12 dgl Exp $'
) =~ s/^.*?(\d\S+) .*?(\d{4}\/\S+) .*$/$1/;
$VERSION .= " ($2)";
$VERSION =~ s/_/./g;
use Socket;
use Symbol; # gensym
$|++;
# Check for IPV6. Bit yucky but avoids errors when module isn't present
BEGIN {
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 {}');
}
# 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;
$SIG{HUP} = $SIG{INT} = $SIG{TERM} = sub { $needtodie = 1 };
# Pipe isn't bad..
$SIG{PIPE} = 'IGNORE';
$SIG{__DIE__} = sub {
error("Program ending: @_");
};
# 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} =~ /([^ ]+)/;
bind($fh, pack_sockaddr_in(0, inet_aton($vhost)));
}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);
$line = format_colourhtml($line);
interface_lineout($info, $line);
}
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 {
%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=Sun, 01-Jan-2011 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};
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;
$name = 'message public hilight';
}elsif($name eq 'message private' && $interface->query) {
$name = 'message private window';
}
if(exists $format->{$name}) {
format_out($name, $info, \@params);
}else{
format_out('default', $info, \@params);
}
}
sub irc_ctcp {
my($name, $info, $to, $nick, $host, $command, $params) = @_;
if($name eq 'ctcp own msg') {
format_out('ctcp own msg', $info, [$nick, $host, $command, $params]);
}elsif($name =~ /^ctcp msg /) {
if(uc($command) eq 'KILL') {
return unless config_set('admin password');
my $crypt = $config->{'admin password'};
my($password, $reason) = split ' ', $params, 2;
return unless length $password and length $crypt;
if(crypt($password, substr($crypt, 0, 2)) eq $crypt) {
message('kill ok', $nick, $reason);
irc_out($ircfh, "QUIT :Killed ($nick ($reason))");
irc_close();
}else{
message('kill wrong', $nick, $reason);
}
}elsif(uc($command) eq 'ACTION' && $irc->is_channel($info->{target})) {
format_out('action public', $info, [$nick, $host, $params]);
return;
}elsif(uc($command) eq 'ACTION') {
format_out('action private', $info, [$nick, $host, $params]);
return;
}elsif(uc($command) eq 'DCC' && lc $to eq lc $irc->{nick}) {
format_out('not supported', $info, [$nick, $host, $params, "DCC"]);
}else{
format_out('ctcp msg', $info, [$to, $nick, $host, $command, $params]);
}
if(defined $ctcptime && $ctcptime > time-4) {
$ctcptime = time;
return;
}
$ctcptime = time;
if(uc($command) eq 'VERSION') {
$irc->ctcpreply($nick, $command,
"CGI:IRC $VERSION - http://cgiirc.sf.net/");
}elsif(uc($command) eq 'PING') {
return if $params =~ /[^0-9 ]/ || length $params > 50;
unless($interface->ctcpping($nick, $params)) {
$irc->ctcpreply($nick, $command, $params);
}
}elsif(uc($command) eq 'USERINFO') {
my $client_ip = $ENV{HTTP_X_FORWARDED_FOR};
$client_ip = $ENV{HTTP_CLIENT_IP} unless defined $client_ip;
$client_ip = 'none' unless defined $client_ip;
$irc->ctcpreply($nick, $command,
config_set('extra_userinfo') ?
"IP: $ENV{REMOTE_ADDR} - Proxy: $ENV{HTTP_VIA} - " .
"Forward IP: $client_ip - User Agent: " .
"$ENV{HTTP_USER_AGENT} - Host: $ENV{SERVER_NAME}"
: "$ENV{REMOTE_ADDR} - $ENV{HTTP_USER_AGENT}"
);
}elsif(uc($command) eq 'TIME') {
$irc->ctcpreply($nick, $command,
scalar localtime());
}elsif(uc($command) eq 'DCC' && lc $to eq lc $irc->{nick}) {
my($type, $subtype) = split ' ', $params;
$type .= " $subtype";
$type = substr($type, 0, 20);
$irc->ctcpreply($nick, $command, "REJECT $type Not Supported");
}
}else{
if(uc($command) eq 'PING') {
$params = time - $params . " seconds";
}
format_out('ctcp reply', $info, [$nick, $host, $command, $params]);
}
}
#### prints a very simple header
sub header {
print "HTTP/1.0 200 OK\r\n" if $0 =~ /nph-/;
print join("\r\n",
'Content-type: text/html; charset=utf-8',
'Pragma: no-cache',
'Cache-control: must-revalidate, no-cache, no-store',
'Expires: -1',
"\r\n");
}
sub flushoutput {
if(@output) {
$interface->lines(@output);
@output = ( );
}
}
#### Error Reporting
sub error {
my $message = "@_";
header() unless $config;
if(defined $interface && ref $interface) {
flushoutput();
if(ref $format) {
my $format = format_parse($format->{error}, {}, [$message]);
$format = format_colourhtml($format);
$interface->error($format);
}else{
$interface->error("Error: $message");
}
}else{
print "An error occured: $message\n";
}
print STDERR "[" . scalar localtime() . "] CGI:IRC Error: $message (" . join(' ',(caller(1))[3,2]) . ")";
irc_close("Error");
}
#### Init
sub init {
$timer = new Timer;
$event = new Event;
$timer->addforever(interval => 15, code => \&interface_keepalive);
$event->add('irc out', code => \&irc_out);
$event->add('unhandled', code => \&irc_event);
$event->add('server connected', code => \&irc_connected);
$config = parse_config($config_path . 'cgiirc.config');
$config->{socket_prefix} ||= '/tmp/cgiirc-';
($config->{socket_prefix}) = $config->{socket_prefix} =~ /(.*)/;
$config->{encoded_ip} = 2 unless exists $config->{encoded_ip};
$config->{access_command} = '!quote' unless exists $config->{access_command};
$config->{format} ||= 'default';
$timer->addforever(interval => 30, code => \&session_timeout);
$cgi = parse_query($ENV{QUERY_STRING});
format_init_smilies();
$format = load_format($cgi->{format});
$cookie = parse_cookie();
header();
error('No CGI Input') unless keys %$cgi;
$cgi->{serv} ||= (split /,/, $config->{default_server})[0];
$cgi->{chan} ||= (split /,/, $config->{default_channel})[0];
$cgi->{port} ||= $config->{default_port};
$cgi->{nick} ||= $config->{default_nick};
$cgi->{name} ||= $config->{default_name};
if($::ENCODE) {
eval {
local $SIG{__DIE__};
binmode STDOUT, ":utf8";
};
}
$cgi->{nick} =~ s/\?/int rand 10/eg;
$interface = load_interface();
if(config_set('login secret')) {
require Digest::MD5;
my $token = Digest::MD5::md5_hex($cgi->{time}
. $config->{'login secret'} . $cgi->{R});
if($token ne $cgi->{token}) {
error("Invalid login token!");
# 30 seconds should be enough (there's no user interaction)
} elsif((time - 30) > $cgi->{time}) {
error("Login token out of date, try logging in again!");
}
}
$cgi->{charset} ||= $config->{'irc charset'} || 'utf8';
if($cgi->{charset} && $::ENCODE && Encode::find_encoding($cgi->{charset})) {
$config->{'irc charset'} = $cgi->{charset};
} elsif($cgi->{charset} && $::ENCODE) {
if($cgi->{charset} =~ /\(([^ )]+)/ || $cgi->{charset} =~ /([^ ]+)/) {
my $charset = $1;
if(Encode::find_encoding($charset)) {
$config->{'irc charset'} = $charset;
} else {
message('default', "Unknown encoding: $charset");
$config->{'irc charset'} = 'utf8';
}
}
}
my($resolved, $resolvedip) = access_check_host($ENV{REMOTE_ADDR});
unless(access_configcheck('server', $cgi->{serv})) {
message('access server denied', $cgi->{serv});
$cgi->{serv} = (split /,/, $config->{default_server})[0];
}
($cgi->{serv}) = $cgi->{serv} =~ /([^ ]+)/; # untaint hack.
if($cgi->{serv} =~ s/:(\d+)$//) {
$cgi->{port} = $1;
}
unless(access_configcheck('port', $cgi->{port})) {
message('access port denied', $cgi->{port});
$cgi->{port} = (split /,/, $config->{default_port})[0];
}
($cgi->{port}) = $cgi->{port} =~ /(\d+)/;
if(config_set('encoded_ip')) {
$cgi->{name} = '[' .
($config->{encoded_ip} <= 2
? encode_ip($resolvedip)
# The resolved hostname in realname if set to 3.
: $resolved
)
. '] ' . $cgi->{name};
}
if(config_set('realhost_as_password')) {
$cgi->{pass} = "CGIIRC_${resolvedip}_${resolved}";
}
my $preconnect;
if(config_set('webirc_password')) {
$preconnect = "WEBIRC $config->{webirc_password} cgiirc $resolved $resolvedip";
}
$unixfh = load_socket();
if(exists $ENV{REMOTE_USER}) {
open(IDENT, ">$config->{socket_prefix}$cgi->{R}/ident")
or error("Ident file: $!");
print IDENT "$ENV{REMOTE_USER}\n";
close(IDENT);
}
message('cgiirc welcome') if exists $format->{'cgiirc welcome'};
$ircfh = irc_connect($cgi->{serv}, $cgi->{port});
$irc = IRC->new(
event => $event,
timer => $timer,
fh => $ircfh,
nick => $cgi->{nick},
# yet another form of host spoofing uses these..
server => $resolvedip,
host => $resolved,
password => defined $cgi->{pass}
? $cgi->{pass}
: (config_set('server_password')
? $config->{server_password}
: ''
),
realname => $cgi->{name},
user => config_set('encoded_ip') && $config->{encoded_ip} > 1
? encode_ip($resolvedip)
: (config_set('default_user')
? $config->{default_user}
: $cgi->{nick}
),
preconnect => $preconnect,
);
# It is usually better to use 'server connected' (this is for the JS
# interface so it knows the script has started ok).
$event->handle("user connected", $irc);
$interface->sendping if $interface->ping;
$intime = $pingtime = time;
}
#### Main loop
sub main_loop {
error("Required objects not loaded")
unless ref $timer
and ref $event
and ref $config;
while(1) {
my @ready = select_canread(2);
for my $fh(@ready) {
if($fh == $unixfh) {
my $newfh = Symbol::gensym;
if(accept($newfh, $fh)) {
net_autoflush($newfh);
select_add($newfh);
}
}else{
my($tmp,$char);
$tmp = sysread( $fh, $char, 4096 );
select_close($fh) unless defined $tmp && length $char;
$inbuffer{$fh} .= $char;
while (my($theline,$therest)=$inbuffer{$fh} =~ /([^\n]*)\n(.*)/s ) {
$inbuffer{$fh} = $therest;
$theline =~ s/\r$//;
if($fh == $ircfh) {
if($::ENCODE) {
my $input = Encode::decode($config->{'irc charset'}, $theline);
$theline = $input if defined $input;
}
$irc->in($theline);
}else{
unix_in($fh,$theline);
}
}
flushoutput();
}
}
irc_close() if $needtodie;
$timer->run;
}
}
init();
main_loop();
|