2 # A very simple perl web server used by Webmin
4 # Require basic libraries
9 eval "use Time::HiRes;";
11 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
13 # Find and read config file
15 die "Usage: miniserv.pl <config file>";
17 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
18 $config_file = $ARGV[0];
22 $config_file = "$pwd/$ARGV[0]";
24 %config = &read_config_file($config_file);
25 if ($config{'perllib'}) {
26 push(@INC, split(/:/, $config{'perllib'}));
27 $ENV{'PERLLIB'} .= ':'.$config{'perllib'};
31 # Check if SSL is enabled and available
33 eval "use Net::SSLeay";
36 # These functions only exist for SSLeay 1.0
37 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
38 eval "Net::SSLeay::load_error_strings()";
39 if ($config{'no_ssl2'}) {
40 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
42 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
43 defined(&Net::SSLeay::CTX_load_verify_locations) &&
44 defined(&Net::SSLeay::CTX_set_verify)) {
50 # Check if IPv6 is enabled and available
51 if ($config{'ipv6'}) {
54 push(@startup_msg, "IPv6 support enabled");
58 push(@startup_msg, "IPv6 support cannot be enabled without ".
59 "the Socket6 perl module");
63 # Check if the syslog module is available to log hacking attempts
64 if ($config{'syslog'} && !$config{'inetd'}) {
65 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
71 # check if the TCP-wrappers module is available
72 if ($config{'libwrap'}) {
73 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
79 # Check if the MD5 perl module is available
85 eval "use Digest::MD5";
87 $use_md5 = "Digest::MD5";
91 # Get miniserv's perl path and location
93 open(SOURCE, $miniserv_path);
94 <SOURCE> =~ /^#!(\S+)/;
101 $linked_perl_path = readlink($perl_path);
103 @miniserv_argv = @ARGV;
105 # Check vital config options
106 &update_vital_config();
108 $sidname = $config{'sidname'};
109 die "Session authentication cannot be used in inetd mode"
110 if ($config{'inetd'} && $config{'session'});
112 # check if the PAM module is available to authenticate
113 if ($config{'assume_pam'}) {
114 # Just assume that it will work. This can also be used to work around
115 # a Solaris bug in which using PAM before forking caused it to fail
119 elsif (!$config{'no_pam'}) {
120 eval "use Authen::PAM;";
122 # check if the PAM authentication can be used by opening a
125 if (ref($pamh = new Authen::PAM($config{'pam'},
126 $config{'pam_test_user'},
128 # Now test a login to see if /etc/pam.d/webmin is set
130 $pam_conv_func_called = 0;
131 $pam_username = "test";
132 $pam_password = "test";
133 $pamh->pam_authenticate();
134 if ($pam_conv_func_called) {
136 "PAM authentication enabled");
141 "PAM test failed - maybe ".
142 "/etc/pam.d/$config{'pam'} does not exist");
147 "PAM initialization of Authen::PAM failed");
152 "Perl module Authen::PAM needed for PAM is ".
153 "not installed : $@");
156 if ($config{'pam_only'} && !$use_pam) {
157 print STDERR $startup_msg[0],"\n";
158 print STDERR "PAM use is mandatory, but could not be enabled!\n";
161 elsif ($pam_msg && !$use_pam) {
163 "Continuing without the Authen::PAM perl module");
166 # Check if the User::Utmp perl module is installed
167 if ($config{'utmp'}) {
168 eval "use User::Utmp;";
171 push(@startup_msg, "UTMP logging enabled");
175 "Perl module User::Utmp needed for Utmp logging is ".
176 "not installed : $@");
180 # See if the crypt function fails
181 eval "crypt('foo', 'xx')";
183 eval "use Crypt::UnixCrypt";
187 "Using Crypt::UnixCrypt for password encryption");
191 "crypt() function un-implemented, and Crypt::UnixCrypt ".
192 "not installed - password authentication will fail");
196 # Check if /dev/urandom really generates random IDs, by calling it twice
197 local $rand1 = &generate_random_id("foo", 1);
198 local $rand2 = &generate_random_id("foo", 2);
199 if ($rand1 eq $rand2) {
202 "Random number generator file /dev/urandom is not reliable");
205 # Check if we can call sudo
206 if ($config{'sudo'} && &has_command("sudo")) {
213 "Perl module IO::Pty needed for calling sudo is not ".
218 # init days and months for http_date
219 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
220 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
221 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
223 # Change dir to the server root
224 @roots = ( $config{'root'} );
225 for($i=0; defined($config{"extraroot_$i"}); $i++) {
226 push(@roots, $config{"extraroot_$i"});
229 eval { $user_homedir = (getpwuid($<))[7]; };
231 # getpwuid doesn't work on windows
232 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
239 # Setup SSL if possible and if requested
240 if (!-r $config{'keyfile'}) {
241 # Key file doesn't exist!
242 if ($config{'keyfile'}) {
243 print STDERR "SSL key file $config{'keyfile'} does not exist\n";
247 elsif ($config{'certfile'} && !-r $config{'certfile'}) {
248 # Cert file doesn't exist!
249 print STDERR "SSL cert file $config{'certfile'} does not exist\n";
252 @ipkeys = &get_ipkeys(\%config);
254 if ($config{'ssl_version'}) {
255 # Force an SSL version
256 $Net::SSLeay::version = $config{'ssl_version'};
257 $Net::SSLeay::ssl_version = $config{'ssl_version'};
259 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
260 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
262 $config{'extracas'});
263 foreach $ipkey (@ipkeys) {
264 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'},
265 $ipkey->{'extracas'} || $config{'extracas'});
266 foreach $ip (@{$ipkey->{'ips'}}) {
267 $ssl_contexts{$ip} = $ctx;
272 # Load gzip library if enabled
273 if ($config{'gzip'} eq '1') {
274 eval "use Compress::Zlib";
280 # Setup syslog support if possible and if requested
282 open(ERRDUP, ">&STDERR");
283 open(STDERR, ">/dev/null");
284 $log_socket = $config{"logsock"} || "unix";
285 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
290 local $msg = ucfirst($config{'pam'})." starting";
291 eval { syslog("info", "%s", $msg); };
295 syslog("info", "%s", $msg);
298 # All attempts to use syslog have failed..
303 open(STDERR, ">&ERRDUP");
307 # Read MIME types file and add extra types
311 if ($config{'log'}) {
312 local(@gmt, @lct, $days, $hours, $mins);
313 @gmt = gmtime(time());
314 @lct = localtime(time());
315 $days = $lct[3] - $gmt[3];
316 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
318 $mins = $hours * 60 + $lct[1] - $gmt[1];
319 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
320 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
323 # Build various maps from the config files
324 &build_config_mappings();
326 # start up external authentication program, if needed
327 if ($config{'extauth'}) {
328 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
329 if (!($extauth = fork())) {
333 open(STDIN, "<&EXTAUTH2");
334 open(STDOUT, ">&EXTAUTH2");
335 exec($config{'extauth'}) or die "exec failed : $!\n";
338 local $os = select(EXTAUTH);
342 # Pre-load any libraries
343 if (!$config{'inetd'}) {
344 foreach $pl (split(/\s+/, $config{'preload'})) {
345 ($pkg, $lib) = split(/=/, $pl);
346 $pkg =~ s/[^A-Za-z0-9]/_/g;
347 eval "package $pkg; do '$config{'root'}/$lib'";
349 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
352 print STDERR "Pre-loaded $lib in $pkg\n";
355 foreach $pl (split(/\s+/, $config{'premodules'})) {
357 ($dir, $mod) = split(/\//, $pl);
360 ($dir, $mod) = (undef, $pl);
362 push(@INC, "$config{'root'}/$dir");
363 eval "package $mod; use $mod ()";
365 print STDERR "Failed to pre-load $mod : $@\n";
368 print STDERR "Pre-loaded $mod\n";
373 # Open debug log if set
374 if ($config{'debuglog'}) {
375 open(DEBUG, ">>$config{'debuglog'}");
376 chmod(0700, $config{'debuglog'});
377 select(DEBUG); $| = 1; select(STDOUT);
378 print DEBUG "miniserv.pl starting ..\n";
381 # Write out (empty) blocked hosts file
382 &write_blocked_file();
384 # Initially read webmin cron functions and last execution times
385 &read_webmin_crons();
386 %webmincron_last = ( );
387 &read_file($config{'webmincron_last'}, \%webmincron_last);
389 # Pre-cache lang files
392 if ($config{'inetd'}) {
393 # We are being run from inetd - go direct to handling the request
394 &redirect_stderr_to_log();
395 $SIG{'HUP'} = 'IGNORE';
396 $SIG{'TERM'} = 'DEFAULT';
397 $SIG{'PIPE'} = 'DEFAULT';
398 open(SOCK, "+>&STDIN");
400 # Check if it is time for the logfile to be cleared
401 if ($config{'logclear'}) {
402 local $write_logtime = 0;
403 local @st = stat("$config{'logfile'}.time");
405 if ($st[9]+$config{'logtime'}*60*60 < time()){
408 unlink($config{'logfile'});
411 else { $write_logtime = 1; }
412 if ($write_logtime) {
413 open(LOGTIME, ">$config{'logfile'}.time");
414 print LOGTIME time(),"\n";
419 # Work out if IPv6 is being used locally
420 local $sn = getsockname(SOCK);
421 print DEBUG "sn=$sn\n";
422 print DEBUG "length=",length($sn),"\n";
423 $localipv6 = length($sn) > 16;
424 print DEBUG "localipv6=$localipv6\n";
426 # Initialize SSL for this connection
428 $ssl_con = &ssl_connection_for_ip(SOCK, $localipv6);
432 # Work out the hostname for this web server
433 $host = &get_socket_name(SOCK, $localipv6);
434 print DEBUG "host=$host\n";
436 $port = $config{'port'};
437 $acptaddr = getpeername(SOCK);
438 print DEBUG "acptaddr=$acptaddr\n";
439 print DEBUG "length=",length($acptaddr),"\n";
442 # Work out remote and local IPs
443 $ipv6 = length($acptaddr) > 16;
444 print DEBUG "ipv6=$ipv6\n";
445 (undef, $locala) = &get_socket_ip(SOCK, $localipv6);
446 print DEBUG "locala=$locala\n";
447 (undef, $peera, undef) = &get_address_ip($acptaddr, $ipv6);
448 print DEBUG "peera=$peera\n";
450 print DEBUG "main: Starting handle_request loop pid=$$\n";
451 while(&handle_request($peera, $locala, $ipv6)) { }
452 print DEBUG "main: Done handle_request loop pid=$$\n";
457 # Build list of sockets to listen on
458 $config{'bind'} = '' if ($config{'bind'} eq '*');
459 if ($config{'bind'}) {
460 # Listening on a specific IP
461 if (&check_ip6address($config{'bind'})) {
463 $use_ipv6 || die "Cannot bind to $config{'bind'} without IPv6";
464 push(@sockets, [ inet_pton(Socket6::AF_INET6(),$config{'bind'}),
466 Socket6::PF_INET6() ]);
470 push(@sockets, [ inet_aton($config{'bind'}),
476 # Listening on all IPs
477 push(@sockets, [ INADDR_ANY, $config{'port'}, PF_INET() ]);
480 push(@sockets, [ in6addr_any(), $config{'port'},
481 Socket6::PF_INET6() ]);
484 foreach $s (split(/\s+/, $config{'sockets'})) {
485 if ($s =~ /^(\d+)$/) {
486 # Just listen on another port on the main IP
487 push(@sockets, [ $sockets[0]->[0], $s, $sockets[0]->[2] ]);
488 if ($use_ipv6 && !$config{'bind'}) {
489 # Also listen on that port on the main IPv6 address
490 push(@sockets, [ $sockets[1]->[0], $s,
494 elsif ($s =~ /^\*:(\d+)$/) {
495 # Listening on all IPs on some port
496 push(@sockets, [ INADDR_ANY, $1,
499 push(@sockets, [ in6addr_any(), $1,
500 Socket6::PF_INET6() ]);
503 elsif ($s =~ /^(\S+):(\d+)$/) {
504 # Listen on a specific port and IP
505 my ($ip, $port) = ($1, $2);
506 if (&check_ip6address($ip)) {
507 $use_ipv6 || die "Cannot bind to $ip without IPv6";
508 push(@sockets, [ inet_pton(Socket6::AF_INET6(),
510 $port, Socket6::PF_INET6() ]);
513 push(@sockets, [ inet_aton($ip), $port,
517 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
518 # Listen on the main port on another IPv4 address
519 push(@sockets, [ inet_aton($1), $sockets[0]->[1],
522 elsif (($s =~ /^([0-9a-f\:]+):\*$/ || $s =~ /^([0-9a-f\:]+)$/) &&
524 # Listen on the main port on another IPv6 address
525 push(@sockets, [ inet_pton(Socket6::AF_INET6(), $1),
527 Socket6::PF_INET6() ]);
531 # Open all the sockets
532 $proto = getprotobyname('tcp');
534 $tried_inaddr_any = 0;
535 for($i=0; $i<@sockets; $i++) {
537 socket($fh, $sockets[$i]->[2], SOCK_STREAM, $proto) ||
538 die "Failed to open socket family $sockets[$i]->[2] : $!";
539 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
540 if ($sockets[$i]->[2] eq PF_INET()) {
541 $pack = pack_sockaddr_in($sockets[$i]->[1], $sockets[$i]->[0]);
544 $pack = pack_sockaddr_in6($sockets[$i]->[1], $sockets[$i]->[0]);
545 setsockopt($fh, 41, 26, pack("l", 1)); # IPv6 only
547 for($j=0; $j<5; $j++) {
548 last if (bind($fh, $pack));
552 # All attempts failed .. give up
553 if ($sockets[$i]->[0] eq INADDR_ANY ||
554 $use_ipv6 && $sockets[$i]->[0] eq in6addr_any()) {
556 "Failed to bind to port $sockets[$i]->[1] : $!");
557 $tried_inaddr_any = 1;
560 $ip = &network_to_address($sockets[$i]->[0]);
562 "Failed to bind to IP $ip port ".
563 "$sockets[$i]->[1] : $!");
567 listen($fh, SOMAXCONN);
568 push(@socketfhs, $fh);
569 $ipv6fhs{$fh} = $sockets[$i]->[2] eq PF_INET() ? 0 : 1;
572 foreach $se (@sockerrs) {
573 print STDERR $se,"\n";
576 # If all binds failed, try binding to any address
577 if (!@socketfhs && !$tried_inaddr_any) {
578 print STDERR "Falling back to listening on any address\n";
580 socket($fh, PF_INET(), SOCK_STREAM, $proto) ||
581 die "Failed to open socket : $!";
582 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
583 if (!bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY))) {
584 print STDERR "Failed to bind to port $sockets[0]->[1] : $!\n";
587 listen($fh, SOMAXCONN);
588 push(@socketfhs, $fh);
590 elsif (!@socketfhs && $tried_inaddr_any) {
591 print STDERR "Could not listen on any ports";
595 if ($config{'listen'}) {
596 # Open the socket that allows other webmin servers to find this one
597 $proto = getprotobyname('udp');
598 if (socket(LISTEN, PF_INET(), SOCK_DGRAM, $proto)) {
599 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
600 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
601 listen(LISTEN, SOMAXCONN);
604 $config{'listen'} = 0;
608 # Split from the controlling terminal, unless configured not to
609 if (!$config{'nofork'}) {
610 if (fork()) { exit; }
612 eval { setsid(); }; # may not work on Windows
614 # Close standard file handles
615 open(STDIN, "</dev/null");
616 open(STDOUT, ">/dev/null");
617 &redirect_stderr_to_log();
618 &log_error("miniserv.pl started");
619 foreach $msg (@startup_msg) {
623 # write out the PID file
626 # Start the log-clearing process, if needed. This checks every minute
627 # to see if the log has passed its reset time, and if so clears it
628 if ($config{'logclear'}) {
629 if (!($logclearer = fork())) {
630 &close_all_sockets();
633 local $write_logtime = 0;
634 local @st = stat("$config{'logfile'}.time");
636 if ($st[9]+$config{'logtime'}*60*60 < time()){
639 unlink($config{'logfile'});
642 else { $write_logtime = 1; }
643 if ($write_logtime) {
644 open(LOGTIME, ">$config{'logfile'}.time");
645 print LOGTIME time(),"\n";
652 push(@childpids, $logclearer);
655 # Setup the logout time dbm if needed
656 if ($config{'session'}) {
657 eval "use SDBM_File";
658 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
659 eval "\$sessiondb{'1111111111'} = 'foo bar';";
661 dbmclose(%sessiondb);
662 eval "use NDBM_File";
663 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
666 delete($sessiondb{'1111111111'});
671 $SIG{'HUP'} = 'miniserv::trigger_restart';
672 $SIG{'TERM'} = 'miniserv::term_handler';
673 $SIG{'USR1'} = 'miniserv::trigger_reload';
674 $SIG{'PIPE'} = 'IGNORE';
675 local $remove_session_count = 0;
676 $need_pipes = $config{'passdelay'} || $config{'session'};
678 # wait for a new connection, or a message from a child process
680 if (@childpids <= $config{'maxconns'}) {
681 # Only accept new main socket connects when ready
683 foreach $s (@socketfhs) {
684 vec($rmask, fileno($s), 1) = 1;
688 printf STDERR "too many children (%d > %d)\n",
689 scalar(@childpids), $config{'maxconns'};
692 for($i=0; $i<@passin; $i++) {
693 vec($rmask, fileno($passin[$i]), 1) = 1;
696 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
698 # Wait for a connection
699 local $sel = select($rmask, undef, undef, 10);
701 # Check the flag files
702 if ($config{'restartflag'} && -r $config{'restartflag'}) {
703 print STDERR "restart flag file detected\n";
704 unlink($config{'restartflag'});
707 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
708 unlink($config{'reloadflag'});
713 # Got a HUP signal while in select() .. restart now
717 # Got a USR1 signal while in select() .. re-read config
719 &reload_config_file();
721 local $time_now = time();
723 # Clean up finished processes
725 do { $pid = waitpid(-1, WNOHANG);
726 @childpids = grep { $_ != $pid } @childpids;
727 } while($pid != 0 && $pid != -1);
729 # run the unblocking procedure to check if enough time has passed to
730 # unblock hosts that heve been blocked because of password failures
732 if ($config{'blockhost_failures'}) {
734 while ($i <= $#deny) {
735 if ($blockhosttime{$deny[$i]} &&
736 $config{'blockhost_time'} != 0 &&
737 ($time_now - $blockhosttime{$deny[$i]}) >=
738 $config{'blockhost_time'}) {
739 # the host can be unblocked now
740 $hostfail{$deny[$i]} = 0;
741 splice(@deny, $i, 1);
748 # Do the same for blocked users
749 if ($config{'blockuser_failures'}) {
751 while ($i <= $#deny) {
752 if ($blockusertime{$deny[$i]} &&
753 $config{'blockuser_time'} != 0 &&
754 ($time_now - $blockusertime{$deny[$i]}) >=
755 $config{'blockuser_time'}) {
756 # the user can be unblocked now
757 $userfail{$deny[$i]} = 0;
758 splice(@denyusers, $i, 1);
765 &write_blocked_file();
768 # Check if any webmin cron jobs are ready to run
769 &execute_ready_webmin_crons();
771 if ($config{'session'} && (++$remove_session_count%50) == 0) {
772 # Remove sessions with more than 7 days of inactivity,
774 foreach $s (keys %sessiondb) {
775 local ($user, $ltime, $lip) =
776 split(/\s+/, $sessiondb{$s});
777 if ($time_now - $ltime > 7*24*60*60) {
778 &run_logout_script($s, $user);
779 &write_logout_utmp($user, $lip);
780 delete($sessiondb{$s});
783 "Timeout of session for $user");
789 if ($use_pam && $config{'pam_conv'}) {
790 # Remove PAM sessions with more than 5 minutes of inactivity
792 foreach $c (values %conversations) {
793 if ($time_now - $c->{'time'} > 5*60) {
794 &end_pam_conversation($c);
796 syslog("info", "%s", "Timeout of PAM ".
797 "session for $c->{'user'}");
803 # Don't check any sockets if there is no activity
806 # Check if any of the main sockets have received a new connection
808 foreach $s (@socketfhs) {
809 if (vec($rmask, fileno($s), 1)) {
811 $acptaddr = accept(SOCK, $s);
812 if (!$acptaddr) { next; }
813 binmode(SOCK); # turn off any Perl IO stuff
816 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
818 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
822 # Work out IP and port of client
823 local ($peerb, $peera, $peerp) =
824 &get_address_ip($acptaddr, $ipv6fhs{$s});
826 # Work out the local IP
827 (undef, $locala) = &get_socket_ip(SOCK, $ipv6fhs{$s});
829 # Check username of connecting user
830 $localauth_user = undef;
831 if ($config{'localauth'} && $peera eq "127.0.0.1") {
832 if (open(TCP, "/proc/net/tcp")) {
833 # Get the info direct from the kernel
834 $peerh = sprintf("%4.4X", $peerp);
837 local @t = split(/[\s:]+/, $_);
838 if ($t[1] eq '0100007F' &&
847 if (!$localauth_user) {
848 # Call lsof for the info
849 local $lsofpid = open(LSOF,
850 "$config{'localauth'} -i ".
851 "TCP\@127.0.0.1:$peerp |");
853 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
854 $2 != $$ && $2 != $lsofpid){
855 $localauth_user = $3;
862 # Work out the hostname for this web server
863 $host = &get_socket_name(SOCK, $ipv6fhs{$s});
866 "Failed to get local socket name : $!\n";
870 $port = $sockets[$sn]->[1];
872 # fork the subprocess
874 if (!($handpid = fork())) {
875 # setup signal handlers
876 $SIG{'TERM'} = 'DEFAULT';
877 $SIG{'PIPE'} = 'DEFAULT';
878 #$SIG{'CHLD'} = 'IGNORE';
879 $SIG{'HUP'} = 'IGNORE';
880 $SIG{'USR1'} = 'IGNORE';
882 # Close the file handle for the session DBM
883 dbmclose(%sessiondb);
885 # close useless pipes
888 close($PASSINr); close($PASSOUTw);
890 &close_all_sockets();
893 # Initialize SSL for this connection
895 $ssl_con = &ssl_connection_for_ip(
901 "main: Starting handle_request loop pid=$$\n";
902 while(&handle_request($peera, $locala,
904 # Loop until keepalive stops
907 "main: Done handle_request loop pid=$$\n";
910 close($PASSINw); close($PASSOUTw);
913 push(@childpids, $handpid);
915 close($PASSINw); close($PASSOUTr);
916 push(@passin, $PASSINr);
917 push(@passout, $PASSOUTw);
924 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
925 # Got UDP packet from another webmin server
927 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
929 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
930 local $toip = inet_ntoa((unpack_sockaddr_in(
931 getsockname(LISTEN)))[1]);
932 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
933 (!@allow || &ip_match($fromip, $toip, @allow))) {
934 local $listenhost = &get_socket_name(LISTEN, 0);
935 send(LISTEN, "$listenhost:$config{'port'}:".
936 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
937 ($config{'listenhost'} ?
938 &get_system_hostname() : ""),
944 # check for session, password-timeout and PAM messages from subprocesses
945 for($i=0; $i<@passin; $i++) {
946 if (vec($rmask, fileno($passin[$i]), 1)) {
947 # this sub-process is asking about a password
948 local $infd = $passin[$i];
949 local $outfd = $passout[$i];
950 #local $inline = <$infd>;
951 local $inline = &sysread_line($infd);
953 print DEBUG "main: inline $inline";
956 print DEBUG "main: inline EOF\n";
958 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
959 # Got a delay request from a subprocess.. for
960 # valid logins, there is no delay (to prevent
961 # denial of service attacks), but for invalid
962 # logins the delay increases with each failed
965 # login OK.. no delay
966 print $outfd "0 0\n";
967 $wasblocked = $hostfail{$2} ||
972 &write_blocked_file();
981 # add the host to the block list,
983 if ($config{'blockhost_failures'} &&
985 $config{'blockhost_failures'}) {
987 $blockhosttime{$2} = $time_now;
990 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
996 # add the user to the user block list,
998 if ($config{'blockuser_failures'} &&
1000 $config{'blockuser_failures'}) {
1001 push(@denyusers, $1);
1002 $blockusertime{$1} = $time_now;
1005 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
1006 syslog("crit", "%s",
1011 # Lock out the user's password, if enabled
1012 if ($config{'blocklock'} &&
1014 $config{'blockuser_failures'}) {
1015 my $lk = &lock_user_password($1);
1018 local $logtext = $lk == 1 ? "Security alert: User $1 locked after $config{'blockuser_failures'} failed logins" : $lk < 0 ? "Security alert: User could not be locked" : "Security alert: User is already locked";
1019 syslog("crit", "%s",
1025 $dl = $userdlay{$1} -
1026 int(($time_now - $userlast{$1})/50);
1027 $dl = $dl < 0 ? 0 : $dl+1;
1028 print $outfd "$dl $blocked\n";
1029 $userdlay{$1} = $dl;
1031 # Write out blocked status file
1033 &write_blocked_file();
1036 $userlast{$1} = $time_now;
1038 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
1039 # Verifying a session ID
1040 local $session_id = $1;
1041 local $notimeout = $2;
1042 local $skey = $sessiondb{$session_id} ?
1044 &hash_session_id($session_id);
1045 if (!defined($sessiondb{$skey})) {
1046 # Session doesn't exist
1047 print $outfd "0 0\n";
1050 local ($user, $ltime) =
1051 split(/\s+/, $sessiondb{$skey});
1052 local $lot = &get_logout_time($user, $session_id);
1054 $time_now - $ltime > $lot*60 &&
1056 # Session has timed out
1057 print $outfd "1 ",$time_now - $ltime,"\n";
1058 #delete($sessiondb{$skey});
1062 print $outfd "2 $user\n";
1064 $time_now - $ltime >
1066 $sessiondb{$skey} = "$user $time_now";
1071 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
1072 # Creating a new session
1073 local $session_id = $1;
1076 $sessiondb{&hash_session_id($session_id)} =
1077 "$user $time_now $ip";
1079 elsif ($inline =~ /^delete\s+(\S+)/) {
1080 # Logging out a session
1081 local $session_id = $1;
1082 local $skey = $sessiondb{$session_id} ?
1084 &hash_session_id($session_id);
1085 local @sdb = split(/\s+/, $sessiondb{$skey});
1086 print $outfd $sdb[0],"\n";
1087 delete($sessiondb{$skey});
1089 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
1090 # Starting a new PAM conversation
1091 local ($cid, $host, $user) = ($1, $2, $3);
1093 # Does this user even need PAM?
1094 local ($realuser, $canlogin) =
1095 &can_user_login($user, undef, $host);
1097 if ($canlogin == 0) {
1098 # Cannot even login!
1099 print $outfd "0 Invalid username\n";
1101 elsif ($canlogin != 2) {
1102 # Not using PAM .. so just ask for
1104 $conv = { 'user' => $realuser,
1109 print $outfd "3 Password\n";
1112 # Start the PAM conversation
1113 # sub-process, and get a question
1114 $conv = { 'user' => $realuser,
1118 local ($PAMINr, $PAMINw, $PAMOUTr,
1119 $PAMOUTw) = &allocate_pipes();
1120 local $pampid = fork();
1122 close($PAMOUTr); close($PAMINw);
1123 &pam_conversation_process(
1127 close($PAMOUTw); close($PAMINr);
1128 $conv->{'pid'} = $pampid;
1129 $conv->{'PAMOUTr'} = $PAMOUTr;
1130 $conv->{'PAMINw'} = $PAMINw;
1131 push(@childpids, $pampid);
1133 # Get the first PAM question
1134 local $pok = &recv_pam_question(
1137 &end_pam_conversation($conv);
1141 $conversations{$cid} = $conv if ($conv);
1143 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1144 # A response to a PAM question
1145 local ($cid, $answer) = ($1, $2);
1146 local $conv = $conversations{$cid};
1148 # No such conversation?
1149 print $outfd "0 Bad login session\n";
1151 elsif ($conv->{'pid'}) {
1152 # Send the PAM response and get
1154 &send_pam_answer($conv, $answer);
1155 local $pok = &recv_pam_question($conv, $outfd);
1157 &end_pam_conversation($conv);
1161 # This must be the password .. try it
1162 # and send back the results
1163 local ($vu, $expired, $nonexist) =
1164 &validate_user($conv->{'user'},
1167 local $ok = $vu ? 1 : 0;
1168 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1169 &end_pam_conversation($conv);
1172 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1173 # Store the fact that some user can sudo to root
1174 local ($user, $ok) = ($1, $2);
1175 $sudocache{$user} = $ok." ".time();
1177 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1178 # Query the user sudo cache (valid for 1 minute)
1180 local ($ok, $last) =
1181 split(/\s+/, $sudocache{$user});
1182 if ($last < time()-60) {
1187 # Tell client OK or not
1188 print $outfd "$ok\n";
1191 elsif ($inline =~ /\S/) {
1192 # Unknown line from pipe?
1193 print DEBUG "main: Unknown line from pipe $inline\n";
1194 print STDERR "Unknown line from pipe $inline\n";
1198 close($infd); close($outfd);
1199 $passin[$i] = $passout[$i] = undef;
1203 @passin = grep { defined($_) } @passin;
1204 @passout = grep { defined($_) } @passout;
1207 # handle_request(remoteaddress, localaddress, ipv6-flag)
1208 # Where the real work is done
1211 local ($acptip, $localip, $ipv6) = @_;
1212 print DEBUG "handle_request: from $acptip to $localip ipv6=$ipv6\n";
1213 if ($config{'loghost'}) {
1214 $acpthost = &to_hostname($acptip);
1215 $acpthost = $acptip if (!$acpthost);
1218 $acpthost = $acptip;
1220 $datestr = &http_date(time());
1222 $ok_message = "Document follows";
1223 $logged_code = undef;
1224 $reqline = $request_uri = $page = undef;
1228 # check address against access list
1229 if (@deny && &ip_match($acptip, $localip, @deny) ||
1230 @allow && !&ip_match($acptip, $localip, @allow)) {
1231 &http_error(403, "Access denied for $acptip");
1236 # Check address with TCP-wrappers
1237 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1238 $acptip, STRING_UNKNOWN)) {
1239 &http_error(403, "Access denied for $acptip by TCP wrappers");
1243 print DEBUG "handle_request: passed IP checks\n";
1245 # Compute a timeout for the start of headers, based on the number of
1246 # child processes. As this increases, we use a shorter timeout to avoid
1247 # an attacker overloading the system.
1248 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1250 # Wait at most 60 secs for start of headers for initial requests, or
1251 # 10 minutes for kept-alive connections
1253 vec($rmask, fileno(SOCK), 1) = 1;
1254 local $to = $checked_timeout ? 10*60 : $header_timeout;
1255 local $sel = select($rmask, undef, undef, $to);
1257 if ($checked_timeout) {
1258 print DEBUG "handle_request: exiting due to timeout of $to\n";
1262 &http_error(400, "Timeout",
1263 "Waited for that $to seconds for start of headers");
1267 print DEBUG "handle_request: passed timeout check\n";
1269 # Read the HTTP request and headers
1270 local $origreqline = &read_line();
1271 ($reqline = $origreqline) =~ s/\r|\n//g;
1272 $method = $page = $request_uri = undef;
1273 print DEBUG "handle_request reqline=$reqline\n";
1274 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1275 # An empty request .. just close the connection
1276 print DEBUG "handle_request: rejecting empty request\n";
1279 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1280 print DEBUG "handle_request: invalid reqline=$reqline\n";
1282 # This could be an http request when it should be https
1284 local $url = $config{'musthost'} ?
1285 "https://$config{'musthost'}:$port/" :
1286 "https://$host:$port/";
1287 if ($config{'ssl_redirect'}) {
1288 # Just re-direct to the correct URL
1289 sleep(1); # Give browser a change to finish
1290 # sending its request
1291 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1292 &write_data("Date: $datestr\r\n");
1293 &write_data("Server: $config{'server'}\r\n");
1294 &write_data("Location: $url\r\n");
1295 &write_keep_alive(0);
1296 &write_data("\r\n");
1300 # Tell user the correct URL
1301 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1304 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1305 # This could be an https request when it should be http ..
1306 # need to fake a HTTP response
1309 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1310 eval "Net::SSLeay::load_error_strings()";
1311 $ssl_ctx = Net::SSLeay::CTX_new();
1312 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1313 $ssl_ctx, $config{'keyfile'},
1314 &Net::SSLeay::FILETYPE_PEM);
1315 Net::SSLeay::CTX_use_certificate_file(
1317 $config{'certfile'} || $config{'keyfile'},
1318 &Net::SSLeay::FILETYPE_PEM);
1319 $ssl_con = Net::SSLeay::new($ssl_ctx);
1323 select(SSLw); $| = 1; select(STDOUT);
1324 print SSLw $origreqline;
1326 while(sysread(SOCK, $buf, 1) > 0) {
1333 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1334 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1335 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1337 local $url = $config{'musthost'} ?
1338 "https://$config{'musthost'}:$port/" :
1339 "https://$host:$port/";
1340 if ($config{'ssl_redirect'}) {
1341 # Just re-direct to the correct URL
1342 sleep(1); # Give browser a change to
1343 # finish sending its request
1344 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1345 &write_data("Date: $datestr\r\n");
1346 &write_data("Server: $config{'server'}\r\n");
1347 &write_data("Location: $url\r\n");
1348 &write_keep_alive(0);
1349 &write_data("\r\n");
1353 # Tell user the correct URL
1354 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1358 &http_error(400, "Bad Request");
1362 &http_error(400, "Bad Request");
1366 $request_uri = $page = $2;
1370 ($headline = &read_line()) =~ s/\r|\n//g;
1371 last if ($headline eq "");
1372 print DEBUG "handle_request: got headline $headline\n";
1373 if ($headline =~ /^(\S+):\s*(.*)$/) {
1374 $header{$lastheader = lc($1)} = $2;
1376 elsif ($headline =~ /^\s+(.*)$/) {
1377 $header{$lastheader} .= $headline;
1380 &http_error(400, "Bad Header $headline");
1383 if (defined($header{'host'})) {
1384 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1385 ($host, $port) = ($1, $2);
1388 $host = $header{'host'};
1390 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1391 # Disallowed hostname used
1392 &http_error(400, "Invalid HTTP hostname");
1396 if ($page =~ /^([^\?]+)\?(.*)$/) {
1397 # There is some query string information
1400 print DEBUG "handle_request: querystring=$querystring\n";
1401 if ($querystring !~ /=/) {
1402 $queryargs = $querystring;
1403 $queryargs =~ s/\+/ /g;
1404 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1408 # Parse query-string parameters
1409 local @in = split(/\&/, $querystring);
1411 local ($k, $v) = split(/=/, $i, 2);
1412 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1413 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1418 $posted_data = undef;
1419 if ($method eq 'POST' &&
1420 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1421 # Read in posted query string information, up the configured maximum
1422 # post request length
1423 $clen = $header{"content-length"};
1424 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1425 while(length($posted_data) < $clen_read) {
1426 $buf = &read_data($clen_read - length($posted_data));
1427 if (!length($buf)) {
1428 &http_error(500, "Failed to read POST request");
1430 chomp($posted_data);
1431 $posted_data =~ s/\015$//mg;
1432 $posted_data .= $buf;
1434 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1435 if ($clen_read != $clen && length($posted_data) > $clen) {
1436 # If the client sent more data than we asked for, chop the
1438 $posted_data = substr($posted_data, 0, $clen);
1440 if (length($posted_data) > $clen) {
1441 # When the client sent too much, delay so that it gets headers
1444 if ($header{'user-agent'} =~ /MSIE/ &&
1445 $header{'user-agent'} !~ /Opera/i) {
1446 # MSIE includes an extra newline in the data
1447 $posted_data =~ s/\r|\n//g;
1449 local @in = split(/\&/, $posted_data);
1451 local ($k, $v) = split(/=/, $i, 2);
1453 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1454 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1457 print DEBUG "handle_request: posted_data=$posted_data\n";
1460 # Reject CONNECT request, which isn't supported
1461 if ($method eq "CONNECT") {
1462 &http_error(405, "Method $method is not supported");
1465 # work out accepted encodings
1466 %acceptenc = map { $_, 1 } split(/,/, $header{'accept-encoding'});
1468 # replace %XX sequences in page
1469 $page =~ s/%(..)/pack("c",hex($1))/ge;
1471 # Check if the browser's user agent indicates a mobile device
1472 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1474 # Check if Host: header is for a mobile URL
1475 foreach my $m (@mobile_prefixes) {
1476 if ($header{'host'} =~ /^\Q$m\E/i) {
1481 # check for the logout flag file, and if existant deny authentication
1482 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1483 print DEBUG "handle_request: logout flag set\n";
1484 $deny_authentication++;
1485 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1486 chop($count = <LOGOUT>);
1490 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1491 print LOGOUT "$count\n";
1495 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1499 # check for any redirect for the requested URL
1500 foreach my $pfx (@strip_prefix) {
1501 my $l = length($pfx);
1502 if(length($page) >= $l &&
1503 substr($page,0,$l) eq $pfx) {
1504 $page=substr($page,$l);
1508 $simple = &simplify_path($page, $bogus);
1510 $rpath .= "&".$querystring if (defined($querystring));
1511 $redir = $redirect{$rpath};
1512 if (defined($redir)) {
1513 print DEBUG "handle_request: redir=$redir\n";
1514 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1515 &write_data("Date: $datestr\r\n");
1516 &write_data("Server: $config{'server'}\r\n");
1517 local $ssl = $use_ssl || $config{'inetd_ssl'};
1518 $portstr = $port == 80 && !$ssl ? "" :
1519 $port == 443 && $ssl ? "" : ":$port";
1520 $prot = $ssl ? "https" : "http";
1521 &write_data("Location: $prot://$host$portstr$redir\r\n");
1522 &write_keep_alive(0);
1523 &write_data("\r\n");
1527 # Check for a DAV request
1529 foreach my $d (@davpaths) {
1530 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1535 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1536 &http_error(400, "Bad Request method $method");
1539 # Check for password if needed
1540 if ($config{'userfile'}) {
1541 print DEBUG "handle_request: Need authentication\n";
1545 # Session authentication is never used for connections by
1546 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1547 # or mobile browsers if requested.
1548 if ($header{'user-agent'} =~ /webmin/i ||
1549 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1550 $sessiononly{$simple} || $davpath ||
1551 $simple eq "/xmlrpc.cgi" ||
1552 $acptip eq $config{'host_nosession'} ||
1553 $mobile_device && $config{'mobile_nosession'}) {
1554 print DEBUG "handle_request: Forcing HTTP authentication\n";
1555 $config{'session'} = 0;
1558 # Check for SSL authentication
1559 if ($use_ssl && $verified_client) {
1560 $peername = Net::SSLeay::X509_NAME_oneline(
1561 Net::SSLeay::X509_get_subject_name(
1562 Net::SSLeay::get_peer_certificate(
1564 $u = &find_user_by_cert($peername);
1569 if ($use_syslog && !$validated) {
1570 syslog("crit", "%s",
1571 "Unknown SSL certificate $peername");
1575 if (!$validated && !$deny_authentication) {
1576 # check for IP-based authentication
1578 foreach $a (keys %ipaccess) {
1579 if ($acptip eq $a) {
1580 # It does! Auth as the user
1582 $baseauthuser = $authuser =
1588 # Check for normal HTTP authentication
1589 if (!$validated && !$deny_authentication && !$config{'session'} &&
1590 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1591 # authorization given..
1592 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1593 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1594 local ($vu, $expired, $nonexist) =
1595 &validate_user($authuser, $authpass, $host,
1597 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1598 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1605 if ($use_syslog && !$validated) {
1606 syslog("crit", "%s",
1607 ($nonexist ? "Non-existent" :
1608 $expired ? "Expired" : "Invalid").
1609 " login as $authuser from $acpthost");
1611 if ($authuser =~ /\r|\n|\s/) {
1612 &http_error(500, "Invalid username",
1613 "Username contains invalid characters");
1615 if ($authpass =~ /\r|\n/) {
1616 &http_error(500, "Invalid password",
1617 "Password contains invalid characters");
1620 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1621 # check with main process for delay
1622 print DEBUG "handle_request: about to ask for password delay\n";
1623 print $PASSINw "delay $authuser $acptip $validated\n";
1624 <$PASSOUTr> =~ /(\d+) (\d+)/;
1626 print DEBUG "handle_request: password delay $1 $2\n";
1631 # Check for a visit to the special session login page
1632 if ($config{'session'} && !$deny_authentication &&
1633 $page eq $config{'session_login'}) {
1634 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1635 # Logout clicked .. remove the session
1637 print $PASSINw "delete $sid\n";
1638 local $louser = <$PASSOUTr>;
1641 $already_session_id = undef;
1642 $authuser = $baseauthuser = undef;
1645 syslog("info", "%s", "Logout by $louser from $acpthost");
1647 &run_logout_script($louser, $sid,
1649 &write_logout_utmp($louser, $actphost);
1654 if ($in{'user'} =~ /\r|\n|\s/) {
1655 &http_error(500, "Invalid username",
1656 "Username contains invalid characters");
1658 if ($in{'pass'} =~ /\r|\n/) {
1659 &http_error(500, "Invalid password",
1660 "Password contains invalid characters");
1663 local ($vu, $expired, $nonexist) =
1664 &validate_user($in{'user'}, $in{'pass'}, $host,
1666 local $hrv = &handle_login(
1667 $vu || $in{'user'}, $vu ? 1 : 0,
1668 $expired, $nonexist, $in{'pass'},
1669 $in{'notestingcookie'});
1670 return $hrv if (defined($hrv));
1674 # Check for a visit to the special PAM login page
1675 if ($config{'session'} && !$deny_authentication &&
1676 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1678 # A question has been entered .. submit it to the main process
1679 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1680 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1681 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1682 &http_error(500, "Invalid response",
1683 "Response contains invalid characters");
1687 # Start of a new conversation - answer must be username
1688 $cid = &generate_random_id($in{'answer'});
1689 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1692 # A response to a previous question
1694 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1697 # Read back the response, and the next question (if any)
1698 local $line = <$PASSOUTr>;
1699 $line =~ s/\r|\n//g;
1700 local ($rv, $question) = split(/\s+/, $line, 2);
1703 local $hrv = &handle_login(
1704 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1707 return $hrv if (defined($hrv));
1709 elsif ($rv == 1 || $rv == 3) {
1710 # Another question .. force use of PAM CGI
1713 $querystring .= "&cid=$cid&question=".
1715 $querystring .= "&password=1" if ($rv == 3);
1717 $page = $config{'pam_login'};
1718 $miniserv_internal = 1;
1722 # Got back a final ok or failure
1723 local ($user, $ok, $expired, $nonexist) =
1724 split(/\s+/, $question);
1725 local $hrv = &handle_login(
1726 $user, $ok, $expired, $nonexist, undef,
1727 $in{'notestingcookie'});
1728 return $hrv if (defined($hrv));
1731 # A message from PAM .. tell the user
1734 $querystring .= "&cid=$cid&message=".
1737 $page = $config{'pam_login'};
1738 $miniserv_internal = 1;
1743 # Check for a visit to the special password change page
1744 if ($config{'session'} && !$deny_authentication &&
1745 $page eq $config{'password_change'} && !$validated) {
1746 # Just let this slide ..
1748 $miniserv_internal = 3;
1751 # Check for an existing session
1752 if ($config{'session'} && !$validated) {
1753 if ($already_session_id) {
1754 $session_id = $already_session_id;
1755 $authuser = $already_authuser;
1758 elsif (!$deny_authentication &&
1759 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1760 # Try all session cookies
1761 local $cookie = $header{'cookie'};
1762 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1765 $in{'webmin_notimeout'} ? 1 : 0;
1766 print $PASSINw "verify $session_id $notimeout\n";
1767 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1769 # Valid session continuation
1772 $already_authuser = $authuser;
1781 # Invalid session ID .. don't set
1788 # Check for local authentication
1789 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1790 my $luser = &get_user_details($localauth_user);
1792 # Local user exists in webmin users file
1794 $authuser = $localauth_user;
1797 # Check if local user is allowed by unixauth
1798 local @can = &can_user_login($localauth_user,
1802 $authuser = $localauth_user;
1805 $localauth_user = undef;
1811 # Check if this path allows anonymous access
1813 foreach $a (keys %anonymous) {
1814 if (substr($simple, 0, length($a)) eq $a) {
1815 # It does! Auth as the user, if IP access
1816 # control allows him.
1817 if (&check_user_ip($anonymous{$a}) &&
1818 &check_user_time($anonymous{$a})) {
1820 $baseauthuser = $authuser =
1828 # Check if this path allows unauthenticated access
1829 local ($u, $unauth);
1830 foreach $u (@unauth) {
1831 $unauth++ if ($simple =~ /$u/);
1833 if (!$bogus && $unauth) {
1834 # Unauthenticated directory or file request - approve it
1836 $baseauthuser = $authuser = undef;
1841 if ($blocked == 0) {
1842 # No password given.. ask
1843 if ($config{'pam_conv'} && $use_pam) {
1844 # Force CGI for PAM question, starting with
1845 # the username which is always needed
1848 $querystring .= "&initial=1&question=".
1849 &urlize("Username");
1850 $querystring .= "&failed=$failed_user" if ($failed_user);
1851 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1853 $page = $config{'pam_login'};
1854 $miniserv_internal = 1;
1857 elsif ($config{'session'}) {
1858 # Force CGI for session login
1861 $querystring .= "&logout=1&page=/";
1864 # Re-direct to current module only
1865 local $rpage = $request_uri;
1866 if (!$config{'loginkeeppage'}) {
1867 $rpage =~ s/\?.*$//;
1868 $rpage =~ s/[^\/]+$//
1870 $querystring = "page=".&urlize($rpage);
1873 $querystring .= "&failed=$failed_user" if ($failed_user);
1874 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1876 $page = $config{'session_login'};
1877 $miniserv_internal = 1;
1881 # Ask for login with HTTP authentication
1882 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1883 &write_data("Date: $datestr\r\n");
1884 &write_data("Server: $config{'server'}\r\n");
1885 &write_data("WWW-authenticate: Basic ".
1886 "realm=\"$config{'realm'}\"\r\n");
1887 &write_keep_alive(0);
1888 &write_data("Content-type: text/html; Charset=iso-8859-1\r\n");
1889 &write_data("\r\n");
1890 &reset_byte_count();
1891 &write_data("<html>\n");
1892 &write_data("<head><title>Unauthorized</title></head>\n");
1893 &write_data("<body><h1>Unauthorized</h1>\n");
1894 &write_data("A password is required to access this\n");
1895 &write_data("web server. Please try again. <p>\n");
1896 &write_data("</body></html>\n");
1897 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1901 elsif ($blocked == 1) {
1902 # when the host has been blocked, give it an error
1903 &http_error(403, "Access denied for $acptip. The host ".
1904 "has been blocked because of too ".
1905 "many authentication failures.");
1907 elsif ($blocked == 2) {
1908 # when the user has been blocked, give it an error
1909 &http_error(403, "Access denied. The user ".
1910 "has been blocked because of too ".
1911 "many authentication failures.");
1915 # Get the real Webmin username
1916 local @can = &can_user_login($authuser, undef, $host);
1917 $baseauthuser = $can[3] || $authuser;
1919 if ($config{'remoteuser'} && !$< && $validated) {
1920 # Switch to the UID of the remote user (if he exists)
1921 local @u = getpwnam($authuser);
1922 if (@u && $< != $u[2]) {
1923 $( = $u[3]; $) = "$u[3] $u[3]";
1924 ($>, $<) = ($u[2], $u[2]);
1927 &http_error(500, "Unix user $authuser does not exist");
1933 # Check per-user IP access control
1934 if (!&check_user_ip($baseauthuser)) {
1935 &http_error(403, "Access denied for $acptip for $baseauthuser");
1939 # Check per-user allowed times
1940 if (!&check_user_time($baseauthuser)) {
1941 &http_error(403, "Access denied at the current time");
1945 $uinfo = &get_user_details($baseauthuser);
1947 # Validate the path, and convert to canonical form
1949 $simple = &simplify_path($page, $bogus);
1950 print DEBUG "handle_request: page=$page simple=$simple\n";
1952 &http_error(400, "Invalid path");
1955 # Check for a DAV request
1957 return &handle_dav_request($davpath);
1960 # Work out the active theme(s)
1961 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1962 $config{'mobile_preroot'} :
1963 $authuser && defined($config{'preroot_'.$authuser}) ?
1964 $config{'preroot_'.$authuser} :
1965 $uinfo && defined($uinfo->{'preroot'}) ?
1966 $uinfo->{'preroot'} :
1968 local @preroots = reverse(split(/\s+/, $preroots));
1970 # Canonicalize the directories
1971 foreach my $preroot (@preroots) {
1972 # Always under the current webmin root
1973 $preroot =~ s/^.*\///g;
1974 $preroot = $roots[0].'/'.$preroot;
1977 # Look in the theme root directories first
1978 local ($full, @stfull);
1980 foreach my $preroot (@preroots) {
1983 $full = $preroot.$sofar;
1984 $scriptname = $simple;
1985 foreach $b (split(/\//, $simple)) {
1986 if ($b ne "") { $sofar .= "/$b"; }
1987 $full = $preroot.$sofar;
1988 @stfull = stat($full);
1989 if (!@stfull) { undef($full); last; }
1991 # Check if this is a directory
1993 # It is.. go on parsing
2001 # Check if this is a CGI program
2002 if (&get_type($full) eq "internal/cgi") {
2003 $pathinfo = substr($simple, length($sofar));
2004 $pathinfo .= "/" if ($page =~ /\/$/);
2005 $scriptname = $sofar;
2010 # Don't stop at a directory unless this is the last theme, which
2011 # is the 'real' one that provides the .cgi scripts
2012 if ($is_directory && $preroot ne $preroots[$#preroots]) {
2019 $cgi_pwd = $roots[0];
2021 elsif ($is_directory) {
2022 $cgi_pwd = "$roots[0]$sofar";
2025 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
2028 $foundroot = $preroot;
2029 if ($is_directory) {
2030 # Check for index files in the directory
2032 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2033 $idxfull = "$full/$idx";
2034 local @stidxfull = stat($idxfull);
2035 if (-r _ && !-d _) {
2037 @stfull = @stidxfull;
2040 if ($scriptname ne "/");
2045 @stfull = stat($full) if (!$foundidx);
2048 last if ($foundroot);
2050 print DEBUG "handle_request: initial full=$full\n";
2052 # Look in the real root directories, stopping when we find a file or directory
2053 if (!$full || $is_directory) {
2054 ROOT: foreach $root (@roots) {
2056 $full = $root.$sofar;
2057 $scriptname = $simple;
2058 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
2059 if ($b ne "") { $sofar .= "/$b"; }
2060 $full = $root.$sofar;
2061 @stfull = stat($full);
2066 # Check if this is a directory
2068 # It is.. go on parsing
2072 # Check if this is a CGI program
2073 if (&get_type($full) eq "internal/cgi") {
2074 $pathinfo = substr($simple, length($sofar));
2075 $pathinfo .= "/" if ($page =~ /\/$/);
2076 $scriptname = $sofar;
2081 # Run CGI in the same directory as whatever file
2083 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
2092 if (!@stfull) { &http_error(404, "File not found"); }
2094 print DEBUG "handle_request: full=$full\n";
2095 @stfull = stat($full) if (!@stfull);
2097 # check filename against denyfile regexp
2098 local $denyfile = $config{'denyfile'};
2099 if ($denyfile && $full =~ /$denyfile/) {
2100 &http_error(403, "Access denied to $page");
2104 # Reached the end of the path OK.. see what we've got
2106 # See if the URL ends with a / as it should
2107 print DEBUG "handle_request: found a directory\n";
2108 if ($page !~ /\/$/) {
2109 # It doesn't.. redirect
2110 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2111 $ssl = $use_ssl || $config{'inetd_ssl'};
2112 $portstr = $port == 80 && !$ssl ? "" :
2113 $port == 443 && $ssl ? "" : ":$port";
2114 &write_data("Date: $datestr\r\n");
2115 &write_data("Server: $config{server}\r\n");
2116 $prot = $ssl ? "https" : "http";
2117 &write_data("Location: $prot://$host$portstr$page/\r\n");
2118 &write_keep_alive(0);
2119 &write_data("\r\n");
2120 &log_request($acpthost, $authuser, $reqline, 302, 0);
2123 # A directory.. check for index files
2125 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2126 $idxfull = "$full/$idx";
2127 @stidxfull = stat($idxfull);
2128 if (-r _ && !-d _) {
2131 @stfull = @stidxfull;
2132 $scriptname .= "/" if ($scriptname ne "/");
2137 @stfull = stat($full) if (!$foundidx);
2140 # This is definately a directory.. list it
2141 print DEBUG "handle_request: listing directory\n";
2142 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2143 "Date: $datestr\r\n".
2144 "Server: $config{server}\r\n".
2145 "Content-type: text/html; Charset=iso-8859-1\r\n";
2147 &write_keep_alive(0);
2148 &write_data("\r\n");
2149 &reset_byte_count();
2150 &write_data("<h1>Index of $simple</h1>\n");
2151 &write_data("<pre>\n");
2152 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2153 "Name", "Last Modified", "Size");
2154 &write_data("<hr>\n");
2155 opendir(DIR, $full);
2156 while($df = readdir(DIR)) {
2157 if ($df =~ /^\./) { next; }
2158 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2159 (@stbuf = stat($fulldf)) || next;
2160 if (-d _) { $df .= "/"; }
2161 @tm = localtime($stbuf[9]);
2162 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2163 $tm[3],$tm[4]+1,$tm[5]+1900,
2164 $tm[0],$tm[1],$tm[2];
2165 $len = length($df); $rest = " "x(35-$len);
2167 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2168 $df, $df, $fdate, $stbuf[7]);
2171 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2175 # CGI or normal file
2177 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2178 # A CGI program to execute
2179 print DEBUG "handle_request: executing CGI\n";
2180 $envtz = $ENV{"TZ"};
2181 $envuser = $ENV{"USER"};
2182 $envpath = $ENV{"PATH"};
2183 $envlang = $ENV{"LANG"};
2184 $envroot = $ENV{"SystemRoot"};
2185 $envperllib = $ENV{'PERLLIB'};
2186 foreach my $k (keys %ENV) {
2189 $ENV{"PATH"} = $envpath if ($envpath);
2190 $ENV{"TZ"} = $envtz if ($envtz);
2191 $ENV{"USER"} = $envuser if ($envuser);
2192 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2193 $ENV{"SystemRoot"} = $envroot if ($envroot);
2194 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2195 $ENV{"HOME"} = $user_homedir;
2196 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2197 $ENV{"SERVER_NAME"} = $host;
2198 $ENV{"SERVER_ADMIN"} = $config{"email"};
2199 $ENV{"SERVER_ROOT"} = $roots[0];
2200 $ENV{"SERVER_REALROOT"} = $realroot;
2201 $ENV{"SERVER_PORT"} = $port;
2202 $ENV{"REMOTE_HOST"} = $acpthost;
2203 $ENV{"REMOTE_ADDR"} = $acptip;
2204 $ENV{"REMOTE_ADDR_PROTOCOL"} = $ipv6 ? 6 : 4;
2205 $ENV{"REMOTE_USER"} = $authuser;
2206 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2207 $baseauthuser : undef;
2208 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2209 $config{'pass_password'});
2210 if ($uinfo && $uinfo->{'proto'}) {
2211 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2212 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2214 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2215 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2216 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2217 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2218 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2219 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2220 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2221 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2222 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2223 $ENV{"REQUEST_METHOD"} = $method;
2224 $ENV{"SCRIPT_NAME"} = $scriptname;
2225 $ENV{"SCRIPT_FILENAME"} = $full;
2226 $ENV{"REQUEST_URI"} = $request_uri;
2227 $ENV{"PATH_INFO"} = $pathinfo;
2229 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2230 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2232 $ENV{"QUERY_STRING"} = $querystring;
2233 $ENV{"MINISERV_CONFIG"} = $config_file;
2234 $ENV{"HTTPS"} = $use_ssl || $config{'inetd_ssl'} ? "ON" : "";
2235 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2236 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2237 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2238 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2239 if (defined($header{"content-length"})) {
2240 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2242 if (defined($header{"content-type"})) {
2243 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2245 foreach $h (keys %header) {
2246 ($hname = $h) =~ tr/a-z/A-Z/;
2248 $ENV{"HTTP_$hname"} = $header{$h};
2250 $ENV{"PWD"} = $cgi_pwd;
2251 foreach $k (keys %config) {
2252 if ($k =~ /^env_(\S+)$/) {
2253 $ENV{$1} = $config{$k};
2256 delete($ENV{'HTTP_AUTHORIZATION'});
2257 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2258 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2260 # Check if the CGI can be handled internally
2262 local $first = <CGI>;
2264 $first =~ s/[#!\r\n]//g;
2265 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2267 if (!$config{'forkcgis'} &&
2268 ($first eq $perl_path || $first eq $linked_perl_path) &&
2270 $config{'internalcgis'}) {
2271 # setup environment for eval
2273 @ARGV = split(/\s+/, $queryargs);
2276 # Already read the post input
2277 $postinput = $posted_data;
2279 $clen = $header{"content-length"};
2280 $SIG{'CHLD'} = 'DEFAULT';
2282 # Have SOCK closed if the perl exec's something
2284 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2288 if ($config{'log'}) {
2289 open(MINISERVLOG, ">>$config{'logfile'}");
2290 if ($config{'logperms'}) {
2291 chmod(oct($config{'logperms'}),
2292 $config{'logfile'});
2295 chmod(0600, $config{'logfile'});
2298 $doing_cgi_eval = 1;
2299 $main_process_id = $$;
2301 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2302 # Eval in package from Webmin module name
2304 $pkg =~ s/[^A-Za-z0-9]/_/g;
2309 tie(*STDOUT, 'miniserv');
2310 tie(*STDIN, 'miniserv');
2311 do \$miniserv::full;
2314 $doing_cgi_eval = 0;
2317 &http_error(500, "Perl execution failed",
2318 $config{'noshowstderr'} ? undef : $@);
2320 elsif (!$doneheaders && !$nph_script) {
2321 &http_error(500, "Missing Headers");
2328 # fork the process that actually executes the CGI
2329 pipe(CGIINr, CGIINw);
2330 pipe(CGIOUTr, CGIOUTw);
2331 pipe(CGIERRr, CGIERRw);
2332 if (!($cgipid = fork())) {
2333 @execargs = ( $full, split(/\s+/, $queryargs) );
2336 open(STDIN, "<&CGIINr");
2337 open(STDOUT, ">&CGIOUTw");
2338 open(STDERR, ">&CGIERRw");
2339 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2341 die "Failed to exec $full : $!\n";
2344 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2347 # write CGI input to a temp file
2348 $infile = "$config{'tempbase'}.$$";
2349 open(CGIINw, ">$infile");
2350 # NOT binary mode, as CGIs don't read in it!
2355 # already read the posted data
2356 print CGIINw $posted_data;
2358 $clen = $header{"content-length"};
2359 if ($method eq "POST" && $clen_read < $clen) {
2360 $SIG{'PIPE'} = 'IGNORE';
2362 while($got < $clen) {
2363 $buf = &read_data($clen-$got);
2364 if (!length($buf)) {
2365 kill('TERM', $cgipid);
2366 unlink($infile) if ($infile);
2367 &http_error(500, "Failed to read ".
2370 $got += length($buf);
2371 local ($wrote) = (print CGIINw $buf);
2374 # If the CGI terminated early, we still need to read
2375 # from the browser and throw away
2376 while($got < $clen) {
2377 $buf = &read_data($clen-$got);
2378 if (!length($buf)) {
2379 kill('TERM', $cgipid);
2380 unlink($infile) if ($infile);
2381 &http_error(500, "Failed to read ".
2384 $got += length($buf);
2386 $SIG{'PIPE'} = 'DEFAULT';
2392 # Run the CGI program, and feed it input
2394 local $qqueryargs = join(" ", map { "\"$_\"" }
2395 split(/\s+/, $queryargs));
2396 if ($first =~ /(perl|perl.exe)$/i) {
2397 # On Windows, run with Perl
2398 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2401 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2407 # read back cgi headers
2408 select(CGIOUTr); $|=1; select(STDOUT);
2412 $line =~ s/\r|\n//g;
2414 if ($got_blank || %cgiheader) { last; }
2418 if ($line !~ /^(\S+):\s+(.*)$/) {
2419 $errs = &read_errors(CGIERRr);
2420 close(CGIOUTr); close(CGIERRr);
2421 unlink($infile) if ($infile);
2422 &http_error(500, "Bad Header", $errs);
2424 $cgiheader{lc($1)} = $2;
2425 push(@cgiheader, [ $1, $2 ]);
2427 if ($cgiheader{"location"}) {
2428 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2429 &write_data("Date: $datestr\r\n");
2430 &write_data("Server: $config{'server'}\r\n");
2431 &write_keep_alive(0);
2432 # ignore the rest of the output. This is a hack,
2433 # but is necessary for IE in some cases :(
2434 close(CGIOUTr); close(CGIERRr);
2436 elsif ($cgiheader{"content-type"} eq "") {
2437 close(CGIOUTr); close(CGIERRr);
2438 unlink($infile) if ($infile);
2439 $errs = &read_errors(CGIERRr);
2440 &http_error(500, "Missing Content-Type Header",
2441 $config{'noshowstderr'} ? undef : $errs);
2444 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2445 &write_data("Date: $datestr\r\n");
2446 &write_data("Server: $config{'server'}\r\n");
2447 &write_keep_alive(0);
2449 foreach $h (@cgiheader) {
2450 &write_data("$h->[0]: $h->[1]\r\n");
2452 &write_data("\r\n");
2454 &reset_byte_count();
2455 while($line = <CGIOUTr>) {
2460 unlink($infile) if ($infile);
2466 print DEBUG "handle_request: outputting file $full\n";
2467 $gzfile = $full.".gz";
2469 if ($config{'gzip'} ne '0' && -r $gzfile && $acceptenc{'gzip'}) {
2470 # Using gzipped version
2471 @stopen = stat($gzfile);
2472 if ($stopen[9] >= $stfull[9] && open(FILE, $gzfile)) {
2473 print DEBUG "handle_request: using gzipped $gzfile\n";
2478 # Using original file
2480 open(FILE, $full) || &http_error(404, "Failed to open file");
2484 # Build common headers
2485 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2486 "Date: $datestr\r\n".
2487 "Server: $config{server}\r\n".
2488 "Content-type: ".&get_type($full)."\r\n".
2489 "Last-Modified: ".&http_date($stopen[9])."\r\n".
2491 &http_date(time()+&get_expires_time($simple))."\r\n";
2493 if (!$gzipped && $use_gzip && $acceptenc{'gzip'} &&
2494 &should_gzip_file($full)) {
2495 # Load and compress file, then output
2496 print DEBUG "handle_request: outputting gzipped file $full\n";
2497 open(FILE, $full) || &http_error(404, "Failed to open file");
2503 @stopen = stat($file);
2504 $data = Compress::Zlib::memGzip($data);
2505 $resp .= "Content-length: ".length($data)."\r\n".
2506 "Content-Encoding: gzip\r\n";
2508 $rv = &write_keep_alive();
2509 &write_data("\r\n");
2510 &reset_byte_count();
2514 # Stream file output
2515 $resp .= "Content-length: $stopen[7]\r\n";
2516 $resp .= "Content-Encoding: gzip\r\n" if ($gzipped);
2518 $rv = &write_keep_alive();
2519 &write_data("\r\n");
2520 &reset_byte_count();
2521 my $bufsize = $config{'bufsize'} || 1024;
2522 while(read(FILE, $buf, $bufsize) > 0) {
2530 &log_request($acpthost, $authuser, $reqline,
2531 $logged_code ? $logged_code :
2532 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2536 # http_error(code, message, body, [dontexit])
2539 local $eh = $error_handler_recurse ? undef :
2540 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2541 $config{'error_handler'} ? $config{'error_handler'} : undef;
2542 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2544 # Call a CGI program for the error
2546 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2547 "&body=".&urlize($_[2]);
2548 $error_handler_recurse++;
2550 $ok_message = $_[1];
2554 # Use the standard error message display
2555 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2556 &write_data("Server: $config{server}\r\n");
2557 &write_data("Date: $datestr\r\n");
2558 &write_data("Content-type: text/html; Charset=iso-8859-1\r\n");
2559 &write_keep_alive(0);
2560 &write_data("\r\n");
2561 &reset_byte_count();
2562 &write_data("<h1>Error - $_[1]</h1>\n");
2564 &write_data("<pre>$_[2]</pre>\n");
2567 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2569 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2576 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2582 return "text/plain";
2585 # simplify_path(path, bogus)
2586 # Given a path, maybe containing stuff like ".." and "." convert it to a
2587 # clean, absolute form.
2590 local($dir, @bits, @fixedbits, $b);
2592 $dir =~ s/\\/\//g; # fix windows \ in path
2595 $dir =~ s/\0//g; # remove null bytes
2596 @bits = split(/\/+/, $dir);
2599 foreach $b (@bits) {
2603 elsif ($b eq ".." || $b eq "...") {
2605 if (scalar(@fixedbits) == 0) {
2613 push(@fixedbits, $b);
2616 return "/" . join('/', @fixedbits);
2620 # Converts a string from base64 format to normal
2623 local($str) = $_[0];
2625 $str =~ tr|A-Za-z0-9+=/||cd;
2627 $str =~ tr|A-Za-z0-9+/| -_|;
2628 while ($str =~ /(.{1,60})/gs) {
2629 my $len = chr(32 + length($1)*3/4);
2630 $res .= unpack("u", $len . $1 );
2635 # ip_match(remoteip, localip, [match]+)
2636 # Checks an IP address against a list of IPs, networks and networks/masks
2639 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2640 @io = &check_ip6address($_[0]) ? split(/:/, $_[0])
2641 : split(/\./, $_[0]);
2642 for($i=2; $i<@_; $i++) {
2643 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2645 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2646 # Reverse-lookup hostname if any rules match based on it
2647 $hn = &to_hostname($_[0]);
2648 if (&check_ip6address($_[0])) {
2649 $hn = "" if (&to_ip6address($hn) ne $_[0]);
2652 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2654 $ip_match_cache{$_[0]} = $hn;
2656 for($i=2; $i<@_; $i++) {
2657 local $mismatch = 0;
2658 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2659 # Convert CIDR to netmask format
2660 $_[$i] = $1."/".&prefix_to_mask($2);
2662 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2663 # Compare with IPv4 network/mask
2664 @mo = split(/\./, $1); @ms = split(/\./, $2);
2665 for($j=0; $j<4; $j++) {
2666 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2671 elsif ($_[$i] =~ /^\*(\S+)$/) {
2672 # Compare with hostname regexp
2673 $mismatch = 1 if ($hn !~ /$1$/);
2675 elsif ($_[$i] eq 'LOCAL' && &check_ipaddress($_[1])) {
2676 # Compare with local IPv4 network
2677 local @lo = split(/\./, $_[1]);
2679 $mismatch = 1 if ($lo[0] != $io[0]);
2681 elsif ($lo[0] < 192) {
2682 $mismatch = 1 if ($lo[0] != $io[0] ||
2686 $mismatch = 1 if ($lo[0] != $io[0] ||
2691 elsif ($_[$i] eq 'LOCAL' && &check_ip6address($_[1])) {
2692 # Compare with local IPv6 network, which is always first 4 words
2693 local @lo = split(/:/, $_[1]);
2694 for(my $i=0; $i<4; $i++) {
2695 $mismatch = 1 if ($lo[$i] ne $io[$i]);
2698 elsif ($_[$i] =~ /^[0-9\.]+$/) {
2699 # Compare with IPv4 address or network
2700 @mo = split(/\./, $_[$i]);
2701 while(@mo && !$mo[$#mo]) { pop(@mo); }
2702 for($j=0; $j<@mo; $j++) {
2703 if ($mo[$j] != $io[$j]) {
2708 elsif ($_[$i] =~ /^[a-f0-9:]+$/) {
2709 # Compare with IPv6 address or network
2710 @mo = split(/:/, $_[$i]);
2711 while(@mo && !$mo[$#mo]) { pop(@mo); }
2712 for($j=0; $j<@mo; $j++) {
2713 if ($mo[$j] ne $io[$j]) {
2718 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2719 # Compare with hostname
2720 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2722 return 1 if (!$mismatch);
2727 # users_match(&uinfo, user, ...)
2728 # Returns 1 if a user is in a list of users and groups
2731 local $uinfo = shift(@_);
2733 local @ginfo = getgrgid($uinfo->[3]);
2735 if ($u =~ /^\@(\S+)$/) {
2736 return 1 if (&is_group_member($uinfo, $1));
2738 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2739 return (!$1 || $uinfo[2] >= $1) &&
2740 (!$2 || $uinfo[2] <= $2);
2743 return 1 if ($u eq $uinfo->[0]);
2749 # restart_miniserv()
2750 # Called when a SIGHUP is received to restart the web server. This is done
2751 # by exec()ing perl with the same command line as was originally used
2752 sub restart_miniserv
2754 print STDERR "restarting miniserv\n";
2755 &log_error("Restarting");
2757 &close_all_sockets();
2759 dbmclose(%sessiondb);
2760 kill('KILL', $logclearer) if ($logclearer);
2761 kill('KILL', $extauth) if ($extauth);
2762 exec($perl_path, $miniserv_path, @miniserv_argv);
2763 die "Failed to restart miniserv with $perl_path $miniserv_path";
2776 # to_ipaddress(address, ...)
2781 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2782 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2783 # A pattern or IP, not a hostname, so don't change
2788 push(@rv, join('.', unpack("CCCC", inet_aton($i))));
2791 return wantarray ? @rv : $rv[0];
2794 # to_ip6address(address, ...)
2799 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2800 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2801 # A pattern, not a hostname, so don't change
2805 # Lookup IPv6 address
2806 local ($inaddr, $addr);
2807 (undef, undef, undef, $inaddr) =
2808 getaddrinfo($i, undef, Socket6::AF_INET6(), SOCK_STREAM);
2813 (undef, $addr) = unpack_sockaddr_in6($inaddr);
2814 push(@rv, inet_ntop(Socket6::AF_INET6(), $addr));
2818 return wantarray ? @rv : $rv[0];
2821 # to_hostname(ipv4|ipv6-address)
2822 # Reverse-resolves an IPv4 or 6 address to a hostname
2826 if (&check_ip6address($_[0])) {
2827 return gethostbyaddr(inet_pton(Socket6::AF_INET6(), $addr),
2828 Socket6::AF_INET6());
2831 return gethostbyaddr(inet_aton($addr), AF_INET);
2835 # read_line(no-wait, no-limit)
2836 # Reads one line from SOCK or SSL
2839 local ($nowait, $nolimit) = @_;
2840 local($idx, $more, $rv);
2841 while(($idx = index($main::read_buffer, "\n")) < 0) {
2842 if (length($main::read_buffer) > 10000 && !$nolimit) {
2843 &http_error(414, "Request too long",
2844 "Received excessive line <pre>$main::read_buffer</pre>");
2847 # need to read more..
2848 &wait_for_data_error() if (!$nowait);
2850 $more = Net::SSLeay::read($ssl_con);
2853 my $bufsize = $config{'bufsize'} || 1024;
2854 local $ok = sysread(SOCK, $more, $bufsize);
2855 $more = undef if ($ok <= 0);
2859 $rv = $main::read_buffer;
2860 undef($main::read_buffer);
2863 $main::read_buffer .= $more;
2865 $rv = substr($main::read_buffer, 0, $idx+1);
2866 $main::read_buffer = substr($main::read_buffer, $idx+1);
2871 # Reads up to some amount of data from SOCK or the SSL connection
2875 if (length($main::read_buffer)) {
2876 if (length($main::read_buffer) > $_[0]) {
2877 # Return the first part of the buffer
2878 $rv = substr($main::read_buffer, 0, $_[0]);
2879 $main::read_buffer = substr($main::read_buffer, $_[0]);
2883 # Return the whole buffer
2884 $rv = $main::read_buffer;
2885 undef($main::read_buffer);
2890 # Call SSL read function
2891 return Net::SSLeay::read($ssl_con, $_[0]);
2894 # Just do a normal read
2896 sysread(SOCK, $buf, $_[0]) || return undef;
2902 # Read a line from a file handle, using sysread to get a byte at a time
2909 $got = sysread($fh, $buf, 1);
2910 last if ($got <= 0);
2912 last if ($buf eq "\n");
2917 # wait_for_data(secs)
2918 # Waits at most the given amount of time for some data on SOCK, returning
2919 # 0 if not found, 1 if some arrived.
2923 vec($rmask, fileno(SOCK), 1) = 1;
2924 local $got = select($rmask, undef, undef, $_[0]);
2925 return $got == 0 ? 0 : 1;
2928 # wait_for_data_error()
2929 # Waits 60 seconds for data on SOCK, and fails if none arrives
2930 sub wait_for_data_error
2932 local $got = &wait_for_data(60);
2934 &http_error(400, "Timeout",
2935 "Waited more than 60 seconds for request data");
2939 # write_data(data, ...)
2940 # Writes a string to SOCK or the SSL connection
2943 local $str = join("", @_);
2945 Net::SSLeay::write($ssl_con, $str);
2948 syswrite(SOCK, $str, length($str));
2950 # Intentionally introduce a small delay to avoid problems where IE reports
2951 # the page as empty / DNS failed when it get a large response too quickly!
2952 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2953 $write_data_count += length($str);
2956 # reset_byte_count()
2957 sub reset_byte_count { $write_data_count = 0; }
2960 sub byte_count { return $write_data_count; }
2962 # log_request(hostname, user, request, code, bytes)
2965 if ($config{'log'}) {
2966 local ($user, $ident, $headers);
2967 if ($config{'logident'}) {
2968 # add support for rfc1413 identity checking here
2970 else { $ident = "-"; }
2971 $user = $_[1] ? $_[1] : "-";
2972 local $dstr = &make_datestr();
2973 if (fileno(MINISERVLOG)) {
2974 seek(MINISERVLOG, 0, 2);
2977 open(MINISERVLOG, ">>$config{'logfile'}");
2978 chmod(0600, $config{'logfile'});
2980 if (defined($config{'logheaders'})) {
2981 foreach $h (split(/\s+/, $config{'logheaders'})) {
2982 $headers .= " $h=\"$header{$h}\"";
2985 elsif ($config{'logclf'}) {
2986 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2991 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2992 "$_[3] $_[4]$headers\n";
3000 local @tm = localtime(time());
3001 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
3002 $tm[3], $month[$tm[4]], $tm[5]+1900,
3003 $tm[2], $tm[1], $tm[0], $timezone;
3006 # log_error(message)
3010 print STDERR "[",&make_datestr(),"] ",
3011 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
3012 $page ? ( $page," : " ) : ( ),
3016 # read_errors(handle)
3017 # Read and return all input from some filehandle
3020 local($fh, $_, $rv);
3022 while(<$fh>) { $rv .= $_; }
3026 sub write_keep_alive
3029 if ($config{'nokeepalive'}) {
3030 # Keep alives have been disabled in config
3033 elsif (@childpids > $config{'maxconns'}*.8) {
3034 # Disable because nearing process limit
3038 # Keep alive specified by caller
3042 # Keep alive determined by browser
3043 $mode = $header{'connection'} =~ /keep-alive/i;
3045 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
3051 kill('TERM', @childpids) if (@childpids);
3052 kill('KILL', $logclearer) if ($logclearer);
3053 kill('KILL', $extauth) if ($extauth);
3059 local @tm = gmtime($_[0]);
3060 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
3061 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
3062 $tm[2], $tm[1], $tm[0];
3067 my $i; bless \$i, shift;
3073 my($buf,$len,$offset) = @_;
3074 &write_to_sock(substr($buf, $offset, $len));
3075 $miniserv::page_capture_out .= substr($buf, $offset, $len)
3076 if ($miniserv::page_capture);
3083 my $buf = join(defined($,) ? $, : "", @_);
3084 $buf .= $\ if defined($\);
3085 &write_to_sock($buf);
3086 $miniserv::page_capture_out .= $buf
3087 if ($miniserv::page_capture);
3094 my $buf = sprintf $fmt, @_;
3095 &write_to_sock($buf);
3096 $miniserv::page_capture_out .= $buf
3097 if ($miniserv::page_capture);
3100 # Send back already read data while we have it, then read from SOCK
3104 my $bufref = \$_[0];
3107 if ($postpos < length($postinput)) {
3108 # Reading from already fetched array
3109 my $left = length($postinput) - $postpos;
3110 my $canread = $len > $left ? $left : $len;
3111 substr($$bufref, $offset, $canread) =
3112 substr($postinput, $postpos, $canread);
3113 $postpos += $canread;
3117 # Read from network socket
3118 local $data = &read_data($len);
3119 if ($data eq '' && $len) {
3121 print STDERR "finished reading - shutting down socket\n";
3124 substr($$bufref, $offset, length($data)) = $data;
3125 return length($data);
3131 #print STDERR "open() called - should never happen!\n";
3134 # Read a line of input
3138 if ($postpos < length($postinput) &&
3139 ($idx = index($postinput, "\n", $postpos)) >= 0) {
3140 # A line exists in the memory buffer .. use it
3141 my $line = substr($postinput, $postpos, $idx-$postpos+1);
3146 # Need to read from the socket
3148 if ($postpos < length($postinput)) {
3149 # Start with in-memory data
3150 $line = substr($postinput, $postpos);
3151 $postpos = length($postinput);
3153 my $nl = &read_line(0, 1);
3156 print STDERR "finished reading - shutting down socket\n";
3159 $line .= $nl if (defined($nl));
3164 # Read one character of input
3169 my $got = READ($r, \$buf, 1, 0);
3170 return $got > 0 ? $buf : undef;
3175 return fileno(SOCK);
3182 # write_to_sock(data, ...)
3187 if ($doneheaders || $miniserv::nph_script) {
3192 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
3193 if ($1 =~ /^(\S+):\s+(.*)$/) {
3194 $cgiheader{lc($1)} = $2;
3195 push(@cgiheader, [ $1, $2 ]);
3197 elsif ($1 !~ /\S/) {
3201 &http_error(500, "Bad Header");
3205 if ($cgiheader{"location"}) {
3207 "HTTP/1.0 302 Moved Temporarily\r\n");
3208 &write_data("Date: $datestr\r\n");
3209 &write_data("Server: $config{server}\r\n");
3210 &write_keep_alive(0);
3212 elsif ($cgiheader{"content-type"} eq "") {
3213 &http_error(500, "Missing Content-Type Header");
3216 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3217 &write_data("Date: $datestr\r\n");
3218 &write_data("Server: $config{server}\r\n");
3219 &write_keep_alive(0);
3221 foreach $h (@cgiheader) {
3222 &write_data("$h->[0]: $h->[1]\r\n");
3224 &write_data("\r\n");
3225 &reset_byte_count();
3226 &write_data($headers);
3234 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3236 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3237 $verified_client = 1 if (!$errnum);
3244 if ($doing_cgi_eval && $$ == $main_process_id) {
3245 # A CGI program called exit! This is a horrible hack to
3246 # finish up before really exiting
3249 close($PASSINw); close($PASSOUTw);
3250 &log_request($acpthost, $authuser, $reqline,
3251 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3256 # Convert a string to a form ok for putting in a URL
3258 local($tmp, $tmp2, $c);
3261 while(($c = chop($tmp)) ne "") {
3262 if ($c !~ /[A-z0-9]/) {
3263 $c = sprintf("%%%2.2X", ord($c));
3270 # validate_user(username, password, host, remote-ip, webmin-port)
3271 # Checks if some username and password are valid. Returns the modified username,
3272 # the expired / temp pass flag, and the non-existence flag
3275 local ($user, $pass, $host, $actpip, $port) = @_;
3276 return ( ) if (!$user);
3277 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3278 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3279 &can_user_login($user, undef, $host);
3280 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3282 # User doesn't even exist, so go no further
3283 return ( undef, 0, 1 );
3285 elsif ($canmode == 0) {
3286 # User does exist but cannot login
3287 return ( $canuser, 0, 0 );
3289 elsif ($canmode == 1) {
3290 # Attempt Webmin authentication
3291 my $uinfo = &get_user_details($webminuser);
3293 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3294 # Password is valid .. but check for expiry
3295 local $lc = $uinfo->{'lastchanges'};
3296 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3297 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3298 local $daysold = (time() - $lc)/(24*60*60);
3299 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3300 if ($config{'pass_lockdays'} &&
3301 $daysold > $config{'pass_lockdays'}) {
3302 # So old that the account is locked
3303 return ( undef, 0, 0 );
3305 elsif ($daysold > $config{'pass_maxdays'}) {
3306 # Password has expired
3307 return ( $user, 1, 0 );
3310 if ($uinfo->{'temppass'}) {
3311 # Temporary password - force change now
3312 return ( $user, 2, 0 );
3314 return ( $user, 0, 0 );
3317 print DEBUG "validate_user: User $webminuser not found\n";
3318 return ( undef, 0, 0 );
3321 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3322 return ( undef, 0, 0 );
3325 elsif ($canmode == 2 || $canmode == 3) {
3326 # Attempt PAM or passwd file authentication
3327 local $val = &validate_unix_user($canuser, $pass, $acptip, $port);
3328 print DEBUG "validate_user: unix val=$val\n";
3329 if ($val && $sudo) {
3330 # Need to check if this Unix user can sudo
3331 if (!&check_sudo_permissions($canuser, $pass)) {
3332 print DEBUG "validate_user: sudo failed\n";
3336 print DEBUG "validate_user: sudo passed\n";
3339 return $val == 2 ? ( $canuser, 1, 0 ) :
3340 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3342 elsif ($canmode == 4) {
3343 # Attempt external authentication
3344 return &validate_external_user($canuser, $pass) ?
3345 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3353 # validate_unix_user(user, password, remote-ip, local-port)
3354 # Returns 1 if a username and password are valid under unix, 0 if not,
3355 # or 2 if the account has expired.
3356 # Checks PAM if available, and falls back to reading the system password
3358 sub validate_unix_user
3362 $pam_username = $_[0];
3363 $pam_password = $_[1];
3364 eval "use Authen::PAM;";
3365 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3368 $pamh->pam_set_item("PAM_RHOST", $_[2]) if ($_[2]);
3369 $pamh->pam_set_item("PAM_TTY", $_[3]) if ($_[3]);
3370 local $pam_ret = $pamh->pam_authenticate();
3371 if ($pam_ret == PAM_SUCCESS()) {
3372 # Logged in OK .. make sure password hasn't expired
3373 local $acct_ret = $pamh->pam_acct_mgmt();
3374 if ($acct_ret == PAM_SUCCESS()) {
3375 $pamh->pam_open_session();
3378 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3379 $acct_ret == PAM_ACCT_EXPIRED()) {
3383 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3390 elsif ($config{'pam_only'}) {
3391 # Pam is not available, but configuration forces it's use!
3394 elsif ($config{'passwd_file'}) {
3395 # Check in a password file
3397 open(FILE, $config{'passwd_file'});
3398 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3399 # Assume in AIX format
3402 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3404 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3405 $rv = $1 eq &password_crypt($_[1], $1) ?
3413 # Read the system password or shadow file
3415 local @l = split(/:/, $_, -1);
3416 local $u = $l[$config{'passwd_uindex'}];
3417 local $p = $l[$config{'passwd_pindex'}];
3419 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3420 if ($config{'passwd_cindex'} ne '' && $rv) {
3421 # Password may have expired!
3422 local $c = $l[$config{'passwd_cindex'}];
3423 local $m = $l[$config{'passwd_mindex'}];
3424 local $day = time()/(24*60*60);
3425 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3431 if ($p eq "" && $config{'passwd_blank'}) {
3432 # Force password change
3440 return $rv if ($rv);
3443 # Fallback option - check password returned by getpw*
3444 local @uinfo = getpwnam($_[0]);
3445 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3449 return 0; # Totally failed
3452 # validate_external_user(user, pass)
3453 # Validate a user by passing the username and password to an external
3454 # squid-style authentication program
3455 sub validate_external_user
3457 return 0 if (!$config{'extauth'});
3459 local $str = "$_[0] $_[1]\n";
3460 syswrite(EXTAUTH, $str, length($str));
3461 local $resp = <EXTAUTH>;
3463 return $resp =~ /^OK/i ? 1 : 0;
3466 # can_user_login(username, no-append, host)
3467 # Checks if a user can login or not.
3468 # First return value is the username.
3469 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3470 # file, 4 if external.
3471 # Third is 1 if the user does not exist at all, 0 if he does.
3472 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3473 # Fifth is a flag indicating if a sudo check is needed.
3476 local $uinfo = &get_user_details($_[0]);
3478 # See if this user exists in Unix and can be validated by the same
3479 # method as the unixauth webmin user
3480 local $realuser = $unixauth{$_[0]};
3484 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3485 if (!$realuser && @uinfo) {
3486 # No unixauth entry for the username .. try his groups
3487 foreach my $ua (keys %unixauth) {
3488 if ($ua =~ /^\@(.*)$/) {
3489 if (&is_group_member(\@uinfo, $1)) {
3490 $realuser = $unixauth{$ua};
3496 if (!$realuser && @uinfo) {
3497 # Fall back to unix auth for all Unix users
3498 $realuser = $unixauth{"*"};
3500 if (!$realuser && $use_sudo && @uinfo) {
3501 # Allow login effectively as root, if sudo permits it
3505 if (!$realuser && !@uinfo && $config{'pamany'}) {
3506 # If the user completely doesn't exist, we can still allow
3507 # him to authenticate via PAM
3508 $realuser = $config{'pamany'};
3512 # For Usermin, always fall back to unix auth for any user,
3513 # so that later checks with domain added / removed are done.
3514 $realuser = $unixauth{"*"};
3516 return (undef, 0, 1, undef) if (!$realuser);
3517 local $uinfo = &get_user_details($realuser);
3518 return (undef, 0, 1, undef) if (!$uinfo);
3519 local $up = $uinfo->{'pass'};
3521 # Work out possible domain names from the hostname
3522 local @doms = ( $_[2] );
3523 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3527 if ($config{'user_mapping'} && !%user_mapping) {
3528 # Read the user mapping file
3530 open(MAPPING, $config{'user_mapping'});
3534 if (/^(\S+)\s+(\S+)/) {
3535 if ($config{'user_mapping_reverse'}) {
3536 $user_mapping{$1} = $2;
3539 $user_mapping{$2} = $1;
3546 # Check the user mapping file to see if there is an entry for the
3547 # user login in which specifies a new effective user
3549 foreach my $d (@doms) {
3550 $um ||= $user_mapping{"$_[0]\@$d"};
3552 $um ||= $user_mapping{$_[0]};
3553 if (defined($um) && ($_[1]&4) == 0) {
3554 # A mapping exists - use it!
3555 return &can_user_login($um, $_[1]+4, $_[2]);
3558 # Check if a user with the entered login and the domains appended
3559 # or prepended exists, and if so take it to be the effective user
3560 if (!@uinfo && $config{'domainuser'}) {
3561 # Try again with name.domain and name.firstpart
3562 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3563 if (($_[1]&1) == 0) {
3565 foreach $a (@firsts, @doms) {
3566 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3567 "${a}.$_[0]", "${a}-$_[0]",
3568 "$_[0]_${a}", "${a}_$_[0]") {
3569 local @vu = &can_user_login(
3570 $p, $_[1]+1, $_[2]);
3571 return @vu if ($vu[1]);
3577 # Check if the user entered a domain at the end of his username when
3578 # he really shouldn't have, and if so try without it
3579 if (!@uinfo && $config{'domainstrip'} &&
3580 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3581 local ($stripped, $dom) = ($1, $2);
3582 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3583 return @vu if ($vu[1]);
3584 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3585 return @vu if ($vu[1]);
3588 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3591 if (scalar(@allowusers)) {
3592 # Only allow people on the allow list
3593 return ( undef, 0, 0, undef )
3594 if (!&users_match(\@uinfo, @allowusers));
3596 elsif (scalar(@denyusers)) {
3597 # Disallow people on the deny list
3598 return ( undef, 0, 0, undef )
3599 if (&users_match(\@uinfo, @denyusers));
3601 if ($config{'shells_deny'}) {
3603 open(SHELLS, $config{'shells_deny'});
3607 $found++ if ($_ eq $uinfo[8]);
3610 return ( undef, 0, 0, undef ) if (!$found);
3615 # PAM or passwd file authentication
3616 print DEBUG "can_user_login: Validate with PAM\n";
3617 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3619 elsif ($up eq 'e') {
3620 # External authentication
3621 print DEBUG "can_user_login: Validate externally\n";
3622 return ( $_[0], 4, 0, $realuser, $sudo );
3625 # Fixed Webmin password
3626 print DEBUG "can_user_login: Validate by Webmin\n";
3627 return ( $_[0], 1, 0, $realuser, $sudo );
3630 elsif ($uinfo->{'pass'} eq 'x') {
3631 # Webmin user authenticated via PAM or password file
3632 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3634 elsif ($uinfo->{'pass'} eq 'e') {
3635 # Webmin user authenticated externally
3636 return ( $_[0], 4, 0, $_[0] );
3639 # Normal Webmin user
3640 return ( $_[0], 1, 0, $_[0] );
3644 # the PAM conversation function for interactive logins
3647 $pam_conv_func_called++;
3654 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3655 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3657 push @res, PAM_SUCCESS();
3660 push @res, PAM_SUCCESS();
3669 # get_socket_ip(handle, ipv6-flag)
3670 # Returns the local IP address of some connection, as both a string and in
3674 local ($fh, $ipv6) = @_;
3675 local $sn = getsockname($fh);
3676 return undef if (!$sn);
3677 return &get_address_ip($sn, $ipv6);
3680 # get_address_ip(address, ipv6-flag)
3681 # Given a sockaddr object in binary format, return the binary address, text
3682 # address and port number
3685 local ($sn, $ipv6) = @_;
3687 local ($p, $b) = unpack_sockaddr_in6($sn);
3688 return ($b, inet_ntop(Socket6::AF_INET6(), $b), $p);
3691 local ($p, $b) = unpack_sockaddr_in($sn);
3692 return ($b, inet_ntoa($b), $p);
3696 # get_socket_name(handle, ipv6-flag)
3697 # Returns the local hostname or IP address of some connection
3700 local ($fh, $ipv6) = @_;
3701 return $config{'host'} if ($config{'host'});
3702 local ($mybin, $myaddr) = &get_socket_ip($fh, $ipv6);
3703 if (!$get_socket_name_cache{$myaddr}) {
3705 if (!$config{'no_resolv_myname'}) {
3706 $myname = gethostbyaddr($mybin,
3707 $ipv6 ? Socket6::AF_INET6() : AF_INET);
3709 $myname ||= $myaddr;
3710 $get_socket_name_cache{$myaddr} = $myname;
3712 return $get_socket_name_cache{$myaddr};
3715 # run_login_script(username, sid, remoteip, localip)
3716 sub run_login_script
3718 if ($config{'login_script'}) {
3720 $SIG{'ALRM'} = sub { die "timeout" };
3722 system($config{'login_script'}.
3723 " ".join(" ", map { quotemeta($_) || '""' } @_).
3724 " >/dev/null 2>&1 </dev/null");
3730 # run_logout_script(username, sid, remoteip, localip)
3731 sub run_logout_script
3733 if ($config{'logout_script'}) {
3735 $SIG{'ALRM'} = sub { die "timeout" };
3737 system($config{'logout_script'}.
3738 " ".join(" ", map { quotemeta($_) || '""' } @_).
3739 " >/dev/null 2>&1 </dev/null");
3745 # close_all_sockets()
3746 # Closes all the main listening sockets
3747 sub close_all_sockets
3750 foreach $s (@socketfhs) {
3756 # Close all pipes for talking to sub-processes
3760 foreach $p (@passin) { close($p); }
3761 foreach $p (@passout) { close($p); }
3762 foreach $p (values %conversations) {
3763 if ($p->{'PAMOUTr'}) {
3764 close($p->{'PAMOUTr'});
3765 close($p->{'PAMINw'});
3770 # check_user_ip(user)
3771 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3774 local ($username) = @_;
3775 local $uinfo = &get_user_details($username);
3776 return 1 if (!$uinfo);
3777 if ($uinfo->{'deny'} &&
3778 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3779 $uinfo->{'allow'} &&
3780 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3786 # check_user_time(user)
3787 # Returns 1 if some user is allowed to login at the current date and time
3790 local ($username) = @_;
3791 local $uinfo = &get_user_details($username);
3792 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3793 local @tm = localtime(time());
3794 if ($uinfo->{'allowdays'}) {
3795 # Make sure day is allowed
3796 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3798 if ($uinfo->{'allowhours'}) {
3799 # Make sure time is allowed
3800 local $m = $tm[2]*60+$tm[1];
3801 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3802 $m > $uinfo->{'allowhours'}->[1]);
3807 # generate_random_id(password, [force-urandom])
3808 # Returns a random session ID number
3809 sub generate_random_id
3811 local ($pass, $force_urandom) = @_;
3813 if (!$bad_urandom) {
3814 # First try /dev/urandom, unless we have marked it as bad
3815 $SIG{ALRM} = "miniserv::urandom_timeout";
3817 if (open(RANDOM, "/dev/urandom")) {
3819 if (read(RANDOM, $tmpsid, 16) == 16) {
3820 $sid = lc(unpack('h*',$tmpsid));
3826 if (!$sid && !$force_urandom) {
3829 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3830 $sid += ord($c) * $mul;
3837 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3838 # Called from handle_session to either mark a user as logged in, or not
3841 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3842 $authuser = $vu if ($ok);
3844 # check if the test cookie is set
3845 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3846 !$config{'no_testing_cookie'} && !$notest) {
3847 &http_error(500, "No cookies",
3848 "Your browser does not support cookies, ".
3849 "which are required for this web server to ".
3850 "work in session authentication mode");
3853 # check with main process for delay
3854 if ($config{'passdelay'} && $vu) {
3855 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3856 print $PASSINw "delay $vu $acptip $ok\n";
3857 <$PASSOUTr> =~ /(\d+) (\d+)/;
3860 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3863 if ($ok && (!$expired ||
3864 $config{'passwd_mode'} == 1)) {
3865 # Logged in OK! Tell the main process about
3867 local $sid = &generate_random_id($pass);
3868 print DEBUG "handle_login: sid=$sid\n";
3869 print $PASSINw "new $sid $authuser $acptip\n";
3871 # Run the post-login script, if any
3872 &run_login_script($authuser, $sid,
3875 # Check for a redirect URL for the user
3876 local $rurl = &login_redirect($authuser, $pass, $host);
3877 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3879 # Got one .. go to it
3880 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3881 &write_data("Date: $datestr\r\n");
3882 &write_data("Server: $config{'server'}\r\n");
3883 &write_data("Location: $rurl\r\n");
3884 &write_keep_alive(0);
3885 &write_data("\r\n");
3886 &log_request($acpthost, $authuser, $reqline, 302, 0);
3889 # Set cookie and redirect to originally requested page
3890 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3891 &write_data("Date: $datestr\r\n");
3892 &write_data("Server: $config{'server'}\r\n");
3893 local $ssl = $use_ssl || $config{'inetd_ssl'};
3894 $portstr = $port == 80 && !$ssl ? "" :
3895 $port == 443 && $ssl ? "" : ":$port";
3896 $prot = $ssl ? "https" : "http";
3897 local $sec = $ssl ? "; secure" : "";
3898 #$sec .= "; httpOnly";
3899 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3900 # Make redirect URL safe
3904 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3907 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3909 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3910 &write_keep_alive(0);
3911 &write_data("\r\n");
3912 &log_request($acpthost, $authuser, $reqline, 302, 0);
3913 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3914 &write_login_utmp($authuser, $acpthost);
3918 elsif ($ok && $expired &&
3919 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3920 # Login was ok, but password has expired or was temporary. Need
3921 # to force display of password change form.
3924 $querystring = "&user=".&urlize($vu).
3926 "&expired=".$expired;
3929 $page = $config{'password_form'};
3931 $miniserv_internal = 2;
3932 syslog("crit", "%s",
3933 "Expired login as $vu ".
3934 "from $acpthost") if ($use_syslog);
3937 # Login failed, or password has expired. The login form will be
3938 # displayed again by later code
3940 $request_uri = $in{'page'};
3941 $already_session_id = undef;
3943 $authuser = $baseauthuser = undef;
3944 syslog("crit", "%s",
3945 ($nonexist ? "Non-existent" :
3946 $expired ? "Expired" : "Invalid").
3947 " login as $vu from $acpthost")
3953 # write_login_utmp(user, host)
3954 # Record the login by some user in utmp
3955 sub write_login_utmp
3958 # Write utmp record for login
3959 %utmp = ( 'ut_host' => $_[1],
3960 'ut_time' => time(),
3962 'ut_type' => 7, # user process
3963 'ut_pid' => $main_process_id,
3964 'ut_line' => $config{'pam'},
3966 if (defined(&User::Utmp::putut)) {
3967 User::Utmp::putut(\%utmp);
3970 User::Utmp::pututline(\%utmp);
3975 # write_logout_utmp(user, host)
3976 # Record the logout by some user in utmp
3977 sub write_logout_utmp
3980 # Write utmp record for logout
3981 %utmp = ( 'ut_host' => $_[1],
3982 'ut_time' => time(),
3984 'ut_type' => 8, # dead process
3985 'ut_pid' => $main_process_id,
3986 'ut_line' => $config{'pam'},
3988 if (defined(&User::Utmp::putut)) {
3989 User::Utmp::putut(\%utmp);
3992 User::Utmp::pututline(\%utmp);
3997 # pam_conversation_process(username, write-pipe, read-pipe)
3998 # This function is called inside a sub-process to communicate with PAM. It sends
3999 # questions down one pipe, and reads responses from another
4000 sub pam_conversation_process
4002 local ($user, $writer, $reader) = @_;
4003 $miniserv::pam_conversation_process_writer = $writer;
4004 $miniserv::pam_conversation_process_reader = $reader;
4005 eval "use Authen::PAM;";
4006 local $convh = new Authen::PAM(
4007 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
4008 local $pam_ret = $convh->pam_authenticate();
4009 if ($pam_ret == PAM_SUCCESS()) {
4010 local $acct_ret = $convh->pam_acct_mgmt();
4011 if ($acct_ret == PAM_SUCCESS()) {
4012 $convh->pam_open_session();
4013 print $writer "x2 $user 1 0 0\n";
4015 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
4016 $acct_ret == PAM_ACCT_EXPIRED()) {
4017 print $writer "x2 $user 1 1 0\n";
4020 print $writer "x0 Unknown PAM account status $acct_ret\n";
4024 print $writer "x2 $user 0 0 0\n";
4029 # pam_conversation_process_func(type, message, [type, message, ...])
4030 # A pipe that talks to both PAM and the master process
4031 sub pam_conversation_process_func
4034 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
4036 local ($type, $msg) = (shift, shift);
4038 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
4039 print $miniserv::pam_conversation_process_writer "\n";
4040 local $answer = <$miniserv::pam_conversation_process_reader>;
4041 $answer =~ s/\r|\n//g;
4042 push(@rv, PAM_SUCCESS(), $answer);
4044 push(@rv, PAM_SUCCESS());
4049 # Returns 4 new pipe file handles
4052 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
4054 local %taken = ( (map { $_, 1 } @passin),
4055 (map { $_->{'PASSINr'} } values %conversations) );
4056 for($p=0; $taken{"PASSINr$p"}; $p++) { }
4057 $PASSINr = "PASSINr$p";
4058 $PASSINw = "PASSINw$p";
4059 $PASSOUTr = "PASSOUTr$p";
4060 $PASSOUTw = "PASSOUTw$p";
4061 pipe($PASSINr, $PASSINw);
4062 pipe($PASSOUTr, $PASSOUTw);
4063 select($PASSINw); $| = 1;
4064 select($PASSINr); $| = 1;
4065 select($PASSOUTw); $| = 1;
4066 select($PASSOUTw); $| = 1;
4068 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
4071 # recv_pam_question(&conv, fd)
4072 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
4073 # Returns 0 if the conversation is over, 1 if not.
4074 sub recv_pam_question
4076 local ($conf, $fh) = @_;
4077 local $pr = $conf->{'PAMOUTr'};
4078 select($pr); $| = 1; select(STDOUT);
4079 local $line = <$pr>;
4080 $line =~ s/\r|\n//g;
4083 $line =~ s/\r|\n//g;
4085 $conf->{'last'} = time();
4088 print $fh "0 PAM conversation error\n";
4092 local ($type, $msg) = split(/\s+/, $line, 2);
4093 if ($type =~ /^x(\d+)/) {
4094 # Pass this status code through
4095 print $fh "$1 $msg\n";
4096 return $1 == 2 || $1 == 0 ? 0 : 1;
4098 elsif ($type == PAM_PROMPT_ECHO_ON()) {
4100 print $fh "1 $msg\n";
4103 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
4105 print $fh "3 $msg\n";
4108 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
4109 # A message that does not require a response
4110 print $fh "4 $msg\n";
4115 print $fh "0 Unknown PAM message type $type\n";
4121 # send_pam_answer(&conv, answer)
4122 # Sends a response from the user to the PAM sub-process
4125 local ($conf, $answer) = @_;
4126 local $pw = $conf->{'PAMINw'};
4127 $conf->{'last'} = time();
4128 print $pw "$answer\n";
4131 # end_pam_conversation(&conv)
4132 # Clean up PAM conversation pipes and processes
4133 sub end_pam_conversation
4136 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
4137 if ($conv->{'PAMINr'}) {
4138 close($conv->{'PAMINr'});
4139 close($conv->{'PAMOUTr'});
4140 close($conv->{'PAMINw'});
4141 close($conv->{'PAMOUTw'});
4143 delete($conversations{$conv->{'cid'}});
4146 # get_ipkeys(&miniserv)
4147 # Returns a list of IP address to key file mappings from a miniserv.conf entry
4151 foreach $k (keys %{$_[0]}) {
4152 if ($k =~ /^ipkey_(\S+)/) {
4153 local $ipkey = { 'ips' => [ split(/,/, $1) ],
4154 'key' => $_[0]->{$k},
4155 'index' => scalar(@rv) };
4156 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
4157 $ipkey->{'extracas'} = $_[0]->{'ipextracas_'.$1};
4164 # create_ssl_context(keyfile, [certfile], [extracas])
4165 sub create_ssl_context
4167 local ($keyfile, $certfile, $extracas) = @_;
4169 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
4170 $ssl_ctx ||= Net::SSLeay::CTX_new();
4171 $ssl_ctx || die "Failed to create SSL context : $!";
4172 if ($client_certs) {
4173 Net::SSLeay::CTX_load_verify_locations(
4174 $ssl_ctx, $config{'ca'}, "");
4175 Net::SSLeay::CTX_set_verify(
4176 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
4178 if ($extracas && $extracas ne "none") {
4179 foreach my $p (split(/\s+/, $extracas)) {
4180 Net::SSLeay::CTX_load_verify_locations(
4185 Net::SSLeay::CTX_use_RSAPrivateKey_file(
4187 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
4188 Net::SSLeay::CTX_use_certificate_file(
4189 $ssl_ctx, $certfile || $keyfile,
4190 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
4195 # ssl_connection_for_ip(socket, ipv6-flag)
4196 # Returns a new SSL connection object for some socket, or undef if failed
4197 sub ssl_connection_for_ip
4199 local ($sock, $ipv6) = @_;
4200 local $sn = getsockname($sock);
4202 print STDERR "Failed to get address for socket $sock\n";
4205 local (undef, $myip, undef) = &get_address_ip($sn, $ipv6);
4206 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
4207 local $ssl_con = Net::SSLeay::new($ssl_ctx);
4208 if ($config{'ssl_cipher_list'}) {
4209 # Force use of ciphers
4210 eval "Net::SSLeay::set_cipher_list(
4211 \$ssl_con, \$config{'ssl_cipher_list'})";
4213 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
4219 Net::SSLeay::set_fd($ssl_con, fileno($sock));
4220 if (!Net::SSLeay::accept($ssl_con)) {
4221 print STDERR "Failed to initialize SSL connection\n";
4227 # login_redirect(username, password, host)
4228 # Calls the login redirect script (if configured), which may output a URL to
4229 # re-direct a user to after logging in.
4232 return undef if (!$config{'login_redirect'});
4233 local $quser = quotemeta($_[0]);
4234 local $qpass = quotemeta($_[1]);
4235 local $qhost = quotemeta($_[2]);
4236 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
4241 # reload_config_file()
4242 # Re-read %config, and call post-config actions
4243 sub reload_config_file
4245 &log_error("Reloading configuration");
4246 %config = &read_config_file($config_file);
4247 &update_vital_config();
4250 &build_config_mappings();
4251 &read_webmin_crons();
4253 if ($config{'session'}) {
4254 dbmclose(%sessiondb);
4255 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4259 # read_config_file(file)
4260 # Reads the given config file, and returns a hash of values
4261 sub read_config_file
4264 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4267 if (/^#/ || !/\S/) { next; }
4269 $name = $1; $val = $2;
4270 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4271 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4278 # update_vital_config()
4279 # Updates %config with defaults, and dies if something vital is missing
4280 sub update_vital_config
4282 my %vital = ("port", 80,
4284 "server", "MiniServ/0.01",
4285 "index_docs", "index.html index.htm index.cgi index.php",
4286 "addtype_html", "text/html",
4287 "addtype_txt", "text/plain",
4288 "addtype_gif", "image/gif",
4289 "addtype_jpg", "image/jpeg",
4290 "addtype_jpeg", "image/jpeg",
4291 "realm", "MiniServ",
4292 "session_login", "/session_login.cgi",
4293 "pam_login", "/pam_login.cgi",
4294 "password_form", "/password_form.cgi",
4295 "password_change", "/password_change.cgi",
4299 "unauth", "^/unauthenticated/ ^/robots.txt\$ ^[A-Za-z0-9\\-/_]+\\.jar\$ ^[A-Za-z0-9\\-/_]+\\.class\$ ^[A-Za-z0-9\\-/_]+\\.gif\$ ^[A-Za-z0-9\\-/_]+\\.png\$ ^[A-Za-z0-9\\-/_]+\\.conf\$ ^[A-Za-z0-9\\-/_]+\\.ico\$ ^/robots.txt\$",
4301 "expires", 7*24*60*60,
4302 "pam_test_user", "root",
4303 "precache", "lang/en */lang/en",
4305 foreach my $v (keys %vital) {
4307 if ($vital{$v} eq "") {
4308 die "Missing config option $v";
4310 $config{$v} = $vital{$v};
4313 if (!$config{'sessiondb'}) {
4314 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4315 $config{'sessiondb'} = "$1/sessiondb";
4317 if (!$config{'errorlog'}) {
4318 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4319 $config{'errorlog'} = "$1/miniserv.error";
4321 if (!$config{'tempbase'}) {
4322 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4323 $config{'tempbase'} = "$1/cgitemp";
4325 if (!$config{'blockedfile'}) {
4326 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4327 $config{'blockedfile'} = "$1/blocked";
4329 if (!$config{'webmincron_dir'}) {
4330 $config_file =~ /^(.*)\/[^\/]+$/;
4331 $config{'webmincron_dir'} = "$1/webmincron/crons";
4333 if (!$config{'webmincron_last'}) {
4334 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4335 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4337 if (!$config{'webmincron_wrapper'}) {
4338 $config{'webmincron_wrapper'} = $config{'root'}.
4339 "/webmincron/webmincron.pl";
4344 # Fills the %users and %certs hashes from the users file in %config
4353 undef(%lastchanges);
4356 if ($config{'userfile'}) {
4357 open(USERS, $config{'userfile'});
4360 local @user = split(/:/, $_, -1);
4361 $users{$user[0]} = $user[1];
4362 $certs{$user[0]} = $user[3] if ($user[3]);
4363 if ($user[4] =~ /^allow\s+(.*)/) {
4364 $allow{$user[0]} = $config{'alwaysresolve'} ?
4365 [ split(/\s+/, $1) ] :
4366 [ &to_ipaddress(split(/\s+/, $1)) ];
4368 elsif ($user[4] =~ /^deny\s+(.*)/) {
4369 $deny{$user[0]} = $config{'alwaysresolve'} ?
4370 [ split(/\s+/, $1) ] :
4371 [ &to_ipaddress(split(/\s+/, $1)) ];
4373 if ($user[5] =~ /days\s+(\S+)/) {
4374 $allowdays{$user[0]} = [ split(/,/, $1) ];
4376 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4377 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4379 $lastchanges{$user[0]} = $user[6];
4380 $nochange{$user[0]} = $user[9];
4381 $temppass{$user[0]} = $user[10];
4386 # Test user DB, if configured
4387 if ($config{'userdb'}) {
4388 my $dbh = &connect_userdb($config{'userdb'});
4390 print STDERR "Failed to open users database : $dbh\n"
4393 &disconnect_userdb($config{'userdb'}, $dbh);
4398 # get_user_details(username)
4399 # Returns a hash ref of user details, either from config files or the user DB
4400 sub get_user_details
4402 my ($username) = @_;
4403 if (exists($users{$username})) {
4405 return { 'name' => $username,
4406 'pass' => $users{$username},
4407 'certs' => $certs{$username},
4408 'allow' => $allow{$username},
4409 'deny' => $deny{$username},
4410 'allowdays' => $allowdays{$username},
4411 'allowhours' => $allowhours{$username},
4412 'lastchanges' => $lastchanges{$username},
4413 'nochange' => $nochange{$username},
4414 'temppass' => $temppass{$username},
4415 'preroot' => $config{'preroot_'.$username},
4418 if ($config{'userdb'}) {
4419 # Try querying user database
4420 if (exists($get_user_details_cache{$username})) {
4422 return $get_user_details_cache{$username};
4424 print DEBUG "get_user_details: Connecting to user database\n";
4425 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4429 print DEBUG "get_user_details: Failed : $dbh\n";
4430 print STDERR "Failed to connect to user database : $dbh\n";
4432 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4433 # Fetch user ID and password with SQL
4434 print DEBUG "get_user_details: Looking for $username in SQL\n";
4435 my $cmd = $dbh->prepare(
4436 "select id,pass from webmin_user where name = ?");
4437 if (!$cmd || !$cmd->execute($username)) {
4438 print STDERR "Failed to lookup user : ",
4442 my ($id, $pass) = $cmd->fetchrow();
4445 &disconnect_userdb($config{'userdb'}, $dbh);
4446 $get_user_details_cache{$username} = undef;
4447 print DEBUG "get_user_details: User not found\n";
4450 print DEBUG "get_user_details: id=$id pass=$pass\n";
4452 # Fetch attributes and add to user object
4453 print DEBUG "get_user_details: finding user attributes\n";
4454 my $cmd = $dbh->prepare(
4455 "select attr,value from webmin_user_attr where id = ?");
4456 if (!$cmd || !$cmd->execute($id)) {
4457 print STDERR "Failed to lookup user attrs : ",
4461 $user = { 'name' => $username,
4464 'proto' => $proto };
4465 while(my ($attr, $value) = $cmd->fetchrow()) {
4466 $attrs{$attr} = $value;
4470 elsif ($proto eq "ldap") {
4471 # Fetch user DN with LDAP
4472 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4473 my $rv = $dbh->search(
4475 filter => '(&(cn='.$username.')(objectClass='.
4476 $args->{'userclass'}.'))',
4478 if (!$rv || $rv->code) {
4479 print STDERR "Failed to lookup user : ",
4480 ($rv ? $rv->error : "Unknown error"),"\n";
4483 my ($u) = $rv->all_entries();
4485 &disconnect_userdb($config{'userdb'}, $dbh);
4486 $get_user_details_cache{$username} = undef;
4487 print DEBUG "get_user_details: User not found\n";
4491 # Extract attributes
4492 my $pass = $u->get_value('webminPass');
4493 $user = { 'name' => $username,
4496 'proto' => $proto };
4497 foreach my $la ($u->get_value('webminAttr')) {
4498 my ($attr, $value) = split(/=/, $la, 2);
4499 $attrs{$attr} = $value;
4503 # Convert DB attributes into user object fields
4505 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4507 $user->{'certs'} = $attrs{'cert'};
4508 if ($attrs{'allow'}) {
4509 $user->{'allow'} = $config{'alwaysresolve'} ?
4510 [ split(/\s+/, $attrs{'allow'}) ] :
4511 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4513 if ($attrs{'deny'}) {
4514 $user->{'deny'} = $config{'alwaysresolve'} ?
4515 [ split(/\s+/, $attrs{'deny'}) ] :
4516 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4518 if ($attrs{'days'}) {
4519 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4521 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4522 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4523 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4524 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4526 $user->{'lastchanges'} = $attrs{'lastchange'};
4527 $user->{'nochange'} = $attrs{'nochange'};
4528 $user->{'temppass'} = $attrs{'temppass'};
4529 $user->{'preroot'} = $attrs{'theme'};
4531 &disconnect_userdb($config{'userdb'}, $dbh);
4532 $get_user_details_cache{$user->{'name'}} = $user;
4538 # find_user_by_cert(cert)
4539 # Returns a username looked up by certificate
4540 sub find_user_by_cert
4542 my ($peername) = @_;
4543 my $peername2 = $peername;
4544 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4546 # First check users in local files
4547 foreach my $username (keys %certs) {
4548 if ($certs{$username} eq $peername ||
4549 $certs{$username} eq $peername2) {
4555 if ($config{'userdb'}) {
4556 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4560 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4562 my $cmd = $dbh->prepare("select webmin_user.name from webmin_user,webmin_user_attr where webmin_user.id = webmin_user_attr.id and webmin_user_attr.attr = 'cert' and webmin_user_attr.value = ?");
4563 return undef if (!$cmd);
4564 foreach my $p ($peername, $peername2) {
4566 if ($cmd->execute($p)) {
4567 ($username) = $cmd->fetchrow();
4570 return $username if ($username);
4573 elsif ($proto eq "ldap") {
4575 my $rv = $dbh->search(
4577 filter => '(objectClass='.
4578 $args->{'userclass'}.')',
4580 attrs => [ 'cn', 'webminAttr' ]);
4581 if ($rv && !$rv->code) {
4582 foreach my $u ($rv->all_entries) {
4583 my @attrs = $u->get_value('webminAttr');
4584 foreach my $la (@attrs) {
4585 my ($attr, $value) = split(/=/, $la, 2);
4586 if ($attr eq "cert" &&
4587 ($value eq $peername ||
4588 $value eq $peername2)) {
4589 return $u->get_value('cn');
4599 # connect_userdb(string)
4600 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4601 # On failure returns an error message string. In an array context, returns the
4602 # protocol type too.
4606 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4607 if ($proto eq "mysql") {
4608 # Connect to MySQL with DBI
4609 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4610 $drh || return $text{'sql_emysqldriver'};
4611 my ($host, $port) = split(/:/, $host);
4612 my $cstr = "database=$prefix;host=$host";
4613 $cstr .= ";port=$port" if ($port);
4614 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4615 my $dbh = $drh->connect($cstr, $user, $pass, { });
4616 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4617 print DEBUG "connect_userdb: Connected OK\n";
4618 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4620 elsif ($proto eq "postgresql") {
4621 # Connect to PostgreSQL with DBI
4622 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4623 $drh || return $text{'sql_epostgresqldriver'};
4624 my ($host, $port) = split(/:/, $host);
4625 my $cstr = "dbname=$prefix;host=$host";
4626 $cstr .= ";port=$port" if ($port);
4627 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4628 my $dbh = $drh->connect($cstr, $user, $pass);
4629 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4630 print DEBUG "connect_userdb: Connected OK\n";
4631 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4633 elsif ($proto eq "ldap") {
4634 # Connect with perl LDAP module
4635 eval "use Net::LDAP";
4636 $@ && return $text{'sql_eldapdriver'};
4637 my ($host, $port) = split(/:/, $host);
4638 my $scheme = $args->{'scheme'} || 'ldap';
4640 $port = $scheme eq 'ldaps' ? 636 : 389;
4642 my $ldap = Net::LDAP->new($host,
4644 'scheme' => $scheme);
4645 $ldap || return &text('sql_eldapconnect', $host);
4647 if ($args->{'tls'}) {
4648 # Switch to TLS mode
4649 eval { $mesg = $ldap->start_tls(); };
4650 if ($@ || !$mesg || $mesg->code) {
4651 return &text('sql_eldaptls',
4652 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4655 # Login to the server
4657 $mesg = $ldap->bind(dn => $user, password => $pass);
4660 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4662 if (!$mesg || $mesg->code) {
4663 return &text('sql_eldaplogin', $user,
4664 $mesg ? $mesg->error : "Unknown error");
4666 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4669 return "Unknown protocol $proto";
4673 # split_userdb_string(string)
4674 # Converts a string like mysql://user:pass@host/db into separate parts
4675 sub split_userdb_string
4678 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4679 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4680 ($1, $2, $3, $4, $5, $7);
4681 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4682 return ($proto, $user, $pass, $host, $prefix, \%args);
4687 # disconnect_userdb(string, &handle)
4688 # Closes a handle opened by connect_userdb
4689 sub disconnect_userdb
4692 if ($str =~ /^(mysql|postgresql):/) {
4696 elsif ($str =~ /^ldap:/) {
4703 # Fills %mime with entries from file in %config and extra settings in %config
4707 if ($config{"mimetypes"} ne "") {
4708 open(MIME, $config{"mimetypes"});
4711 if (/^(\S+)\s+(.*)$/) {
4713 my @exts = split(/\s+/, $2);
4714 foreach my $ext (@exts) {
4715 $mime{$ext} = $type;
4721 foreach my $k (keys %config) {
4722 if ($k !~ /^addtype_(.*)$/) { next; }
4723 $mime{$1} = $config{$k};
4727 # build_config_mappings()
4728 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4729 # redirect mapping and allow and deny lists from %config
4730 sub build_config_mappings
4732 # build anonymous access list
4734 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4735 if ($a =~ /^([^=]+)=(\S+)$/) {
4736 $anonymous{$1} = $2;
4740 # build IP access list
4742 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4743 if ($a =~ /^([^=]+)=(\S+)$/) {
4748 # build unauthenticated URLs list
4749 @unauth = split(/\s+/, $config{'unauth'});
4751 # build redirect mapping
4753 foreach my $r (split(/\s+/, $config{'redirect'})) {
4754 if ($r =~ /^([^=]+)=(\S+)$/) {
4759 # build prefixes to be stripped
4760 undef(@strip_prefix);
4761 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4762 push(@strip_prefix, $r);
4765 # Init allow and deny lists
4766 @deny = split(/\s+/, $config{"deny"});
4767 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4768 @allow = split(/\s+/, $config{"allow"});
4769 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4772 if ($config{'allowusers'}) {
4773 @allowusers = split(/\s+/, $config{'allowusers'});
4775 elsif ($config{'denyusers'}) {
4776 @denyusers = split(/\s+/, $config{'denyusers'});
4779 # Build list of unixauth mappings
4781 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4782 if ($ua =~ /^(\S+)=(\S+)$/) {
4786 $unixauth{"*"} = $ua;
4790 # Build list of non-session-auth pages
4791 undef(%sessiononly);
4792 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4793 $sessiononly{$sp} = 1;
4796 # Build list of logout times
4797 undef(@logouttimes);
4798 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4799 if ($a =~ /^([^=]+)=(\S+)$/) {
4800 push(@logouttimes, [ $1, $2 ]);
4803 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4805 # Build list of DAV pathss
4807 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4808 push(@davpaths, $d);
4810 @davusers = split(/\s+/, $config{'dav_users'});
4812 # Mobile agent substrings and hostname prefixes
4813 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4814 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4817 @expires_paths = ( );
4818 foreach my $pe (split(/\t+/, $config{'expires_paths'})) {
4819 my ($p, $e) = split(/=/, $pe);
4820 if ($p && $e ne '') {
4821 push(@expires_paths, [ $p, $e ]);
4827 if ($config{'debug'}) {
4828 open(DEBUG, ">>$config{'debug'}");
4831 open(DEBUG, ">/dev/null");
4834 # Reset cache of sudo checks
4838 # is_group_member(&uinfo, groupname)
4839 # Returns 1 if some user is a primary or secondary member of a group
4842 local ($uinfo, $group) = @_;
4843 local @ginfo = getgrnam($group);
4844 return 0 if (!@ginfo);
4845 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4846 foreach my $m (split(/\s+/, $ginfo[3])) {
4847 return 1 if ($m eq $uinfo->[0]);
4852 # prefix_to_mask(prefix)
4853 # Converts a number like 24 to a mask like 255.255.255.0
4856 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4857 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4858 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4859 (256-(2 ** (8-$_[0]))).".0.0.0";
4862 # get_logout_time(user, session-id)
4863 # Given a username, returns the idle time before he will be logged out
4866 local ($user, $sid) = @_;
4867 if (!defined($logout_time_cache{$user,$sid})) {
4869 foreach my $l (@logouttimes) {
4870 if ($l->[0] =~ /^\@(.*)$/) {
4871 # Check group membership
4872 local @uinfo = getpwnam($user);
4873 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4877 elsif ($l->[0] =~ /^\//) {
4878 # Check file contents
4879 open(FILE, $l->[0]);
4896 if ($l->[0] eq $user) {
4900 last if (defined($time));
4902 $logout_time_cache{$user,$sid} = $time;
4904 return $logout_time_cache{$user,$sid};
4907 # password_crypt(password, salt)
4908 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4909 # of a password. Otherwise, do Unix crypt.
4912 local ($pass, $salt) = @_;
4913 if ($salt =~ /^\$1\$/ && $use_md5) {
4914 return &encrypt_md5($pass, $salt);
4917 return &unix_crypt($pass, $salt);
4921 # unix_crypt(password, salt)
4922 # Performs standard Unix hashing for a password
4925 local ($pass, $salt) = @_;
4926 if ($use_perl_crypt) {
4927 return Crypt::UnixCrypt::crypt($pass, $salt);
4930 return crypt($pass, $salt);
4934 # handle_dav_request(davpath)
4935 # Pass a request on to the Net::DAV::Server module
4936 sub handle_dav_request
4939 eval "use Filesys::Virtual::Plain";
4940 eval "use Net::DAV::Server";
4941 eval "use HTTP::Request";
4942 eval "use HTTP::Headers";
4944 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4945 delete $Net::DAV::Server::implemented{lock};
4946 delete $Net::DAV::Server::implemented{unlock};
4949 # Read in request data
4950 if (!$posted_data) {
4951 local $clen = $header{"content-length"};
4952 while(length($posted_data) < $clen) {
4953 $buf = &read_data($clen - length($posted_data));
4954 if (!length($buf)) {
4955 &http_error(500, "Failed to read POST request");
4957 $posted_data .= $buf;
4961 # For subsequent logging
4962 open(MINISERVLOG, ">>$config{'logfile'}");
4966 local @u = getpwnam($authuser);
4967 if ($config{'dav_remoteuser'} && !$< && $validated) {
4970 $( = $u[3]; $) = "$u[3] $u[3]";
4971 ($>, $<) = ($u[2], $u[2]);
4973 if ($config{'dav_root'} eq '*') {
4978 &http_error(500, "Unix user $authuser does not exist");
4982 $root ||= $config{'dav_root'};
4985 # Check if this user can use DAV
4987 &users_match(\@u, @davusers) ||
4988 &http_error(500, "You are not allowed to access DAV");
4992 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4993 my $webdav = Net::DAV::Server->new();
4994 $webdav->filesys($filesys);
4996 # Make up a request object, and feed to DAV
4997 local $ho = HTTP::Headers->new;
4998 foreach my $h (keys %header) {
4999 next if (lc($h) eq "connection");
5000 $ho->header($h => $header{$h});
5003 $request_uri =~ s/^\Q$path\E//;
5004 $request_uri = "/" if ($request_uri eq "");
5006 my $request = HTTP::Request->new($method, $request_uri, $ho,
5008 if ($config{'dav_debug'}) {
5009 print STDERR "DAV request :\n";
5010 print STDERR "---------------------------------------------\n";
5011 print STDERR $request->as_string();
5012 print STDERR "---------------------------------------------\n";
5014 my $response = $webdav->run($request);
5016 # Send back the reply
5017 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
5018 local $content = $response->content();
5020 $content =~ s|href>/(.+)<|href>$path/$1<|g;
5021 $content =~ s|href>/<|href>$path<|g;
5023 foreach my $h ($response->header_field_names) {
5024 next if (lc($h) eq "connection" || lc($h) eq "content-length");
5025 &write_data("$h: ",$response->header($h),"\r\n");
5027 &write_data("Content-length: ",length($content),"\r\n");
5028 local $rv = &write_keep_alive(0);
5029 &write_data("\r\n");
5030 &write_data($content);
5032 if ($config{'dav_debug'}) {
5033 print STDERR "DAV reply :\n";
5034 print STDERR "---------------------------------------------\n";
5035 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
5036 foreach my $h ($response->header_field_names) {
5037 next if (lc($h) eq "connection" || lc($h) eq "content-length");
5038 print STDERR "$h: ",$response->header($h),"\r\n";
5040 print STDERR "Content-length: ",length($content),"\r\n";
5041 print STDERR "\r\n";
5042 print STDERR $content;
5043 print STDERR "---------------------------------------------\n";
5047 &log_request($acpthost, $authuser, $reqline, $response->code(),
5048 length($response->content()));
5051 # get_system_hostname()
5052 # Returns the hostname of this system, for reporting to listeners
5053 sub get_system_hostname
5055 # On Windows, try computername environment variable
5056 return $ENV{'computername'} if ($ENV{'computername'});
5057 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
5059 # If a specific command is set, use it first
5060 if ($config{'hostname_command'}) {
5061 local $out = `($config{'hostname_command'}) 2>&1`;
5068 # First try the hostname command
5069 local $out = `hostname 2>&1`;
5070 if (!$? && $out =~ /\S/) {
5075 # Try the Sys::Hostname module
5076 eval "use Sys::Hostname";
5078 local $rv = eval "hostname()";
5084 # Must use net name on Windows
5085 local $out = `net name 2>&1`;
5086 if ($out =~ /\-+\r?\n(\S+)/) {
5093 # indexof(string, array)
5094 # Returns the index of some value in an array, or -1
5097 for($i=1; $i <= $#_; $i++) {
5098 if ($_[$i] eq $_[0]) { return $i - 1; }
5104 # has_command(command)
5105 # Returns the full path if some command is in the path, undef if not
5109 if (!$_[0]) { return undef; }
5110 if (exists($has_command_cache{$_[0]})) {
5111 return $has_command_cache{$_[0]};
5114 if ($_[0] =~ /^\//) {
5115 $rv = -x $_[0] ? $_[0] : undef;
5118 local $sp = $on_windows ? ';' : ':';
5119 foreach $d (split($sp, $ENV{PATH})) {
5120 if (-x "$d/$_[0]") {
5125 foreach my $sfx (".exe", ".com", ".bat") {
5126 if (-r "$d/$_[0]".$sfx) {
5127 $rv = "$d/$_[0]".$sfx;
5134 $has_command_cache{$_[0]} = $rv;
5138 # check_sudo_permissions(user, pass)
5139 # Returns 1 if some user can run any command via sudo
5140 sub check_sudo_permissions
5142 local ($user, $pass) = @_;
5144 # First try the pipes
5146 print DEBUG "check_sudo_permissions: querying cache for $user\n";
5147 print $PASSINw "readsudo $user\n";
5148 local $can = <$PASSOUTr>;
5150 print DEBUG "check_sudo_permissions: cache said $can\n";
5151 if ($can =~ /^\d+$/ && $can != 2) {
5156 local $ptyfh = new IO::Pty;
5157 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
5159 print STDERR "Failed to create new PTY with IO::Pty\n";
5162 local @uinfo = getpwnam($user);
5164 print STDERR "Unix user $user does not exist for sudo\n";
5168 # Execute sudo in a sub-process, via a pty
5169 local $ttyfh = $ptyfh->slave();
5170 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
5171 local $tty = $ptyfh->ttyname();
5172 print DEBUG "check_sudo_permissions: tty=$tty\n";
5173 chown($uinfo[2], $uinfo[3], $tty);
5175 print DEBUG "check_sudo_permissions: about to fork..\n";
5176 local $pid = fork();
5177 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
5179 print STDERR "fork for sudo failed : $!\n";
5184 $ptyfh->make_slave_controlling_terminal();
5185 close(STDIN); close(STDOUT); close(STDERR);
5186 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
5187 close($PASSINw); close($PASSOUTr);
5188 ($(, $)) = ( $uinfo[3],
5189 "$uinfo[3] ".join(" ", $uinfo[3],
5190 &other_groups($uinfo[0])) );
5191 ($>, $<) = ($uinfo[2], $uinfo[2]);
5196 open(STDIN, "<&SUDOr");
5197 open(STDOUT, ">$tty");
5198 open(STDERR, ">&STDOUT");
5201 print "Exec failed : $!\n";
5204 print DEBUG "check_sudo_permissions: pid=$pid\n";
5206 $ptyfh->close_slave();
5208 # Send password, and get back response
5209 local $oldfh = select(SUDOw);
5212 print DEBUG "check_sudo_permissions: about to send pass\n";
5213 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
5214 print SUDOw $pass,"\n";
5215 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
5219 print DEBUG "check_sudo_permissions: got $_";
5225 local ($ok) = ($out =~ /\(ALL\)\s+ALL|\(ALL\)\s+NOPASSWD:\s+ALL|\(ALL\s*:\s*ALL\)\s+ALL/ ? 1 : 0);
5229 print $PASSINw "writesudo $user $ok\n";
5240 while(my @g = getgrent()) {
5241 my @m = split(/\s+/, $g[3]);
5242 push(@rv, $g[2]) if (&indexof($user, @m) >= 0);
5248 # is_mobile_useragent(agent)
5249 # Returns 1 if some user agent looks like a cellphone or other mobile device,
5251 sub is_mobile_useragent
5253 local ($agent) = @_;
5255 "UP.Link", # Openwave
5256 "Nokia", # All Nokias start with Nokia
5257 "MOT-", # All Motorola phones start with MOT-
5258 "SAMSUNG", # Samsung browsers
5259 "Samsung", # Samsung browsers
5260 "SEC-", # Samsung browsers
5261 "AU-MIC", # Samsung browsers
5262 "AUDIOVOX", # Audiovox
5263 "BlackBerry", # BlackBerry
5264 "hiptop", # Danger hiptop Sidekick
5265 "SonyEricsson", # Sony Ericsson
5266 "Ericsson", # Old Ericsson browsers , mostly WAP
5267 "Mitsu/1.1.A", # Mitsubishi phones
5268 "Panasonic WAP", # Panasonic old WAP phones
5269 "DoCoMo", # DoCoMo phones
5270 "Lynx", # Lynx text-mode linux browser
5271 "Links", # Another text-mode linux browser
5273 local @substrings = (
5274 "UP.Browser", # Openwave
5275 "MobilePhone", # NetFront
5276 "AU-MIC-A700", # Samsung A700 Obigo browsers
5277 "Danger hiptop", # Danger Sidekick hiptop
5278 "Windows CE", # Windows CE Pocket PC
5279 "IEMobile", # Windows mobile browser
5280 "Blazer", # Palm Treo Blazer
5281 "BlackBerry", # BlackBerries can emulate other browsers, but
5282 # they still keep this string in the UserAgent
5283 "SymbianOS", # New Series60 browser has safari in it and
5284 # SymbianOS is the only distinguishing string
5285 "iPhone", # Apple iPhone KHTML browser
5286 "iPod", # iPod touch browser
5287 "MobileSafari", # HTTP client in iPhone
5288 "Opera Mini", # Opera Mini
5289 "HTC_P3700", # HTC mobile device
5291 "webOS/", # Palm WebOS
5292 "Nintendo DS", # DSi / DSi-XL
5295 "Android.*Mobile", # Android phone
5297 foreach my $p (@prefixes) {
5298 return 1 if ($agent =~ /^\Q$p\E/);
5300 foreach my $s (@substrings, @mobile_agents) {
5301 return 1 if ($agent =~ /\Q$s\E/);
5303 foreach my $s (@regexps) {
5304 return 1 if ($agent =~ /$s/);
5309 # write_blocked_file()
5310 # Writes out a text file of blocked hosts and users
5311 sub write_blocked_file
5313 open(BLOCKED, ">$config{'blockedfile'}");
5314 foreach my $d (grep { $hostfail{$_} } @deny) {
5315 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5317 foreach my $d (grep { $userfail{$_} } @denyusers) {
5318 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5321 chmod(0700, $config{'blockedfile'});
5326 open(PIDFILE, ">$config{'pidfile'}");
5327 printf PIDFILE "%d\n", getpid();
5329 $miniserv_main_pid = getpid();
5332 # lock_user_password(user)
5333 # Updates a user's password file entry to lock it, both in memory and on disk.
5334 # Returns 1 if done, -1 if no such user, 0 if already locked
5335 sub lock_user_password
5338 local $uinfo = &get_user_details($user);
5343 if ($uinfo->{'pass'} =~ /^\!/) {
5347 if (!$uinfo->{'proto'}) {
5348 # Write to users file
5349 $users{$user} = "!".$users{$user};
5350 open(USERS, $config{'userfile'});
5351 local @ufile = <USERS>;
5353 foreach my $u (@ufile) {
5354 local @uinfo = split(/:/, $u);
5355 if ($uinfo[0] eq $user) {
5356 $uinfo[1] = $users{$user};
5358 $u = join(":", @uinfo);
5360 open(USERS, ">$config{'userfile'}");
5366 if ($config{'userdb'}) {
5368 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5372 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5373 # Update user attribute
5374 my $cmd = $dbh->prepare(
5375 "update webmin_user set pass = ? where id = ?");
5376 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5379 print STDERR "Failed to lock password : ",
5383 $cmd->finish() if ($cmd);
5385 elsif ($proto eq "ldap") {
5386 # Update LDAP object
5387 my $rv = $dbh->modify($uinfo->{'id'},
5388 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5389 if (!$rv || $rv->code) {
5390 print STDERR "Failed to lock password : ",
5391 ($rv ? $rv->error : "Unknown error"),"\n";
5395 &disconnect_userdb($config{'userdb'}, $dbh);
5399 return -1; # This should never be reached
5402 # hash_session_id(sid)
5403 # Returns an MD5 or Unix-crypted session ID
5407 if (!$hash_session_id_cache{$sid}) {
5410 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5414 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5417 return $hash_session_id_cache{$sid};
5420 # encrypt_md5(string, [salt])
5421 # Returns a string encrypted in MD5 format
5424 local ($passwd, $salt) = @_;
5425 local $magic = '$1$';
5426 if ($salt =~ /^\$1\$([^\$]+)/) {
5427 # Extract actual salt from already encrypted password
5432 local $ctx = eval "new $use_md5";
5439 # Add some more stuff from the hash of the password and salt
5440 local $ctx1 = eval "new $use_md5";
5441 $ctx1->add($passwd);
5445 $ctx1->add($passwd);
5446 local $final = $ctx1->digest();
5447 for($pl=length($passwd); $pl>0; $pl-=16) {
5448 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5451 # This piece of code seems rather pointless, but it's in the C code that
5452 # does MD5 in PAM so it has to go in!
5455 for($i=length($passwd); $i; $i >>= 1) {
5460 $ctx->add(substr($passwd, $j, 1));
5463 $final = $ctx->digest();
5466 # This loop exists only to waste time
5467 for($i=0; $i<1000; $i++) {
5468 $ctx1 = eval "new $use_md5";
5469 $ctx1->add($i & 1 ? $passwd : $final);
5470 $ctx1->add($salt) if ($i % 3);
5471 $ctx1->add($passwd) if ($i % 7);
5472 $ctx1->add($i & 1 ? $final : $passwd);
5473 $final = $ctx1->digest();
5477 # Convert the 16-byte final string into a readable form
5479 local @final = map { ord($_) } split(//, $final);
5480 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5481 $rv .= &to64($l, 4);
5482 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5483 $rv .= &to64($l, 4);
5484 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5485 $rv .= &to64($l, 4);
5486 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5487 $rv .= &to64($l, 4);
5488 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5489 $rv .= &to64($l, 4);
5491 $rv .= &to64($l, 2);
5493 # Add salt if needed
5495 return $magic.$salt.'$'.$rv;
5504 local ($v, $n) = @_;
5507 $r .= $itoa64[$v & 0x3f];
5513 # read_file(file, &assoc, [&order], [lowercase])
5514 # Fill an associative array with name=value pairs from a file
5517 open(ARFILE, $_[0]) || return 0;
5520 if (!/^#/ && /^([^=]*)=(.*)$/) {
5521 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5522 push(@{$_[2]}, $1) if ($_[2]);
5529 # write_file(file, array)
5530 # Write out the contents of an associative array as name=value lines
5533 local(%old, @order);
5534 &read_file($_[0], \%old, \@order);
5535 open(ARFILE, ">$_[0]");
5536 foreach $k (@order) {
5537 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5539 foreach $k (keys %{$_[1]}) {
5540 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5545 # execute_ready_webmin_crons()
5546 # Find and run any cron jobs that are due, based on their last run time and
5547 # execution interval
5548 sub execute_ready_webmin_crons
5552 foreach my $cron (@webmincrons) {
5554 if (!$webmincron_last{$cron->{'id'}}) {
5555 # If not ever run before, don't run right away
5556 $webmincron_last{$cron->{'id'}} = $now;
5559 elsif ($cron->{'interval'} &&
5560 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5561 # Older than interval .. time to run
5564 elsif ($cron->{'mins'}) {
5565 # Check if current time matches spec, and we haven't run in the
5567 my @tm = localtime($now);
5568 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5569 &matches_cron($cron->{'hours'}, $tm[2]) &&
5570 &matches_cron($cron->{'days'}, $tm[3]) &&
5571 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5572 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5573 $now - $webmincron_last{$cron->{'id'}} > 60) {
5579 print DEBUG "Running cron id=$cron->{'id'} ".
5580 "module=$cron->{'module'} func=$cron->{'func'}\n";
5581 $webmincron_last{$cron->{'id'}} = $now;
5585 # Run via a wrapper command, which we run like a CGI
5586 dbmclose(%sessiondb);
5588 # Setup CGI-like environment
5589 $envtz = $ENV{"TZ"};
5590 $envuser = $ENV{"USER"};
5591 $envpath = $ENV{"PATH"};
5592 $envlang = $ENV{"LANG"};
5593 $envroot = $ENV{"SystemRoot"};
5594 $envperllib = $ENV{'PERLLIB'};
5595 foreach my $k (keys %ENV) {
5598 $ENV{"PATH"} = $envpath if ($envpath);
5599 $ENV{"TZ"} = $envtz if ($envtz);
5600 $ENV{"USER"} = $envuser if ($envuser);
5601 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5602 $ENV{"SystemRoot"} = $envroot if ($envroot);
5603 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5604 $ENV{"HOME"} = $user_homedir;
5605 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5606 $ENV{"SERVER_ADMIN"} = $config{"email"};
5608 $ENV{"SERVER_ROOT"} = $root0;
5609 $ENV{"SERVER_REALROOT"} = $root0;
5610 $ENV{"SERVER_PORT"} = $config{'port'};
5611 $ENV{"WEBMIN_CRON"} = 1;
5612 $ENV{"DOCUMENT_ROOT"} = $root0;
5613 $ENV{"DOCUMENT_REALROOT"} = $root0;
5614 $ENV{"MINISERV_CONFIG"} = $config_file;
5615 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5616 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5617 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5618 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5619 $ENV{"SCRIPT_NAME"} = $1;
5621 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5623 foreach $k (keys %config) {
5624 if ($k =~ /^env_(\S+)$/) {
5625 $ENV{$1} = $config{$k};
5629 $SIG{'CHLD'} = 'DEFAULT';
5631 # Have SOCK closed if the perl exec's something
5633 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5636 # Run the wrapper script by evaling it
5637 $pkg = "webmincron";
5638 $0 = $config{'webmincron_wrapper'};
5640 $main_process_id = $$;
5644 do \$miniserv::config{'webmincron_wrapper'};
5648 print STDERR "Perl cron failure : $@\n";
5653 push(@childpids, $pid);
5657 # Write out file containing last run times
5658 &write_file($config{'webmincron_last'}, \%webmincron_last);
5662 # matches_cron(cron-spec, time)
5663 # Checks if some minute or hour matches some cron spec, which can be * or a list
5667 my ($spec, $tm) = @_;
5672 foreach my $s (split(/,/, $spec)) {
5674 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5682 # read_webmin_crons()
5683 # Read all scheduled webmin cron functions and store them in the @webmincrons
5685 sub read_webmin_crons
5688 opendir(CRONS, $config{'webmincron_dir'});
5689 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5690 foreach my $f (readdir(CRONS)) {
5691 if ($f =~ /^(\d+)\.cron$/) {
5693 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5696 foreach my $n ('module', 'func') {
5698 print STDERR "Cron $1 missing $n\n";
5702 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5703 print STDERR "Cron $1 missing any time spec\n";
5706 if ($cron{'special'} eq 'hourly') {
5707 # Run every hour on the hour
5709 $cron{'hours'} = '*';
5710 $cron{'days'} = '*';
5711 $cron{'months'} = '*';
5712 $cron{'weekdays'} = '*';
5714 elsif ($cron{'special'} eq 'daily') {
5715 # Run every day at midnight
5717 $cron{'hours'} = '0';
5718 $cron{'days'} = '*';
5719 $cron{'months'} = '*';
5720 $cron{'weekdays'} = '*';
5722 elsif ($cron{'special'} eq 'monthly') {
5723 # Run every month on the 1st
5725 $cron{'hours'} = '0';
5726 $cron{'days'} = '1';
5727 $cron{'months'} = '*';
5728 $cron{'weekdays'} = '*';
5730 elsif ($cron{'special'} eq 'weekly') {
5731 # Run every month on the 1st
5733 $cron{'hours'} = '0';
5734 $cron{'days'} = '*';
5735 $cron{'months'} = '*';
5736 $cron{'weekdays'} = '0';
5738 elsif ($cron{'special'} eq 'yearly' ||
5739 $cron{'special'} eq 'annually') {
5740 # Run every year on 1st january
5742 $cron{'hours'} = '0';
5743 $cron{'days'} = '1';
5744 $cron{'months'} = '1';
5745 $cron{'weekdays'} = '*';
5747 elsif ($cron{'special'}) {
5748 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5751 if ($cron{'special'}) {
5752 delete($cron{'special'});
5755 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5756 push(@webmincrons, \%cron);
5763 # Read into the Webmin cache all files marked for pre-caching
5766 undef(%main::read_file_cache);
5767 foreach my $g (split(/\s+/, $config{'precache'})) {
5768 next if ($g eq "none");
5769 foreach my $f (glob("$config{'root'}/$g")) {
5772 $main::read_file_cache{$f} = { };
5773 &read_file($f, $main::read_file_cache{$f});
5774 $main::read_file_cache_time{$f} = $st[9];
5779 # Check if some address is valid IPv4, returns 1 if so.
5782 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5783 $1 >= 0 && $1 <= 255 &&
5784 $2 >= 0 && $2 <= 255 &&
5785 $3 >= 0 && $3 <= 255 &&
5786 $4 >= 0 && $4 <= 255;
5789 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5790 sub check_ip6address
5792 my @blocks = split(/:/, $_[0]);
5793 return 0 if (@blocks == 0 || @blocks > 8);
5795 my $where = index($blocks[$ib],"/");
5798 my $b = substr($blocks[$ib],0,$where);
5799 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5802 return 0 if ($m <0 || $m >128);
5805 foreach $b (@blocks) {
5806 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5807 $empty++ if ($b eq "");
5809 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5813 # network_to_address(binary)
5814 # Given a network address in binary IPv4 or v4 format, return the string form
5815 sub network_to_address
5818 if (length($addr) == 4 || !$use_ipv6) {
5819 return inet_ntoa($addr);
5822 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);
5826 # redirect_stderr_to_log()
5827 # Re-direct STDERR to error log file
5828 sub redirect_stderr_to_log
5830 if ($config{'errorlog'} ne '-') {
5831 open(STDERR, ">>$config{'errorlog'}") ||
5832 die "failed to open $config{'errorlog'} : $!";
5833 if ($config{'logperms'}) {
5834 chmod(oct($config{'logperms'}), $config{'errorlog'});
5837 select(STDERR); $| = 1; select(STDOUT);
5840 # should_gzip_file(filename)
5841 # Returns 1 if some path should be gzipped
5842 sub should_gzip_file
5845 return $path !~ /\.(gif|png|jpg|jpeg|tif|tiff)$/i;
5848 # get_expires_time(path)
5849 # Given a URL path, return the client-side expiry time in seconds
5850 sub get_expires_time
5853 foreach my $pe (@expires_paths) {
5854 if ($path =~ /$pe->[0]/i) {
5858 return $config{'expires'};