Add option for mode that assumes PAM is working
[webmin.git] / miniserv.pl
1 #!/usr/local/bin/perl
2 # A very simple perl web server used by Webmin
3
4 # Require basic libraries
5 package miniserv;
6 use Socket;
7 use POSIX;
8 use Time::Local;
9
10 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
11
12 # Find and read config file
13 if (@ARGV != 1) {
14         die "Usage: miniserv.pl <config file>";
15         }
16 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
17         $config_file = $ARGV[0];
18         }
19 else {
20         chop($pwd = `pwd`);
21         $config_file = "$pwd/$ARGV[0]";
22         }
23 %config = &read_config_file($config_file);
24 if ($config{'perllib'}) {
25         push(@INC, split(/:/, $config{'perllib'}));
26         $ENV{'PERLLIB'} .= ':'.$config{'perllib'};
27         }
28
29 # Check is SSL is enabled and available
30 if ($config{'ssl'}) {
31         eval "use Net::SSLeay";
32         if (!$@) {
33                 $use_ssl = 1;
34                 # These functions only exist for SSLeay 1.0
35                 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
36                 eval "Net::SSLeay::load_error_strings()";
37                 if ($config{'no_ssl2'}) {
38                         eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
39                         }
40                 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
41                     defined(&Net::SSLeay::CTX_load_verify_locations) &&
42                     defined(&Net::SSLeay::CTX_set_verify)) {
43                         $client_certs = 1;
44                         }
45                 }
46         }
47
48 # Check if the syslog module is available to log hacking attempts
49 if ($config{'syslog'} && !$config{'inetd'}) {
50         eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
51         if (!$@) {
52                 $use_syslog = 1;
53                 }
54         }
55
56 # check if the TCP-wrappers module is available
57 if ($config{'libwrap'}) {
58         eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
59         if (!$@) {
60                 $use_libwrap = 1;
61                 }
62         }
63
64 # Check if the MD5 perl module is available
65 eval "use MD5";
66 if (!$@) {
67         $use_md5 = "MD5";
68         }
69 else {
70         eval "use Digest::MD5";
71         if (!$@) {
72                 $use_md5 = "Digest::MD5";
73                 }
74         }
75
76 # Get miniserv's perl path and location
77 $miniserv_path = $0;
78 open(SOURCE, $miniserv_path);
79 <SOURCE> =~ /^#!(\S+)/;
80 $perl_path = $1;
81 close(SOURCE);
82 if (!-x $perl_path) {
83         $perl_path = $^X;
84         }
85 if (-l $perl_path) {
86         $linked_perl_path = readlink($perl_path);
87         }
88 @miniserv_argv = @ARGV;
89
90 # Check vital config options
91 &update_vital_config();
92
93 $sidname = $config{'sidname'};
94 die "Session authentication cannot be used in inetd mode"
95         if ($config{'inetd'} && $config{'session'});
96
97 # check if the PAM module is available to authenticate
98 if ($config{'assume_pam'}) {
99         # Just assume that it will work. This can also be used to work around
100         # a Solaris bug in which using PAM before forking caused it to fail
101         # later!
102         $use_pam = 1;
103         }
104 elsif (!$config{'no_pam'}) {
105         eval "use Authen::PAM;";
106         if (!$@) {
107                 # check if the PAM authentication can be used by opening a
108                 # PAM handle
109                 local $pamh;
110                 if (ref($pamh = new Authen::PAM($config{'pam'},
111                                                 $config{'pam_test_user'},
112                                                 \&pam_conv_func))) {
113                         # Now test a login to see if /etc/pam.d/XXX is set
114                         # up properly.
115                         $pam_conv_func_called = 0;
116                         $pam_username = "test";
117                         $pam_password = "test";
118                         $pamh->pam_authenticate();
119                         if ($pam_conv_func_called) {
120                                 $pam_msg = "PAM authentication enabled";
121                                 $use_pam = 1;
122                                 }
123                         else {
124                                 $pam_msg = "PAM test failed - maybe /etc/pam.d/$config{'pam'} does not exist";
125                                 }
126                         }
127                 else {
128                         $pam_msg = "PAM initialization of Authen::PAM failed";
129                         }
130                 }
131         else {
132                 $pam_msg = "Perl module Authen::PAM needed for PAM is not installed : $@";
133                 }
134         }
135 if ($config{'pam_only'} && !$use_pam) {
136         print STDERR $pam_msg;
137         print STDERR "PAM use is mandatory, but could not be enabled!\n";
138         exit(1);
139         }
140 elsif ($pam_msg && !$use_pam) {
141         $pam_msg2 = "Continuing without the Authen::PAM perl module";
142         }
143
144 # Check if the User::Utmp perl module is installed
145 if ($config{'utmp'}) {
146         eval "use User::Utmp;";
147         if (!$@) {
148                 $write_utmp = 1;
149                 $utmp_msg = "UTMP logging enabled";
150                 }
151         else {
152                 $utmp_msg = "Perl module User::Utmp needed for Utmp logging is not installed : $@";
153                 }
154         }
155
156 # See if the crypt function fails
157 eval "crypt('foo', 'xx')";
158 if ($@) {
159         eval "use Crypt::UnixCrypt";
160         if (!$@) {
161                 $use_perl_crypt = 1;
162                 $crypt_msg = "Using Crypt::UnixCrypt for password encryption\n";
163                 }
164         else {
165                 $crypt_msg = "crypt() function un-implemented, and Crypt::UnixCrypt not installed - password authentication will probably fail\n";
166                 }
167         }
168
169 # Check if /dev/urandom really generates random IDs, by calling it twice
170 local $rand1 = &generate_random_id("foo", 1);
171 local $rand2 = &generate_random_id("foo", 2);
172 local $rand_msg;
173 if ($rand1 eq $rand2) {
174         $bad_urandom = 1;
175         $rand_msg = "Random number generator file /dev/urandom is not reliable";
176         }
177
178 # Check if we can call sudo
179 if ($config{'sudo'} && &has_command("sudo")) {
180         eval "use IO::Pty";
181         if (!$@) {
182                 $use_sudo = 1;
183                 }
184         else {
185                 $sudo_msg = "Perl module IO::Pty needed for calling sudo is not installed : $@";
186                 }
187         }
188
189 # init days and months for http_date
190 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
191 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
192            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
193
194 # Change dir to the server root
195 @roots = ( $config{'root'} );
196 for($i=0; defined($config{"extraroot_$i"}); $i++) {
197         push(@roots, $config{"extraroot_$i"});
198         }
199 chdir($roots[0]);
200 eval { $user_homedir = (getpwuid($<))[7]; };
201 if ($@) {
202         # getpwuid doesn't work on windows
203         $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
204         $on_windows = 1;
205         }
206
207 # Read users file
208 &read_users_file();
209
210 # Setup SSL if possible and if requested
211 if (!-r $config{'keyfile'} ||
212     $config{'certfile'} && !-r $config{'certfile'}) {
213         # Key file doesn't exist!
214         $use_ssl = 0;
215         }
216 @ipkeys = &get_ipkeys(\%config);
217 if ($use_ssl) {
218         if ($config{'ssl_version'}) {
219                 # Force an SSL version
220                 $Net::SSLeay::version = $config{'ssl_version'};
221                 $Net::SSLeay::ssl_version = $config{'ssl_version'};
222                 }
223         $client_certs = 0 if (!-r $config{'ca'} || !%certs);
224         $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
225                                                  $config{'certfile'});
226         foreach $ipkey (@ipkeys) {
227                 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
228                 foreach $ip (@{$ipkey->{'ips'}}) {
229                         $ssl_contexts{$ip} = $ctx;
230                         }
231                 }
232         }
233
234 # Setup syslog support if possible and if requested
235 if ($use_syslog) {
236         open(ERRDUP, ">&STDERR");
237         open(STDERR, ">/dev/null");
238         $log_socket = $config{"logsock"} || "unix";
239         eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
240         if ($@) {
241                 $use_syslog = 0;
242                 }
243         else {
244                 local $msg = ucfirst($config{'pam'})." starting";
245                 eval { syslog("info", "%s", $msg); };
246                 if ($@) {
247                         eval {
248                                 setlogsock("inet");
249                                 syslog("info", "%s", $msg);
250                                 };
251                         if ($@) {
252                                 # All attempts to use syslog have failed..
253                                 $use_syslog = 0;
254                                 }
255                         }
256                 }
257         open(STDERR, ">&ERRDUP");
258         close(ERRDUP);
259         }
260
261 # Read MIME types file and add extra types
262 &read_mime_types();
263
264 # get the time zone
265 if ($config{'log'}) {
266         local(@gmt, @lct, $days, $hours, $mins);
267         @gmt = gmtime(time());
268         @lct = localtime(time());
269         $days = $lct[3] - $gmt[3];
270         $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
271                  $lct[2] - $gmt[2];
272         $mins = $hours * 60 + $lct[1] - $gmt[1];
273         $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
274         $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
275         }
276
277 # Build various maps from the config files
278 &build_config_mappings();
279
280 # start up external authentication program, if needed
281 if ($config{'extauth'}) {
282         socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
283         if (!($extauth = fork())) {
284                 close(EXTAUTH);
285                 close(STDIN);
286                 close(STDOUT);
287                 open(STDIN, "<&EXTAUTH2");
288                 open(STDOUT, ">&EXTAUTH2");
289                 exec($config{'extauth'}) or die "exec failed : $!\n";
290                 }
291         close(EXTAUTH2);
292         local $os = select(EXTAUTH);
293         $| = 1; select($os);
294         }
295
296 # Pre-load any libraries
297 if (!$config{'inetd'}) {
298         foreach $pl (split(/\s+/, $config{'preload'})) {
299                 ($pkg, $lib) = split(/=/, $pl);
300                 $pkg =~ s/[^A-Za-z0-9]/_/g;
301                 eval "package $pkg; do '$config{'root'}/$lib'";
302                 if ($@) {
303                         print STDERR "Failed to pre-load $lib in $pkg : $@\n";
304                         }
305                 else {
306                         print STDERR "Pre-loaded $lib in $pkg\n";
307                         }
308                 }
309         foreach $pl (split(/\s+/, $config{'premodules'})) {
310                 if ($pl =~ /\//) {
311                         ($dir, $mod) = split(/\//, $pl);
312                         }
313                 else {
314                         ($dir, $mod) = (undef, $pl);
315                         }
316                 push(@INC, "$config{'root'}/$dir");
317                 eval "package $mod; use $mod ()";
318                 if ($@) {
319                         print STDERR "Failed to pre-load $mod : $@\n";
320                         }
321                 else {
322                         print STDERR "Pre-loaded $mod\n";
323                         }
324                 }
325         }
326
327 # Open debug log if set
328 if ($config{'debuglog'}) {
329         open(DEBUG, ">>$config{'debuglog'}");
330         chmod(0700, $config{'debuglog'});
331         select(DEBUG); $| = 1; select(STDOUT);
332         print DEBUG "miniserv.pl starting ..\n";
333         }
334
335 # Write out (empty) blocked hosts file
336 &write_blocked_file();
337
338 # Initially read webmin cron functions and last execution times
339 &read_webmin_crons();
340 %webmincron_last = ( );
341 &read_file($config{'webmincron_last'}, \%webmincron_last);
342
343 # Re-direct STDERR to a log file
344 if ($config{'errorlog'} ne '-') {
345         open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
346         if ($config{'logperms'}) {
347                 chmod(oct($config{'logperms'}), $config{'errorlog'});
348                 }
349         }
350 select(STDERR); $| = 1; select(STDOUT);
351
352 if ($config{'inetd'}) {
353         # We are being run from inetd - go direct to handling the request
354         $SIG{'HUP'} = 'IGNORE';
355         $SIG{'TERM'} = 'DEFAULT';
356         $SIG{'PIPE'} = 'DEFAULT';
357         open(SOCK, "+>&STDIN");
358
359         # Check if it is time for the logfile to be cleared
360         if ($config{'logclear'}) {
361                 local $write_logtime = 0;
362                 local @st = stat("$config{'logfile'}.time");
363                 if (@st) {
364                         if ($st[9]+$config{'logtime'}*60*60 < time()){
365                                 # need to clear log
366                                 $write_logtime = 1;
367                                 unlink($config{'logfile'});
368                                 }
369                         }
370                 else { $write_logtime = 1; }
371                 if ($write_logtime) {
372                         open(LOGTIME, ">$config{'logfile'}.time");
373                         print LOGTIME time(),"\n";
374                         close(LOGTIME);
375                         }
376                 }
377
378         # Initialize SSL for this connection
379         if ($use_ssl) {
380                 $ssl_con = &ssl_connection_for_ip(SOCK);
381                 $ssl_con || exit;
382                 }
383
384         # Work out the hostname for this web server
385         $host = &get_socket_name(SOCK);
386         $host || exit;
387         $port = $config{'port'};
388         $acptaddr = getpeername(SOCK);
389         $acptaddr || exit;
390
391         print DEBUG "main: Starting handle_request loop pid=$$\n";
392         while(&handle_request($acptaddr, getsockname(SOCK))) { }
393         print DEBUG "main: Done handle_request loop pid=$$\n";
394         close(SOCK);
395         exit;
396         }
397
398 # Build list of sockets to listen on
399 if ($config{"bind"} && $config{"bind"} ne "*") {
400         push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
401         }
402 else {
403         push(@sockets, [ INADDR_ANY, $config{'port'} ]);
404         }
405 foreach $s (split(/\s+/, $config{'sockets'})) {
406         if ($s =~ /^(\d+)$/) {
407                 # Just listen on another port on the main IP
408                 push(@sockets, [ $sockets[0]->[0], $s ]);
409                 }
410         elsif ($s =~ /^(\S+):(\d+)$/) {
411                 # Listen on a specific port and IP
412                 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
413                 }
414         elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
415                 # Listen on the main port on another IP
416                 push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
417                 }
418         }
419
420 # Open all the sockets
421 $proto = getprotobyname('tcp');
422 @sockerrs = ( );
423 $tried_inaddr_any = 0;
424 for($i=0; $i<@sockets; $i++) {
425         $fh = "MAIN$i";
426         socket($fh, PF_INET, SOCK_STREAM, $proto) ||
427                 die "Failed to open socket : $!";
428         setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
429         for($j=0; $j<5; $j++) {
430                 last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
431                                                     $sockets[$i]->[0])));
432                 sleep(1);
433                 }
434         if ($j == 5) {
435                 # All attempts failed .. give up
436                 if ($sockets[$i]->[0] eq INADDR_ANY) {
437                         push(@sockerrs, "Failed to bind to port $sockets[$i]->[1] : $!");
438                         $tried_inaddr_any = 1;
439                         }
440                 else {
441                         $ip = inet_ntoa($sockets[$i]->[0]);
442                         push(@sockerrs, "Failed to bind to IP $ip port $sockets[$i]->[1] : $!");
443                         }
444                 }
445         else {
446                 listen($fh, SOMAXCONN);
447                 push(@socketfhs, $fh);
448                 }
449         }
450 foreach $se (@sockerrs) {
451         print STDERR $se,"\n";
452         }
453
454 # If all binds failed, try binding to any address
455 if (!@socketfhs && !$tried_inaddr_any) {
456         print STDERR "Falling back to listening on any address\n";
457         $fh = "MAIN";
458         socket($fh, PF_INET, SOCK_STREAM, $proto) ||
459                 die "Failed to open socket : $!";
460         setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
461         bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
462                 die "Failed to bind to port $sockets[0]->[1] : $!";
463         listen($fh, SOMAXCONN);
464         push(@socketfhs, $fh);
465         }
466 elsif (!@socketfhs && $tried_inaddr_any) {
467         die "Could not listen on any ports";
468         }
469
470 if ($config{'listen'}) {
471         # Open the socket that allows other webmin servers to find this one
472         $proto = getprotobyname('udp');
473         if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
474                 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
475                 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
476                 listen(LISTEN, SOMAXCONN);
477                 }
478         else {
479                 $config{'listen'} = 0;
480                 }
481         }
482
483 # Split from the controlling terminal, unless configured not to
484 if (!$config{'nofork'}) {
485         if (fork()) { exit; }
486         }
487 eval { setsid(); };     # may not work on Windows
488
489 # Close standard file handles
490 open(STDIN, "</dev/null");
491 open(STDOUT, ">/dev/null");
492 &log_error("miniserv.pl started");
493 &log_error($pam_msg) if ($pam_msg);
494 &log_error($pam_msg2) if ($pam_msg2);
495 &log_error($utmp_msg) if ($utmp_msg);
496 &log_error($crypt_msg) if ($crypt_msg);
497 &log_error($sudo_msg) if ($sudo_msg);
498 &log_error($rand_msg) if ($rand_msg);
499
500 # write out the PID file
501 &write_pid_file();
502
503 # Start the log-clearing process, if needed. This checks every minute
504 # to see if the log has passed its reset time, and if so clears it
505 if ($config{'logclear'}) {
506         if (!($logclearer = fork())) {
507                 &close_all_sockets();
508                 close(LISTEN);
509                 while(1) {
510                         local $write_logtime = 0;
511                         local @st = stat("$config{'logfile'}.time");
512                         if (@st) {
513                                 if ($st[9]+$config{'logtime'}*60*60 < time()){
514                                         # need to clear log
515                                         $write_logtime = 1;
516                                         unlink($config{'logfile'});
517                                         }
518                                 }
519                         else { $write_logtime = 1; }
520                         if ($write_logtime) {
521                                 open(LOGTIME, ">$config{'logfile'}.time");
522                                 print LOGTIME time(),"\n";
523                                 close(LOGTIME);
524                                 }
525                         sleep(5*60);
526                         }
527                 exit;
528                 }
529         push(@childpids, $logclearer);
530         }
531
532 # Setup the logout time dbm if needed
533 if ($config{'session'}) {
534         eval "use SDBM_File";
535         dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
536         eval "\$sessiondb{'1111111111'} = 'foo bar';";
537         if ($@) {
538                 dbmclose(%sessiondb);
539                 eval "use NDBM_File";
540                 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
541                 }
542         else {
543                 delete($sessiondb{'1111111111'});
544                 }
545         }
546
547 # Run the main loop
548 $SIG{'HUP'} = 'miniserv::trigger_restart';
549 $SIG{'TERM'} = 'miniserv::term_handler';
550 $SIG{'USR1'} = 'miniserv::trigger_reload';
551 $SIG{'PIPE'} = 'IGNORE';
552 local $remove_session_count = 0;
553 $need_pipes = $config{'passdelay'} || $config{'session'};
554 while(1) {
555         # wait for a new connection, or a message from a child process
556         local ($i, $rmask);
557         if (@childpids <= $config{'maxconns'}) {
558                 # Only accept new main socket connects when ready
559                 local $s;
560                 foreach $s (@socketfhs) {
561                         vec($rmask, fileno($s), 1) = 1;
562                         }
563                 }
564         else {
565                 printf STDERR "too many children (%d > %d)\n",
566                         scalar(@childpids), $config{'maxconns'};
567                 }
568         if ($need_pipes) {
569                 for($i=0; $i<@passin; $i++) {
570                         vec($rmask, fileno($passin[$i]), 1) = 1;
571                         }
572                 }
573         vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
574
575         # Wait for a connection
576         local $sel = select($rmask, undef, undef, 10);
577
578         # Check the flag files
579         if ($config{'restartflag'} && -r $config{'restartflag'}) {
580                 print STDERR "restart flag file detected\n";
581                 unlink($config{'restartflag'});
582                 $need_restart = 1;
583                 }
584         if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
585                 unlink($config{'reloadflag'});
586                 $need_reload = 1;
587                 }
588
589         if ($need_restart) {
590                 # Got a HUP signal while in select() .. restart now
591                 &restart_miniserv();
592                 }
593         if ($need_reload) {
594                 # Got a USR1 signal while in select() .. re-read config
595                 $need_reload = 0;
596                 &reload_config_file();
597                 }
598         local $time_now = time();
599
600         # Clean up finished processes
601         local $pid;
602         do {    $pid = waitpid(-1, WNOHANG);
603                 @childpids = grep { $_ != $pid } @childpids;
604                 } while($pid != 0 && $pid != -1);
605
606         # run the unblocking procedure to check if enough time has passed to
607         # unblock hosts that heve been blocked because of password failures
608         $unblocked = 0;
609         if ($config{'blockhost_failures'}) {
610                 $i = 0;
611                 while ($i <= $#deny) {
612                         if ($blockhosttime{$deny[$i]} &&
613                             $config{'blockhost_time'} != 0 &&
614                             ($time_now - $blockhosttime{$deny[$i]}) >=
615                              $config{'blockhost_time'}) {
616                                 # the host can be unblocked now
617                                 $hostfail{$deny[$i]} = 0;
618                                 splice(@deny, $i, 1);
619                                 $unblocked = 1;
620                                 }
621                         $i++;
622                         }
623                 }
624
625         # Do the same for blocked users
626         if ($config{'blockuser_failures'}) {
627                 $i = 0;
628                 while ($i <= $#deny) {
629                         if ($blockusertime{$deny[$i]} &&
630                             $config{'blockuser_time'} != 0 &&
631                             ($time_now - $blockusertime{$deny[$i]}) >=
632                              $config{'blockuser_time'}) {
633                                 # the user can be unblocked now
634                                 $userfail{$deny[$i]} = 0;
635                                 splice(@denyusers, $i, 1);
636                                 $unblocked = 1;
637                                 }
638                         $i++;
639                         }
640                 }
641         if ($unblocked) {
642                 &write_blocked_file();
643                 }
644
645         # Check if any webmin cron jobs are ready to run
646         &execute_ready_webmin_crons();
647
648         if ($config{'session'} && (++$remove_session_count%50) == 0) {
649                 # Remove sessions with more than 7 days of inactivity,
650                 local $s;
651                 foreach $s (keys %sessiondb) {
652                         local ($user, $ltime, $lip) =
653                                 split(/\s+/, $sessiondb{$s});
654                         if ($time_now - $ltime > 7*24*60*60) {
655                                 &run_logout_script($s, $user);
656                                 &write_logout_utmp($user, $lip);
657                                 delete($sessiondb{$s});
658                                 if ($use_syslog) {
659                                         syslog("info", "%s",
660                                               "Timeout of session for $user");
661                                         }
662                                 }
663                         }
664                 }
665
666         if ($use_pam && $config{'pam_conv'}) {
667                 # Remove PAM sessions with more than 5 minutes of inactivity
668                 local $c;
669                 foreach $c (values %conversations) {
670                         if ($time_now - $c->{'time'} > 5*60) {
671                                 &end_pam_conversation($c);
672                                 if ($use_syslog) {
673                                         syslog("info", "%s", "Timeout of PAM ".
674                                                 "session for $c->{'user'}");
675                                         }
676                                 }
677                         }
678                 }
679
680         # Don't check any sockets if there is no activity
681         next if ($sel <= 0);
682
683         # Check if any of the main sockets have received a new connection
684         local $sn = 0;
685         foreach $s (@socketfhs) {
686                 if (vec($rmask, fileno($s), 1)) {
687                         # got new connection
688                         $acptaddr = accept(SOCK, $s);
689                         if (!$acptaddr) { next; }
690                         binmode(SOCK);  # turn off any Perl IO stuff
691
692                         # create pipes
693                         local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
694                         if ($need_pipes) {
695                                 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
696                                         &allocate_pipes();
697                                 }
698
699                         # Check username of connecting user
700                         local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
701                         $localauth_user = undef;
702                         if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
703                                 if (open(TCP, "/proc/net/tcp")) {
704                                         # Get the info direct from the kernel
705                                         while(<TCP>) {
706                                                 s/^\s+//;
707                                                 local @t = split(/[\s:]+/, $_);
708                                                 if ($t[1] eq '0100007F' &&
709                                                     $t[2] eq sprintf("%4.4X", $peerp)) {
710                                                         $localauth_user = getpwuid($t[11]);
711                                                         last;
712                                                         }
713                                                 }
714                                         close(TCP);
715                                         }
716                                 if (!$localauth_user) {
717                                         # Call lsof for the info
718                                         local $lsofpid = open(LSOF,
719                                                 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
720                                         while(<LSOF>) {
721                                                 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
722                                                     $2 != $$ && $2 != $lsofpid) {
723                                                         $localauth_user = $3;
724                                                         }
725                                                 }
726                                         close(LSOF);
727                                         }
728                                 }
729
730                         # Work out the hostname for this web server
731                         $host = &get_socket_name(SOCK);
732                         if (!$host) {
733                                 print STDERR "Failed to get local socket name : $!\n";
734                                 close(SOCK);
735                                 next;
736                                 }
737                         $port = $sockets[$sn]->[1];
738
739                         # fork the subprocess
740                         local $handpid;
741                         if (!($handpid = fork())) {
742                                 # setup signal handlers
743                                 $SIG{'TERM'} = 'DEFAULT';
744                                 $SIG{'PIPE'} = 'DEFAULT';
745                                 #$SIG{'CHLD'} = 'IGNORE';
746                                 $SIG{'HUP'} = 'IGNORE';
747                                 $SIG{'USR1'} = 'IGNORE';
748
749                                 # Initialize SSL for this connection
750                                 if ($use_ssl) {
751                                         $ssl_con = &ssl_connection_for_ip(SOCK);
752                                         $ssl_con || exit;
753                                         }
754
755                                 # Close the file handle for the session DBM
756                                 dbmclose(%sessiondb);
757
758                                 # close useless pipes
759                                 if ($need_pipes) {
760                                         &close_all_pipes();
761                                         close($PASSINr); close($PASSOUTw);
762                                         }
763                                 &close_all_sockets();
764                                 close(LISTEN);
765
766                                 print DEBUG
767                                   "main: Starting handle_request loop pid=$$\n";
768                                 while(&handle_request($acptaddr,
769                                                       getsockname(SOCK))) { }
770                                 print DEBUG
771                                   "main: Done handle_request loop pid=$$\n";
772                                 shutdown(SOCK, 1);
773                                 close(SOCK);
774                                 close($PASSINw); close($PASSOUTw);
775                                 exit;
776                                 }
777                         push(@childpids, $handpid);
778                         if ($need_pipes) {
779                                 close($PASSINw); close($PASSOUTr);
780                                 push(@passin, $PASSINr);
781                                 push(@passout, $PASSOUTw);
782                                 }
783                         close(SOCK);
784                         }
785                 $sn++;
786                 }
787
788         if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
789                 # Got UDP packet from another webmin server
790                 local $rcvbuf;
791                 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
792                 next if (!$from);
793                 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
794                 local $toip = inet_ntoa((unpack_sockaddr_in(
795                                          getsockname(LISTEN)))[1]);
796                 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
797                     (!@allow || &ip_match($fromip, $toip, @allow))) {
798                         local $listenhost = &get_socket_name(LISTEN);
799                         send(LISTEN, "$listenhost:$config{'port'}:".
800                                   ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
801                                   ($config{'listenhost'} ?
802                                         &get_system_hostname() : ""),
803                                   0, $from)
804                                 if ($listenhost);
805                         }
806                 }
807
808         # check for session, password-timeout and PAM messages from subprocesses
809         for($i=0; $i<@passin; $i++) {
810                 if (vec($rmask, fileno($passin[$i]), 1)) {
811                         # this sub-process is asking about a password
812                         local $infd = $passin[$i];
813                         local $outfd = $passout[$i];
814                         #local $inline = <$infd>;
815                         local $inline = &sysread_line($infd);
816                         if ($inline) {
817                                 print DEBUG "main: inline $inline";
818                                 }
819                         else {
820                                 print DEBUG "main: inline EOF\n";
821                                 }
822                         if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
823                                 # Got a delay request from a subprocess.. for
824                                 # valid logins, there is no delay (to prevent
825                                 # denial of service attacks), but for invalid
826                                 # logins the delay increases with each failed
827                                 # attempt.
828                                 if ($3) {
829                                         # login OK.. no delay
830                                         print $outfd "0 0\n";
831                                         $wasblocked = $hostfail{$2} ||
832                                                       $userfail{$1};
833                                         $hostfail{$2} = 0;
834                                         $userfail{$1} = 0;
835                                         if ($wasblocked) {
836                                                 &write_blocked_file();
837                                                 }
838                                         }
839                                 else {
840                                         # login failed..
841                                         $hostfail{$2}++;
842                                         $userfail{$1}++;
843                                         $blocked = 0;
844
845                                         # add the host to the block list,
846                                         # if configured
847                                         if ($config{'blockhost_failures'} &&
848                                             $hostfail{$2} >=
849                                               $config{'blockhost_failures'}) {
850                                                 push(@deny, $2);
851                                                 $blockhosttime{$2} = $time_now;
852                                                 $blocked = 1;
853                                                 if ($use_syslog) {
854                                                         local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
855                                                         syslog("crit", "%s",
856                                                                 $logtext);
857                                                         }
858                                                 }
859
860                                         # add the user to the user block list,
861                                         # if configured
862                                         if ($config{'blockuser_failures'} &&
863                                             $userfail{$1} >=
864                                               $config{'blockuser_failures'}) {
865                                                 push(@denyusers, $1);
866                                                 $blockusertime{$1} = $time_now;
867                                                 $blocked = 2;
868                                                 if ($use_syslog) {
869                                                         local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
870                                                         syslog("crit", "%s",
871                                                                 $logtext);
872                                                         }
873                                                 }
874
875                                         # Lock out the user's password, if enabled
876                                         if ($config{'blocklock'} &&
877                                             $userfail{$1} >=
878                                               $config{'blockuser_failures'}) {
879                                                 my $lk = &lock_user_password($1);
880                                                 $blocked = 2;
881                                                 if ($use_syslog) {
882                                                         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";
883                                                         syslog("crit", "%s",
884                                                                 $logtext);
885                                                         }
886                                                 }
887
888                                         # Send back a delay
889                                         $dl = $userdlay{$1} -
890                                            int(($time_now - $userlast{$1})/50);
891                                         $dl = $dl < 0 ? 0 : $dl+1;
892                                         print $outfd "$dl $blocked\n";
893                                         $userdlay{$1} = $dl;
894
895                                         # Write out blocked status file
896                                         if ($blocked) {
897                                                 &write_blocked_file();
898                                                 }
899                                         }
900                                 $userlast{$1} = $time_now;
901                                 }
902                         elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
903                                 # Verifying a session ID
904                                 local $session_id = $1;
905                                 local $notimeout = $2;
906                                 local $skey = $sessiondb{$session_id} ?
907                                                 $session_id : 
908                                                 &hash_session_id($session_id);
909                                 if (!defined($sessiondb{$skey})) {
910                                         # Session doesn't exist
911                                         print $outfd "0 0\n";
912                                         }
913                                 else {
914                                         local ($user, $ltime) =
915                                           split(/\s+/, $sessiondb{$skey});
916                                         local $lot = &get_logout_time($user, $session_id);
917                                         if ($lot &&
918                                             $time_now - $ltime > $lot*60 &&
919                                             !$notimeout) {
920                                                 # Session has timed out
921                                                 print $outfd "1 ",$time_now - $ltime,"\n";
922                                                 #delete($sessiondb{$skey});
923                                                 }
924                                         else {
925                                                 # Session is OK
926                                                 print $outfd "2 $user\n";
927                                                 if ($lot &&
928                                                     $time_now - $ltime >
929                                                     ($lot*60)/2) {
930                                                         $sessiondb{$skey} = "$user $time_now";
931                                                         }
932                                                 }
933                                         }
934                                 }
935                         elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
936                                 # Creating a new session
937                                 local $session_id = $1;
938                                 local $user = $2;
939                                 local $ip = $3;
940                                 $sessiondb{&hash_session_id($session_id)} =
941                                         "$user $time_now $ip";
942                                 }
943                         elsif ($inline =~ /^delete\s+(\S+)/) {
944                                 # Logging out a session
945                                 local $session_id = $1;
946                                 local $skey = $sessiondb{$session_id} ?
947                                                 $session_id : 
948                                                 &hash_session_id($session_id);
949                                 local @sdb = split(/\s+/, $sessiondb{$skey});
950                                 print $outfd $sdb[0],"\n";
951                                 delete($sessiondb{$skey});
952                                 }
953                         elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
954                                 # Starting a new PAM conversation
955                                 local ($cid, $host, $user) = ($1, $2, $3);
956
957                                 # Does this user even need PAM?
958                                 local ($realuser, $canlogin) =
959                                         &can_user_login($user, undef, $host);
960                                 local $conv;
961                                 if ($canlogin == 0) {
962                                         # Cannot even login!
963                                         print $outfd "0 Invalid username\n";
964                                         }
965                                 elsif ($canlogin != 2) {
966                                         # Not using PAM .. so just ask for
967                                         # the password.
968                                         $conv = { 'user' => $realuser,
969                                                   'host' => $host,
970                                                   'step' => 0,
971                                                   'cid' => $cid,
972                                                   'time' => time() };
973                                         print $outfd "3 Password\n";
974                                         }
975                                 else {
976                                         # Start the PAM conversation
977                                         # sub-process, and get a question
978                                         $conv = { 'user' => $realuser,
979                                                   'host' => $host,
980                                                   'cid' => $cid,
981                                                   'time' => time() };
982                                         local ($PAMINr, $PAMINw, $PAMOUTr,
983                                                 $PAMOUTw) = &allocate_pipes();
984                                         local $pampid = fork();
985                                         if (!$pampid) {
986                                                 close($PAMOUTr); close($PAMINw);
987                                                 &pam_conversation_process(
988                                                         $realuser,
989                                                         $PAMOUTw, $PAMINr);
990                                                 }
991                                         close($PAMOUTw); close($PAMINr);
992                                         $conv->{'pid'} = $pampid;
993                                         $conv->{'PAMOUTr'} = $PAMOUTr;
994                                         $conv->{'PAMINw'} = $PAMINw;
995                                         push(@childpids, $pampid);
996
997                                         # Get the first PAM question
998                                         local $pok = &recv_pam_question(
999                                                 $conv, $outfd);
1000                                         if (!$pok) {
1001                                                 &end_pam_conversation($conv);
1002                                                 }
1003                                         }
1004
1005                                 $conversations{$cid} = $conv if ($conv);
1006                                 }
1007                         elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1008                                 # A response to a PAM question
1009                                 local ($cid, $answer) = ($1, $2);
1010                                 local $conv = $conversations{$cid};
1011                                 if (!$conv) {
1012                                         # No such conversation?
1013                                         print $outfd "0 Bad login session\n";
1014                                         }
1015                                 elsif ($conv->{'pid'}) {
1016                                         # Send the PAM response and get
1017                                         # the next question
1018                                         &send_pam_answer($conv, $answer);
1019                                         local $pok = &recv_pam_question($conv, $outfd);
1020                                         if (!$pok) {
1021                                                 &end_pam_conversation($conv);
1022                                                 }
1023                                         }
1024                                 else {
1025                                         # This must be the password .. try it
1026                                         # and send back the results
1027                                         local ($vu, $expired, $nonexist) =
1028                                                 &validate_user($conv->{'user'},
1029                                                                $answer,
1030                                                                $conf->{'host'});
1031                                         local $ok = $vu ? 1 : 0;
1032                                         print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1033                                         &end_pam_conversation($conv);
1034                                         }
1035                                 }
1036                         elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1037                                 # Store the fact that some user can sudo to root
1038                                 local ($user, $ok) = ($1, $2);
1039                                 $sudocache{$user} = $ok." ".time();
1040                                 }
1041                         elsif ($inline =~ /^readsudo\s+(\S+)/) {
1042                                 # Query the user sudo cache (valid for 1 minute)
1043                                 local $user = $1;
1044                                 local ($ok, $last) =
1045                                         split(/\s+/, $sudocache{$user});
1046                                 if ($last < time()-60) {
1047                                         # Cache too old
1048                                         print $outfd "2\n";
1049                                         }
1050                                 else {
1051                                         # Tell client OK or not
1052                                         print $outfd "$ok\n";
1053                                         }
1054                                 }
1055                         elsif ($inline =~ /\S/) {
1056                                 # Unknown line from pipe?
1057                                 print DEBUG "main: Unknown line from pipe $inline\n";
1058                                 print STDERR "Unknown line from pipe $inline\n";
1059                                 }
1060                         else {
1061                                 # close pipe
1062                                 close($infd); close($outfd);
1063                                 $passin[$i] = $passout[$i] = undef;
1064                                 }
1065                         }
1066                 }
1067         @passin = grep { defined($_) } @passin;
1068         @passout = grep { defined($_) } @passout;
1069         }
1070
1071 # handle_request(remoteaddress, localaddress)
1072 # Where the real work is done
1073 sub handle_request
1074 {
1075 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1076 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1077 print DEBUG "handle_request: from $acptip to $localip\n";
1078 if ($config{'loghost'}) {
1079         $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1080         $acpthost = $acptip if (!$acpthost);
1081         }
1082 else {
1083         $acpthost = $acptip;
1084         }
1085 $datestr = &http_date(time());
1086 $ok_code = 200;
1087 $ok_message = "Document follows";
1088 $logged_code = undef;
1089 $reqline = $request_uri = $page = undef;
1090 $authuser = undef;
1091 $validated = undef;
1092
1093 # check address against access list
1094 if (@deny && &ip_match($acptip, $localip, @deny) ||
1095     @allow && !&ip_match($acptip, $localip, @allow)) {
1096         &http_error(403, "Access denied for $acptip");
1097         return 0;
1098         }
1099
1100 if ($use_libwrap) {
1101         # Check address with TCP-wrappers
1102         if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1103                        $acptip, STRING_UNKNOWN)) {
1104                 &http_error(403, "Access denied for $acptip by TCP wrappers");
1105                 return 0;
1106                 }
1107         }
1108 print DEBUG "handle_request: passed IP checks\n";
1109
1110 # Compute a timeout for the start of headers, based on the number of
1111 # child processes. As this increases, we use a shorter timeout to avoid
1112 # an attacker overloading the system.
1113 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1114
1115 # Wait at most 60 secs for start of headers for initial requests, or
1116 # 10 minutes for kept-alive connections
1117 local $rmask;
1118 vec($rmask, fileno(SOCK), 1) = 1;
1119 local $to = $checked_timeout ? 10*60 : $header_timeout;
1120 local $sel = select($rmask, undef, undef, $to);
1121 if (!$sel) {
1122         if ($checked_timeout) {
1123                 print DEBUG "handle_request: exiting due to timeout of $to\n";
1124                 exit;
1125                 }
1126         else {
1127                 &http_error(400, "Timeout",
1128                             "Waited for that $to seconds for start of headers");
1129                 }
1130         }
1131 $checked_timeout++;
1132 print DEBUG "handle_request: passed timeout check\n";
1133
1134 # Read the HTTP request and headers
1135 local $origreqline = &read_line();
1136 ($reqline = $origreqline) =~ s/\r|\n//g;
1137 $method = $page = $request_uri = undef;
1138 print DEBUG "handle_request reqline=$reqline\n";
1139 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1140         # An empty request .. just close the connection
1141         print DEBUG "handle_request: rejecting empty request\n";
1142         return 0;
1143         }
1144 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1145         print DEBUG "handle_request: invalid reqline=$reqline\n";
1146         if ($use_ssl) {
1147                 # This could be an http request when it should be https
1148                 $use_ssl = 0;
1149                 local $url = $config{'musthost'} ?
1150                                 "https://$config{'musthost'}:$port/" :
1151                                 "https://$host:$port/";
1152                 if ($config{'ssl_redirect'}) {
1153                         # Just re-direct to the correct URL
1154                         sleep(1);       # Give browser a change to finish
1155                                         # sending its request
1156                         &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1157                         &write_data("Date: $datestr\r\n");
1158                         &write_data("Server: $config{'server'}\r\n");
1159                         &write_data("Location: $url\r\n");
1160                         &write_keep_alive(0);
1161                         &write_data("\r\n");
1162                         return 0;
1163                         }
1164                 else {
1165                         # Tell user the correct URL
1166                         &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1167                         }
1168                 }
1169         elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1170                 # This could be an https request when it should be http ..
1171                 # need to fake a HTTP response
1172                 eval <<'EOF';
1173                         use Net::SSLeay;
1174                         eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1175                         eval "Net::SSLeay::load_error_strings()";
1176                         $ssl_ctx = Net::SSLeay::CTX_new();
1177                         Net::SSLeay::CTX_use_RSAPrivateKey_file(
1178                                 $ssl_ctx, $config{'keyfile'},
1179                                 &Net::SSLeay::FILETYPE_PEM);
1180                         Net::SSLeay::CTX_use_certificate_file(
1181                                 $ssl_ctx,
1182                                 $config{'certfile'} || $config{'keyfile'},
1183                                 &Net::SSLeay::FILETYPE_PEM);
1184                         $ssl_con = Net::SSLeay::new($ssl_ctx);
1185                         pipe(SSLr, SSLw);
1186                         if (!fork()) {
1187                                 close(SSLr);
1188                                 select(SSLw); $| = 1; select(STDOUT);
1189                                 print SSLw $origreqline;
1190                                 local $buf;
1191                                 while(sysread(SOCK, $buf, 1) > 0) {
1192                                         print SSLw $buf;
1193                                         }
1194                                 close(SOCK);
1195                                 exit;
1196                                 }
1197                         close(SSLw);
1198                         Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1199                         Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1200                         Net::SSLeay::accept($ssl_con) || die "accept() failed";
1201                         $use_ssl = 1;
1202                         local $url = $config{'musthost'} ?
1203                                         "https://$config{'musthost'}:$port/" :
1204                                         "https://$host:$port/";
1205                         if ($config{'ssl_redirect'}) {
1206                                 # Just re-direct to the correct URL
1207                                 sleep(1);       # Give browser a change to
1208                                                 # finish sending its request
1209                                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1210                                 &write_data("Date: $datestr\r\n");
1211                                 &write_data("Server: $config{'server'}\r\n");
1212                                 &write_data("Location: $url\r\n");
1213                                 &write_keep_alive(0);
1214                                 &write_data("\r\n");
1215                                 return 0;
1216                                 }
1217                         else {
1218                                 # Tell user the correct URL
1219                                 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1220                                 }
1221 EOF
1222                 if ($@) {
1223                         &http_error(400, "Bad Request");
1224                         }
1225                 }
1226         else {
1227                 &http_error(400, "Bad Request");
1228                 }
1229         }
1230 $method = $1;
1231 $request_uri = $page = $2;
1232 %header = ();
1233 local $lastheader;
1234 while(1) {
1235         ($headline = &read_line()) =~ s/\r|\n//g;
1236         last if ($headline eq "");
1237         print DEBUG "handle_request: got headline $headline\n";
1238         if ($headline =~ /^(\S+):\s*(.*)$/) {
1239                 $header{$lastheader = lc($1)} = $2;
1240                 }
1241         elsif ($headline =~ /^\s+(.*)$/) {
1242                 $header{$lastheader} .= $headline;
1243                 }
1244         else {
1245                 &http_error(400, "Bad Header $headline");
1246                 }
1247         }
1248 if (defined($header{'host'})) {
1249         if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1250                 ($host, $port) = ($1, $2);
1251                 }
1252         else {
1253                 $host = $header{'host'};
1254                 }
1255         if ($config{'musthost'} && $host ne $config{'musthost'}) {
1256                 # Disallowed hostname used
1257                 &http_error(400, "Invalid HTTP hostname");
1258                 }
1259         }
1260 undef(%in);
1261 if ($page =~ /^([^\?]+)\?(.*)$/) {
1262         # There is some query string information
1263         $page = $1;
1264         $querystring = $2;
1265         print DEBUG "handle_request: querystring=$querystring\n";
1266         if ($querystring !~ /=/) {
1267                 $queryargs = $querystring;
1268                 $queryargs =~ s/\+/ /g;
1269                 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1270                 $querystring = "";
1271                 }
1272         else {
1273                 # Parse query-string parameters
1274                 local @in = split(/\&/, $querystring);
1275                 foreach $i (@in) {
1276                         local ($k, $v) = split(/=/, $i, 2);
1277                         $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1278                         $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1279                         $in{$k} = $v;
1280                         }
1281                 }
1282         }
1283 $posted_data = undef;
1284 if ($method eq 'POST' &&
1285     $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1286         # Read in posted query string information, up the configured maximum
1287         # post request length
1288         $clen = $header{"content-length"};
1289         $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1290         while(length($posted_data) < $clen_read) {
1291                 $buf = &read_data($clen_read - length($posted_data));
1292                 if (!length($buf)) {
1293                         &http_error(500, "Failed to read POST request");
1294                         }
1295                 chomp($posted_data);
1296                 $posted_data =~ s/\015$//mg;
1297                 $posted_data .= $buf;
1298                 }
1299         print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1300         if ($clen_read != $clen && length($posted_data) > $clen) {
1301                 # If the client sent more data than we asked for, chop the
1302                 # rest off
1303                 $posted_data = substr($posted_data, 0, $clen);
1304                 }
1305         if (length($posted_data) > $clen) {
1306                 # When the client sent too much, delay so that it gets headers
1307                 sleep(3);
1308                 }
1309         if ($header{'user-agent'} =~ /MSIE/ &&
1310             $header{'user-agent'} !~ /Opera/i) {
1311                 # MSIE includes an extra newline in the data
1312                 $posted_data =~ s/\r|\n//g;
1313                 }
1314         local @in = split(/\&/, $posted_data);
1315         foreach $i (@in) {
1316                 local ($k, $v) = split(/=/, $i, 2);
1317                 #$v =~ s/\r|\n//g;
1318                 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1319                 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1320                 $in{$k} = $v;
1321                 }
1322         print DEBUG "handle_request: posted_data=$posted_data\n";
1323         }
1324
1325 # replace %XX sequences in page
1326 $page =~ s/%(..)/pack("c",hex($1))/ge;
1327
1328 # Check if the browser's user agent indicates a mobile device
1329 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1330
1331 # Check if Host: header is for a mobile URL
1332 foreach my $m (@mobile_prefixes) {
1333         if ($header{'host'} =~ /^\Q$m\E/i) {
1334                 $mobile_device = 1;
1335                 }
1336         }
1337
1338 # check for the logout flag file, and if existant deny authentication
1339 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1340         print DEBUG "handle_request: logout flag set\n";
1341         $deny_authentication++;
1342         open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1343         chop($count = <LOGOUT>);
1344         close(LOGOUT);
1345         $count--;
1346         if ($count > 0) {
1347                 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1348                 print LOGOUT "$count\n";
1349                 close(LOGOUT);
1350                 }
1351         else {
1352                 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1353                 }
1354         }
1355
1356 # check for any redirect for the requested URL
1357 foreach my $pfx (@strip_prefix) {
1358         my $l = length($pfx);
1359         if(length($page) >= $l &&
1360            substr($page,0,$l) eq $pfx) {
1361                 $page=substr($page,$l);
1362                 last;
1363                 }
1364         }
1365 $simple = &simplify_path($page, $bogus);
1366 $rpath = $simple;
1367 $rpath .= "&".$querystring if (defined($querystring));
1368 $redir = $redirect{$rpath};
1369 if (defined($redir)) {
1370         print DEBUG "handle_request: redir=$redir\n";
1371         &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1372         &write_data("Date: $datestr\r\n");
1373         &write_data("Server: $config{'server'}\r\n");
1374         local $ssl = $use_ssl || $config{'inetd_ssl'};
1375         $portstr = $port == 80 && !$ssl ? "" :
1376                    $port == 443 && $ssl ? "" : ":$port";
1377         $prot = $ssl ? "https" : "http";
1378         &write_data("Location: $prot://$host$portstr$redir\r\n");
1379         &write_keep_alive(0);
1380         &write_data("\r\n");
1381         return 0;
1382         }
1383
1384 # Check for a DAV request
1385 $davpath = undef;
1386 foreach my $d (@davpaths) {
1387         if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1388                 $davpath = $d;
1389                 last;
1390                 }
1391         }
1392 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1393         &http_error(400, "Bad Request method $method");
1394         }
1395
1396 # Check for password if needed
1397 if (%users) {
1398         print DEBUG "handle_request: Need authentication\n";
1399         $validated = 0;
1400         $blocked = 0;
1401
1402         # Session authentication is never used for connections by
1403         # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1404         # or mobile browsers if requested.
1405         if ($header{'user-agent'} =~ /webmin/i ||
1406             $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1407             $sessiononly{$simple} || $davpath ||
1408             $simple eq "/xmlrpc.cgi" ||
1409             $acptip eq $config{'host_nosession'} ||
1410             $mobile_device && $config{'mobile_nosession'}) {
1411                 print DEBUG "handle_request: Forcing HTTP authentication\n";
1412                 $config{'session'} = 0;
1413                 }
1414
1415         # check for SSL authentication
1416         if ($use_ssl && $verified_client) {
1417                 $peername = Net::SSLeay::X509_NAME_oneline(
1418                                 Net::SSLeay::X509_get_subject_name(
1419                                         Net::SSLeay::get_peer_certificate(
1420                                                 $ssl_con)));
1421                 local $peername2 = $peername;
1422                 $peername2 =~ s/Email=/emailAddress=/ ||
1423                         $peername2 =~ s/emailAddress=/Email=/;
1424                 foreach $u (keys %certs) {
1425                         if ($certs{$u} eq $peername ||
1426                             $certs{$u} eq $peername2) {
1427                                 $authuser = $u;
1428                                 $validated = 2;
1429                                 #syslog("info", "%s", "SSL login as $authuser from $acpthost") if ($use_syslog);
1430                                 last;
1431                                 }
1432                         }
1433                 if ($use_syslog && !$validated) {
1434                         syslog("crit", "%s",
1435                                "Unknown SSL certificate $peername");
1436                         }
1437                 }
1438
1439         if (!$validated && !$deny_authentication) {
1440                 # check for IP-based authentication
1441                 local $a;
1442                 foreach $a (keys %ipaccess) {
1443                         if ($acptip eq $a) {
1444                                 # It does! Auth as the user
1445                                 $validated = 3;
1446                                 $baseauthuser = $authuser =
1447                                         $ipaccess{$a};
1448                                 }
1449                         }
1450                 }
1451
1452         # Check for normal HTTP authentication
1453         if (!$validated && !$deny_authentication && !$config{'session'} &&
1454             $header{authorization} =~ /^basic\s+(\S+)$/i) {
1455                 # authorization given..
1456                 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1457                 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1458                 local ($vu, $expired, $nonexist) =
1459                         &validate_user($authuser, $authpass, $host);
1460                 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1461                 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1462                         $authuser = $vu;
1463                         $validated = 1;
1464                         }
1465                 else {
1466                         $validated = 0;
1467                         }
1468                 if ($use_syslog && !$validated) {
1469                         syslog("crit", "%s",
1470                                ($nonexist ? "Non-existent" :
1471                                 $expired ? "Expired" : "Invalid").
1472                                " login as $authuser from $acpthost");
1473                         }
1474                 if ($authuser =~ /\r|\n|\s/) {
1475                         &http_error(500, "Invalid username",
1476                                     "Username contains invalid characters");
1477                         }
1478                 if ($authpass =~ /\r|\n/) {
1479                         &http_error(500, "Invalid password",
1480                                     "Password contains invalid characters");
1481                         }
1482
1483                 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1484                         # check with main process for delay
1485                         print DEBUG "handle_request: about to ask for password delay\n";
1486                         print $PASSINw "delay $authuser $acptip $validated\n";
1487                         <$PASSOUTr> =~ /(\d+) (\d+)/;
1488                         $blocked = $2;
1489                         print DEBUG "handle_request: password delay $1 $2\n";
1490                         sleep($1);
1491                         }
1492                 }
1493
1494         # Check for a visit to the special session login page
1495         if ($config{'session'} && !$deny_authentication &&
1496             $page eq $config{'session_login'}) {
1497                 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1498                         # Logout clicked .. remove the session
1499                         local $sid = $2;
1500                         print $PASSINw "delete $sid\n";
1501                         local $louser = <$PASSOUTr>;
1502                         chop($louser);
1503                         $logout = 1;
1504                         $already_session_id = undef;
1505                         $authuser = $baseauthuser = undef;
1506                         if ($louser) {
1507                                 if ($use_syslog) {
1508                                         syslog("info", "%s", "Logout by $louser from $acpthost");
1509                                         }
1510                                 &run_logout_script($louser, $sid,
1511                                                    $acptip, $localip);
1512                                 &write_logout_utmp($louser, $actphost);
1513                                 }
1514                         }
1515                 else {
1516                         # Validate the user
1517                         if ($in{'user'} =~ /\r|\n|\s/) {
1518                                 &http_error(500, "Invalid username",
1519                                     "Username contains invalid characters");
1520                                 }
1521                         if ($in{'pass'} =~ /\r|\n/) {
1522                                 &http_error(500, "Invalid password",
1523                                     "Password contains invalid characters");
1524                                 }
1525
1526                         local ($vu, $expired, $nonexist) =
1527                                 &validate_user($in{'user'}, $in{'pass'}, $host);
1528                         local $hrv = &handle_login(
1529                                         $vu || $in{'user'}, $vu ? 1 : 0,
1530                                         $expired, $nonexist, $in{'pass'},
1531                                         $in{'notestingcookie'});
1532                         return $hrv if (defined($hrv));
1533                         }
1534                 }
1535
1536         # Check for a visit to the special PAM login page
1537         if ($config{'session'} && !$deny_authentication &&
1538             $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1539             !$in{'restart'}) {
1540                 # A question has been entered .. submit it to the main process
1541                 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1542                 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1543                 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1544                         &http_error(500, "Invalid response",
1545                             "Response contains invalid characters");
1546                         }
1547
1548                 if (!$in{'cid'}) {
1549                         # Start of a new conversation - answer must be username
1550                         $cid = &generate_random_id($in{'answer'});
1551                         print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1552                         }
1553                 else {
1554                         # A response to a previous question
1555                         $cid = $in{'cid'};
1556                         print $PASSINw "pamanswer $cid $in{'answer'}\n";
1557                         }
1558
1559                 # Read back the response, and the next question (if any)
1560                 local $line = <$PASSOUTr>;
1561                 $line =~ s/\r|\n//g;
1562                 local ($rv, $question) = split(/\s+/, $line, 2);
1563                 if ($rv == 0) {
1564                         # Cannot login!
1565                         local $hrv = &handle_login(
1566                                 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1567                                                              : "unknown",
1568                                 0, 0, 1, undef);
1569                         return $hrv if (defined($hrv));
1570                         }
1571                 elsif ($rv == 1 || $rv == 3) {
1572                         # Another question .. force use of PAM CGI
1573                         $validated = 1;
1574                         $method = "GET";
1575                         $querystring .= "&cid=$cid&question=".
1576                                         &urlize($question);
1577                         $querystring .= "&password=1" if ($rv == 3);
1578                         $queryargs = "";
1579                         $page = $config{'pam_login'};
1580                         $miniserv_internal = 1;
1581                         $logged_code = 401;
1582                         }
1583                 elsif ($rv == 2) {
1584                         # Got back a final ok or failure
1585                         local ($user, $ok, $expired, $nonexist) =
1586                                 split(/\s+/, $question);
1587                         local $hrv = &handle_login(
1588                                 $user, $ok, $expired, $nonexist, undef,
1589                                 $in{'notestingcookie'});
1590                         return $hrv if (defined($hrv));
1591                         }
1592                 elsif ($rv == 4) {
1593                         # A message from PAM .. tell the user
1594                         $validated = 1;
1595                         $method = "GET";
1596                         $querystring .= "&cid=$cid&message=".
1597                                         &urlize($question);
1598                         $queryargs = "";
1599                         $page = $config{'pam_login'};
1600                         $miniserv_internal = 1;
1601                         $logged_code = 401;
1602                         }
1603                 }
1604
1605         # Check for a visit to the special password change page
1606         if ($config{'session'} && !$deny_authentication &&
1607             $page eq $config{'password_change'} && !$validated) {
1608                 # Just let this slide ..
1609                 $validated = 1;
1610                 $miniserv_internal = 3;
1611                 }
1612
1613         # Check for an existing session
1614         if ($config{'session'} && !$validated) {
1615                 if ($already_session_id) {
1616                         $session_id = $already_session_id;
1617                         $authuser = $already_authuser;
1618                         $validated = 1;
1619                         }
1620                 elsif (!$deny_authentication &&
1621                        $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1622                         # Try all session cookies
1623                         local $cookie = $header{'cookie'};
1624                         while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1625                                 $session_id = $2;
1626                                 local $notimeout =
1627                                         $in{'webmin_notimeout'} ? 1 : 0;
1628                                 print $PASSINw "verify $session_id $notimeout\n";
1629                                 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1630                                 if ($1 == 2) {
1631                                         # Valid session continuation
1632                                         $validated = 1;
1633                                         $authuser = $2;
1634                                         $already_authuser = $authuser;
1635                                         $timed_out = undef;
1636                                         last;
1637                                         }
1638                                 elsif ($1 == 1) {
1639                                         # Session timed out
1640                                         $timed_out = $2;
1641                                         }
1642                                 else {
1643                                         # Invalid session ID .. don't set
1644                                         # verified flag
1645                                         }
1646                                 }
1647                         }
1648                 }
1649
1650         # Check for local authentication
1651         if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1652                 if (defined($users{$localauth_user})) {
1653                         # Local user exists in webmin users file
1654                         $validated = 1;
1655                         $authuser = $localauth_user;
1656                         }
1657                 else {
1658                         # Check if local user is allowed by unixauth
1659                         local @can = &can_user_login($localauth_user,
1660                                                      undef, $host);
1661                         if ($can[0]) {
1662                                 $validated = 2;
1663                                 $authuser = $localauth_user;
1664                                 }
1665                         else {
1666                                 $localauth_user = undef;
1667                                 }
1668                         }
1669                 }
1670
1671         if (!$validated) {
1672                 # Check if this path allows anonymous access
1673                 local $a;
1674                 foreach $a (keys %anonymous) {
1675                         if (substr($simple, 0, length($a)) eq $a) {
1676                                 # It does! Auth as the user, if IP access
1677                                 # control allows him.
1678                                 if (&check_user_ip($anonymous{$a}) &&
1679                                     &check_user_time($anonymous{$a})) {
1680                                         $validated = 3;
1681                                         $baseauthuser = $authuser =
1682                                                 $anonymous{$a};
1683                                         }
1684                                 }
1685                         }
1686                 }
1687
1688         if (!$validated) {
1689                 # Check if this path allows unauthenticated access
1690                 local ($u, $unauth);
1691                 foreach $u (@unauth) {
1692                         $unauth++ if ($simple =~ /$u/);
1693                         }
1694                 if (!$bogus && $unauth) {
1695                         # Unauthenticated directory or file request - approve it
1696                         $validated = 4;
1697                         $baseauthuser = $authuser = undef;
1698                         }
1699                 }
1700
1701         if (!$validated) {
1702                 if ($blocked == 0) {
1703                         # No password given.. ask
1704                         if ($config{'pam_conv'} && $use_pam) {
1705                                 # Force CGI for PAM question, starting with
1706                                 # the username which is always needed
1707                                 $validated = 1;
1708                                 $method = "GET";
1709                                 $querystring .= "&initial=1&question=".
1710                                                 &urlize("Username");
1711                                 $querystring .= "&failed=$failed_user" if ($failed_user);
1712                                 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1713                                 $queryargs = "";
1714                                 $page = $config{'pam_login'};
1715                                 $miniserv_internal = 1;
1716                                 $logged_code = 401;
1717                                 }
1718                         elsif ($config{'session'}) {
1719                                 # Force CGI for session login
1720                                 $validated = 1;
1721                                 if ($logout) {
1722                                         $querystring .= "&logout=1&page=/";
1723                                         }
1724                                 else {
1725                                         # Re-direct to current module only
1726                                         local $rpage = $request_uri;
1727                                         if (!$config{'loginkeeppage'}) {
1728                                                 $rpage =~ s/\?.*$//;
1729                                                 $rpage =~ s/[^\/]+$//
1730                                                 }
1731                                         $querystring = "page=".&urlize($rpage);
1732                                         }
1733                                 $method = "GET";
1734                                 $querystring .= "&failed=$failed_user" if ($failed_user);
1735                                 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1736                                 $queryargs = "";
1737                                 $page = $config{'session_login'};
1738                                 $miniserv_internal = 1;
1739                                 $logged_code = 401;
1740                                 }
1741                         else {
1742                                 # Ask for login with HTTP authentication
1743                                 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1744                                 &write_data("Date: $datestr\r\n");
1745                                 &write_data("Server: $config{'server'}\r\n");
1746                                 &write_data("WWW-authenticate: Basic ".
1747                                            "realm=\"$config{'realm'}\"\r\n");
1748                                 &write_keep_alive(0);
1749                                 &write_data("Content-type: text/html\r\n");
1750                                 &write_data("\r\n");
1751                                 &reset_byte_count();
1752                                 &write_data("<html>\n");
1753                                 &write_data("<head><title>Unauthorized</title></head>\n");
1754                                 &write_data("<body><h1>Unauthorized</h1>\n");
1755                                 &write_data("A password is required to access this\n");
1756                                 &write_data("web server. Please try again. <p>\n");
1757                                 &write_data("</body></html>\n");
1758                                 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1759                                 return 0;
1760                                 }
1761                         }
1762                 elsif ($blocked == 1) {
1763                         # when the host has been blocked, give it an error
1764                         &http_error(403, "Access denied for $acptip. The host ".
1765                                          "has been blocked because of too ".
1766                                          "many authentication failures.");
1767                         }
1768                 elsif ($blocked == 2) {
1769                         # when the user has been blocked, give it an error
1770                         &http_error(403, "Access denied. The user ".
1771                                          "has been blocked because of too ".
1772                                          "many authentication failures.");
1773                         }
1774                 }
1775         else {
1776                 # Get the real Webmin username
1777                 local @can = &can_user_login($authuser, undef, $host);
1778                 $baseauthuser = $can[3] || $authuser;
1779
1780                 if ($config{'remoteuser'} && !$< && $validated) {
1781                         # Switch to the UID of the remote user (if he exists)
1782                         local @u = getpwnam($authuser);
1783                         if (@u && $< != $u[2]) {
1784                                 $( = $u[3]; $) = "$u[3] $u[3]";
1785                                 ($>, $<) = ($u[2], $u[2]);
1786                                 }
1787                         else {
1788                                 &http_error(500, "Unix user $authuser does not exist");
1789                                 return 0;
1790                                 }
1791                         }
1792                 }
1793
1794         # Check per-user IP access control
1795         if (!&check_user_ip($baseauthuser)) {
1796                 &http_error(403, "Access denied for $acptip for $baseauthuser");
1797                 return 0;
1798                 }
1799
1800         # Check per-user allowed times
1801         if (!&check_user_time($baseauthuser)) {
1802                 &http_error(403, "Access denied at the current time");
1803                 return 0;
1804                 }
1805         }
1806
1807 # Validate the path, and convert to canonical form
1808 rerun:
1809 $simple = &simplify_path($page, $bogus);
1810 print DEBUG "handle_request: page=$page simple=$simple\n";
1811 if ($bogus) {
1812         &http_error(400, "Invalid path");
1813         }
1814
1815 # Check for a DAV request
1816 if ($davpath) {
1817         return &handle_dav_request($davpath);
1818         }
1819
1820 # Work out the active theme(s)
1821 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1822                         $config{'mobile_preroot'} :
1823                  $authuser && defined($config{'preroot_'.$authuser}) ?
1824                         $config{'preroot_'.$authuser} :
1825                  $authuser && $baseauthuser &&
1826                      defined($config{'preroot_'.$baseauthuser}) ?
1827                         $config{'preroot_'.$baseauthuser} :
1828                         $config{'preroot'};
1829 local @preroots = reverse(split(/\s+/, $preroots));
1830
1831 # Canonicalize the directories
1832 foreach my $preroot (@preroots) {
1833         # Always under the current webmin root
1834         $preroot =~ s/^.*\///g;
1835         $preroot = $roots[0].'/'.$preroot;
1836         }
1837
1838 # Look in the theme root directories first
1839 local ($full, @stfull);
1840 $foundroot = undef;
1841 foreach my $preroot (@preroots) {
1842         $is_directory = 1;
1843         $sofar = "";
1844         $full = $preroot.$sofar;
1845         $scriptname = $simple;
1846         foreach $b (split(/\//, $simple)) {
1847                 if ($b ne "") { $sofar .= "/$b"; }
1848                 $full = $preroot.$sofar;
1849                 @stfull = stat($full);
1850                 if (!@stfull) { undef($full); last; }
1851
1852                 # Check if this is a directory
1853                 if (-d _) {
1854                         # It is.. go on parsing
1855                         $is_directory = 1;
1856                         next;
1857                         }
1858                 else {
1859                         $is_directory = 0;
1860                         }
1861
1862                 # Check if this is a CGI program
1863                 if (&get_type($full) eq "internal/cgi") {
1864                         $pathinfo = substr($simple, length($sofar));
1865                         $pathinfo .= "/" if ($page =~ /\/$/);
1866                         $scriptname = $sofar;
1867                         last;
1868                         }
1869                 }
1870
1871         # Don't stop at a directory unless this is the last theme, which
1872         # is the 'real' one that provides the .cgi scripts
1873         if ($is_directory && $preroot ne $preroots[$#preroots]) {
1874                 next;
1875                 }
1876
1877         if ($full) {
1878                 # Found it!
1879                 if ($sofar eq '') {
1880                         $cgi_pwd = $roots[0];
1881                         }
1882                 elsif ($is_directory) {
1883                         $cgi_pwd = "$roots[0]$sofar";
1884                         }
1885                 else {
1886                         "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1887                         $cgi_pwd = $1;
1888                         }
1889                 $foundroot = $preroot;
1890                 if ($is_directory) {
1891                         # Check for index files in the directory
1892                         local $foundidx;
1893                         foreach $idx (split(/\s+/, $config{"index_docs"})) {
1894                                 $idxfull = "$full/$idx";
1895                                 local @stidxfull = stat($idxfull);
1896                                 if (-r _ && !-d _) {
1897                                         $full = $idxfull;
1898                                         @stfull = @stidxfull;
1899                                         $is_directory = 0;
1900                                         $scriptname .= "/"
1901                                                 if ($scriptname ne "/");
1902                                         $foundidx++;
1903                                         last;
1904                                         }
1905                                 }
1906                         @stfull = stat($full) if (!$foundidx);
1907                         }
1908                 }
1909         last if ($foundroot);
1910         }
1911 print DEBUG "handle_request: initial full=$full\n";
1912
1913 # Look in the real root directories, stopping when we find a file or directory
1914 if (!$full || $is_directory) {
1915         ROOT: foreach $root (@roots) {
1916                 $sofar = "";
1917                 $full = $root.$sofar;
1918                 $scriptname = $simple;
1919                 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1920                         if ($b ne "") { $sofar .= "/$b"; }
1921                         $full = $root.$sofar;
1922                         @stfull = stat($full);
1923                         if (!@stfull) {
1924                                 next ROOT;
1925                                 }
1926
1927                         # Check if this is a directory
1928                         if (-d _) {
1929                                 # It is.. go on parsing
1930                                 next;
1931                                 }
1932
1933                         # Check if this is a CGI program
1934                         if (&get_type($full) eq "internal/cgi") {
1935                                 $pathinfo = substr($simple, length($sofar));
1936                                 $pathinfo .= "/" if ($page =~ /\/$/);
1937                                 $scriptname = $sofar;
1938                                 last;
1939                                 }
1940                         }
1941
1942                 # Run CGI in the same directory as whatever file
1943                 # was requested
1944                 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1945
1946                 if (-e $full) {
1947                         # Found something!
1948                         $realroot = $root;
1949                         $foundroot = $root;
1950                         last;
1951                         }
1952                 }
1953         if (!@stfull) { &http_error(404, "File not found"); }
1954         }
1955 print DEBUG "handle_request: full=$full\n";
1956 @stfull = stat($full) if (!@stfull);
1957
1958 # check filename against denyfile regexp
1959 local $denyfile = $config{'denyfile'};
1960 if ($denyfile && $full =~ /$denyfile/) {
1961         &http_error(403, "Access denied to $page");
1962         return 0;
1963         }
1964
1965 # Reached the end of the path OK.. see what we've got
1966 if (-d _) {
1967         # See if the URL ends with a / as it should
1968         print DEBUG "handle_request: found a directory\n";
1969         if ($page !~ /\/$/) {
1970                 # It doesn't.. redirect
1971                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1972                 $ssl = $use_ssl || $config{'inetd_ssl'};
1973                 $portstr = $port == 80 && !$ssl ? "" :
1974                            $port == 443 && $ssl ? "" : ":$port";
1975                 &write_data("Date: $datestr\r\n");
1976                 &write_data("Server: $config{server}\r\n");
1977                 $prot = $ssl ? "https" : "http";
1978                 &write_data("Location: $prot://$host$portstr$page/\r\n");
1979                 &write_keep_alive(0);
1980                 &write_data("\r\n");
1981                 &log_request($acpthost, $authuser, $reqline, 302, 0);
1982                 return 0;
1983                 }
1984         # A directory.. check for index files
1985         local $foundidx;
1986         foreach $idx (split(/\s+/, $config{"index_docs"})) {
1987                 $idxfull = "$full/$idx";
1988                 @stidxfull = stat($idxfull);
1989                 if (-r _ && !-d _) {
1990                         $cgi_pwd = $full;
1991                         $full = $idxfull;
1992                         @stfull = @stidxfull;
1993                         $scriptname .= "/" if ($scriptname ne "/");
1994                         $foundidx++;
1995                         last;
1996                         }
1997                 }
1998         @stfull = stat($full) if (!$foundidx);
1999         }
2000 if (-d _) {
2001         # This is definately a directory.. list it
2002         print DEBUG "handle_request: listing directory\n";
2003         local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2004                       "Date: $datestr\r\n".
2005                       "Server: $config{server}\r\n".
2006                       "Content-type: text/html\r\n";
2007         &write_data($resp);
2008         &write_keep_alive(0);
2009         &write_data("\r\n");
2010         &reset_byte_count();
2011         &write_data("<h1>Index of $simple</h1>\n");
2012         &write_data("<pre>\n");
2013         &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2014                         "Name", "Last Modified", "Size");
2015         &write_data("<hr>\n");
2016         opendir(DIR, $full);
2017         while($df = readdir(DIR)) {
2018                 if ($df =~ /^\./) { next; }
2019                 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2020                 (@stbuf = stat($fulldf)) || next;
2021                 if (-d _) { $df .= "/"; }
2022                 @tm = localtime($stbuf[9]);
2023                 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2024                                 $tm[3],$tm[4]+1,$tm[5]+1900,
2025                                 $tm[0],$tm[1],$tm[2];
2026                 $len = length($df); $rest = " "x(35-$len);
2027                 &write_data(sprintf 
2028                  "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2029                  $df, $df, $fdate, $stbuf[7]);
2030                 }
2031         closedir(DIR);
2032         &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2033         return 0;
2034         }
2035
2036 # CGI or normal file
2037 local $rv;
2038 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2039         # A CGI program to execute
2040         print DEBUG "handle_request: executing CGI\n";
2041         $envtz = $ENV{"TZ"};
2042         $envuser = $ENV{"USER"};
2043         $envpath = $ENV{"PATH"};
2044         $envlang = $ENV{"LANG"};
2045         $envroot = $ENV{"SystemRoot"};
2046         $envperllib = $ENV{'PERLLIB'};
2047         foreach my $k (keys %ENV) {
2048                 delete($ENV{$k});
2049                 }
2050         $ENV{"PATH"} = $envpath if ($envpath);
2051         $ENV{"TZ"} = $envtz if ($envtz);
2052         $ENV{"USER"} = $envuser if ($envuser);
2053         $ENV{"OLD_LANG"} = $envlang if ($envlang);
2054         $ENV{"SystemRoot"} = $envroot if ($envroot);
2055         $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2056         $ENV{"HOME"} = $user_homedir;
2057         $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2058         $ENV{"SERVER_NAME"} = $host;
2059         $ENV{"SERVER_ADMIN"} = $config{"email"};
2060         $ENV{"SERVER_ROOT"} = $roots[0];
2061         $ENV{"SERVER_REALROOT"} = $realroot;
2062         $ENV{"SERVER_PORT"} = $port;
2063         $ENV{"REMOTE_HOST"} = $acpthost;
2064         $ENV{"REMOTE_ADDR"} = $acptip;
2065         $ENV{"REMOTE_USER"} = $authuser;
2066         $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2067                                         $baseauthuser : undef;
2068         $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2069                                             $config{'pass_password'});
2070         print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2071         print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2072         $ENV{"SSL_USER"} = $peername if ($validated == 2);
2073         $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2074         $ENV{"DOCUMENT_ROOT"} = $roots[0];
2075         $ENV{"DOCUMENT_REALROOT"} = $realroot;
2076         $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2077         $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2078         $ENV{"REQUEST_METHOD"} = $method;
2079         $ENV{"SCRIPT_NAME"} = $scriptname;
2080         $ENV{"SCRIPT_FILENAME"} = $full;
2081         $ENV{"REQUEST_URI"} = $request_uri;
2082         $ENV{"PATH_INFO"} = $pathinfo;
2083         if ($pathinfo) {
2084                 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2085                 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2086                 }
2087         $ENV{"QUERY_STRING"} = $querystring;
2088         $ENV{"MINISERV_CONFIG"} = $config_file;
2089         $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2090         $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2091         $ENV{"SESSION_ID"} = $session_id if ($session_id);
2092         $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2093         $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2094         if (defined($header{"content-length"})) {
2095                 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2096                 }
2097         if (defined($header{"content-type"})) {
2098                 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2099                 }
2100         foreach $h (keys %header) {
2101                 ($hname = $h) =~ tr/a-z/A-Z/;
2102                 $hname =~ s/\-/_/g;
2103                 $ENV{"HTTP_$hname"} = $header{$h};
2104                 }
2105         $ENV{"PWD"} = $cgi_pwd;
2106         foreach $k (keys %config) {
2107                 if ($k =~ /^env_(\S+)$/) {
2108                         $ENV{$1} = $config{$k};
2109                         }
2110                 }
2111         delete($ENV{'HTTP_AUTHORIZATION'});
2112         $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2113         $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2114
2115         # Check if the CGI can be handled internally
2116         open(CGI, $full);
2117         local $first = <CGI>;
2118         close(CGI);
2119         $first =~ s/[#!\r\n]//g;
2120         $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2121         seek(STDERR, 0, 2);
2122         if (!$config{'forkcgis'} &&
2123             ($first eq $perl_path || $first eq $linked_perl_path) &&
2124               $] >= 5.004 ||
2125             $config{'internalcgis'}) {
2126                 # setup environment for eval
2127                 chdir($ENV{"PWD"});
2128                 @ARGV = split(/\s+/, $queryargs);
2129                 $0 = $full;
2130                 if ($posted_data) {
2131                         # Already read the post input
2132                         $postinput = $posted_data;
2133                         }
2134                 $clen = $header{"content-length"};
2135                 $SIG{'CHLD'} = 'DEFAULT';
2136                 eval {
2137                         # Have SOCK closed if the perl exec's something
2138                         use Fcntl;
2139                         fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2140                         };
2141                 #shutdown(SOCK, 0);
2142
2143                 if ($config{'log'}) {
2144                         open(MINISERVLOG, ">>$config{'logfile'}");
2145                         if ($config{'logperms'}) {
2146                                 chmod(oct($config{'logperms'}),
2147                                       $config{'logfile'});
2148                                 }
2149                         else {
2150                                 chmod(0600, $config{'logfile'});
2151                                 }
2152                         }
2153                 $doing_cgi_eval = 1;
2154                 $main_process_id = $$;
2155                 $pkg = "main";
2156                 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2157                         # Eval in package from Webmin module name
2158                         $pkg = $1;
2159                         $pkg =~ s/[^A-Za-z0-9]/_/g;
2160                         }
2161                 eval "
2162                         \%pkg::ENV = \%ENV;
2163                         package $pkg;
2164                         tie(*STDOUT, 'miniserv');
2165                         tie(*STDIN, 'miniserv');
2166                         do \$miniserv::full;
2167                         die \$@ if (\$@);
2168                         ";
2169                 $doing_cgi_eval = 0;
2170                 if ($@) {
2171                         # Error in perl!
2172                         &http_error(500, "Perl execution failed",
2173                                     $config{'noshowstderr'} ? undef : $@);
2174                         }
2175                 elsif (!$doneheaders && !$nph_script) {
2176                         &http_error(500, "Missing Headers");
2177                         }
2178                 $rv = 0;
2179                 }
2180         else {
2181                 $infile = undef;
2182                 if (!$on_windows) {
2183                         # fork the process that actually executes the CGI
2184                         pipe(CGIINr, CGIINw);
2185                         pipe(CGIOUTr, CGIOUTw);
2186                         pipe(CGIERRr, CGIERRw);
2187                         if (!($cgipid = fork())) {
2188                                 @execargs = ( $full, split(/\s+/, $queryargs) );
2189                                 chdir($ENV{"PWD"});
2190                                 close(SOCK);
2191                                 open(STDIN, "<&CGIINr");
2192                                 open(STDOUT, ">&CGIOUTw");
2193                                 open(STDERR, ">&CGIERRw");
2194                                 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2195                                 exec(@execargs) ||
2196                                         die "Failed to exec $full : $!\n";
2197                                 exit(0);
2198                                 }
2199                         close(CGIINr); close(CGIOUTw); close(CGIERRw);
2200                         }
2201                 else {
2202                         # write CGI input to a temp file
2203                         $infile = "$config{'tempbase'}.$$";
2204                         open(CGIINw, ">$infile");
2205                         # NOT binary mode, as CGIs don't read in it!
2206                         }
2207
2208                 # send post data
2209                 if ($posted_data) {
2210                         # already read the posted data
2211                         print CGIINw $posted_data;
2212                         }
2213                 $clen = $header{"content-length"};
2214                 if ($method eq "POST" && $clen_read < $clen) {
2215                         $SIG{'PIPE'} = 'IGNORE';
2216                         $got = $clen_read;
2217                         while($got < $clen) {
2218                                 $buf = &read_data($clen-$got);
2219                                 if (!length($buf)) {
2220                                         kill('TERM', $cgipid);
2221                                         unlink($infile) if ($infile);
2222                                         &http_error(500, "Failed to read ".
2223                                                          "POST request");
2224                                         }
2225                                 $got += length($buf);
2226                                 local ($wrote) = (print CGIINw $buf);
2227                                 last if (!$wrote);
2228                                 }
2229                         # If the CGI terminated early, we still need to read
2230                         # from the browser and throw away
2231                         while($got < $clen) {
2232                                 $buf = &read_data($clen-$got);
2233                                 if (!length($buf)) {
2234                                         kill('TERM', $cgipid);
2235                                         unlink($infile) if ($infile);
2236                                         &http_error(500, "Failed to read ".
2237                                                          "POST request");
2238                                         }
2239                                 $got += length($buf);
2240                                 }
2241                         $SIG{'PIPE'} = 'DEFAULT';
2242                         }
2243                 close(CGIINw);
2244                 shutdown(SOCK, 0);
2245
2246                 if ($on_windows) {
2247                         # Run the CGI program, and feed it input
2248                         chdir($ENV{"PWD"});
2249                         local $qqueryargs = join(" ", map { "\"$_\"" }
2250                                                  split(/\s+/, $queryargs));
2251                         if ($first =~ /(perl|perl.exe)$/i) {
2252                                 # On Windows, run with Perl
2253                                 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2254                                 }
2255                         else {
2256                                 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2257                                 }
2258                         binmode(CGIOUTr);
2259                         }
2260
2261                 if (!$nph_script) {
2262                         # read back cgi headers
2263                         select(CGIOUTr); $|=1; select(STDOUT);
2264                         $got_blank = 0;
2265                         while(1) {
2266                                 $line = <CGIOUTr>;
2267                                 $line =~ s/\r|\n//g;
2268                                 if ($line eq "") {
2269                                         if ($got_blank || %cgiheader) { last; }
2270                                         $got_blank++;
2271                                         next;
2272                                         }
2273                                 if ($line !~ /^(\S+):\s+(.*)$/) {
2274                                         $errs = &read_errors(CGIERRr);
2275                                         close(CGIOUTr); close(CGIERRr);
2276                                         unlink($infile) if ($infile);
2277                                         &http_error(500, "Bad Header", $errs);
2278                                         }
2279                                 $cgiheader{lc($1)} = $2;
2280                                 push(@cgiheader, [ $1, $2 ]);
2281                                 }
2282                         if ($cgiheader{"location"}) {
2283                                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2284                                 &write_data("Date: $datestr\r\n");
2285                                 &write_data("Server: $config{'server'}\r\n");
2286                                 &write_keep_alive(0);
2287                                 # ignore the rest of the output. This is a hack,
2288                                 # but is necessary for IE in some cases :(
2289                                 close(CGIOUTr); close(CGIERRr);
2290                                 }
2291                         elsif ($cgiheader{"content-type"} eq "") {
2292                                 close(CGIOUTr); close(CGIERRr);
2293                                 unlink($infile) if ($infile);
2294                                 $errs = &read_errors(CGIERRr);
2295                                 &http_error(500, "Missing Content-Type Header",
2296                                     $config{'noshowstderr'} ? undef : $errs);
2297                                 }
2298                         else {
2299                                 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2300                                 &write_data("Date: $datestr\r\n");
2301                                 &write_data("Server: $config{'server'}\r\n");
2302                                 &write_keep_alive(0);
2303                                 }
2304                         foreach $h (@cgiheader) {
2305                                 &write_data("$h->[0]: $h->[1]\r\n");
2306                                 }
2307                         &write_data("\r\n");
2308                         }
2309                 &reset_byte_count();
2310                 while($line = <CGIOUTr>) {
2311                         &write_data($line);
2312                         }
2313                 close(CGIOUTr);
2314                 close(CGIERRr);
2315                 unlink($infile) if ($infile);
2316                 $rv = 0;
2317                 }
2318         }
2319 else {
2320         # A file to output
2321         print DEBUG "handle_request: outputting file\n";
2322         open(FILE, $full) || &http_error(404, "Failed to open file");
2323         binmode(FILE);
2324         local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2325                       "Date: $datestr\r\n".
2326                       "Server: $config{server}\r\n".
2327                       "Content-type: ".&get_type($full)."\r\n".
2328                       "Content-length: $stfull[7]\r\n".
2329                       "Last-Modified: ".&http_date($stfull[9])."\r\n".
2330                       "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2331         &write_data($resp);
2332         $rv = &write_keep_alive();
2333         &write_data("\r\n");
2334         &reset_byte_count();
2335         while(read(FILE, $buf, 1024) > 0) {
2336                 &write_data($buf);
2337                 }
2338         close(FILE);
2339         }
2340
2341 # log the request
2342 &log_request($acpthost, $authuser, $reqline,
2343              $logged_code ? $logged_code :
2344              $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2345 return $rv;
2346 }
2347
2348 # http_error(code, message, body, [dontexit])
2349 sub http_error
2350 {
2351 local $eh = $error_handler_recurse ? undef :
2352             $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2353             $config{'error_handler'} ? $config{'error_handler'} : undef;
2354 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2355 if ($eh) {
2356         # Call a CGI program for the error
2357         $page = "/$eh";
2358         $querystring = "code=$_[0]&message=".&urlize($_[1]).
2359                        "&body=".&urlize($_[2]);
2360         $error_handler_recurse++;
2361         $ok_code = $_[0];
2362         $ok_message = $_[1];
2363         goto rerun;
2364         }
2365 else {
2366         # Use the standard error message display
2367         &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2368         &write_data("Server: $config{server}\r\n");
2369         &write_data("Date: $datestr\r\n");
2370         &write_data("Content-type: text/html\r\n");
2371         &write_keep_alive(0);
2372         &write_data("\r\n");
2373         &reset_byte_count();
2374         &write_data("<h1>Error - $_[1]</h1>\n");
2375         if ($_[2]) {
2376                 &write_data("<pre>$_[2]</pre>\n");
2377                 }
2378         }
2379 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2380         if ($reqline);
2381 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2382 shutdown(SOCK, 1);
2383 exit if (!$_[3]);
2384 }
2385
2386 sub get_type
2387 {
2388 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2389         $t = $mime{$1};
2390         if ($t ne "") {
2391                 return $t;
2392                 }
2393         }
2394 return "text/plain";
2395 }
2396
2397 # simplify_path(path, bogus)
2398 # Given a path, maybe containing stuff like ".." and "." convert it to a
2399 # clean, absolute form.
2400 sub simplify_path
2401 {
2402 local($dir, @bits, @fixedbits, $b);
2403 $dir = $_[0];
2404 $dir =~ s/\\/\//g;      # fix windows \ in path
2405 $dir =~ s/^\/+//g;
2406 $dir =~ s/\/+$//g;
2407 $dir =~ s/\0//g;        # remove null bytes
2408 @bits = split(/\/+/, $dir);
2409 @fixedbits = ();
2410 $_[1] = 0;
2411 foreach $b (@bits) {
2412         if ($b eq ".") {
2413                 # Do nothing..
2414                 }
2415         elsif ($b eq ".." || $b eq "...") {
2416                 # Remove last dir
2417                 if (scalar(@fixedbits) == 0) {
2418                         $_[1] = 1;
2419                         return "/";
2420                         }
2421                 pop(@fixedbits);
2422                 }
2423         else {
2424                 # Add dir to list
2425                 push(@fixedbits, $b);
2426                 }
2427         }
2428 return "/" . join('/', @fixedbits);
2429 }
2430
2431 # b64decode(string)
2432 # Converts a string from base64 format to normal
2433 sub b64decode
2434 {
2435     local($str) = $_[0];
2436     local($res);
2437     $str =~ tr|A-Za-z0-9+=/||cd;
2438     $str =~ s/=+$//;
2439     $str =~ tr|A-Za-z0-9+/| -_|;
2440     while ($str =~ /(.{1,60})/gs) {
2441         my $len = chr(32 + length($1)*3/4);
2442         $res .= unpack("u", $len . $1 );
2443     }
2444     return $res;
2445 }
2446
2447 # ip_match(remoteip, localip, [match]+)
2448 # Checks an IP address against a list of IPs, networks and networks/masks
2449 sub ip_match
2450 {
2451 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2452 @io = split(/\./, $_[0]);
2453 for($i=2; $i<@_; $i++) {
2454         $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2455         }
2456 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2457         $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2458         $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2459         $ip_match_cache{$_[0]} = $hn;
2460         }
2461 for($i=2; $i<@_; $i++) {
2462         local $mismatch = 0;
2463         if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2464                 # Convert CIDR to netmask format
2465                 $_[$i] = $1."/".&prefix_to_mask($2);
2466                 }
2467         if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2468                 # Compare with network/mask
2469                 @mo = split(/\./, $1); @ms = split(/\./, $2);
2470                 for($j=0; $j<4; $j++) {
2471                         if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2472                                 $mismatch = 1;
2473                                 }
2474                         }
2475                 }
2476         elsif ($_[$i] =~ /^\*(\S+)$/) {
2477                 # Compare with hostname regexp
2478                 $mismatch = 1 if ($hn !~ /$1$/);
2479                 }
2480         elsif ($_[$i] eq 'LOCAL') {
2481                 # Compare with local network
2482                 local @lo = split(/\./, $_[1]);
2483                 if ($lo[0] < 128) {
2484                         $mismatch = 1 if ($lo[0] != $io[0]);
2485                         }
2486                 elsif ($lo[0] < 192) {
2487                         $mismatch = 1 if ($lo[0] != $io[0] ||
2488                                           $lo[1] != $io[1]);
2489                         }
2490                 else {
2491                         $mismatch = 1 if ($lo[0] != $io[0] ||
2492                                           $lo[1] != $io[1] ||
2493                                           $lo[2] != $io[2]);
2494                         }
2495                 }
2496         elsif ($_[$i] !~ /^[0-9\.]+$/) {
2497                 # Compare with hostname
2498                 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2499                 }
2500         else {
2501                 # Compare with IP or network
2502                 @mo = split(/\./, $_[$i]);
2503                 while(@mo && !$mo[$#mo]) { pop(@mo); }
2504                 for($j=0; $j<@mo; $j++) {
2505                         if ($mo[$j] != $io[$j]) {
2506                                 $mismatch = 1;
2507                                 }
2508                         }
2509                 }
2510         return 1 if (!$mismatch);
2511         }
2512 return 0;
2513 }
2514
2515 # users_match(&uinfo, user, ...)
2516 # Returns 1 if a user is in a list of users and groups
2517 sub users_match
2518 {
2519 local $uinfo = shift(@_);
2520 local $u;
2521 local @ginfo = getgrgid($uinfo->[3]);
2522 foreach $u (@_) {
2523         if ($u =~ /^\@(\S+)$/) {
2524                 return 1 if (&is_group_member($uinfo, $1));
2525                 }
2526         elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2527                 return (!$1 || $uinfo[2] >= $1) &&
2528                        (!$2 || $uinfo[2] <= $2);
2529                 }
2530         else {
2531                 return 1 if ($u eq $uinfo->[0]);
2532                 }
2533         }
2534 return 0;
2535 }
2536
2537 # restart_miniserv()
2538 # Called when a SIGHUP is received to restart the web server. This is done
2539 # by exec()ing perl with the same command line as was originally used
2540 sub restart_miniserv
2541 {
2542 print STDERR "restarting miniserv\n";
2543 &log_error("Restarting");
2544 close(SOCK);
2545 &close_all_sockets();
2546 &close_all_pipes();
2547 dbmclose(%sessiondb);
2548 kill('KILL', $logclearer) if ($logclearer);
2549 kill('KILL', $extauth) if ($extauth);
2550 exec($perl_path, $miniserv_path, @miniserv_argv);
2551 die "Failed to restart miniserv with $perl_path $miniserv_path";
2552 }
2553
2554 sub trigger_restart
2555 {
2556 $need_restart = 1;
2557 }
2558
2559 sub trigger_reload
2560 {
2561 $need_reload = 1;
2562 }
2563
2564 sub to_ipaddress
2565 {
2566 local (@rv, $i);
2567 foreach $i (@_) {
2568         if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2569             $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2570         else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2571         }
2572 return wantarray ? @rv : $rv[0];
2573 }
2574
2575 # read_line(no-wait, no-limit)
2576 # Reads one line from SOCK or SSL
2577 sub read_line
2578 {
2579 local ($nowait, $nolimit) = @_;
2580 local($idx, $more, $rv);
2581 while(($idx = index($main::read_buffer, "\n")) < 0) {
2582         if (length($main::read_buffer) > 10000 && !$nolimit) {
2583                 &http_error(414, "Request too long",
2584                     "Received excessive line <pre>$main::read_buffer</pre>");
2585                 }
2586
2587         # need to read more..
2588         &wait_for_data_error() if (!$nowait);
2589         if ($use_ssl) {
2590                 $more = Net::SSLeay::read($ssl_con);
2591                 }
2592         else {
2593                 local $ok = sysread(SOCK, $more, 1024);
2594                 $more = undef if ($ok <= 0);
2595                 }
2596         if ($more eq '') {
2597                 # end of the data
2598                 $rv = $main::read_buffer;
2599                 undef($main::read_buffer);
2600                 return $rv;
2601                 }
2602         $main::read_buffer .= $more;
2603         }
2604 $rv = substr($main::read_buffer, 0, $idx+1);
2605 $main::read_buffer = substr($main::read_buffer, $idx+1);
2606 return $rv;
2607 }
2608
2609 # read_data(length)
2610 # Reads up to some amount of data from SOCK or the SSL connection
2611 sub read_data
2612 {
2613 local ($rv);
2614 if (length($main::read_buffer)) {
2615         if (length($main::read_buffer) > $_[0]) {
2616                 # Return the first part of the buffer
2617                 $rv = substr($main::read_buffer, 0, $_[0]);
2618                 $main::read_buffer = substr($main::read_buffer, $_[0]);
2619                 return $rv;
2620                 }
2621         else {
2622                 # Return the whole buffer
2623                 $rv = $main::read_buffer;
2624                 undef($main::read_buffer);
2625                 return $rv;
2626                 }
2627         }
2628 elsif ($use_ssl) {
2629         # Call SSL read function
2630         return Net::SSLeay::read($ssl_con, $_[0]);
2631         }
2632 else {
2633         # Just do a normal read
2634         local $buf;
2635         sysread(SOCK, $buf, $_[0]) || return undef;
2636         return $buf;
2637         }
2638 }
2639
2640 # sysread_line(fh)
2641 # Read a line from a file handle, using sysread to get a byte at a time
2642 sub sysread_line
2643 {
2644 local ($fh) = @_;
2645 local $line;
2646 while(1) {
2647         local ($buf, $got);
2648         $got = sysread($fh, $buf, 1);
2649         last if ($got <= 0);
2650         $line .= $buf;
2651         last if ($buf eq "\n");
2652         }
2653 return $line;
2654 }
2655
2656 # wait_for_data(secs)
2657 # Waits at most the given amount of time for some data on SOCK, returning
2658 # 0 if not found, 1 if some arrived.
2659 sub wait_for_data
2660 {
2661 local $rmask;
2662 vec($rmask, fileno(SOCK), 1) = 1;
2663 local $got = select($rmask, undef, undef, $_[0]);
2664 return $got == 0 ? 0 : 1;
2665 }
2666
2667 # wait_for_data_error()
2668 # Waits 60 seconds for data on SOCK, and fails if none arrives
2669 sub wait_for_data_error
2670 {
2671 local $got = &wait_for_data(60);
2672 if (!$got) {
2673         &http_error(400, "Timeout",
2674                     "Waited more than 60 seconds for request data");
2675         }
2676 }
2677
2678 # write_data(data, ...)
2679 # Writes a string to SOCK or the SSL connection
2680 sub write_data
2681 {
2682 local $str = join("", @_);
2683 if ($use_ssl) {
2684         Net::SSLeay::write($ssl_con, $str);
2685         }
2686 else {
2687         syswrite(SOCK, $str, length($str));
2688         }
2689 # Intentionally introduce a small delay to avoid problems where IE reports
2690 # the page as empty / DNS failed when it get a large response too quickly!
2691 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2692 $write_data_count += length($str);
2693 }
2694
2695 # reset_byte_count()
2696 sub reset_byte_count { $write_data_count = 0; }
2697
2698 # byte_count()
2699 sub byte_count { return $write_data_count; }
2700
2701 # log_request(hostname, user, request, code, bytes)
2702 sub log_request
2703 {
2704 if ($config{'log'}) {
2705         local ($user, $ident, $headers);
2706         if ($config{'logident'}) {
2707                 # add support for rfc1413 identity checking here
2708                 }
2709         else { $ident = "-"; }
2710         $user = $_[1] ? $_[1] : "-";
2711         local $dstr = &make_datestr();
2712         if (fileno(MINISERVLOG)) {
2713                 seek(MINISERVLOG, 0, 2);
2714                 }
2715         else {
2716                 open(MINISERVLOG, ">>$config{'logfile'}");
2717                 chmod(0600, $config{'logfile'});
2718                 }
2719         if (defined($config{'logheaders'})) {
2720                 foreach $h (split(/\s+/, $config{'logheaders'})) {
2721                         $headers .= " $h=\"$header{$h}\"";
2722                         }
2723                 }
2724         elsif ($config{'logclf'}) {
2725                 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2726                 }
2727         else {
2728                 $headers = "";
2729                 }
2730         print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2731                           "$_[3] $_[4]$headers\n";
2732         close(MINISERVLOG);
2733         }
2734 }
2735
2736 # make_datestr()
2737 sub make_datestr
2738 {
2739 local @tm = localtime(time());
2740 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2741                 $tm[3], $month[$tm[4]], $tm[5]+1900,
2742                 $tm[2], $tm[1], $tm[0], $timezone;
2743 }
2744
2745 # log_error(message)
2746 sub log_error
2747 {
2748 seek(STDERR, 0, 2);
2749 print STDERR "[",&make_datestr(),"] ",
2750         $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2751         $page ? ( $page," : " ) : ( ),
2752         @_,"\n";
2753 }
2754
2755 # read_errors(handle)
2756 # Read and return all input from some filehandle
2757 sub read_errors
2758 {
2759 local($fh, $_, $rv);
2760 $fh = $_[0];
2761 while(<$fh>) { $rv .= $_; }
2762 return $rv;
2763 }
2764
2765 sub write_keep_alive
2766 {
2767 local $mode;
2768 if ($config{'nokeepalive'}) {
2769         # Keep alives have been disabled in config
2770         $mode = 0;
2771         }
2772 elsif (@childpids > $config{'maxconns'}*.8) {
2773         # Disable because nearing process limit
2774         $mode = 0;
2775         }
2776 elsif (@_) {
2777         # Keep alive specified by caller
2778         $mode = $_[0];
2779         }
2780 else {
2781         # Keep alive determined by browser
2782         $mode = $header{'connection'} =~ /keep-alive/i;
2783         }
2784 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2785 return $mode;
2786 }
2787
2788 sub term_handler
2789 {
2790 kill('TERM', @childpids) if (@childpids);
2791 kill('KILL', $logclearer) if ($logclearer);
2792 kill('KILL', $extauth) if ($extauth);
2793 exit(1);
2794 }
2795
2796 sub http_date
2797 {
2798 local @tm = gmtime($_[0]);
2799 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2800                 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2801                 $tm[2], $tm[1], $tm[0];
2802 }
2803
2804 sub TIEHANDLE
2805 {
2806 my $i; bless \$i, shift;
2807 }
2808  
2809 sub WRITE
2810 {
2811 $r = shift;
2812 my($buf,$len,$offset) = @_;
2813 &write_to_sock(substr($buf, $offset, $len));
2814 }
2815  
2816 sub PRINT
2817 {
2818 $r = shift;
2819 $$r++;
2820 my $buf = join(defined($,) ? $, : "", @_);
2821 $buf .= $\ if defined($\);
2822 &write_to_sock($buf);
2823 }
2824  
2825 sub PRINTF
2826 {
2827 shift;
2828 my $fmt = shift;
2829 &write_to_sock(sprintf $fmt, @_);
2830 }
2831  
2832 # Send back already read data while we have it, then read from SOCK
2833 sub READ
2834 {
2835 my $r = shift;
2836 my $bufref = \$_[0];
2837 my $len = $_[1];
2838 my $offset = $_[2];
2839 if ($postpos < length($postinput)) {
2840         # Reading from already fetched array
2841         my $left = length($postinput) - $postpos;
2842         my $canread = $len > $left ? $left : $len;
2843         substr($$bufref, $offset, $canread) =
2844                 substr($postinput, $postpos, $canread);
2845         $postpos += $canread;
2846         return $canread;
2847         }
2848 else {
2849         # Read from network socket
2850         local $data = &read_data($len);
2851         if ($data eq '' && $len) {
2852                 # End of socket
2853                 print STDERR "finished reading - shutting down socket\n";
2854                 shutdown(SOCK, 0);
2855                 }
2856         substr($$bufref, $offset, length($data)) = $data;
2857         return length($data);
2858         }
2859 }
2860
2861 sub OPEN
2862 {
2863 #print STDERR "open() called - should never happen!\n";
2864 }
2865  
2866 # Read a line of input
2867 sub READLINE
2868 {
2869 my $r = shift;
2870 if ($postpos < length($postinput) &&
2871     ($idx = index($postinput, "\n", $postpos)) >= 0) {
2872         # A line exists in the memory buffer .. use it
2873         my $line = substr($postinput, $postpos, $idx-$postpos+1);
2874         $postpos = $idx+1;
2875         return $line;
2876         }
2877 else {
2878         # Need to read from the socket
2879         my $line;
2880         if ($postpos < length($postinput)) {
2881                 # Start with in-memory data
2882                 $line = substr($postinput, $postpos);
2883                 $postpos = length($postinput);
2884                 }
2885         my $nl = &read_line(0, 1);
2886         if ($nl eq '') {
2887                 # End of socket
2888                 print STDERR "finished reading - shutting down socket\n";
2889                 shutdown(SOCK, 0);
2890                 }
2891         $line .= $nl if (defined($nl));
2892         return $line;
2893         }
2894 }
2895  
2896 # Read one character of input
2897 sub GETC
2898 {
2899 my $r = shift;
2900 my $buf;
2901 my $got = READ($r, \$buf, 1, 0);
2902 return $got > 0 ? $buf : undef;
2903 }
2904
2905 sub FILENO
2906 {
2907 return fileno(SOCK);
2908 }
2909  
2910 sub CLOSE { }
2911  
2912 sub DESTROY { }
2913
2914 # write_to_sock(data, ...)
2915 sub write_to_sock
2916 {
2917 local $d;
2918 foreach $d (@_) {
2919         if ($doneheaders || $miniserv::nph_script) {
2920                 &write_data($d);
2921                 }
2922         else {
2923                 $headers .= $d;
2924                 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2925                         if ($1 =~ /^(\S+):\s+(.*)$/) {
2926                                 $cgiheader{lc($1)} = $2;
2927                                 push(@cgiheader, [ $1, $2 ]);
2928                                 }
2929                         elsif ($1 !~ /\S/) {
2930                                 $doneheaders++;
2931                                 }
2932                         else {
2933                                 &http_error(500, "Bad Header");
2934                                 }
2935                         }
2936                 if ($doneheaders) {
2937                         if ($cgiheader{"location"}) {
2938                                 &write_data(
2939                                         "HTTP/1.0 302 Moved Temporarily\r\n");
2940                                 &write_data("Date: $datestr\r\n");
2941                                 &write_data("Server: $config{server}\r\n");
2942                                 &write_keep_alive(0);
2943                                 }
2944                         elsif ($cgiheader{"content-type"} eq "") {
2945                                 &http_error(500, "Missing Content-Type Header");
2946                                 }
2947                         else {
2948                                 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2949                                 &write_data("Date: $datestr\r\n");
2950                                 &write_data("Server: $config{server}\r\n");
2951                                 &write_keep_alive(0);
2952                                 }
2953                         foreach $h (@cgiheader) {
2954                                 &write_data("$h->[0]: $h->[1]\r\n");
2955                                 }
2956                         &write_data("\r\n");
2957                         &reset_byte_count();
2958                         &write_data($headers);
2959                         }
2960                 }
2961         }
2962 }
2963
2964 sub verify_client
2965 {
2966 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2967 if ($cert) {
2968         local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2969         $verified_client = 1 if (!$errnum);
2970         }
2971 return 1;
2972 }
2973
2974 sub END
2975 {
2976 if ($doing_cgi_eval && $$ == $main_process_id) {
2977         # A CGI program called exit! This is a horrible hack to 
2978         # finish up before really exiting
2979         shutdown(SOCK, 1);
2980         close(SOCK);
2981         close($PASSINw); close($PASSOUTw);
2982         &log_request($acpthost, $authuser, $reqline,
2983                      $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2984         }
2985 }
2986
2987 # urlize
2988 # Convert a string to a form ok for putting in a URL
2989 sub urlize {
2990   local($tmp, $tmp2, $c);
2991   $tmp = $_[0];
2992   $tmp2 = "";
2993   while(($c = chop($tmp)) ne "") {
2994         if ($c !~ /[A-z0-9]/) {
2995                 $c = sprintf("%%%2.2X", ord($c));
2996                 }
2997         $tmp2 = $c . $tmp2;
2998         }
2999   return $tmp2;
3000 }
3001
3002 # validate_user(username, password, host)
3003 # Checks if some username and password are valid. Returns the modified username,
3004 # the expired / temp pass flag, and the non-existence flag
3005 sub validate_user
3006 {
3007 local ($user, $pass, $host) = @_;
3008 return ( ) if (!$user);
3009 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3010 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3011         &can_user_login($user, undef, $host);
3012 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3013 if ($notexist) {
3014         # User doesn't even exist, so go no further
3015         return ( undef, 0, 1 );
3016         }
3017 elsif ($canmode == 0) {
3018         # User does exist but cannot login
3019         return ( $canuser, 0, 0 );
3020         }
3021 elsif ($canmode == 1) {
3022         # Attempt Webmin authentication
3023         if ($users{$webminuser} eq
3024             &password_crypt($pass, $users{$webminuser})) {
3025                 # Password is valid .. but check for expiry
3026                 local $lc = $lastchanges{$user};
3027                 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
3028                         local $daysold = (time() - $lc)/(24*60*60);
3029                         print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
3030                         if ($config{'pass_lockdays'} &&
3031                             $daysold > $config{'pass_lockdays'}) {
3032                                 # So old that the account is locked
3033                                 return ( undef, 0, 0 );
3034                                 }
3035                         elsif ($daysold > $config{'pass_maxdays'}) {
3036                                 # Password has expired
3037                                 return ( $user, 1, 0 );
3038                                 }
3039                         }
3040                 if ($temppass{$user}) {
3041                         # Temporary password - force change now
3042                         return ( $user, 2, 0 );
3043                         }
3044                 return ( $user, 0, 0 );
3045                 }
3046         else {
3047                 return ( undef, 0, 0 );
3048                 }
3049         }
3050 elsif ($canmode == 2 || $canmode == 3) {
3051         # Attempt PAM or passwd file authentication
3052         local $val = &validate_unix_user($canuser, $pass);
3053         print DEBUG "validate_user: unix val=$val\n";
3054         if ($val && $sudo) {
3055                 # Need to check if this Unix user can sudo
3056                 if (!&check_sudo_permissions($canuser, $pass)) {
3057                         print DEBUG "validate_user: sudo failed\n";
3058                         $val = 0;
3059                         }
3060                 else {
3061                         print DEBUG "validate_user: sudo passed\n";
3062                         }
3063                 }
3064         return $val == 2 ? ( $canuser, 1, 0 ) :
3065                $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3066         }
3067 elsif ($canmode == 4) {
3068         # Attempt external authentication
3069         return &validate_external_user($canuser, $pass) ?
3070                 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3071         }
3072 else {
3073         # Can't happen!
3074         return ( );
3075         }
3076 }
3077
3078 # validate_unix_user(user, password)
3079 # Returns 1 if a username and password are valid under unix, 0 if not,
3080 # or 2 if the account has expired.
3081 # Checks PAM if available, and falls back to reading the system password
3082 # file otherwise.
3083 sub validate_unix_user
3084 {
3085 if ($use_pam) {
3086         # Check with PAM
3087         $pam_username = $_[0];
3088         $pam_password = $_[1];
3089         eval "use Authen::PAM;";
3090         local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3091                                       \&pam_conv_func);
3092         if (ref($pamh)) {
3093                 local $pam_ret = $pamh->pam_authenticate();
3094                 if ($pam_ret == PAM_SUCCESS()) {
3095                         # Logged in OK .. make sure password hasn't expired
3096                         local $acct_ret = $pamh->pam_acct_mgmt();
3097                         if ($acct_ret == PAM_SUCCESS()) {
3098                                 $pamh->pam_open_session();
3099                                 return 1;
3100                                 }
3101                         elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3102                                $acct_ret == PAM_ACCT_EXPIRED()) {
3103                                 return 2;
3104                                 }
3105                         else {
3106                                 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3107                                 return 0;
3108                                 }
3109                         }
3110                 return 0;
3111                 }
3112         }
3113 elsif ($config{'pam_only'}) {
3114         # Pam is not available, but configuration forces it's use!
3115         return 0;
3116         }
3117 elsif ($config{'passwd_file'}) {
3118         # Check in a password file
3119         local $rv = 0;
3120         open(FILE, $config{'passwd_file'});
3121         if ($config{'passwd_file'} eq '/etc/security/passwd') {
3122                 # Assume in AIX format
3123                 while(<FILE>) {
3124                         s/\s*$//;
3125                         if (/^\s*(\S+):/ && $1 eq $_[0]) {
3126                                 $_ = <FILE>;
3127                                 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3128                                         $rv = $1 eq &password_crypt($_[1], $1) ?
3129                                                 1 : 0;
3130                                         }
3131                                 last;
3132                                 }
3133                         }
3134                 }
3135         else {
3136                 # Read the system password or shadow file
3137                 while(<FILE>) {
3138                         local @l = split(/:/, $_, -1);
3139                         local $u = $l[$config{'passwd_uindex'}];
3140                         local $p = $l[$config{'passwd_pindex'}];
3141                         if ($u eq $_[0]) {
3142                                 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3143                                 if ($config{'passwd_cindex'} ne '' && $rv) {
3144                                         # Password may have expired!
3145                                         local $c = $l[$config{'passwd_cindex'}];
3146                                         local $m = $l[$config{'passwd_mindex'}];
3147                                         local $day = time()/(24*60*60);
3148                                         if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3149                                             $day - $c > $m) {
3150                                                 # Yep, it has ..
3151                                                 $rv = 2;
3152                                                 }
3153                                         }
3154                                 if ($p eq "" && $config{'passwd_blank'}) {
3155                                         # Force password change
3156                                         $rv = 2;
3157                                         }
3158                                 last;
3159                                 }
3160                         }
3161                 }
3162         close(FILE);
3163         return $rv if ($rv);
3164         }
3165
3166 # Fallback option - check password returned by getpw*
3167 local @uinfo = getpwnam($_[0]);
3168 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3169         return 1;
3170         }
3171
3172 return 0;       # Totally failed
3173 }
3174
3175 # validate_external_user(user, pass)
3176 # Validate a user by passing the username and password to an external
3177 # squid-style authentication program
3178 sub validate_external_user
3179 {
3180 return 0 if (!$config{'extauth'});
3181 flock(EXTAUTH, 2);
3182 local $str = "$_[0] $_[1]\n";
3183 syswrite(EXTAUTH, $str, length($str));
3184 local $resp = <EXTAUTH>;
3185 flock(EXTAUTH, 8);
3186 return $resp =~ /^OK/i ? 1 : 0;
3187 }
3188
3189 # can_user_login(username, no-append, host)
3190 # Checks if a user can login or not.
3191 # First return value is the username.
3192 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3193 # file, 4 if external.
3194 # Third is 1 if the user does not exist at all, 0 if he does.
3195 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3196 # Fifth is a flag indicating if a sudo check is needed.
3197 sub can_user_login
3198 {
3199 if (!$users{$_[0]}) {
3200         # See if this user exists in Unix and can be validated by the same
3201         # method as the unixauth webmin user
3202         local $realuser = $unixauth{$_[0]};
3203         local @uinfo;
3204         local $sudo = 0;
3205         local $pamany = 0;
3206         eval { @uinfo = getpwnam($_[0]); };     # may fail on windows
3207         if (!$realuser && @uinfo) {
3208                 # No unixauth entry for the username .. try his groups 
3209                 foreach my $ua (keys %unixauth) {
3210                         if ($ua =~ /^\@(.*)$/) {
3211                                 if (&is_group_member(\@uinfo, $1)) {
3212                                         $realuser = $unixauth{$ua};
3213                                         last;
3214                                         }
3215                                 }
3216                         }
3217                 }
3218         if (!$realuser && @uinfo) {
3219                 # Fall back to unix auth for all Unix users
3220                 $realuser = $unixauth{"*"};
3221                 }
3222         if (!$realuser && $use_sudo && @uinfo) {
3223                 # Allow login effectively as root, if sudo permits it
3224                 $sudo = 1;
3225                 $realuser = "root";
3226                 }
3227         if (!$realuser && !@uinfo && $config{'pamany'}) {
3228                 # If the user completely doesn't exist, we can still allow
3229                 # him to authenticate via PAM
3230                 $realuser = $config{'pamany'};
3231                 $pamany = 1;
3232                 }
3233         if (!$realuser) {
3234                 # For Usermin, always fall back to unix auth for any user,
3235                 # so that later checks with domain added / removed are done.
3236                 $realuser = $unixauth{"*"};
3237                 }
3238         return (undef, 0, 1, undef) if (!$realuser);
3239         local $up = $users{$realuser};
3240         return (undef, 0, 1, undef) if (!defined($up));
3241
3242         # Work out possible domain names from the hostname
3243         local @doms = ( $_[2] );
3244         if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3245                 push(@doms, $2);
3246                 }
3247
3248         if ($config{'user_mapping'} && !%user_mapping) {
3249                 # Read the user mapping file
3250                 %user_mapping = ();
3251                 open(MAPPING, $config{'user_mapping'});
3252                 while(<MAPPING>) {
3253                         s/\r|\n//g;
3254                         s/#.*$//;
3255                         if (/^(\S+)\s+(\S+)/) {
3256                                 if ($config{'user_mapping_reverse'}) {
3257                                         $user_mapping{$1} = $2;
3258                                         }
3259                                 else {
3260                                         $user_mapping{$2} = $1;
3261                                         }
3262                                 }
3263                         }
3264                 close(MAPPING);
3265                 }
3266
3267         # Check the user mapping file to see if there is an entry for the
3268         # user login in which specifies a new effective user
3269         local $um;
3270         foreach my $d (@doms) {
3271                 $um ||= $user_mapping{"$_[0]\@$d"};
3272                 }
3273         $um ||= $user_mapping{$_[0]};
3274         if (defined($um) && ($_[1]&4) == 0) {
3275                 # A mapping exists - use it!
3276                 return &can_user_login($um, $_[1]+4, $_[2]);
3277                 }
3278
3279         # Check if a user with the entered login and the domains appended
3280         # or prepended exists, and if so take it to be the effective user
3281         if (!@uinfo && $config{'domainuser'}) {
3282                 # Try again with name.domain and name.firstpart
3283                 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3284                 if (($_[1]&1) == 0) {
3285                         local ($a, $p);
3286                         foreach $a (@firsts, @doms) {
3287                                 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3288                                             "${a}.$_[0]", "${a}-$_[0]",
3289                                             "$_[0]_${a}", "${a}_$_[0]") {
3290                                         local @vu = &can_user_login(
3291                                                         $p, $_[1]+1, $_[2]);
3292                                         return @vu if ($vu[1]);
3293                                         }
3294                                 }
3295                         }
3296                 }
3297
3298         # Check if the user entered a domain at the end of his username when
3299         # he really shouldn't have, and if so try without it
3300         if (!@uinfo && $config{'domainstrip'} &&
3301             $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3302                 local ($stripped, $dom) = ($1, $2);
3303                 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3304                 return @vu if ($vu[1]);
3305                 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3306                 return @vu if ($vu[1]);
3307                 }
3308
3309         return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3310
3311         if (@uinfo) {
3312                 if (defined(@allowusers)) {
3313                         # Only allow people on the allow list
3314                         return ( undef, 0, 0, undef )
3315                                 if (!&users_match(\@uinfo, @allowusers));
3316                         }
3317                 elsif (defined(@denyusers)) {
3318                         # Disallow people on the deny list
3319                         return ( undef, 0, 0, undef )
3320                                 if (&users_match(\@uinfo, @denyusers));
3321                         }
3322                 if ($config{'shells_deny'}) {
3323                         local $found = 0;
3324                         open(SHELLS, $config{'shells_deny'});
3325                         while(<SHELLS>) {
3326                                 s/\r|\n//g;
3327                                 s/#.*$//;
3328                                 $found++ if ($_ eq $uinfo[8]);
3329                                 }
3330                         close(SHELLS);
3331                         return ( undef, 0, 0, undef ) if (!$found);
3332                         }
3333                 }
3334
3335         if ($up eq 'x') {
3336                 # PAM or passwd file authentication
3337                 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3338                 }
3339         elsif ($up eq 'e') {
3340                 # External authentication
3341                 return ( $_[0], 4, 0, $realuser, $sudo );
3342                 }
3343         else {
3344                 # Fixed Webmin password
3345                 return ( $_[0], 1, 0, $realuser, $sudo );
3346                 }
3347         }
3348 elsif ($users{$_[0]} eq 'x') {
3349         # Webmin user authenticated via PAM or password file
3350         return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3351         }
3352 elsif ($users{$_[0]} eq 'e') {
3353         # Webmin user authenticated externally
3354         return ( $_[0], 4, 0, $_[0] );
3355         }
3356 else {
3357         # Normal Webmin user
3358         return ( $_[0], 1, 0, $_[0] );
3359         }
3360 }
3361
3362 # the PAM conversation function for interactive logins
3363 sub pam_conv_func
3364 {
3365 $pam_conv_func_called++;
3366 my @res;
3367 while ( @_ ) {
3368         my $code = shift;
3369         my $msg = shift;
3370         my $ans = "";
3371
3372         $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3373         $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3374
3375         push @res, PAM_SUCCESS();
3376         push @res, $ans;
3377         }
3378 push @res, PAM_SUCCESS();
3379 return @res;
3380 }
3381
3382 sub urandom_timeout
3383 {
3384 close(RANDOM);
3385 }
3386
3387 # get_socket_name(handle)
3388 # Returns the local hostname or IP address of some connection
3389 sub get_socket_name
3390 {
3391 return $config{'host'} if ($config{'host'});
3392 local $sn = getsockname($_[0]);
3393 return undef if (!$sn);
3394 local $myaddr = (unpack_sockaddr_in($sn))[1];
3395 if (!$get_socket_name_cache{$myaddr}) {
3396         local $myname;
3397         if (!$config{'no_resolv_myname'}) {
3398                 $myname = gethostbyaddr($myaddr, AF_INET);
3399                 }
3400         if ($myname eq "") {
3401                 $myname = inet_ntoa($myaddr);
3402                 }
3403         $get_socket_name_cache{$myaddr} = $myname;
3404         }
3405 return $get_socket_name_cache{$myaddr};
3406 }
3407
3408 # run_login_script(username, sid, remoteip, localip)
3409 sub run_login_script
3410 {
3411 if ($config{'login_script'}) {
3412         system($config{'login_script'}.
3413                " ".join(" ", map { quotemeta($_) || '""' } @_).
3414                " >/dev/null 2>&1 </dev/null");
3415         }
3416 }
3417
3418 # run_logout_script(username, sid, remoteip, localip)
3419 sub run_logout_script
3420 {
3421 if ($config{'logout_script'}) {
3422         system($config{'logout_script'}.
3423                " ".join(" ", map { quotemeta($_) || '""' } @_).
3424                " >/dev/null 2>&1 </dev/null");
3425         }
3426 }
3427
3428 # close_all_sockets()
3429 # Closes all the main listening sockets
3430 sub close_all_sockets
3431 {
3432 local $s;
3433 foreach $s (@socketfhs) {
3434         close($s);
3435         }
3436 }
3437
3438 # close_all_pipes()
3439 # Close all pipes for talking to sub-processes
3440 sub close_all_pipes
3441 {
3442 local $p;
3443 foreach $p (@passin) { close($p); }
3444 foreach $p (@passout) { close($p); }
3445 foreach $p (values %conversations) {
3446         if ($p->{'PAMOUTr'}) {
3447                 close($p->{'PAMOUTr'});
3448                 close($p->{'PAMINw'});
3449                 }
3450         }
3451 }
3452
3453 # check_user_ip(user)
3454 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3455 sub check_user_ip
3456 {
3457 if ($deny{$_[0]} &&
3458     &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3459     $allow{$_[0]} &&
3460     !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3461         return 0;
3462         }
3463 return 1;
3464 }
3465
3466 # check_user_time(user)
3467 # Returns 1 if some user is allowed to login at the current date and time
3468 sub check_user_time
3469 {
3470 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3471 local @tm = localtime(time());
3472 if ($allowdays{$_[0]}) {
3473         # Make sure day is allowed
3474         return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3475         }
3476 if ($allowhours{$_[0]}) {
3477         # Make sure time is allowed
3478         local $m = $tm[2]*60+$tm[1];
3479         return 0 if ($m < $allowhours{$_[0]}->[0] ||
3480                      $m > $allowhours{$_[0]}->[1]);
3481         }
3482 return 1;
3483 }
3484
3485 # generate_random_id(password, [force-urandom])
3486 # Returns a random session ID number
3487 sub generate_random_id
3488 {
3489 local ($pass, $force_urandom) = @_;
3490 local $sid;
3491 if (!$bad_urandom) {
3492         # First try /dev/urandom, unless we have marked it as bad
3493         $SIG{ALRM} = "miniserv::urandom_timeout";
3494         alarm(5);
3495         if (open(RANDOM, "/dev/urandom")) {
3496                 my $tmpsid;
3497                 if (read(RANDOM, $tmpsid, 16) == 16) {
3498                         $sid = lc(unpack('h*',$tmpsid));
3499                         }
3500                 close(RANDOM);
3501                 }
3502         alarm(0);
3503         }
3504 if (!$sid && !$force_urandom) {
3505         $sid = time();
3506         local $mul = 1;
3507         foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3508                 $sid += ord($c) * $mul;
3509                 $mul *= 3;
3510                 }
3511         }
3512 return $sid;
3513 }
3514
3515 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3516 # Called from handle_session to either mark a user as logged in, or not
3517 sub handle_login
3518 {
3519 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3520 $authuser = $vu if ($ok);
3521
3522 # check if the test cookie is set
3523 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3524     !$config{'no_testing_cookie'} && !$notest) {
3525         &http_error(500, "No cookies",
3526            "Your browser does not support cookies, ".
3527            "which are required for this web server to ".
3528            "work in session authentication mode");
3529         }
3530
3531 # check with main process for delay
3532 if ($config{'passdelay'} && $vu) {
3533         print $PASSINw "delay $vu $acptip $ok\n";
3534         <$PASSOUTr> =~ /(\d+) (\d+)/;
3535         $blocked = $2;
3536         sleep($1);
3537         }
3538
3539 if ($ok && (!$expired ||
3540             $config{'passwd_mode'} == 1)) {
3541         # Logged in OK! Tell the main process about
3542         # the new SID
3543         local $sid = &generate_random_id($pass);
3544         print $PASSINw "new $sid $authuser $acptip\n";
3545
3546         # Run the post-login script, if any
3547         &run_login_script($authuser, $sid,
3548                           $acptip, $localip);
3549
3550         # Check for a redirect URL for the user
3551         local $rurl = &login_redirect($authuser, $pass, $host);
3552         if ($rurl) {
3553                 # Got one .. go to it
3554                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3555                 &write_data("Date: $datestr\r\n");
3556                 &write_data("Server: $config{'server'}\r\n");
3557                 &write_data("Location: $rurl\r\n");
3558                 &write_keep_alive(0);
3559                 &write_data("\r\n");
3560                 &log_request($acpthost, $authuser, $reqline, 302, 0);
3561                 }
3562         else {
3563                 # Set cookie and redirect to originally requested page
3564                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3565                 &write_data("Date: $datestr\r\n");
3566                 &write_data("Server: $config{'server'}\r\n");
3567                 local $ssl = $use_ssl || $config{'inetd_ssl'};
3568                 $portstr = $port == 80 && !$ssl ? "" :
3569                            $port == 443 && $ssl ? "" : ":$port";
3570                 $prot = $ssl ? "https" : "http";
3571                 local $sec = $ssl ? "; secure" : "";
3572                 #$sec .= "; httpOnly";
3573                 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3574                         # Make redirect URL safe
3575                         $in{'page'} = "/";
3576                         }
3577                 if ($in{'save'}) {
3578                         &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3579                         }
3580                 else {
3581                         &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3582                         }
3583                 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3584                 &write_keep_alive(0);
3585                 &write_data("\r\n");
3586                 &log_request($acpthost, $authuser, $reqline, 302, 0);
3587                 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3588                 &write_login_utmp($authuser, $acpthost);
3589                 }
3590         return 0;
3591         }
3592 elsif ($ok && $expired &&
3593        ($config{'passwd_mode'} == 2 || $expired == 2)) {
3594         # Login was ok, but password has expired or was temporary. Need
3595         # to force display of password change form.
3596         $validated = 1;
3597         $authuser = undef;
3598         $querystring = "&user=".&urlize($vu).
3599                        "&pam=".$use_pam.
3600                        "&expired=".$expired;
3601         $method = "GET";
3602         $queryargs = "";
3603         $page = $config{'password_form'};
3604         $logged_code = 401;
3605         $miniserv_internal = 2;
3606         syslog("crit", "%s",
3607                 "Expired login as $vu ".
3608                 "from $acpthost") if ($use_syslog);
3609         }
3610 else {
3611         # Login failed, or password has expired. The login form will be
3612         # displayed again by later code
3613         $failed_user = $vu;
3614         $request_uri = $in{'page'};
3615         $already_session_id = undef;
3616         $method = "GET";
3617         $authuser = $baseauthuser = undef;
3618         syslog("crit", "%s",
3619                 ($nonexist ? "Non-existent" :
3620                  $expired ? "Expired" : "Invalid").
3621                 " login as $vu from $acpthost")
3622                 if ($use_syslog);
3623         }
3624 return undef;
3625 }
3626
3627 # write_login_utmp(user, host)
3628 # Record the login by some user in utmp
3629 sub write_login_utmp
3630 {
3631 if ($write_utmp) {
3632         # Write utmp record for login
3633         %utmp = ( 'ut_host' => $_[1],
3634                   'ut_time' => time(),
3635                   'ut_user' => $_[0],
3636                   'ut_type' => 7,       # user process
3637                   'ut_pid' => $main_process_id,
3638                   'ut_line' => $config{'pam'},
3639                   'ut_id' => '' );
3640         if (defined(&User::Utmp::putut)) {
3641                 User::Utmp::putut(\%utmp);
3642                 }
3643         else {
3644                 User::Utmp::pututline(\%utmp);
3645                 }
3646         }
3647 }
3648
3649 # write_logout_utmp(user, host)
3650 # Record the logout by some user in utmp
3651 sub write_logout_utmp
3652 {
3653 if ($write_utmp) {
3654         # Write utmp record for logout
3655         %utmp = ( 'ut_host' => $_[1],
3656                   'ut_time' => time(),
3657                   'ut_user' => $_[0],
3658                   'ut_type' => 8,       # dead process
3659                   'ut_pid' => $main_process_id,
3660                   'ut_line' => $config{'pam'},
3661                   'ut_id' => '' );
3662         if (defined(&User::Utmp::putut)) {
3663                 User::Utmp::putut(\%utmp);
3664                 }
3665         else {
3666                 User::Utmp::pututline(\%utmp);
3667                 }
3668         }
3669 }
3670
3671 # pam_conversation_process(username, write-pipe, read-pipe)
3672 # This function is called inside a sub-process to communicate with PAM. It sends
3673 # questions down one pipe, and reads responses from another
3674 sub pam_conversation_process
3675 {
3676 local ($user, $writer, $reader) = @_;
3677 $miniserv::pam_conversation_process_writer = $writer;
3678 $miniserv::pam_conversation_process_reader = $reader;
3679 eval "use Authen::PAM;";
3680 local $convh = new Authen::PAM(
3681         $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3682 local $pam_ret = $convh->pam_authenticate();
3683 if ($pam_ret == PAM_SUCCESS()) {
3684         local $acct_ret = $convh->pam_acct_mgmt();
3685         if ($acct_ret == PAM_SUCCESS()) {
3686                 $convh->pam_open_session();
3687                 print $writer "x2 $user 1 0 0\n";
3688                 }
3689         elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3690                $acct_ret == PAM_ACCT_EXPIRED()) {
3691                 print $writer "x2 $user 1 1 0\n";
3692                 }
3693         else {
3694                 print $writer "x0 Unknown PAM account status $acct_ret\n";
3695                 }
3696         }
3697 else {
3698         print $writer "x2 $user 0 0 0\n";
3699         }
3700 exit(0);
3701 }
3702
3703 # pam_conversation_process_func(type, message, [type, message, ...])
3704 # A pipe that talks to both PAM and the master process
3705 sub pam_conversation_process_func
3706 {
3707 local @rv;
3708 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3709 while(@_) {
3710         local ($type, $msg) = (shift, shift);
3711         $msg =~ s/\r|\n//g;
3712         local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3713         print $miniserv::pam_conversation_process_writer "\n";
3714         local $answer = <$miniserv::pam_conversation_process_reader>;
3715         $answer =~ s/\r|\n//g;
3716         push(@rv, PAM_SUCCESS(), $answer);
3717         }
3718 push(@rv, PAM_SUCCESS());
3719 return @rv;
3720 }
3721
3722 # allocate_pipes()
3723 # Returns 4 new pipe file handles
3724 sub allocate_pipes
3725 {
3726 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3727 local $p;
3728 local %taken = ( (map { $_, 1 } @passin),
3729                  (map { $_->{'PASSINr'} } values %conversations) );
3730 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3731 $PASSINr = "PASSINr$p";
3732 $PASSINw = "PASSINw$p";
3733 $PASSOUTr = "PASSOUTr$p";
3734 $PASSOUTw = "PASSOUTw$p";
3735 pipe($PASSINr, $PASSINw);
3736 pipe($PASSOUTr, $PASSOUTw);
3737 select($PASSINw); $| = 1;
3738 select($PASSINr); $| = 1;
3739 select($PASSOUTw); $| = 1;
3740 select($PASSOUTw); $| = 1;
3741 select(STDOUT);
3742 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3743 }
3744
3745 # recv_pam_question(&conv, fd)
3746 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3747 # Returns 0 if the conversation is over, 1 if not.
3748 sub recv_pam_question
3749 {
3750 local ($conf, $fh) = @_;
3751 local $pr = $conf->{'PAMOUTr'};
3752 select($pr); $| = 1; select(STDOUT);
3753 local $line = <$pr>;
3754 $line =~ s/\r|\n//g;
3755 if (!$line) {
3756         $line = <$pr>;
3757         $line =~ s/\r|\n//g;
3758         }
3759 $conf->{'last'} = time();
3760 if (!$line) {
3761         # Failed!
3762         print $fh "0 PAM conversation error\n";
3763         return 0;
3764         }
3765 else {
3766         local ($type, $msg) = split(/\s+/, $line, 2);
3767         if ($type =~ /^x(\d+)/) {
3768                 # Pass this status code through
3769                 print $fh "$1 $msg\n";
3770                 return $1 == 2 || $1 == 0 ? 0 : 1;
3771                 }
3772         elsif ($type == PAM_PROMPT_ECHO_ON()) {
3773                 # A normal question
3774                 print $fh "1 $msg\n";
3775                 return 1;
3776                 }
3777         elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3778                 # A password
3779                 print $fh "3 $msg\n";
3780                 return 1;
3781                 }
3782         elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3783                 # A message that does not require a response
3784                 print $fh "4 $msg\n";
3785                 return 1;
3786                 }
3787         else {
3788                 # Unknown type!
3789                 print $fh "0 Unknown PAM message type $type\n";
3790                 return 0;
3791                 }
3792         }
3793 }
3794
3795 # send_pam_answer(&conv, answer)
3796 # Sends a response from the user to the PAM sub-process
3797 sub send_pam_answer
3798 {
3799 local ($conf, $answer) = @_;
3800 local $pw = $conf->{'PAMINw'};
3801 $conf->{'last'} = time();
3802 print $pw "$answer\n";
3803 }
3804
3805 # end_pam_conversation(&conv)
3806 # Clean up PAM conversation pipes and processes
3807 sub end_pam_conversation
3808 {
3809 local ($conv) = @_;
3810 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3811 if ($conv->{'PAMINr'}) {
3812         close($conv->{'PAMINr'});
3813         close($conv->{'PAMOUTr'});
3814         close($conv->{'PAMINw'});
3815         close($conv->{'PAMOUTw'});
3816         }
3817 delete($conversations{$conv->{'cid'}});
3818 }
3819
3820 # get_ipkeys(&miniserv)
3821 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3822 sub get_ipkeys
3823 {
3824 local (@rv, $k);
3825 foreach $k (keys %{$_[0]}) {
3826         if ($k =~ /^ipkey_(\S+)/) {
3827                 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3828                                  'key' => $_[0]->{$k},
3829                                  'index' => scalar(@rv) };
3830                 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3831                 push(@rv, $ipkey);
3832                 }
3833         }
3834 return @rv;
3835 }
3836
3837 # create_ssl_context(keyfile, [certfile])
3838 sub create_ssl_context
3839 {
3840 local ($keyfile, $certfile) = @_;
3841 local $ssl_ctx;
3842 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3843 $ssl_ctx ||= Net::SSLeay::CTX_new();
3844 $ssl_ctx || die "Failed to create SSL context : $!";
3845 if ($client_certs) {
3846         Net::SSLeay::CTX_load_verify_locations(
3847                 $ssl_ctx, $config{'ca'}, "");
3848         Net::SSLeay::CTX_set_verify(
3849                 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3850         }
3851 if ($config{'extracas'}) {
3852         local $p;
3853         foreach $p (split(/\s+/, $config{'extracas'})) {
3854                 Net::SSLeay::CTX_load_verify_locations(
3855                         $ssl_ctx, $p, "");
3856                 }
3857         }
3858
3859 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3860         $ssl_ctx, $keyfile,
3861         &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3862 Net::SSLeay::CTX_use_certificate_file(
3863         $ssl_ctx, $certfile || $keyfile,
3864         &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3865
3866 return $ssl_ctx;
3867 }
3868
3869 # ssl_connection_for_ip(socket)
3870 # Returns a new SSL connection object for some socket, or undef if failed
3871 sub ssl_connection_for_ip
3872 {
3873 local ($sock) = @_;
3874 local $sn = getsockname($sock);
3875 if (!$sn) {
3876         print STDERR "Failed to get address for socket $sock\n";
3877         return undef;
3878         }
3879 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3880 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3881 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3882 if ($config{'ssl_cipher_list'}) {
3883         # Force use of ciphers
3884         eval "Net::SSLeay::set_cipher_list(
3885                         \$ssl_con, \$config{'ssl_cipher_list'})";
3886         if ($@) {
3887                 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3888                              "$@\n";
3889                 }
3890         else {
3891                 }
3892         }
3893 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3894 if (!Net::SSLeay::accept($ssl_con)) {
3895         print STDERR "Failed to initialize SSL connection\n";
3896         return undef;
3897         }
3898 return $ssl_con;
3899 }
3900
3901 # login_redirect(username, password, host)
3902 # Calls the login redirect script (if configured), which may output a URL to
3903 # re-direct a user to after logging in.
3904 sub login_redirect
3905 {
3906 return undef if (!$config{'login_redirect'});
3907 local $quser = quotemeta($_[0]);
3908 local $qpass = quotemeta($_[1]);
3909 local $qhost = quotemeta($_[2]);
3910 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3911 chop($url);
3912 return $url;
3913 }
3914
3915 # reload_config_file()
3916 # Re-read %config, and call post-config actions
3917 sub reload_config_file
3918 {
3919 &log_error("Reloading configuration");
3920 %config = &read_config_file($config_file);
3921 &update_vital_config();
3922 &read_users_file();
3923 &read_mime_types();
3924 &build_config_mappings();
3925 &read_webmin_crons();
3926 if ($config{'session'}) {
3927         dbmclose(%sessiondb);
3928         dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3929         }
3930 }
3931
3932 # read_config_file(file)
3933 # Reads the given config file, and returns a hash of values
3934 sub read_config_file
3935 {
3936 local %rv;
3937 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3938 while(<CONF>) {
3939         s/\r|\n//g;
3940         if (/^#/ || !/\S/) { next; }
3941         /^([^=]+)=(.*)$/;
3942         $name = $1; $val = $2;
3943         $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3944         $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3945         $rv{$name} = $val;
3946         }
3947 close(CONF);
3948 return %rv;
3949 }
3950
3951 # update_vital_config()
3952 # Updates %config with defaults, and dies if something vital is missing
3953 sub update_vital_config
3954 {
3955 my %vital = ("port", 80,
3956           "root", "./",
3957           "server", "MiniServ/0.01",
3958           "index_docs", "index.html index.htm index.cgi index.php",
3959           "addtype_html", "text/html",
3960           "addtype_txt", "text/plain",
3961           "addtype_gif", "image/gif",
3962           "addtype_jpg", "image/jpeg",
3963           "addtype_jpeg", "image/jpeg",
3964           "realm", "MiniServ",
3965           "session_login", "/session_login.cgi",
3966           "pam_login", "/pam_login.cgi",
3967           "password_form", "/password_form.cgi",
3968           "password_change", "/password_change.cgi",
3969           "maxconns", 50,
3970           "pam", "webmin",
3971           "sidname", "sid",
3972           "unauth", "^/unauthenticated/ ^/robots.txt\$ ^[A-Za-z0-9\\-/_]+\\.jar\$ ^[A-Za-z0-9\\-/_]+\\.class\$ ^[A-Za-z0-9\\-/_]+\\.gif\$ ^[A-Za-z0-9\\-/_]+\\.conf\$ ^[A-Za-z0-9\\-/_]+\\.ico\$ ^/robots.txt\$",
3973           "max_post", 10000,
3974           "expires", 7*24*60*60,
3975           "pam_test_user", "root",
3976          );
3977 foreach my $v (keys %vital) {
3978         if (!$config{$v}) {
3979                 if ($vital{$v} eq "") {
3980                         die "Missing config option $v";
3981                         }
3982                 $config{$v} = $vital{$v};
3983                 }
3984         }
3985 if (!$config{'sessiondb'}) {
3986         $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3987         $config{'sessiondb'} = "$1/sessiondb";
3988         }
3989 if (!$config{'errorlog'}) {
3990         $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3991         $config{'errorlog'} = "$1/miniserv.error";
3992         }
3993 if (!$config{'tempbase'}) {
3994         $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3995         $config{'tempbase'} = "$1/cgitemp";
3996         }
3997 if (!$config{'blockedfile'}) {
3998         $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3999         $config{'blockedfile'} = "$1/blocked";
4000         }
4001 if (!$config{'webmincron_dir'}) {
4002         $config_file =~ /^(.*)\/[^\/]+$/;
4003         $config{'webmincron_dir'} = "$1/webmincron/crons";
4004         }
4005 if (!$config{'webmincron_last'}) {
4006         $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4007         $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4008         }
4009 if (!$config{'webmincron_wrapper'}) {
4010         $config{'webmincron_wrapper'} = $config{'root'}.
4011                                         "/webmincron/webmincron.pl";
4012         }
4013 }
4014
4015 # read_users_file()
4016 # Fills the %users and %certs hashes from the users file in %config
4017 sub read_users_file
4018 {
4019 undef(%users);
4020 undef(%certs);
4021 undef(%allow);
4022 undef(%deny);
4023 undef(%allowdays);
4024 undef(%allowhours);
4025 undef(%lastchanges);
4026 undef(%nochange);
4027 undef(%temppass);
4028 if ($config{'userfile'}) {
4029         open(USERS, $config{'userfile'});
4030         while(<USERS>) {
4031                 s/\r|\n//g;
4032                 local @user = split(/:/, $_, -1);
4033                 $users{$user[0]} = $user[1];
4034                 $certs{$user[0]} = $user[3] if ($user[3]);
4035                 if ($user[4] =~ /^allow\s+(.*)/) {
4036                         $allow{$user[0]} = $config{'alwaysresolve'} ?
4037                                 [ split(/\s+/, $1) ] :
4038                                 [ &to_ipaddress(split(/\s+/, $1)) ];
4039                         }
4040                 elsif ($user[4] =~ /^deny\s+(.*)/) {
4041                         $deny{$user[0]} = $config{'alwaysresolve'} ?
4042                                 [ split(/\s+/, $1) ] :
4043                                 [ &to_ipaddress(split(/\s+/, $1)) ];
4044                         }
4045                 if ($user[5] =~ /days\s+(\S+)/) {
4046                         $allowdays{$user[0]} = [ split(/,/, $1) ];
4047                         }
4048                 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4049                         $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4050                         }
4051                 $lastchanges{$user[0]} = $user[6];
4052                 $nochange{$user[0]} = $user[9];
4053                 $temppass{$user[0]} = $user[10];
4054                 }
4055         close(USERS);
4056         }
4057 }
4058
4059 # read_mime_types()
4060 # Fills %mime with entries from file in %config and extra settings in %config
4061 sub read_mime_types
4062 {
4063 undef(%mime);
4064 if ($config{"mimetypes"} ne "") {
4065         open(MIME, $config{"mimetypes"});
4066         while(<MIME>) {
4067                 chop; s/#.*$//;
4068                 if (/^(\S+)\s+(.*)$/) {
4069                         my $type = $1;
4070                         my @exts = split(/\s+/, $2);
4071                         foreach my $ext (@exts) {
4072                                 $mime{$ext} = $type;
4073                                 }
4074                         }
4075                 }
4076         close(MIME);
4077         }
4078 foreach my $k (keys %config) {
4079         if ($k !~ /^addtype_(.*)$/) { next; }
4080         $mime{$1} = $config{$k};
4081         }
4082 }
4083
4084 # build_config_mappings()
4085 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4086 # redirect mapping and allow and deny lists from %config
4087 sub build_config_mappings
4088 {
4089 # build anonymous access list
4090 undef(%anonymous);
4091 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4092         if ($a =~ /^([^=]+)=(\S+)$/) {
4093                 $anonymous{$1} = $2;
4094                 }
4095         }
4096
4097 # build IP access list
4098 undef(%ipaccess);
4099 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4100         if ($a =~ /^([^=]+)=(\S+)$/) {
4101                 $ipaccess{$1} = $2;
4102                 }
4103         }
4104
4105 # build unauthenticated URLs list
4106 @unauth = split(/\s+/, $config{'unauth'});
4107
4108 # build redirect mapping
4109 undef(%redirect);
4110 foreach my $r (split(/\s+/, $config{'redirect'})) {
4111         if ($r =~ /^([^=]+)=(\S+)$/) {
4112                 $redirect{$1} = $2;
4113                 }
4114         }
4115
4116 # build prefixes to be stripped
4117 undef(@strip_prefix);
4118 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4119         push(@strip_prefix, $r);
4120         }
4121
4122 # Init allow and deny lists
4123 @deny = split(/\s+/, $config{"deny"});
4124 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4125 @allow = split(/\s+/, $config{"allow"});
4126 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4127 undef(@allowusers);
4128 undef(@denyusers);
4129 if ($config{'allowusers'}) {
4130         @allowusers = split(/\s+/, $config{'allowusers'});
4131         }
4132 elsif ($config{'denyusers'}) {
4133         @denyusers = split(/\s+/, $config{'denyusers'});
4134         }
4135
4136 # Build list of unixauth mappings
4137 undef(%unixauth);
4138 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4139         if ($ua =~ /^(\S+)=(\S+)$/) {
4140                 $unixauth{$1} = $2;
4141                 }
4142         else {
4143                 $unixauth{"*"} = $ua;
4144                 }
4145         }
4146
4147 # Build list of non-session-auth pages
4148 undef(%sessiononly);
4149 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4150         $sessiononly{$sp} = 1;
4151         }
4152
4153 # Build list of logout times
4154 undef(@logouttimes);
4155 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4156         if ($a =~ /^([^=]+)=(\S+)$/) {
4157                 push(@logouttimes, [ $1, $2 ]);
4158                 }
4159         }
4160 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4161
4162 # Build list of DAV pathss
4163 undef(@davpaths);
4164 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4165         push(@davpaths, $d);
4166         }
4167 @davusers = split(/\s+/, $config{'dav_users'});
4168
4169 # Mobile agent substrings and hostname prefixes
4170 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4171 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4172
4173 # Open debug log
4174 close(DEBUG);
4175 if ($config{'debug'}) {
4176         open(DEBUG, ">>$config{'debug'}");
4177         }
4178 else {
4179         open(DEBUG, ">/dev/null");
4180         }
4181
4182 # Reset cache of sudo checks
4183 undef(%sudocache);
4184 }
4185
4186 # is_group_member(&uinfo, groupname)
4187 # Returns 1 if some user is a primary or secondary member of a group
4188 sub is_group_member
4189 {
4190 local ($uinfo, $group) = @_;
4191 local @ginfo = getgrnam($group);
4192 return 0 if (!@ginfo);
4193 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4194 foreach my $m (split(/\s+/, $ginfo[3])) {
4195         return 1 if ($m eq $uinfo->[0]);
4196         }
4197 return 0;
4198 }
4199
4200 # prefix_to_mask(prefix)
4201 # Converts a number like 24 to a mask like 255.255.255.0
4202 sub prefix_to_mask
4203 {
4204 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4205        $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4206        $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4207                      (256-(2 ** (8-$_[0]))).".0.0.0";
4208 }
4209
4210 # get_logout_time(user, session-id)
4211 # Given a username, returns the idle time before he will be logged out
4212 sub get_logout_time
4213 {
4214 local ($user, $sid) = @_;
4215 if (!defined($logout_time_cache{$user,$sid})) {
4216         local $time;
4217         foreach my $l (@logouttimes) {
4218                 if ($l->[0] =~ /^\@(.*)$/) {
4219                         # Check group membership
4220                         local @uinfo = getpwnam($user);
4221                         if (@uinfo && &is_group_member(\@uinfo, $1)) {
4222                                 $time = $l->[1];
4223                                 }
4224                         }
4225                 elsif ($l->[0] =~ /^\//) {
4226                         # Check file contents
4227                         open(FILE, $l->[0]);
4228                         while(<FILE>) {
4229                                 s/\r|\n//g;
4230                                 s/^\s*#.*$//;
4231                                 if ($user eq $_) {
4232                                         $time = $l->[1];
4233                                         last;
4234                                         }
4235                                 }
4236                         close(FILE);
4237                         }
4238                 elsif (!$l->[0]) {
4239                         # Always match
4240                         $time = $l->[1];
4241                         }
4242                 else {
4243                         # Check username
4244                         if ($l->[0] eq $user) {
4245                                 $time = $l->[1];
4246                                 }
4247                         }
4248                 last if (defined($time));
4249                 }
4250         $logout_time_cache{$user,$sid} = $time;
4251         }
4252 return $logout_time_cache{$user,$sid};
4253 }
4254
4255 # password_crypt(password, salt)
4256 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4257 # of a password. Otherwise, do Unix crypt.
4258 sub password_crypt
4259 {
4260 local ($pass, $salt) = @_;
4261 if ($salt =~ /^\$1\$/ && $use_md5) {
4262         return &encrypt_md5($pass, $salt);
4263         }
4264 else {
4265         return &unix_crypt($pass, $salt);
4266         }
4267 }
4268
4269 # unix_crypt(password, salt)
4270 # Performs standard Unix hashing for a password
4271 sub unix_crypt
4272 {
4273 local ($pass, $salt) = @_;
4274 if ($use_perl_crypt) {
4275         return Crypt::UnixCrypt::crypt($pass, $salt);
4276         }
4277 else {
4278         return crypt($pass, $salt);
4279         }
4280 }
4281
4282 # handle_dav_request(davpath)
4283 # Pass a request on to the Net::DAV::Server module
4284 sub handle_dav_request
4285 {
4286 local ($path) = @_;
4287 eval "use Filesys::Virtual::Plain";
4288 eval "use Net::DAV::Server";
4289 eval "use HTTP::Request";
4290 eval "use HTTP::Headers";
4291
4292 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4293         delete $Net::DAV::Server::implemented{lock};
4294         delete $Net::DAV::Server::implemented{unlock};
4295         }
4296
4297 # Read in request data
4298 if (!$posted_data) {
4299         local $clen = $header{"content-length"};
4300         while(length($posted_data) < $clen) {
4301                 $buf = &read_data($clen - length($posted_data));
4302                 if (!length($buf)) {
4303                         &http_error(500, "Failed to read POST request");
4304                         }
4305                 $posted_data .= $buf;
4306                 }
4307         }
4308
4309 # For subsequent logging
4310 open(MINISERVLOG, ">>$config{'logfile'}");
4311
4312 # Switch to user
4313 local $root;
4314 local @u = getpwnam($authuser);
4315 if ($config{'dav_remoteuser'} && !$< && $validated) {
4316         if (@u) {
4317                 if ($u[2] != 0) {
4318                         $( = $u[3]; $) = "$u[3] $u[3]";
4319                         ($>, $<) = ($u[2], $u[2]);
4320                         }
4321                 if ($config{'dav_root'} eq '*') {
4322                         $root = $u[7];
4323                         }
4324                 }
4325         else {
4326                 &http_error(500, "Unix user $authuser does not exist");
4327                 return 0;
4328                 }
4329         }
4330 $root ||= $config{'dav_root'};
4331 $root ||= "/";
4332
4333 # Check if this user can use DAV
4334 if (@davusers) {
4335         &users_match(\@u, @davusers) ||
4336                 &http_error(500, "You are not allowed to access DAV");
4337         }
4338
4339 # Create DAV server
4340 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4341 my $webdav = Net::DAV::Server->new();
4342 $webdav->filesys($filesys);
4343
4344 # Make up a request object, and feed to DAV
4345 local $ho = HTTP::Headers->new;
4346 foreach my $h (keys %header) {
4347         next if (lc($h) eq "connection");
4348         $ho->header($h => $header{$h});
4349         }
4350 if ($path ne "/") {
4351         $request_uri =~ s/^\Q$path\E//;
4352         $request_uri = "/" if ($request_uri eq "");
4353         }
4354 my $request = HTTP::Request->new($method, $request_uri, $ho,
4355                                  $posted_data);
4356 if ($config{'dav_debug'}) {
4357         print STDERR "DAV request :\n";
4358         print STDERR "---------------------------------------------\n";
4359         print STDERR $request->as_string();
4360         print STDERR "---------------------------------------------\n";
4361         }
4362 my $response = $webdav->run($request);
4363
4364 # Send back the reply
4365 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4366 local $content = $response->content();
4367 if ($path ne "/") {
4368         $content =~ s|href>/(.+)<|href>$path/$1<|g;
4369         $content =~ s|href>/<|href>$path<|g;
4370         }
4371 foreach my $h ($response->header_field_names) {
4372         next if (lc($h) eq "connection" || lc($h) eq "content-length");
4373         &write_data("$h: ",$response->header($h),"\r\n");
4374         }
4375 &write_data("Content-length: ",length($content),"\r\n");
4376 local $rv = &write_keep_alive(0);
4377 &write_data("\r\n");
4378 &write_data($content);
4379
4380 if ($config{'dav_debug'}) {
4381         print STDERR "DAV reply :\n";
4382         print STDERR "---------------------------------------------\n";
4383         print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4384         foreach my $h ($response->header_field_names) {
4385                 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4386                 print STDERR "$h: ",$response->header($h),"\r\n";
4387                 }
4388         print STDERR "Content-length: ",length($content),"\r\n";
4389         print STDERR "\r\n";
4390         print STDERR $content;
4391         print STDERR "---------------------------------------------\n";
4392         }
4393
4394 # Log it
4395 &log_request($acpthost, $authuser, $reqline, $response->code(), 
4396              length($response->content()));
4397 }
4398
4399 # get_system_hostname()
4400 # Returns the hostname of this system, for reporting to listeners
4401 sub get_system_hostname
4402 {
4403 # On Windows, try computername environment variable
4404 return $ENV{'computername'} if ($ENV{'computername'});
4405 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4406
4407 # If a specific command is set, use it first
4408 if ($config{'hostname_command'}) {
4409         local $out = `($config{'hostname_command'}) 2>&1`;
4410         if (!$?) {
4411                 $out =~ s/\r|\n//g;
4412                 return $out;
4413                 }
4414         }
4415
4416 # First try the hostname command
4417 local $out = `hostname 2>&1`;
4418 if (!$? && $out =~ /\S/) {
4419         $out =~ s/\r|\n//g;
4420         return $out;
4421         }
4422
4423 # Try the Sys::Hostname module
4424 eval "use Sys::Hostname";
4425 if (!$@) {
4426         local $rv = eval "hostname()";
4427         if (!$@ && $rv) {
4428                 return $rv;
4429                 }
4430         }
4431
4432 # Must use net name on Windows
4433 local $out = `net name 2>&1`;
4434 if ($out =~ /\-+\r?\n(\S+)/) {
4435         return $1;
4436         }
4437
4438 return undef;
4439 }
4440
4441 # indexof(string, array)
4442 # Returns the index of some value in an array, or -1
4443 sub indexof {
4444   local($i);
4445   for($i=1; $i <= $#_; $i++) {
4446     if ($_[$i] eq $_[0]) { return $i - 1; }
4447   }
4448   return -1;
4449 }
4450
4451
4452 # has_command(command)
4453 # Returns the full path if some command is in the path, undef if not
4454 sub has_command
4455 {
4456 local($d);
4457 if (!$_[0]) { return undef; }
4458 if (exists($has_command_cache{$_[0]})) {
4459         return $has_command_cache{$_[0]};
4460         }
4461 local $rv = undef;
4462 if ($_[0] =~ /^\//) {
4463         $rv = -x $_[0] ? $_[0] : undef;
4464         }
4465 else {
4466         local $sp = $on_windows ? ';' : ':';
4467         foreach $d (split($sp, $ENV{PATH})) {
4468                 if (-x "$d/$_[0]") {
4469                         $rv = "$d/$_[0]";
4470                         last;
4471                         }
4472                 if ($on_windows) {
4473                         foreach my $sfx (".exe", ".com", ".bat") {
4474                                 if (-r "$d/$_[0]".$sfx) {
4475                                         $rv = "$d/$_[0]".$sfx;
4476                                         last;
4477                                         }
4478                                 }
4479                         }
4480                 }
4481         }
4482 $has_command_cache{$_[0]} = $rv;
4483 return $rv;
4484 }
4485
4486 # check_sudo_permissions(user, pass)
4487 # Returns 1 if some user can run any command via sudo
4488 sub check_sudo_permissions
4489 {
4490 local ($user, $pass) = @_;
4491
4492 # First try the pipes
4493 if ($PASSINw) {
4494         print DEBUG "check_sudo_permissions: querying cache for $user\n";
4495         print $PASSINw "readsudo $user\n";
4496         local $can = <$PASSOUTr>;
4497         chop($can);
4498         print DEBUG "check_sudo_permissions: cache said $can\n";
4499         if ($can =~ /^\d+$/ && $can != 2) {
4500                 return int($can);
4501                 }
4502         }
4503
4504 local $ptyfh = new IO::Pty;
4505 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4506 if (!$ptyfh) {
4507         print STDERR "Failed to create new PTY with IO::Pty\n";
4508         return 0;
4509         }
4510 local @uinfo = getpwnam($user);
4511 if (!@uinfo) {
4512         print STDERR "Unix user $user does not exist for sudo\n";
4513         return 0;
4514         }
4515
4516 # Execute sudo in a sub-process, via a pty
4517 local $ttyfh = $ptyfh->slave();
4518 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4519 local $tty = $ptyfh->ttyname();
4520 print DEBUG "check_sudo_permissions: tty=$tty\n";
4521 chown($uinfo[2], $uinfo[3], $tty);
4522 pipe(SUDOr, SUDOw);
4523 print DEBUG "check_sudo_permissions: about to fork..\n";
4524 local $pid = fork();
4525 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4526 if ($pid < 0) {
4527         print STDERR "fork for sudo failed : $!\n";
4528         return 0;
4529         }
4530 if (!$pid) {
4531         setsid();
4532         $ptyfh->make_slave_controlling_terminal();
4533         close(STDIN); close(STDOUT); close(STDERR);
4534         untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4535         close($PASSINw); close($PASSOUTr);
4536         $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4537         ($>, $<) = ($uinfo[2], $uinfo[2]);
4538
4539         close(SUDOw);
4540         close(SOCK);
4541         close(MAIN);
4542         open(STDIN, "<&SUDOr");
4543         open(STDOUT, ">$tty");
4544         open(STDERR, ">&STDOUT");
4545         close($ptyfh);
4546         exec("sudo -l -S");
4547         print "Exec failed : $!\n";
4548         exit 1;
4549         }
4550 print DEBUG "check_sudo_permissions: pid=$pid\n";
4551 close(SUDOr);
4552 $ptyfh->close_slave();
4553
4554 # Send password, and get back response
4555 local $oldfh = select(SUDOw);
4556 $| = 1;
4557 select($oldfh);
4558 print DEBUG "check_sudo_permissions: about to send pass\n";
4559 local $SIG{'PIPE'} = 'ignore';  # Sometimes sudo doesn't ask for a password
4560 print SUDOw $pass,"\n";
4561 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4562 close(SUDOw);
4563 local $out;
4564 while(<$ptyfh>) {
4565         print DEBUG "check_sudo_permissions: got $_";
4566         $out .= $_;
4567         }
4568 close($ptyfh);
4569 kill('KILL', $pid);
4570 waitpid($pid, 0);
4571 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4572
4573 # Update cache
4574 if ($PASSINw) {
4575         print $PASSINw "writesudo $user $ok\n";
4576         }
4577
4578 return $ok;
4579 }
4580
4581 # is_mobile_useragent(agent)
4582 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4583 # such as a treo.
4584 sub is_mobile_useragent
4585 {
4586 local ($agent) = @_;
4587 local @prefixes = ( 
4588     "UP.Link",    # Openwave
4589     "Nokia",      # All Nokias start with Nokia
4590     "MOT-",       # All Motorola phones start with MOT-
4591     "SAMSUNG",    # Samsung browsers
4592     "Samsung",    # Samsung browsers
4593     "SEC-",       # Samsung browsers
4594     "AU-MIC",     # Samsung browsers
4595     "AUDIOVOX",   # Audiovox
4596     "BlackBerry", # BlackBerry
4597     "hiptop",     # Danger hiptop Sidekick
4598     "SonyEricsson", # Sony Ericsson
4599     "Ericsson",     # Old Ericsson browsers , mostly WAP
4600     "Mitsu/1.1.A",  # Mitsubishi phones
4601     "Panasonic WAP", # Panasonic old WAP phones
4602     "DoCoMo",     # DoCoMo phones
4603     "Lynx",       # Lynx text-mode linux browser
4604     "Links",      # Another text-mode linux browser
4605     );
4606 local @substrings = (
4607     "UP.Browser",         # Openwave
4608     "MobilePhone",        # NetFront
4609     "AU-MIC-A700",        # Samsung A700 Obigo browsers
4610     "Danger hiptop",      # Danger Sidekick hiptop
4611     "Windows CE",         # Windows CE Pocket PC
4612     "IEMobile",           # Windows mobile browser
4613     "Blazer",             # Palm Treo Blazer
4614     "BlackBerry",         # BlackBerries can emulate other browsers, but
4615                           # they still keep this string in the UserAgent
4616     "SymbianOS",          # New Series60 browser has safari in it and
4617                           # SymbianOS is the only distinguishing string
4618     "iPhone",             # Apple iPhone KHTML browser
4619     "iPod",               # iPod touch browser
4620     "MobileSafari",       # HTTP client in iPhone
4621     "Android",            # gPhone
4622     "Opera Mini",         # Opera Mini
4623     "HTC_P3700",          # HTC mobile device
4624     "Pre/",               # Palm Pre
4625     "webOS/",             # Palm WebOS
4626     "Nintendo DS",        # DSi / DSi-XL
4627     );
4628 foreach my $p (@prefixes) {
4629         return 1 if ($agent =~ /^\Q$p\E/);
4630         }
4631 foreach my $s (@substrings, @mobile_agents) {
4632         return 1 if ($agent =~ /\Q$s\E/);
4633         }
4634 return 0;
4635 }
4636
4637 # write_blocked_file()
4638 # Writes out a text file of blocked hosts and users
4639 sub write_blocked_file
4640 {
4641 open(BLOCKED, ">$config{'blockedfile'}");
4642 foreach my $d (grep { $hostfail{$_} } @deny) {
4643         print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4644         }
4645 foreach my $d (grep { $userfail{$_} } @denyusers) {
4646         print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4647         }
4648 close(BLOCKED);
4649 chmod(0700, $config{'blockedfile'});
4650 }
4651
4652 sub write_pid_file
4653 {
4654 open(PIDFILE, ">$config{'pidfile'}");
4655 printf PIDFILE "%d\n", getpid();
4656 close(PIDFILE);
4657 $miniserv_main_pid = getpid();
4658 }
4659
4660 # lock_user_password(user)
4661 # Updates a user's password file entry to lock it, both in memory and on disk.
4662 # Returns 1 if done, -1 if no such user, 0 if already locked
4663 sub lock_user_password
4664 {
4665 local ($user) = @_;
4666 if ($users{$user}) {
4667         if ($users{$user} !~ /^\!/) {
4668                 # Lock the password
4669                 $users{$user} = "!".$users{$user};
4670                 open(USERS, $config{'userfile'});
4671                 local @ufile = <USERS>;
4672                 close(USERS);
4673                 foreach my $u (@ufile) {
4674                         local @uinfo = split(/:/, $u);
4675                         if ($uinfo[0] eq $user) {
4676                                 $uinfo[1] = $users{$user};
4677                                 }
4678                         $u = join(":", @uinfo);
4679                         }
4680                 open(USERS, ">$config{'userfile'}");
4681                 print USERS @ufile;
4682                 close(USERS);
4683                 return 1;
4684                 }
4685         return 0;
4686         }
4687 return -1;
4688 }
4689
4690 # hash_session_id(sid)
4691 # Returns an MD5 or Unix-crypted session ID
4692 sub hash_session_id
4693 {
4694 local ($sid) = @_;
4695 if (!$hash_session_id_cache{$sid}) {
4696         if ($use_md5) {
4697                 # Take MD5 hash
4698                 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4699                 }
4700         else {
4701                 # Unix crypt
4702                 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4703                 }
4704         }
4705 return $hash_session_id_cache{$sid};
4706 }
4707
4708 # encrypt_md5(string, [salt])
4709 # Returns a string encrypted in MD5 format
4710 sub encrypt_md5
4711 {
4712 local ($passwd, $salt) = @_;
4713 local $magic = '$1$';
4714 if ($salt =~ /^\$1\$([^\$]+)/) {
4715         # Extract actual salt from already encrypted password
4716         $salt = $1;
4717         }
4718
4719 # Add the password
4720 local $ctx = eval "new $use_md5";
4721 $ctx->add($passwd);
4722 if ($salt) {
4723         $ctx->add($magic);
4724         $ctx->add($salt);
4725         }
4726
4727 # Add some more stuff from the hash of the password and salt
4728 local $ctx1 = eval "new $use_md5";
4729 $ctx1->add($passwd);
4730 if ($salt) {
4731         $ctx1->add($salt);
4732         }
4733 $ctx1->add($passwd);
4734 local $final = $ctx1->digest();
4735 for($pl=length($passwd); $pl>0; $pl-=16) {
4736         $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4737         }
4738
4739 # This piece of code seems rather pointless, but it's in the C code that
4740 # does MD5 in PAM so it has to go in!
4741 local $j = 0;
4742 local ($i, $l);
4743 for($i=length($passwd); $i; $i >>= 1) {
4744         if ($i & 1) {
4745                 $ctx->add("\0");
4746                 }
4747         else {
4748                 $ctx->add(substr($passwd, $j, 1));
4749                 }
4750         }
4751 $final = $ctx->digest();
4752
4753 if ($salt) {
4754         # This loop exists only to waste time
4755         for($i=0; $i<1000; $i++) {
4756                 $ctx1 = eval "new $use_md5";
4757                 $ctx1->add($i & 1 ? $passwd : $final);
4758                 $ctx1->add($salt) if ($i % 3);
4759                 $ctx1->add($passwd) if ($i % 7);
4760                 $ctx1->add($i & 1 ? $final : $passwd);
4761                 $final = $ctx1->digest();
4762                 }
4763         }
4764
4765 # Convert the 16-byte final string into a readable form
4766 local $rv;
4767 local @final = map { ord($_) } split(//, $final);
4768 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4769 $rv .= &to64($l, 4);
4770 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4771 $rv .= &to64($l, 4);
4772 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4773 $rv .= &to64($l, 4);
4774 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4775 $rv .= &to64($l, 4);
4776 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4777 $rv .= &to64($l, 4);
4778 $l = $final[11];
4779 $rv .= &to64($l, 2);
4780
4781 # Add salt if needed
4782 if ($salt) {
4783         return $magic.$salt.'$'.$rv;
4784         }
4785 else {
4786         return $rv;
4787         }
4788 }
4789
4790 sub to64
4791 {
4792 local ($v, $n) = @_;
4793 local $r;
4794 while(--$n >= 0) {
4795         $r .= $itoa64[$v & 0x3f];
4796         $v >>= 6;
4797         }
4798 return $r;
4799 }
4800
4801 # read_file(file, &assoc, [&order], [lowercase])
4802 # Fill an associative array with name=value pairs from a file
4803 sub read_file
4804 {
4805 open(ARFILE, $_[0]) || return 0;
4806 while(<ARFILE>) {
4807         s/\r|\n//g;
4808         if (!/^#/ && /^([^=]*)=(.*)$/) {
4809                 $_[1]->{$_[3] ? lc($1) : $1} = $2;
4810                 push(@{$_[2]}, $1) if ($_[2]);
4811                 }
4812         }
4813 close(ARFILE);
4814 return 1;
4815 }
4816  
4817 # write_file(file, array)
4818 # Write out the contents of an associative array as name=value lines
4819 sub write_file
4820 {
4821 local(%old, @order);
4822 &read_file($_[0], \%old, \@order);
4823 open(ARFILE, ">$_[0]");
4824 foreach $k (@order) {
4825         print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
4826         }
4827 foreach $k (keys %{$_[1]}) {
4828         print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
4829         }
4830 close(ARFILE);
4831 }
4832
4833 # execute_ready_webmin_crons()
4834 # Find and run any cron jobs that are due, based on their last run time and
4835 # execution interval
4836 sub execute_ready_webmin_crons
4837 {
4838 my $now = time();
4839 my $changed = 0;
4840 foreach my $cron (@webmincrons) {
4841         my $run = 0;
4842         if (!$webmincron_last{$cron->{'id'}}) {
4843                 # If not ever run before, don't run right away
4844                 $webmincron_last{$cron->{'id'}} = $now;
4845                 $changed = 1;
4846                 }
4847         elsif ($cron->{'interval'} &&
4848                $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
4849                 # Older than interval .. time to run
4850                 $run = 1;
4851                 }
4852         elsif ($cron->{'mins'}) {
4853                 # Check if current time matches spec, and we haven't run in the
4854                 # last minute
4855                 my @tm = localtime($now);
4856                 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
4857                     &matches_cron($cron->{'hours'}, $tm[2]) &&
4858                     &matches_cron($cron->{'days'}, $tm[3]) &&
4859                     &matches_cron($cron->{'months'}, $tm[4]+1) &&
4860                     &matches_cron($cron->{'weekdays'}, $tm[6]) &&
4861                     $now - $webmincron_last{$cron->{'id'}} > 60) {
4862                         $run = 1;
4863                         }
4864                 }
4865
4866         if ($run) {
4867                 print DEBUG "Running cron id=$cron->{'id'} ".
4868                             "module=$cron->{'module'} func=$cron->{'func'}\n";
4869                 $webmincron_last{$cron->{'id'}} = $now;
4870                 $changed = 1;
4871                 my $pid = fork();
4872                 if (!$pid) {
4873                         # Run via a wrapper command, which we run like a CGI
4874
4875                         # Setup CGI-like environment
4876                         $envtz = $ENV{"TZ"};
4877                         $envuser = $ENV{"USER"};
4878                         $envpath = $ENV{"PATH"};
4879                         $envlang = $ENV{"LANG"};
4880                         $envroot = $ENV{"SystemRoot"};
4881                         $envperllib = $ENV{'PERLLIB'};
4882                         foreach my $k (keys %ENV) {
4883                                 delete($ENV{$k});
4884                                 }
4885                         $ENV{"PATH"} = $envpath if ($envpath);
4886                         $ENV{"TZ"} = $envtz if ($envtz);
4887                         $ENV{"USER"} = $envuser if ($envuser);
4888                         $ENV{"OLD_LANG"} = $envlang if ($envlang);
4889                         $ENV{"SystemRoot"} = $envroot if ($envroot);
4890                         $ENV{'PERLLIB'} = $envperllib if ($envperllib);
4891                         $ENV{"HOME"} = $user_homedir;
4892                         $ENV{"SERVER_SOFTWARE"} = $config{"server"};
4893                         $ENV{"SERVER_ADMIN"} = $config{"email"};
4894                         $root0 = $roots[0];
4895                         $ENV{"SERVER_ROOT"} = $root0;
4896                         $ENV{"SERVER_REALROOT"} = $root0;
4897                         $ENV{"SERVER_PORT"} = $config{'port'};
4898                         $ENV{"WEBMIN_CRON"} = 1;
4899                         $ENV{"DOCUMENT_ROOT"} = $root0;
4900                         $ENV{"DOCUMENT_REALROOT"} = $root0;
4901                         $ENV{"MINISERV_CONFIG"} = $config_file;
4902                         $ENV{"HTTPS"} = "ON" if ($use_ssl);
4903                         $ENV{"MINISERV_PID"} = $miniserv_main_pid;
4904                         $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
4905                         if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
4906                                 $ENV{"SCRIPT_NAME"} = $1;
4907                                 }
4908                         $config{'webmincron_wrapper'} =~ /^(.*)\//;
4909                         $ENV{"PWD"} = $1;
4910                         foreach $k (keys %config) {
4911                                 if ($k =~ /^env_(\S+)$/) {
4912                                         $ENV{$1} = $config{$k};
4913                                         }
4914                                 }
4915                         chdir($ENV{"PWD"});
4916                         $SIG{'CHLD'} = 'DEFAULT';
4917                         eval {
4918                                 # Have SOCK closed if the perl exec's something
4919                                 use Fcntl;
4920                                 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
4921                                 };
4922
4923                         # Run the wrapper script by evaling it
4924                         $pkg = "webmincron";
4925                         $0 = $config{'webmincron_wrapper'};
4926                         @ARGV = ( $cron );
4927                         $main_process_id = $$;
4928                         eval "
4929                                 \%pkg::ENV = \%ENV;
4930                                 package $pkg;
4931                                 do \$miniserv::config{'webmincron_wrapper'};
4932                                 die \$@ if (\$@);
4933                                 ";
4934                         if ($@) {
4935                                 print STDERR "Perl cron failure : $@\n";
4936                                 }
4937
4938                         exit(0);
4939                         }
4940                 push(@childpids, $pid);
4941                 }
4942         }
4943 if ($changed) {
4944         # Write out file containing last run times
4945         &write_file($config{'webmincron_last'}, \%webmincron_last);
4946         }
4947 }
4948
4949 # matches_cron(cron-spec, time)
4950 # Checks if some minute or hour matches some cron spec, which can be * or a list
4951 # of numbers.
4952 sub matches_cron
4953 {
4954 my ($spec, $tm) = @_;
4955 if ($spec eq '*') {
4956         return 1;
4957         }
4958 else {
4959         foreach my $s (split(/,/, $spec)) {
4960                 if ($s == $tm ||
4961                     $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
4962                         return 1;
4963                         }
4964                 }
4965         return 0;
4966         }
4967 }
4968
4969 # read_webmin_crons()
4970 # Read all scheduled webmin cron functions and store them in the @webmincrons
4971 # global list
4972 sub read_webmin_crons
4973 {
4974 @webmincrons = ( );
4975 opendir(CRONS, $config{'webmincron_dir'});
4976 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
4977 foreach my $f (readdir(CRONS)) {
4978         if ($f =~ /^(\d+)\.cron$/) {
4979                 my %cron;
4980                 &read_file("$config{'webmincron_dir'}/$f", \%cron);
4981                 $cron{'id'} = $1;
4982                 my $broken = 0;
4983                 foreach my $n ('module', 'func') {
4984                         if (!$cron{$n}) {
4985                                 print STDERR "Cron $1 missing $n\n";
4986                                 $broken = 1;
4987                                 }
4988                         }
4989                 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
4990                         print STDERR "Cron $1 missing any time spec\n";
4991                         $broken = 1;
4992                         }
4993                 if ($cron{'special'} eq 'hourly') {
4994                         # Run every hour on the hour
4995                         $cron{'mins'} = 0;
4996                         $cron{'hours'} = '*';
4997                         $cron{'days'} = '*';
4998                         $cron{'months'} = '*';
4999                         $cron{'weekdays'} = '*';
5000                         }
5001                 elsif ($cron{'special'} eq 'daily') {
5002                         # Run every day at midnight
5003                         $cron{'mins'} = 0;
5004                         $cron{'hours'} = '0';
5005                         $cron{'days'} = '*';
5006                         $cron{'months'} = '*';
5007                         $cron{'weekdays'} = '*';
5008                         }
5009                 elsif ($cron{'special'} eq 'monthly') {
5010                         # Run every month on the 1st
5011                         $cron{'mins'} = 0;
5012                         $cron{'hours'} = '0';
5013                         $cron{'days'} = '1';
5014                         $cron{'months'} = '*';
5015                         $cron{'weekdays'} = '*';
5016                         }
5017                 elsif ($cron{'special'} eq 'weekly') {
5018                         # Run every month on the 1st
5019                         $cron{'mins'} = 0;
5020                         $cron{'hours'} = '0';
5021                         $cron{'days'} = '*';
5022                         $cron{'months'} = '*';
5023                         $cron{'weekdays'} = '0';
5024                         }
5025                 elsif ($cron{'special'} eq 'yearly' ||
5026                        $cron{'special'} eq 'annually') {
5027                         # Run every year on 1st january
5028                         $cron{'mins'} = 0;
5029                         $cron{'hours'} = '0';
5030                         $cron{'days'} = '1';
5031                         $cron{'months'} = '1';
5032                         $cron{'weekdays'} = '*';
5033                         }
5034                 elsif ($cron{'special'}) {
5035                         print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5036                         $broken = 1;
5037                         }
5038                 if ($cron{'special'}) {
5039                         delete($cron{'special'});
5040                         }
5041                 if (!$broken) {
5042                         print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5043                         push(@webmincrons, \%cron);
5044                         }
5045                 }
5046         }
5047 }