Query user DB in miniserv and read_acl
[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 ($config{'userfile'}) {
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                 my $luser = &get_user_details($localauth_user);
1653                 if ($luser) {
1654                         # Local user exists in webmin users file
1655                         $validated = 1;
1656                         $authuser = $localauth_user;
1657                         }
1658                 else {
1659                         # Check if local user is allowed by unixauth
1660                         local @can = &can_user_login($localauth_user,
1661                                                      undef, $host);
1662                         if ($can[0]) {
1663                                 $validated = 2;
1664                                 $authuser = $localauth_user;
1665                                 }
1666                         else {
1667                                 $localauth_user = undef;
1668                                 }
1669                         }
1670                 }
1671
1672         if (!$validated) {
1673                 # Check if this path allows anonymous access
1674                 local $a;
1675                 foreach $a (keys %anonymous) {
1676                         if (substr($simple, 0, length($a)) eq $a) {
1677                                 # It does! Auth as the user, if IP access
1678                                 # control allows him.
1679                                 if (&check_user_ip($anonymous{$a}) &&
1680                                     &check_user_time($anonymous{$a})) {
1681                                         $validated = 3;
1682                                         $baseauthuser = $authuser =
1683                                                 $anonymous{$a};
1684                                         }
1685                                 }
1686                         }
1687                 }
1688
1689         if (!$validated) {
1690                 # Check if this path allows unauthenticated access
1691                 local ($u, $unauth);
1692                 foreach $u (@unauth) {
1693                         $unauth++ if ($simple =~ /$u/);
1694                         }
1695                 if (!$bogus && $unauth) {
1696                         # Unauthenticated directory or file request - approve it
1697                         $validated = 4;
1698                         $baseauthuser = $authuser = undef;
1699                         }
1700                 }
1701
1702         if (!$validated) {
1703                 if ($blocked == 0) {
1704                         # No password given.. ask
1705                         if ($config{'pam_conv'} && $use_pam) {
1706                                 # Force CGI for PAM question, starting with
1707                                 # the username which is always needed
1708                                 $validated = 1;
1709                                 $method = "GET";
1710                                 $querystring .= "&initial=1&question=".
1711                                                 &urlize("Username");
1712                                 $querystring .= "&failed=$failed_user" if ($failed_user);
1713                                 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1714                                 $queryargs = "";
1715                                 $page = $config{'pam_login'};
1716                                 $miniserv_internal = 1;
1717                                 $logged_code = 401;
1718                                 }
1719                         elsif ($config{'session'}) {
1720                                 # Force CGI for session login
1721                                 $validated = 1;
1722                                 if ($logout) {
1723                                         $querystring .= "&logout=1&page=/";
1724                                         }
1725                                 else {
1726                                         # Re-direct to current module only
1727                                         local $rpage = $request_uri;
1728                                         if (!$config{'loginkeeppage'}) {
1729                                                 $rpage =~ s/\?.*$//;
1730                                                 $rpage =~ s/[^\/]+$//
1731                                                 }
1732                                         $querystring = "page=".&urlize($rpage);
1733                                         }
1734                                 $method = "GET";
1735                                 $querystring .= "&failed=$failed_user" if ($failed_user);
1736                                 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1737                                 $queryargs = "";
1738                                 $page = $config{'session_login'};
1739                                 $miniserv_internal = 1;
1740                                 $logged_code = 401;
1741                                 }
1742                         else {
1743                                 # Ask for login with HTTP authentication
1744                                 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1745                                 &write_data("Date: $datestr\r\n");
1746                                 &write_data("Server: $config{'server'}\r\n");
1747                                 &write_data("WWW-authenticate: Basic ".
1748                                            "realm=\"$config{'realm'}\"\r\n");
1749                                 &write_keep_alive(0);
1750                                 &write_data("Content-type: text/html\r\n");
1751                                 &write_data("\r\n");
1752                                 &reset_byte_count();
1753                                 &write_data("<html>\n");
1754                                 &write_data("<head><title>Unauthorized</title></head>\n");
1755                                 &write_data("<body><h1>Unauthorized</h1>\n");
1756                                 &write_data("A password is required to access this\n");
1757                                 &write_data("web server. Please try again. <p>\n");
1758                                 &write_data("</body></html>\n");
1759                                 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1760                                 return 0;
1761                                 }
1762                         }
1763                 elsif ($blocked == 1) {
1764                         # when the host has been blocked, give it an error
1765                         &http_error(403, "Access denied for $acptip. The host ".
1766                                          "has been blocked because of too ".
1767                                          "many authentication failures.");
1768                         }
1769                 elsif ($blocked == 2) {
1770                         # when the user has been blocked, give it an error
1771                         &http_error(403, "Access denied. The user ".
1772                                          "has been blocked because of too ".
1773                                          "many authentication failures.");
1774                         }
1775                 }
1776         else {
1777                 # Get the real Webmin username
1778                 local @can = &can_user_login($authuser, undef, $host);
1779                 $baseauthuser = $can[3] || $authuser;
1780
1781                 if ($config{'remoteuser'} && !$< && $validated) {
1782                         # Switch to the UID of the remote user (if he exists)
1783                         local @u = getpwnam($authuser);
1784                         if (@u && $< != $u[2]) {
1785                                 $( = $u[3]; $) = "$u[3] $u[3]";
1786                                 ($>, $<) = ($u[2], $u[2]);
1787                                 }
1788                         else {
1789                                 &http_error(500, "Unix user $authuser does not exist");
1790                                 return 0;
1791                                 }
1792                         }
1793                 }
1794
1795         # Check per-user IP access control
1796         if (!&check_user_ip($baseauthuser)) {
1797                 &http_error(403, "Access denied for $acptip for $baseauthuser");
1798                 return 0;
1799                 }
1800
1801         # Check per-user allowed times
1802         if (!&check_user_time($baseauthuser)) {
1803                 &http_error(403, "Access denied at the current time");
1804                 return 0;
1805                 }
1806         }
1807
1808 # Validate the path, and convert to canonical form
1809 rerun:
1810 $simple = &simplify_path($page, $bogus);
1811 print DEBUG "handle_request: page=$page simple=$simple\n";
1812 if ($bogus) {
1813         &http_error(400, "Invalid path");
1814         }
1815
1816 # Check for a DAV request
1817 if ($davpath) {
1818         return &handle_dav_request($davpath);
1819         }
1820
1821 # Work out the active theme(s)
1822 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1823                         $config{'mobile_preroot'} :
1824                  $authuser && defined($config{'preroot_'.$authuser}) ?
1825                         $config{'preroot_'.$authuser} :
1826                  $authuser && $baseauthuser &&
1827                      defined($config{'preroot_'.$baseauthuser}) ?
1828                         $config{'preroot_'.$baseauthuser} :
1829                         $config{'preroot'};
1830 local @preroots = reverse(split(/\s+/, $preroots));
1831
1832 # Canonicalize the directories
1833 foreach my $preroot (@preroots) {
1834         # Always under the current webmin root
1835         $preroot =~ s/^.*\///g;
1836         $preroot = $roots[0].'/'.$preroot;
1837         }
1838
1839 # Look in the theme root directories first
1840 local ($full, @stfull);
1841 $foundroot = undef;
1842 foreach my $preroot (@preroots) {
1843         $is_directory = 1;
1844         $sofar = "";
1845         $full = $preroot.$sofar;
1846         $scriptname = $simple;
1847         foreach $b (split(/\//, $simple)) {
1848                 if ($b ne "") { $sofar .= "/$b"; }
1849                 $full = $preroot.$sofar;
1850                 @stfull = stat($full);
1851                 if (!@stfull) { undef($full); last; }
1852
1853                 # Check if this is a directory
1854                 if (-d _) {
1855                         # It is.. go on parsing
1856                         $is_directory = 1;
1857                         next;
1858                         }
1859                 else {
1860                         $is_directory = 0;
1861                         }
1862
1863                 # Check if this is a CGI program
1864                 if (&get_type($full) eq "internal/cgi") {
1865                         $pathinfo = substr($simple, length($sofar));
1866                         $pathinfo .= "/" if ($page =~ /\/$/);
1867                         $scriptname = $sofar;
1868                         last;
1869                         }
1870                 }
1871
1872         # Don't stop at a directory unless this is the last theme, which
1873         # is the 'real' one that provides the .cgi scripts
1874         if ($is_directory && $preroot ne $preroots[$#preroots]) {
1875                 next;
1876                 }
1877
1878         if ($full) {
1879                 # Found it!
1880                 if ($sofar eq '') {
1881                         $cgi_pwd = $roots[0];
1882                         }
1883                 elsif ($is_directory) {
1884                         $cgi_pwd = "$roots[0]$sofar";
1885                         }
1886                 else {
1887                         "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1888                         $cgi_pwd = $1;
1889                         }
1890                 $foundroot = $preroot;
1891                 if ($is_directory) {
1892                         # Check for index files in the directory
1893                         local $foundidx;
1894                         foreach $idx (split(/\s+/, $config{"index_docs"})) {
1895                                 $idxfull = "$full/$idx";
1896                                 local @stidxfull = stat($idxfull);
1897                                 if (-r _ && !-d _) {
1898                                         $full = $idxfull;
1899                                         @stfull = @stidxfull;
1900                                         $is_directory = 0;
1901                                         $scriptname .= "/"
1902                                                 if ($scriptname ne "/");
1903                                         $foundidx++;
1904                                         last;
1905                                         }
1906                                 }
1907                         @stfull = stat($full) if (!$foundidx);
1908                         }
1909                 }
1910         last if ($foundroot);
1911         }
1912 print DEBUG "handle_request: initial full=$full\n";
1913
1914 # Look in the real root directories, stopping when we find a file or directory
1915 if (!$full || $is_directory) {
1916         ROOT: foreach $root (@roots) {
1917                 $sofar = "";
1918                 $full = $root.$sofar;
1919                 $scriptname = $simple;
1920                 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1921                         if ($b ne "") { $sofar .= "/$b"; }
1922                         $full = $root.$sofar;
1923                         @stfull = stat($full);
1924                         if (!@stfull) {
1925                                 next ROOT;
1926                                 }
1927
1928                         # Check if this is a directory
1929                         if (-d _) {
1930                                 # It is.. go on parsing
1931                                 next;
1932                                 }
1933
1934                         # Check if this is a CGI program
1935                         if (&get_type($full) eq "internal/cgi") {
1936                                 $pathinfo = substr($simple, length($sofar));
1937                                 $pathinfo .= "/" if ($page =~ /\/$/);
1938                                 $scriptname = $sofar;
1939                                 last;
1940                                 }
1941                         }
1942
1943                 # Run CGI in the same directory as whatever file
1944                 # was requested
1945                 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1946
1947                 if (-e $full) {
1948                         # Found something!
1949                         $realroot = $root;
1950                         $foundroot = $root;
1951                         last;
1952                         }
1953                 }
1954         if (!@stfull) { &http_error(404, "File not found"); }
1955         }
1956 print DEBUG "handle_request: full=$full\n";
1957 @stfull = stat($full) if (!@stfull);
1958
1959 # check filename against denyfile regexp
1960 local $denyfile = $config{'denyfile'};
1961 if ($denyfile && $full =~ /$denyfile/) {
1962         &http_error(403, "Access denied to $page");
1963         return 0;
1964         }
1965
1966 # Reached the end of the path OK.. see what we've got
1967 if (-d _) {
1968         # See if the URL ends with a / as it should
1969         print DEBUG "handle_request: found a directory\n";
1970         if ($page !~ /\/$/) {
1971                 # It doesn't.. redirect
1972                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1973                 $ssl = $use_ssl || $config{'inetd_ssl'};
1974                 $portstr = $port == 80 && !$ssl ? "" :
1975                            $port == 443 && $ssl ? "" : ":$port";
1976                 &write_data("Date: $datestr\r\n");
1977                 &write_data("Server: $config{server}\r\n");
1978                 $prot = $ssl ? "https" : "http";
1979                 &write_data("Location: $prot://$host$portstr$page/\r\n");
1980                 &write_keep_alive(0);
1981                 &write_data("\r\n");
1982                 &log_request($acpthost, $authuser, $reqline, 302, 0);
1983                 return 0;
1984                 }
1985         # A directory.. check for index files
1986         local $foundidx;
1987         foreach $idx (split(/\s+/, $config{"index_docs"})) {
1988                 $idxfull = "$full/$idx";
1989                 @stidxfull = stat($idxfull);
1990                 if (-r _ && !-d _) {
1991                         $cgi_pwd = $full;
1992                         $full = $idxfull;
1993                         @stfull = @stidxfull;
1994                         $scriptname .= "/" if ($scriptname ne "/");
1995                         $foundidx++;
1996                         last;
1997                         }
1998                 }
1999         @stfull = stat($full) if (!$foundidx);
2000         }
2001 if (-d _) {
2002         # This is definately a directory.. list it
2003         print DEBUG "handle_request: listing directory\n";
2004         local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2005                       "Date: $datestr\r\n".
2006                       "Server: $config{server}\r\n".
2007                       "Content-type: text/html\r\n";
2008         &write_data($resp);
2009         &write_keep_alive(0);
2010         &write_data("\r\n");
2011         &reset_byte_count();
2012         &write_data("<h1>Index of $simple</h1>\n");
2013         &write_data("<pre>\n");
2014         &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2015                         "Name", "Last Modified", "Size");
2016         &write_data("<hr>\n");
2017         opendir(DIR, $full);
2018         while($df = readdir(DIR)) {
2019                 if ($df =~ /^\./) { next; }
2020                 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2021                 (@stbuf = stat($fulldf)) || next;
2022                 if (-d _) { $df .= "/"; }
2023                 @tm = localtime($stbuf[9]);
2024                 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2025                                 $tm[3],$tm[4]+1,$tm[5]+1900,
2026                                 $tm[0],$tm[1],$tm[2];
2027                 $len = length($df); $rest = " "x(35-$len);
2028                 &write_data(sprintf 
2029                  "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2030                  $df, $df, $fdate, $stbuf[7]);
2031                 }
2032         closedir(DIR);
2033         &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2034         return 0;
2035         }
2036
2037 # CGI or normal file
2038 local $rv;
2039 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2040         # A CGI program to execute
2041         print DEBUG "handle_request: executing CGI\n";
2042         $envtz = $ENV{"TZ"};
2043         $envuser = $ENV{"USER"};
2044         $envpath = $ENV{"PATH"};
2045         $envlang = $ENV{"LANG"};
2046         $envroot = $ENV{"SystemRoot"};
2047         $envperllib = $ENV{'PERLLIB'};
2048         foreach my $k (keys %ENV) {
2049                 delete($ENV{$k});
2050                 }
2051         $ENV{"PATH"} = $envpath if ($envpath);
2052         $ENV{"TZ"} = $envtz if ($envtz);
2053         $ENV{"USER"} = $envuser if ($envuser);
2054         $ENV{"OLD_LANG"} = $envlang if ($envlang);
2055         $ENV{"SystemRoot"} = $envroot if ($envroot);
2056         $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2057         $ENV{"HOME"} = $user_homedir;
2058         $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2059         $ENV{"SERVER_NAME"} = $host;
2060         $ENV{"SERVER_ADMIN"} = $config{"email"};
2061         $ENV{"SERVER_ROOT"} = $roots[0];
2062         $ENV{"SERVER_REALROOT"} = $realroot;
2063         $ENV{"SERVER_PORT"} = $port;
2064         $ENV{"REMOTE_HOST"} = $acpthost;
2065         $ENV{"REMOTE_ADDR"} = $acptip;
2066         $ENV{"REMOTE_USER"} = $authuser;
2067         $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2068                                         $baseauthuser : undef;
2069         $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2070                                             $config{'pass_password'});
2071         print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2072         print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2073         $ENV{"SSL_USER"} = $peername if ($validated == 2);
2074         $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2075         $ENV{"DOCUMENT_ROOT"} = $roots[0];
2076         $ENV{"DOCUMENT_REALROOT"} = $realroot;
2077         $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2078         $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2079         $ENV{"REQUEST_METHOD"} = $method;
2080         $ENV{"SCRIPT_NAME"} = $scriptname;
2081         $ENV{"SCRIPT_FILENAME"} = $full;
2082         $ENV{"REQUEST_URI"} = $request_uri;
2083         $ENV{"PATH_INFO"} = $pathinfo;
2084         if ($pathinfo) {
2085                 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2086                 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2087                 }
2088         $ENV{"QUERY_STRING"} = $querystring;
2089         $ENV{"MINISERV_CONFIG"} = $config_file;
2090         $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2091         $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2092         $ENV{"SESSION_ID"} = $session_id if ($session_id);
2093         $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2094         $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2095         if (defined($header{"content-length"})) {
2096                 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2097                 }
2098         if (defined($header{"content-type"})) {
2099                 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2100                 }
2101         foreach $h (keys %header) {
2102                 ($hname = $h) =~ tr/a-z/A-Z/;
2103                 $hname =~ s/\-/_/g;
2104                 $ENV{"HTTP_$hname"} = $header{$h};
2105                 }
2106         $ENV{"PWD"} = $cgi_pwd;
2107         foreach $k (keys %config) {
2108                 if ($k =~ /^env_(\S+)$/) {
2109                         $ENV{$1} = $config{$k};
2110                         }
2111                 }
2112         delete($ENV{'HTTP_AUTHORIZATION'});
2113         $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2114         $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2115
2116         # Check if the CGI can be handled internally
2117         open(CGI, $full);
2118         local $first = <CGI>;
2119         close(CGI);
2120         $first =~ s/[#!\r\n]//g;
2121         $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2122         seek(STDERR, 0, 2);
2123         if (!$config{'forkcgis'} &&
2124             ($first eq $perl_path || $first eq $linked_perl_path) &&
2125               $] >= 5.004 ||
2126             $config{'internalcgis'}) {
2127                 # setup environment for eval
2128                 chdir($ENV{"PWD"});
2129                 @ARGV = split(/\s+/, $queryargs);
2130                 $0 = $full;
2131                 if ($posted_data) {
2132                         # Already read the post input
2133                         $postinput = $posted_data;
2134                         }
2135                 $clen = $header{"content-length"};
2136                 $SIG{'CHLD'} = 'DEFAULT';
2137                 eval {
2138                         # Have SOCK closed if the perl exec's something
2139                         use Fcntl;
2140                         fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2141                         };
2142                 #shutdown(SOCK, 0);
2143
2144                 if ($config{'log'}) {
2145                         open(MINISERVLOG, ">>$config{'logfile'}");
2146                         if ($config{'logperms'}) {
2147                                 chmod(oct($config{'logperms'}),
2148                                       $config{'logfile'});
2149                                 }
2150                         else {
2151                                 chmod(0600, $config{'logfile'});
2152                                 }
2153                         }
2154                 $doing_cgi_eval = 1;
2155                 $main_process_id = $$;
2156                 $pkg = "main";
2157                 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2158                         # Eval in package from Webmin module name
2159                         $pkg = $1;
2160                         $pkg =~ s/[^A-Za-z0-9]/_/g;
2161                         }
2162                 eval "
2163                         \%pkg::ENV = \%ENV;
2164                         package $pkg;
2165                         tie(*STDOUT, 'miniserv');
2166                         tie(*STDIN, 'miniserv');
2167                         do \$miniserv::full;
2168                         die \$@ if (\$@);
2169                         ";
2170                 $doing_cgi_eval = 0;
2171                 if ($@) {
2172                         # Error in perl!
2173                         &http_error(500, "Perl execution failed",
2174                                     $config{'noshowstderr'} ? undef : $@);
2175                         }
2176                 elsif (!$doneheaders && !$nph_script) {
2177                         &http_error(500, "Missing Headers");
2178                         }
2179                 $rv = 0;
2180                 }
2181         else {
2182                 $infile = undef;
2183                 if (!$on_windows) {
2184                         # fork the process that actually executes the CGI
2185                         pipe(CGIINr, CGIINw);
2186                         pipe(CGIOUTr, CGIOUTw);
2187                         pipe(CGIERRr, CGIERRw);
2188                         if (!($cgipid = fork())) {
2189                                 @execargs = ( $full, split(/\s+/, $queryargs) );
2190                                 chdir($ENV{"PWD"});
2191                                 close(SOCK);
2192                                 open(STDIN, "<&CGIINr");
2193                                 open(STDOUT, ">&CGIOUTw");
2194                                 open(STDERR, ">&CGIERRw");
2195                                 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2196                                 exec(@execargs) ||
2197                                         die "Failed to exec $full : $!\n";
2198                                 exit(0);
2199                                 }
2200                         close(CGIINr); close(CGIOUTw); close(CGIERRw);
2201                         }
2202                 else {
2203                         # write CGI input to a temp file
2204                         $infile = "$config{'tempbase'}.$$";
2205                         open(CGIINw, ">$infile");
2206                         # NOT binary mode, as CGIs don't read in it!
2207                         }
2208
2209                 # send post data
2210                 if ($posted_data) {
2211                         # already read the posted data
2212                         print CGIINw $posted_data;
2213                         }
2214                 $clen = $header{"content-length"};
2215                 if ($method eq "POST" && $clen_read < $clen) {
2216                         $SIG{'PIPE'} = 'IGNORE';
2217                         $got = $clen_read;
2218                         while($got < $clen) {
2219                                 $buf = &read_data($clen-$got);
2220                                 if (!length($buf)) {
2221                                         kill('TERM', $cgipid);
2222                                         unlink($infile) if ($infile);
2223                                         &http_error(500, "Failed to read ".
2224                                                          "POST request");
2225                                         }
2226                                 $got += length($buf);
2227                                 local ($wrote) = (print CGIINw $buf);
2228                                 last if (!$wrote);
2229                                 }
2230                         # If the CGI terminated early, we still need to read
2231                         # from the browser and throw away
2232                         while($got < $clen) {
2233                                 $buf = &read_data($clen-$got);
2234                                 if (!length($buf)) {
2235                                         kill('TERM', $cgipid);
2236                                         unlink($infile) if ($infile);
2237                                         &http_error(500, "Failed to read ".
2238                                                          "POST request");
2239                                         }
2240                                 $got += length($buf);
2241                                 }
2242                         $SIG{'PIPE'} = 'DEFAULT';
2243                         }
2244                 close(CGIINw);
2245                 shutdown(SOCK, 0);
2246
2247                 if ($on_windows) {
2248                         # Run the CGI program, and feed it input
2249                         chdir($ENV{"PWD"});
2250                         local $qqueryargs = join(" ", map { "\"$_\"" }
2251                                                  split(/\s+/, $queryargs));
2252                         if ($first =~ /(perl|perl.exe)$/i) {
2253                                 # On Windows, run with Perl
2254                                 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2255                                 }
2256                         else {
2257                                 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2258                                 }
2259                         binmode(CGIOUTr);
2260                         }
2261
2262                 if (!$nph_script) {
2263                         # read back cgi headers
2264                         select(CGIOUTr); $|=1; select(STDOUT);
2265                         $got_blank = 0;
2266                         while(1) {
2267                                 $line = <CGIOUTr>;
2268                                 $line =~ s/\r|\n//g;
2269                                 if ($line eq "") {
2270                                         if ($got_blank || %cgiheader) { last; }
2271                                         $got_blank++;
2272                                         next;
2273                                         }
2274                                 if ($line !~ /^(\S+):\s+(.*)$/) {
2275                                         $errs = &read_errors(CGIERRr);
2276                                         close(CGIOUTr); close(CGIERRr);
2277                                         unlink($infile) if ($infile);
2278                                         &http_error(500, "Bad Header", $errs);
2279                                         }
2280                                 $cgiheader{lc($1)} = $2;
2281                                 push(@cgiheader, [ $1, $2 ]);
2282                                 }
2283                         if ($cgiheader{"location"}) {
2284                                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2285                                 &write_data("Date: $datestr\r\n");
2286                                 &write_data("Server: $config{'server'}\r\n");
2287                                 &write_keep_alive(0);
2288                                 # ignore the rest of the output. This is a hack,
2289                                 # but is necessary for IE in some cases :(
2290                                 close(CGIOUTr); close(CGIERRr);
2291                                 }
2292                         elsif ($cgiheader{"content-type"} eq "") {
2293                                 close(CGIOUTr); close(CGIERRr);
2294                                 unlink($infile) if ($infile);
2295                                 $errs = &read_errors(CGIERRr);
2296                                 &http_error(500, "Missing Content-Type Header",
2297                                     $config{'noshowstderr'} ? undef : $errs);
2298                                 }
2299                         else {
2300                                 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2301                                 &write_data("Date: $datestr\r\n");
2302                                 &write_data("Server: $config{'server'}\r\n");
2303                                 &write_keep_alive(0);
2304                                 }
2305                         foreach $h (@cgiheader) {
2306                                 &write_data("$h->[0]: $h->[1]\r\n");
2307                                 }
2308                         &write_data("\r\n");
2309                         }
2310                 &reset_byte_count();
2311                 while($line = <CGIOUTr>) {
2312                         &write_data($line);
2313                         }
2314                 close(CGIOUTr);
2315                 close(CGIERRr);
2316                 unlink($infile) if ($infile);
2317                 $rv = 0;
2318                 }
2319         }
2320 else {
2321         # A file to output
2322         print DEBUG "handle_request: outputting file\n";
2323         open(FILE, $full) || &http_error(404, "Failed to open file");
2324         binmode(FILE);
2325         local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2326                       "Date: $datestr\r\n".
2327                       "Server: $config{server}\r\n".
2328                       "Content-type: ".&get_type($full)."\r\n".
2329                       "Content-length: $stfull[7]\r\n".
2330                       "Last-Modified: ".&http_date($stfull[9])."\r\n".
2331                       "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2332         &write_data($resp);
2333         $rv = &write_keep_alive();
2334         &write_data("\r\n");
2335         &reset_byte_count();
2336         while(read(FILE, $buf, 1024) > 0) {
2337                 &write_data($buf);
2338                 }
2339         close(FILE);
2340         }
2341
2342 # log the request
2343 &log_request($acpthost, $authuser, $reqline,
2344              $logged_code ? $logged_code :
2345              $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2346 return $rv;
2347 }
2348
2349 # http_error(code, message, body, [dontexit])
2350 sub http_error
2351 {
2352 local $eh = $error_handler_recurse ? undef :
2353             $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2354             $config{'error_handler'} ? $config{'error_handler'} : undef;
2355 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2356 if ($eh) {
2357         # Call a CGI program for the error
2358         $page = "/$eh";
2359         $querystring = "code=$_[0]&message=".&urlize($_[1]).
2360                        "&body=".&urlize($_[2]);
2361         $error_handler_recurse++;
2362         $ok_code = $_[0];
2363         $ok_message = $_[1];
2364         goto rerun;
2365         }
2366 else {
2367         # Use the standard error message display
2368         &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2369         &write_data("Server: $config{server}\r\n");
2370         &write_data("Date: $datestr\r\n");
2371         &write_data("Content-type: text/html\r\n");
2372         &write_keep_alive(0);
2373         &write_data("\r\n");
2374         &reset_byte_count();
2375         &write_data("<h1>Error - $_[1]</h1>\n");
2376         if ($_[2]) {
2377                 &write_data("<pre>$_[2]</pre>\n");
2378                 }
2379         }
2380 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2381         if ($reqline);
2382 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2383 shutdown(SOCK, 1);
2384 exit if (!$_[3]);
2385 }
2386
2387 sub get_type
2388 {
2389 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2390         $t = $mime{$1};
2391         if ($t ne "") {
2392                 return $t;
2393                 }
2394         }
2395 return "text/plain";
2396 }
2397
2398 # simplify_path(path, bogus)
2399 # Given a path, maybe containing stuff like ".." and "." convert it to a
2400 # clean, absolute form.
2401 sub simplify_path
2402 {
2403 local($dir, @bits, @fixedbits, $b);
2404 $dir = $_[0];
2405 $dir =~ s/\\/\//g;      # fix windows \ in path
2406 $dir =~ s/^\/+//g;
2407 $dir =~ s/\/+$//g;
2408 $dir =~ s/\0//g;        # remove null bytes
2409 @bits = split(/\/+/, $dir);
2410 @fixedbits = ();
2411 $_[1] = 0;
2412 foreach $b (@bits) {
2413         if ($b eq ".") {
2414                 # Do nothing..
2415                 }
2416         elsif ($b eq ".." || $b eq "...") {
2417                 # Remove last dir
2418                 if (scalar(@fixedbits) == 0) {
2419                         $_[1] = 1;
2420                         return "/";
2421                         }
2422                 pop(@fixedbits);
2423                 }
2424         else {
2425                 # Add dir to list
2426                 push(@fixedbits, $b);
2427                 }
2428         }
2429 return "/" . join('/', @fixedbits);
2430 }
2431
2432 # b64decode(string)
2433 # Converts a string from base64 format to normal
2434 sub b64decode
2435 {
2436     local($str) = $_[0];
2437     local($res);
2438     $str =~ tr|A-Za-z0-9+=/||cd;
2439     $str =~ s/=+$//;
2440     $str =~ tr|A-Za-z0-9+/| -_|;
2441     while ($str =~ /(.{1,60})/gs) {
2442         my $len = chr(32 + length($1)*3/4);
2443         $res .= unpack("u", $len . $1 );
2444     }
2445     return $res;
2446 }
2447
2448 # ip_match(remoteip, localip, [match]+)
2449 # Checks an IP address against a list of IPs, networks and networks/masks
2450 sub ip_match
2451 {
2452 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2453 @io = split(/\./, $_[0]);
2454 for($i=2; $i<@_; $i++) {
2455         $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2456         }
2457 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2458         $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2459         $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2460         $ip_match_cache{$_[0]} = $hn;
2461         }
2462 for($i=2; $i<@_; $i++) {
2463         local $mismatch = 0;
2464         if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2465                 # Convert CIDR to netmask format
2466                 $_[$i] = $1."/".&prefix_to_mask($2);
2467                 }
2468         if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2469                 # Compare with network/mask
2470                 @mo = split(/\./, $1); @ms = split(/\./, $2);
2471                 for($j=0; $j<4; $j++) {
2472                         if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2473                                 $mismatch = 1;
2474                                 }
2475                         }
2476                 }
2477         elsif ($_[$i] =~ /^\*(\S+)$/) {
2478                 # Compare with hostname regexp
2479                 $mismatch = 1 if ($hn !~ /$1$/);
2480                 }
2481         elsif ($_[$i] eq 'LOCAL') {
2482                 # Compare with local network
2483                 local @lo = split(/\./, $_[1]);
2484                 if ($lo[0] < 128) {
2485                         $mismatch = 1 if ($lo[0] != $io[0]);
2486                         }
2487                 elsif ($lo[0] < 192) {
2488                         $mismatch = 1 if ($lo[0] != $io[0] ||
2489                                           $lo[1] != $io[1]);
2490                         }
2491                 else {
2492                         $mismatch = 1 if ($lo[0] != $io[0] ||
2493                                           $lo[1] != $io[1] ||
2494                                           $lo[2] != $io[2]);
2495                         }
2496                 }
2497         elsif ($_[$i] !~ /^[0-9\.]+$/) {
2498                 # Compare with hostname
2499                 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2500                 }
2501         else {
2502                 # Compare with IP or network
2503                 @mo = split(/\./, $_[$i]);
2504                 while(@mo && !$mo[$#mo]) { pop(@mo); }
2505                 for($j=0; $j<@mo; $j++) {
2506                         if ($mo[$j] != $io[$j]) {
2507                                 $mismatch = 1;
2508                                 }
2509                         }
2510                 }
2511         return 1 if (!$mismatch);
2512         }
2513 return 0;
2514 }
2515
2516 # users_match(&uinfo, user, ...)
2517 # Returns 1 if a user is in a list of users and groups
2518 sub users_match
2519 {
2520 local $uinfo = shift(@_);
2521 local $u;
2522 local @ginfo = getgrgid($uinfo->[3]);
2523 foreach $u (@_) {
2524         if ($u =~ /^\@(\S+)$/) {
2525                 return 1 if (&is_group_member($uinfo, $1));
2526                 }
2527         elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2528                 return (!$1 || $uinfo[2] >= $1) &&
2529                        (!$2 || $uinfo[2] <= $2);
2530                 }
2531         else {
2532                 return 1 if ($u eq $uinfo->[0]);
2533                 }
2534         }
2535 return 0;
2536 }
2537
2538 # restart_miniserv()
2539 # Called when a SIGHUP is received to restart the web server. This is done
2540 # by exec()ing perl with the same command line as was originally used
2541 sub restart_miniserv
2542 {
2543 print STDERR "restarting miniserv\n";
2544 &log_error("Restarting");
2545 close(SOCK);
2546 &close_all_sockets();
2547 &close_all_pipes();
2548 dbmclose(%sessiondb);
2549 kill('KILL', $logclearer) if ($logclearer);
2550 kill('KILL', $extauth) if ($extauth);
2551 exec($perl_path, $miniserv_path, @miniserv_argv);
2552 die "Failed to restart miniserv with $perl_path $miniserv_path";
2553 }
2554
2555 sub trigger_restart
2556 {
2557 $need_restart = 1;
2558 }
2559
2560 sub trigger_reload
2561 {
2562 $need_reload = 1;
2563 }
2564
2565 sub to_ipaddress
2566 {
2567 local (@rv, $i);
2568 foreach $i (@_) {
2569         if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2570             $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2571         else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2572         }
2573 return wantarray ? @rv : $rv[0];
2574 }
2575
2576 # read_line(no-wait, no-limit)
2577 # Reads one line from SOCK or SSL
2578 sub read_line
2579 {
2580 local ($nowait, $nolimit) = @_;
2581 local($idx, $more, $rv);
2582 while(($idx = index($main::read_buffer, "\n")) < 0) {
2583         if (length($main::read_buffer) > 10000 && !$nolimit) {
2584                 &http_error(414, "Request too long",
2585                     "Received excessive line <pre>$main::read_buffer</pre>");
2586                 }
2587
2588         # need to read more..
2589         &wait_for_data_error() if (!$nowait);
2590         if ($use_ssl) {
2591                 $more = Net::SSLeay::read($ssl_con);
2592                 }
2593         else {
2594                 local $ok = sysread(SOCK, $more, 1024);
2595                 $more = undef if ($ok <= 0);
2596                 }
2597         if ($more eq '') {
2598                 # end of the data
2599                 $rv = $main::read_buffer;
2600                 undef($main::read_buffer);
2601                 return $rv;
2602                 }
2603         $main::read_buffer .= $more;
2604         }
2605 $rv = substr($main::read_buffer, 0, $idx+1);
2606 $main::read_buffer = substr($main::read_buffer, $idx+1);
2607 return $rv;
2608 }
2609
2610 # read_data(length)
2611 # Reads up to some amount of data from SOCK or the SSL connection
2612 sub read_data
2613 {
2614 local ($rv);
2615 if (length($main::read_buffer)) {
2616         if (length($main::read_buffer) > $_[0]) {
2617                 # Return the first part of the buffer
2618                 $rv = substr($main::read_buffer, 0, $_[0]);
2619                 $main::read_buffer = substr($main::read_buffer, $_[0]);
2620                 return $rv;
2621                 }
2622         else {
2623                 # Return the whole buffer
2624                 $rv = $main::read_buffer;
2625                 undef($main::read_buffer);
2626                 return $rv;
2627                 }
2628         }
2629 elsif ($use_ssl) {
2630         # Call SSL read function
2631         return Net::SSLeay::read($ssl_con, $_[0]);
2632         }
2633 else {
2634         # Just do a normal read
2635         local $buf;
2636         sysread(SOCK, $buf, $_[0]) || return undef;
2637         return $buf;
2638         }
2639 }
2640
2641 # sysread_line(fh)
2642 # Read a line from a file handle, using sysread to get a byte at a time
2643 sub sysread_line
2644 {
2645 local ($fh) = @_;
2646 local $line;
2647 while(1) {
2648         local ($buf, $got);
2649         $got = sysread($fh, $buf, 1);
2650         last if ($got <= 0);
2651         $line .= $buf;
2652         last if ($buf eq "\n");
2653         }
2654 return $line;
2655 }
2656
2657 # wait_for_data(secs)
2658 # Waits at most the given amount of time for some data on SOCK, returning
2659 # 0 if not found, 1 if some arrived.
2660 sub wait_for_data
2661 {
2662 local $rmask;
2663 vec($rmask, fileno(SOCK), 1) = 1;
2664 local $got = select($rmask, undef, undef, $_[0]);
2665 return $got == 0 ? 0 : 1;
2666 }
2667
2668 # wait_for_data_error()
2669 # Waits 60 seconds for data on SOCK, and fails if none arrives
2670 sub wait_for_data_error
2671 {
2672 local $got = &wait_for_data(60);
2673 if (!$got) {
2674         &http_error(400, "Timeout",
2675                     "Waited more than 60 seconds for request data");
2676         }
2677 }
2678
2679 # write_data(data, ...)
2680 # Writes a string to SOCK or the SSL connection
2681 sub write_data
2682 {
2683 local $str = join("", @_);
2684 if ($use_ssl) {
2685         Net::SSLeay::write($ssl_con, $str);
2686         }
2687 else {
2688         syswrite(SOCK, $str, length($str));
2689         }
2690 # Intentionally introduce a small delay to avoid problems where IE reports
2691 # the page as empty / DNS failed when it get a large response too quickly!
2692 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2693 $write_data_count += length($str);
2694 }
2695
2696 # reset_byte_count()
2697 sub reset_byte_count { $write_data_count = 0; }
2698
2699 # byte_count()
2700 sub byte_count { return $write_data_count; }
2701
2702 # log_request(hostname, user, request, code, bytes)
2703 sub log_request
2704 {
2705 if ($config{'log'}) {
2706         local ($user, $ident, $headers);
2707         if ($config{'logident'}) {
2708                 # add support for rfc1413 identity checking here
2709                 }
2710         else { $ident = "-"; }
2711         $user = $_[1] ? $_[1] : "-";
2712         local $dstr = &make_datestr();
2713         if (fileno(MINISERVLOG)) {
2714                 seek(MINISERVLOG, 0, 2);
2715                 }
2716         else {
2717                 open(MINISERVLOG, ">>$config{'logfile'}");
2718                 chmod(0600, $config{'logfile'});
2719                 }
2720         if (defined($config{'logheaders'})) {
2721                 foreach $h (split(/\s+/, $config{'logheaders'})) {
2722                         $headers .= " $h=\"$header{$h}\"";
2723                         }
2724                 }
2725         elsif ($config{'logclf'}) {
2726                 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2727                 }
2728         else {
2729                 $headers = "";
2730                 }
2731         print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2732                           "$_[3] $_[4]$headers\n";
2733         close(MINISERVLOG);
2734         }
2735 }
2736
2737 # make_datestr()
2738 sub make_datestr
2739 {
2740 local @tm = localtime(time());
2741 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2742                 $tm[3], $month[$tm[4]], $tm[5]+1900,
2743                 $tm[2], $tm[1], $tm[0], $timezone;
2744 }
2745
2746 # log_error(message)
2747 sub log_error
2748 {
2749 seek(STDERR, 0, 2);
2750 print STDERR "[",&make_datestr(),"] ",
2751         $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2752         $page ? ( $page," : " ) : ( ),
2753         @_,"\n";
2754 }
2755
2756 # read_errors(handle)
2757 # Read and return all input from some filehandle
2758 sub read_errors
2759 {
2760 local($fh, $_, $rv);
2761 $fh = $_[0];
2762 while(<$fh>) { $rv .= $_; }
2763 return $rv;
2764 }
2765
2766 sub write_keep_alive
2767 {
2768 local $mode;
2769 if ($config{'nokeepalive'}) {
2770         # Keep alives have been disabled in config
2771         $mode = 0;
2772         }
2773 elsif (@childpids > $config{'maxconns'}*.8) {
2774         # Disable because nearing process limit
2775         $mode = 0;
2776         }
2777 elsif (@_) {
2778         # Keep alive specified by caller
2779         $mode = $_[0];
2780         }
2781 else {
2782         # Keep alive determined by browser
2783         $mode = $header{'connection'} =~ /keep-alive/i;
2784         }
2785 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2786 return $mode;
2787 }
2788
2789 sub term_handler
2790 {
2791 kill('TERM', @childpids) if (@childpids);
2792 kill('KILL', $logclearer) if ($logclearer);
2793 kill('KILL', $extauth) if ($extauth);
2794 exit(1);
2795 }
2796
2797 sub http_date
2798 {
2799 local @tm = gmtime($_[0]);
2800 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2801                 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2802                 $tm[2], $tm[1], $tm[0];
2803 }
2804
2805 sub TIEHANDLE
2806 {
2807 my $i; bless \$i, shift;
2808 }
2809  
2810 sub WRITE
2811 {
2812 $r = shift;
2813 my($buf,$len,$offset) = @_;
2814 &write_to_sock(substr($buf, $offset, $len));
2815 }
2816  
2817 sub PRINT
2818 {
2819 $r = shift;
2820 $$r++;
2821 my $buf = join(defined($,) ? $, : "", @_);
2822 $buf .= $\ if defined($\);
2823 &write_to_sock($buf);
2824 }
2825  
2826 sub PRINTF
2827 {
2828 shift;
2829 my $fmt = shift;
2830 &write_to_sock(sprintf $fmt, @_);
2831 }
2832  
2833 # Send back already read data while we have it, then read from SOCK
2834 sub READ
2835 {
2836 my $r = shift;
2837 my $bufref = \$_[0];
2838 my $len = $_[1];
2839 my $offset = $_[2];
2840 if ($postpos < length($postinput)) {
2841         # Reading from already fetched array
2842         my $left = length($postinput) - $postpos;
2843         my $canread = $len > $left ? $left : $len;
2844         substr($$bufref, $offset, $canread) =
2845                 substr($postinput, $postpos, $canread);
2846         $postpos += $canread;
2847         return $canread;
2848         }
2849 else {
2850         # Read from network socket
2851         local $data = &read_data($len);
2852         if ($data eq '' && $len) {
2853                 # End of socket
2854                 print STDERR "finished reading - shutting down socket\n";
2855                 shutdown(SOCK, 0);
2856                 }
2857         substr($$bufref, $offset, length($data)) = $data;
2858         return length($data);
2859         }
2860 }
2861
2862 sub OPEN
2863 {
2864 #print STDERR "open() called - should never happen!\n";
2865 }
2866  
2867 # Read a line of input
2868 sub READLINE
2869 {
2870 my $r = shift;
2871 if ($postpos < length($postinput) &&
2872     ($idx = index($postinput, "\n", $postpos)) >= 0) {
2873         # A line exists in the memory buffer .. use it
2874         my $line = substr($postinput, $postpos, $idx-$postpos+1);
2875         $postpos = $idx+1;
2876         return $line;
2877         }
2878 else {
2879         # Need to read from the socket
2880         my $line;
2881         if ($postpos < length($postinput)) {
2882                 # Start with in-memory data
2883                 $line = substr($postinput, $postpos);
2884                 $postpos = length($postinput);
2885                 }
2886         my $nl = &read_line(0, 1);
2887         if ($nl eq '') {
2888                 # End of socket
2889                 print STDERR "finished reading - shutting down socket\n";
2890                 shutdown(SOCK, 0);
2891                 }
2892         $line .= $nl if (defined($nl));
2893         return $line;
2894         }
2895 }
2896  
2897 # Read one character of input
2898 sub GETC
2899 {
2900 my $r = shift;
2901 my $buf;
2902 my $got = READ($r, \$buf, 1, 0);
2903 return $got > 0 ? $buf : undef;
2904 }
2905
2906 sub FILENO
2907 {
2908 return fileno(SOCK);
2909 }
2910  
2911 sub CLOSE { }
2912  
2913 sub DESTROY { }
2914
2915 # write_to_sock(data, ...)
2916 sub write_to_sock
2917 {
2918 local $d;
2919 foreach $d (@_) {
2920         if ($doneheaders || $miniserv::nph_script) {
2921                 &write_data($d);
2922                 }
2923         else {
2924                 $headers .= $d;
2925                 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2926                         if ($1 =~ /^(\S+):\s+(.*)$/) {
2927                                 $cgiheader{lc($1)} = $2;
2928                                 push(@cgiheader, [ $1, $2 ]);
2929                                 }
2930                         elsif ($1 !~ /\S/) {
2931                                 $doneheaders++;
2932                                 }
2933                         else {
2934                                 &http_error(500, "Bad Header");
2935                                 }
2936                         }
2937                 if ($doneheaders) {
2938                         if ($cgiheader{"location"}) {
2939                                 &write_data(
2940                                         "HTTP/1.0 302 Moved Temporarily\r\n");
2941                                 &write_data("Date: $datestr\r\n");
2942                                 &write_data("Server: $config{server}\r\n");
2943                                 &write_keep_alive(0);
2944                                 }
2945                         elsif ($cgiheader{"content-type"} eq "") {
2946                                 &http_error(500, "Missing Content-Type Header");
2947                                 }
2948                         else {
2949                                 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2950                                 &write_data("Date: $datestr\r\n");
2951                                 &write_data("Server: $config{server}\r\n");
2952                                 &write_keep_alive(0);
2953                                 }
2954                         foreach $h (@cgiheader) {
2955                                 &write_data("$h->[0]: $h->[1]\r\n");
2956                                 }
2957                         &write_data("\r\n");
2958                         &reset_byte_count();
2959                         &write_data($headers);
2960                         }
2961                 }
2962         }
2963 }
2964
2965 sub verify_client
2966 {
2967 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2968 if ($cert) {
2969         local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2970         $verified_client = 1 if (!$errnum);
2971         }
2972 return 1;
2973 }
2974
2975 sub END
2976 {
2977 if ($doing_cgi_eval && $$ == $main_process_id) {
2978         # A CGI program called exit! This is a horrible hack to 
2979         # finish up before really exiting
2980         shutdown(SOCK, 1);
2981         close(SOCK);
2982         close($PASSINw); close($PASSOUTw);
2983         &log_request($acpthost, $authuser, $reqline,
2984                      $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2985         }
2986 }
2987
2988 # urlize
2989 # Convert a string to a form ok for putting in a URL
2990 sub urlize {
2991   local($tmp, $tmp2, $c);
2992   $tmp = $_[0];
2993   $tmp2 = "";
2994   while(($c = chop($tmp)) ne "") {
2995         if ($c !~ /[A-z0-9]/) {
2996                 $c = sprintf("%%%2.2X", ord($c));
2997                 }
2998         $tmp2 = $c . $tmp2;
2999         }
3000   return $tmp2;
3001 }
3002
3003 # validate_user(username, password, host)
3004 # Checks if some username and password are valid. Returns the modified username,
3005 # the expired / temp pass flag, and the non-existence flag
3006 sub validate_user
3007 {
3008 local ($user, $pass, $host) = @_;
3009 return ( ) if (!$user);
3010 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3011 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3012         &can_user_login($user, undef, $host);
3013 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3014 if ($notexist) {
3015         # User doesn't even exist, so go no further
3016         return ( undef, 0, 1 );
3017         }
3018 elsif ($canmode == 0) {
3019         # User does exist but cannot login
3020         return ( $canuser, 0, 0 );
3021         }
3022 elsif ($canmode == 1) {
3023         # Attempt Webmin authentication
3024         my $uinfo = &get_user_details($webminuser);
3025         if ($uinfo && &password_crypt($pass, $uinfo->{'pass'})) {
3026                 # Password is valid .. but check for expiry
3027                 local $lc = $lastchanges{$user};
3028                 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
3029                         local $daysold = (time() - $lc)/(24*60*60);
3030                         print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
3031                         if ($config{'pass_lockdays'} &&
3032                             $daysold > $config{'pass_lockdays'}) {
3033                                 # So old that the account is locked
3034                                 return ( undef, 0, 0 );
3035                                 }
3036                         elsif ($daysold > $config{'pass_maxdays'}) {
3037                                 # Password has expired
3038                                 return ( $user, 1, 0 );
3039                                 }
3040                         }
3041                 if ($temppass{$user}) {
3042                         # Temporary password - force change now
3043                         return ( $user, 2, 0 );
3044                         }
3045                 return ( $user, 0, 0 );
3046                 }
3047         else {
3048                 return ( undef, 0, 0 );
3049                 }
3050         }
3051 elsif ($canmode == 2 || $canmode == 3) {
3052         # Attempt PAM or passwd file authentication
3053         local $val = &validate_unix_user($canuser, $pass);
3054         print DEBUG "validate_user: unix val=$val\n";
3055         if ($val && $sudo) {
3056                 # Need to check if this Unix user can sudo
3057                 if (!&check_sudo_permissions($canuser, $pass)) {
3058                         print DEBUG "validate_user: sudo failed\n";
3059                         $val = 0;
3060                         }
3061                 else {
3062                         print DEBUG "validate_user: sudo passed\n";
3063                         }
3064                 }
3065         return $val == 2 ? ( $canuser, 1, 0 ) :
3066                $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3067         }
3068 elsif ($canmode == 4) {
3069         # Attempt external authentication
3070         return &validate_external_user($canuser, $pass) ?
3071                 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3072         }
3073 else {
3074         # Can't happen!
3075         return ( );
3076         }
3077 }
3078
3079 # validate_unix_user(user, password)
3080 # Returns 1 if a username and password are valid under unix, 0 if not,
3081 # or 2 if the account has expired.
3082 # Checks PAM if available, and falls back to reading the system password
3083 # file otherwise.
3084 sub validate_unix_user
3085 {
3086 if ($use_pam) {
3087         # Check with PAM
3088         $pam_username = $_[0];
3089         $pam_password = $_[1];
3090         eval "use Authen::PAM;";
3091         local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3092                                       \&pam_conv_func);
3093         if (ref($pamh)) {
3094                 local $pam_ret = $pamh->pam_authenticate();
3095                 if ($pam_ret == PAM_SUCCESS()) {
3096                         # Logged in OK .. make sure password hasn't expired
3097                         local $acct_ret = $pamh->pam_acct_mgmt();
3098                         if ($acct_ret == PAM_SUCCESS()) {
3099                                 $pamh->pam_open_session();
3100                                 return 1;
3101                                 }
3102                         elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3103                                $acct_ret == PAM_ACCT_EXPIRED()) {
3104                                 return 2;
3105                                 }
3106                         else {
3107                                 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3108                                 return 0;
3109                                 }
3110                         }
3111                 return 0;
3112                 }
3113         }
3114 elsif ($config{'pam_only'}) {
3115         # Pam is not available, but configuration forces it's use!
3116         return 0;
3117         }
3118 elsif ($config{'passwd_file'}) {
3119         # Check in a password file
3120         local $rv = 0;
3121         open(FILE, $config{'passwd_file'});
3122         if ($config{'passwd_file'} eq '/etc/security/passwd') {
3123                 # Assume in AIX format
3124                 while(<FILE>) {
3125                         s/\s*$//;
3126                         if (/^\s*(\S+):/ && $1 eq $_[0]) {
3127                                 $_ = <FILE>;
3128                                 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3129                                         $rv = $1 eq &password_crypt($_[1], $1) ?
3130                                                 1 : 0;
3131                                         }
3132                                 last;
3133                                 }
3134                         }
3135                 }
3136         else {
3137                 # Read the system password or shadow file
3138                 while(<FILE>) {
3139                         local @l = split(/:/, $_, -1);
3140                         local $u = $l[$config{'passwd_uindex'}];
3141                         local $p = $l[$config{'passwd_pindex'}];
3142                         if ($u eq $_[0]) {
3143                                 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3144                                 if ($config{'passwd_cindex'} ne '' && $rv) {
3145                                         # Password may have expired!
3146                                         local $c = $l[$config{'passwd_cindex'}];
3147                                         local $m = $l[$config{'passwd_mindex'}];
3148                                         local $day = time()/(24*60*60);
3149                                         if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3150                                             $day - $c > $m) {
3151                                                 # Yep, it has ..
3152                                                 $rv = 2;
3153                                                 }
3154                                         }
3155                                 if ($p eq "" && $config{'passwd_blank'}) {
3156                                         # Force password change
3157                                         $rv = 2;
3158                                         }
3159                                 last;
3160                                 }
3161                         }
3162                 }
3163         close(FILE);
3164         return $rv if ($rv);
3165         }
3166
3167 # Fallback option - check password returned by getpw*
3168 local @uinfo = getpwnam($_[0]);
3169 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3170         return 1;
3171         }
3172
3173 return 0;       # Totally failed
3174 }
3175
3176 # validate_external_user(user, pass)
3177 # Validate a user by passing the username and password to an external
3178 # squid-style authentication program
3179 sub validate_external_user
3180 {
3181 return 0 if (!$config{'extauth'});
3182 flock(EXTAUTH, 2);
3183 local $str = "$_[0] $_[1]\n";
3184 syswrite(EXTAUTH, $str, length($str));
3185 local $resp = <EXTAUTH>;
3186 flock(EXTAUTH, 8);
3187 return $resp =~ /^OK/i ? 1 : 0;
3188 }
3189
3190 # can_user_login(username, no-append, host)
3191 # Checks if a user can login or not.
3192 # First return value is the username.
3193 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3194 # file, 4 if external.
3195 # Third is 1 if the user does not exist at all, 0 if he does.
3196 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3197 # Fifth is a flag indicating if a sudo check is needed.
3198 sub can_user_login
3199 {
3200 local $uinfo = &get_user_details($_[0]);
3201 if (!$uinfo) {
3202         # See if this user exists in Unix and can be validated by the same
3203         # method as the unixauth webmin user
3204         local $realuser = $unixauth{$_[0]};
3205         local @uinfo;
3206         local $sudo = 0;
3207         local $pamany = 0;
3208         eval { @uinfo = getpwnam($_[0]); };     # may fail on windows
3209         if (!$realuser && @uinfo) {
3210                 # No unixauth entry for the username .. try his groups 
3211                 foreach my $ua (keys %unixauth) {
3212                         if ($ua =~ /^\@(.*)$/) {
3213                                 if (&is_group_member(\@uinfo, $1)) {
3214                                         $realuser = $unixauth{$ua};
3215                                         last;
3216                                         }
3217                                 }
3218                         }
3219                 }
3220         if (!$realuser && @uinfo) {
3221                 # Fall back to unix auth for all Unix users
3222                 $realuser = $unixauth{"*"};
3223                 }
3224         if (!$realuser && $use_sudo && @uinfo) {
3225                 # Allow login effectively as root, if sudo permits it
3226                 $sudo = 1;
3227                 $realuser = "root";
3228                 }
3229         if (!$realuser && !@uinfo && $config{'pamany'}) {
3230                 # If the user completely doesn't exist, we can still allow
3231                 # him to authenticate via PAM
3232                 $realuser = $config{'pamany'};
3233                 $pamany = 1;
3234                 }
3235         if (!$realuser) {
3236                 # For Usermin, always fall back to unix auth for any user,
3237                 # so that later checks with domain added / removed are done.
3238                 $realuser = $unixauth{"*"};
3239                 }
3240         return (undef, 0, 1, undef) if (!$realuser);
3241         local $uinfo = &get_user_details($realuser);
3242         return (undef, 0, 1, undef) if (!$uinfo);
3243         local $up = $uinfo{'pass'};
3244
3245         # Work out possible domain names from the hostname
3246         local @doms = ( $_[2] );
3247         if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3248                 push(@doms, $2);
3249                 }
3250
3251         if ($config{'user_mapping'} && !%user_mapping) {
3252                 # Read the user mapping file
3253                 %user_mapping = ();
3254                 open(MAPPING, $config{'user_mapping'});
3255                 while(<MAPPING>) {
3256                         s/\r|\n//g;
3257                         s/#.*$//;
3258                         if (/^(\S+)\s+(\S+)/) {
3259                                 if ($config{'user_mapping_reverse'}) {
3260                                         $user_mapping{$1} = $2;
3261                                         }
3262                                 else {
3263                                         $user_mapping{$2} = $1;
3264                                         }
3265                                 }
3266                         }
3267                 close(MAPPING);
3268                 }
3269
3270         # Check the user mapping file to see if there is an entry for the
3271         # user login in which specifies a new effective user
3272         local $um;
3273         foreach my $d (@doms) {
3274                 $um ||= $user_mapping{"$_[0]\@$d"};
3275                 }
3276         $um ||= $user_mapping{$_[0]};
3277         if (defined($um) && ($_[1]&4) == 0) {
3278                 # A mapping exists - use it!
3279                 return &can_user_login($um, $_[1]+4, $_[2]);
3280                 }
3281
3282         # Check if a user with the entered login and the domains appended
3283         # or prepended exists, and if so take it to be the effective user
3284         if (!@uinfo && $config{'domainuser'}) {
3285                 # Try again with name.domain and name.firstpart
3286                 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3287                 if (($_[1]&1) == 0) {
3288                         local ($a, $p);
3289                         foreach $a (@firsts, @doms) {
3290                                 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3291                                             "${a}.$_[0]", "${a}-$_[0]",
3292                                             "$_[0]_${a}", "${a}_$_[0]") {
3293                                         local @vu = &can_user_login(
3294                                                         $p, $_[1]+1, $_[2]);
3295                                         return @vu if ($vu[1]);
3296                                         }
3297                                 }
3298                         }
3299                 }
3300
3301         # Check if the user entered a domain at the end of his username when
3302         # he really shouldn't have, and if so try without it
3303         if (!@uinfo && $config{'domainstrip'} &&
3304             $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3305                 local ($stripped, $dom) = ($1, $2);
3306                 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3307                 return @vu if ($vu[1]);
3308                 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3309                 return @vu if ($vu[1]);
3310                 }
3311
3312         return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3313
3314         if (@uinfo) {
3315                 if (defined(@allowusers)) {
3316                         # Only allow people on the allow list
3317                         return ( undef, 0, 0, undef )
3318                                 if (!&users_match(\@uinfo, @allowusers));
3319                         }
3320                 elsif (defined(@denyusers)) {
3321                         # Disallow people on the deny list
3322                         return ( undef, 0, 0, undef )
3323                                 if (&users_match(\@uinfo, @denyusers));
3324                         }
3325                 if ($config{'shells_deny'}) {
3326                         local $found = 0;
3327                         open(SHELLS, $config{'shells_deny'});
3328                         while(<SHELLS>) {
3329                                 s/\r|\n//g;
3330                                 s/#.*$//;
3331                                 $found++ if ($_ eq $uinfo[8]);
3332                                 }
3333                         close(SHELLS);
3334                         return ( undef, 0, 0, undef ) if (!$found);
3335                         }
3336                 }
3337
3338         if ($up eq 'x') {
3339                 # PAM or passwd file authentication
3340                 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3341                 }
3342         elsif ($up eq 'e') {
3343                 # External authentication
3344                 return ( $_[0], 4, 0, $realuser, $sudo );
3345                 }
3346         else {
3347                 # Fixed Webmin password
3348                 return ( $_[0], 1, 0, $realuser, $sudo );
3349                 }
3350         }
3351 elsif ($uinfo->{'pass'} eq 'x') {
3352         # Webmin user authenticated via PAM or password file
3353         return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3354         }
3355 elsif ($uinfo->{'pass'} eq 'e') {
3356         # Webmin user authenticated externally
3357         return ( $_[0], 4, 0, $_[0] );
3358         }
3359 else {
3360         # Normal Webmin user
3361         return ( $_[0], 1, 0, $_[0] );
3362         }
3363 }
3364
3365 # the PAM conversation function for interactive logins
3366 sub pam_conv_func
3367 {
3368 $pam_conv_func_called++;
3369 my @res;
3370 while ( @_ ) {
3371         my $code = shift;
3372         my $msg = shift;
3373         my $ans = "";
3374
3375         $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3376         $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3377
3378         push @res, PAM_SUCCESS();
3379         push @res, $ans;
3380         }
3381 push @res, PAM_SUCCESS();
3382 return @res;
3383 }
3384
3385 sub urandom_timeout
3386 {
3387 close(RANDOM);
3388 }
3389
3390 # get_socket_name(handle)
3391 # Returns the local hostname or IP address of some connection
3392 sub get_socket_name
3393 {
3394 return $config{'host'} if ($config{'host'});
3395 local $sn = getsockname($_[0]);
3396 return undef if (!$sn);
3397 local $myaddr = (unpack_sockaddr_in($sn))[1];
3398 if (!$get_socket_name_cache{$myaddr}) {
3399         local $myname;
3400         if (!$config{'no_resolv_myname'}) {
3401                 $myname = gethostbyaddr($myaddr, AF_INET);
3402                 }
3403         if ($myname eq "") {
3404                 $myname = inet_ntoa($myaddr);
3405                 }
3406         $get_socket_name_cache{$myaddr} = $myname;
3407         }
3408 return $get_socket_name_cache{$myaddr};
3409 }
3410
3411 # run_login_script(username, sid, remoteip, localip)
3412 sub run_login_script
3413 {
3414 if ($config{'login_script'}) {
3415         system($config{'login_script'}.
3416                " ".join(" ", map { quotemeta($_) || '""' } @_).
3417                " >/dev/null 2>&1 </dev/null");
3418         }
3419 }
3420
3421 # run_logout_script(username, sid, remoteip, localip)
3422 sub run_logout_script
3423 {
3424 if ($config{'logout_script'}) {
3425         system($config{'logout_script'}.
3426                " ".join(" ", map { quotemeta($_) || '""' } @_).
3427                " >/dev/null 2>&1 </dev/null");
3428         }
3429 }
3430
3431 # close_all_sockets()
3432 # Closes all the main listening sockets
3433 sub close_all_sockets
3434 {
3435 local $s;
3436 foreach $s (@socketfhs) {
3437         close($s);
3438         }
3439 }
3440
3441 # close_all_pipes()
3442 # Close all pipes for talking to sub-processes
3443 sub close_all_pipes
3444 {
3445 local $p;
3446 foreach $p (@passin) { close($p); }
3447 foreach $p (@passout) { close($p); }
3448 foreach $p (values %conversations) {
3449         if ($p->{'PAMOUTr'}) {
3450                 close($p->{'PAMOUTr'});
3451                 close($p->{'PAMINw'});
3452                 }
3453         }
3454 }
3455
3456 # check_user_ip(user)
3457 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3458 sub check_user_ip
3459 {
3460 if ($deny{$_[0]} &&
3461     &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3462     $allow{$_[0]} &&
3463     !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3464         return 0;
3465         }
3466 return 1;
3467 }
3468
3469 # check_user_time(user)
3470 # Returns 1 if some user is allowed to login at the current date and time
3471 sub check_user_time
3472 {
3473 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3474 local @tm = localtime(time());
3475 if ($allowdays{$_[0]}) {
3476         # Make sure day is allowed
3477         return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3478         }
3479 if ($allowhours{$_[0]}) {
3480         # Make sure time is allowed
3481         local $m = $tm[2]*60+$tm[1];
3482         return 0 if ($m < $allowhours{$_[0]}->[0] ||
3483                      $m > $allowhours{$_[0]}->[1]);
3484         }
3485 return 1;
3486 }
3487
3488 # generate_random_id(password, [force-urandom])
3489 # Returns a random session ID number
3490 sub generate_random_id
3491 {
3492 local ($pass, $force_urandom) = @_;
3493 local $sid;
3494 if (!$bad_urandom) {
3495         # First try /dev/urandom, unless we have marked it as bad
3496         $SIG{ALRM} = "miniserv::urandom_timeout";
3497         alarm(5);
3498         if (open(RANDOM, "/dev/urandom")) {
3499                 my $tmpsid;
3500                 if (read(RANDOM, $tmpsid, 16) == 16) {
3501                         $sid = lc(unpack('h*',$tmpsid));
3502                         }
3503                 close(RANDOM);
3504                 }
3505         alarm(0);
3506         }
3507 if (!$sid && !$force_urandom) {
3508         $sid = time();
3509         local $mul = 1;
3510         foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3511                 $sid += ord($c) * $mul;
3512                 $mul *= 3;
3513                 }
3514         }
3515 return $sid;
3516 }
3517
3518 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3519 # Called from handle_session to either mark a user as logged in, or not
3520 sub handle_login
3521 {
3522 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3523 $authuser = $vu if ($ok);
3524
3525 # check if the test cookie is set
3526 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3527     !$config{'no_testing_cookie'} && !$notest) {
3528         &http_error(500, "No cookies",
3529            "Your browser does not support cookies, ".
3530            "which are required for this web server to ".
3531            "work in session authentication mode");
3532         }
3533
3534 # check with main process for delay
3535 if ($config{'passdelay'} && $vu) {
3536         print $PASSINw "delay $vu $acptip $ok\n";
3537         <$PASSOUTr> =~ /(\d+) (\d+)/;
3538         $blocked = $2;
3539         sleep($1);
3540         }
3541
3542 if ($ok && (!$expired ||
3543             $config{'passwd_mode'} == 1)) {
3544         # Logged in OK! Tell the main process about
3545         # the new SID
3546         local $sid = &generate_random_id($pass);
3547         print $PASSINw "new $sid $authuser $acptip\n";
3548
3549         # Run the post-login script, if any
3550         &run_login_script($authuser, $sid,
3551                           $acptip, $localip);
3552
3553         # Check for a redirect URL for the user
3554         local $rurl = &login_redirect($authuser, $pass, $host);
3555         if ($rurl) {
3556                 # Got one .. go to it
3557                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3558                 &write_data("Date: $datestr\r\n");
3559                 &write_data("Server: $config{'server'}\r\n");
3560                 &write_data("Location: $rurl\r\n");
3561                 &write_keep_alive(0);
3562                 &write_data("\r\n");
3563                 &log_request($acpthost, $authuser, $reqline, 302, 0);
3564                 }
3565         else {
3566                 # Set cookie and redirect to originally requested page
3567                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3568                 &write_data("Date: $datestr\r\n");
3569                 &write_data("Server: $config{'server'}\r\n");
3570                 local $ssl = $use_ssl || $config{'inetd_ssl'};
3571                 $portstr = $port == 80 && !$ssl ? "" :
3572                            $port == 443 && $ssl ? "" : ":$port";
3573                 $prot = $ssl ? "https" : "http";
3574                 local $sec = $ssl ? "; secure" : "";
3575                 #$sec .= "; httpOnly";
3576                 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3577                         # Make redirect URL safe
3578                         $in{'page'} = "/";
3579                         }
3580                 if ($in{'save'}) {
3581                         &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3582                         }
3583                 else {
3584                         &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3585                         }
3586                 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3587                 &write_keep_alive(0);
3588                 &write_data("\r\n");
3589                 &log_request($acpthost, $authuser, $reqline, 302, 0);
3590                 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3591                 &write_login_utmp($authuser, $acpthost);
3592                 }
3593         return 0;
3594         }
3595 elsif ($ok && $expired &&
3596        ($config{'passwd_mode'} == 2 || $expired == 2)) {
3597         # Login was ok, but password has expired or was temporary. Need
3598         # to force display of password change form.
3599         $validated = 1;
3600         $authuser = undef;
3601         $querystring = "&user=".&urlize($vu).
3602                        "&pam=".$use_pam.
3603                        "&expired=".$expired;
3604         $method = "GET";
3605         $queryargs = "";
3606         $page = $config{'password_form'};
3607         $logged_code = 401;
3608         $miniserv_internal = 2;
3609         syslog("crit", "%s",
3610                 "Expired login as $vu ".
3611                 "from $acpthost") if ($use_syslog);
3612         }
3613 else {
3614         # Login failed, or password has expired. The login form will be
3615         # displayed again by later code
3616         $failed_user = $vu;
3617         $request_uri = $in{'page'};
3618         $already_session_id = undef;
3619         $method = "GET";
3620         $authuser = $baseauthuser = undef;
3621         syslog("crit", "%s",
3622                 ($nonexist ? "Non-existent" :
3623                  $expired ? "Expired" : "Invalid").
3624                 " login as $vu from $acpthost")
3625                 if ($use_syslog);
3626         }
3627 return undef;
3628 }
3629
3630 # write_login_utmp(user, host)
3631 # Record the login by some user in utmp
3632 sub write_login_utmp
3633 {
3634 if ($write_utmp) {
3635         # Write utmp record for login
3636         %utmp = ( 'ut_host' => $_[1],
3637                   'ut_time' => time(),
3638                   'ut_user' => $_[0],
3639                   'ut_type' => 7,       # user process
3640                   'ut_pid' => $main_process_id,
3641                   'ut_line' => $config{'pam'},
3642                   'ut_id' => '' );
3643         if (defined(&User::Utmp::putut)) {
3644                 User::Utmp::putut(\%utmp);
3645                 }
3646         else {
3647                 User::Utmp::pututline(\%utmp);
3648                 }
3649         }
3650 }
3651
3652 # write_logout_utmp(user, host)
3653 # Record the logout by some user in utmp
3654 sub write_logout_utmp
3655 {
3656 if ($write_utmp) {
3657         # Write utmp record for logout
3658         %utmp = ( 'ut_host' => $_[1],
3659                   'ut_time' => time(),
3660                   'ut_user' => $_[0],
3661                   'ut_type' => 8,       # dead process
3662                   'ut_pid' => $main_process_id,
3663                   'ut_line' => $config{'pam'},
3664                   'ut_id' => '' );
3665         if (defined(&User::Utmp::putut)) {
3666                 User::Utmp::putut(\%utmp);
3667                 }
3668         else {
3669                 User::Utmp::pututline(\%utmp);
3670                 }
3671         }
3672 }
3673
3674 # pam_conversation_process(username, write-pipe, read-pipe)
3675 # This function is called inside a sub-process to communicate with PAM. It sends
3676 # questions down one pipe, and reads responses from another
3677 sub pam_conversation_process
3678 {
3679 local ($user, $writer, $reader) = @_;
3680 $miniserv::pam_conversation_process_writer = $writer;
3681 $miniserv::pam_conversation_process_reader = $reader;
3682 eval "use Authen::PAM;";
3683 local $convh = new Authen::PAM(
3684         $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3685 local $pam_ret = $convh->pam_authenticate();
3686 if ($pam_ret == PAM_SUCCESS()) {
3687         local $acct_ret = $convh->pam_acct_mgmt();
3688         if ($acct_ret == PAM_SUCCESS()) {
3689                 $convh->pam_open_session();
3690                 print $writer "x2 $user 1 0 0\n";
3691                 }
3692         elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3693                $acct_ret == PAM_ACCT_EXPIRED()) {
3694                 print $writer "x2 $user 1 1 0\n";
3695                 }
3696         else {
3697                 print $writer "x0 Unknown PAM account status $acct_ret\n";
3698                 }
3699         }
3700 else {
3701         print $writer "x2 $user 0 0 0\n";
3702         }
3703 exit(0);
3704 }
3705
3706 # pam_conversation_process_func(type, message, [type, message, ...])
3707 # A pipe that talks to both PAM and the master process
3708 sub pam_conversation_process_func
3709 {
3710 local @rv;
3711 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3712 while(@_) {
3713         local ($type, $msg) = (shift, shift);
3714         $msg =~ s/\r|\n//g;
3715         local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3716         print $miniserv::pam_conversation_process_writer "\n";
3717         local $answer = <$miniserv::pam_conversation_process_reader>;
3718         $answer =~ s/\r|\n//g;
3719         push(@rv, PAM_SUCCESS(), $answer);
3720         }
3721 push(@rv, PAM_SUCCESS());
3722 return @rv;
3723 }
3724
3725 # allocate_pipes()
3726 # Returns 4 new pipe file handles
3727 sub allocate_pipes
3728 {
3729 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3730 local $p;
3731 local %taken = ( (map { $_, 1 } @passin),
3732                  (map { $_->{'PASSINr'} } values %conversations) );
3733 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3734 $PASSINr = "PASSINr$p";
3735 $PASSINw = "PASSINw$p";
3736 $PASSOUTr = "PASSOUTr$p";
3737 $PASSOUTw = "PASSOUTw$p";
3738 pipe($PASSINr, $PASSINw);
3739 pipe($PASSOUTr, $PASSOUTw);
3740 select($PASSINw); $| = 1;
3741 select($PASSINr); $| = 1;
3742 select($PASSOUTw); $| = 1;
3743 select($PASSOUTw); $| = 1;
3744 select(STDOUT);
3745 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3746 }
3747
3748 # recv_pam_question(&conv, fd)
3749 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3750 # Returns 0 if the conversation is over, 1 if not.
3751 sub recv_pam_question
3752 {
3753 local ($conf, $fh) = @_;
3754 local $pr = $conf->{'PAMOUTr'};
3755 select($pr); $| = 1; select(STDOUT);
3756 local $line = <$pr>;
3757 $line =~ s/\r|\n//g;
3758 if (!$line) {
3759         $line = <$pr>;
3760         $line =~ s/\r|\n//g;
3761         }
3762 $conf->{'last'} = time();
3763 if (!$line) {
3764         # Failed!
3765         print $fh "0 PAM conversation error\n";
3766         return 0;
3767         }
3768 else {
3769         local ($type, $msg) = split(/\s+/, $line, 2);
3770         if ($type =~ /^x(\d+)/) {
3771                 # Pass this status code through
3772                 print $fh "$1 $msg\n";
3773                 return $1 == 2 || $1 == 0 ? 0 : 1;
3774                 }
3775         elsif ($type == PAM_PROMPT_ECHO_ON()) {
3776                 # A normal question
3777                 print $fh "1 $msg\n";
3778                 return 1;
3779                 }
3780         elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3781                 # A password
3782                 print $fh "3 $msg\n";
3783                 return 1;
3784                 }
3785         elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3786                 # A message that does not require a response
3787                 print $fh "4 $msg\n";
3788                 return 1;
3789                 }
3790         else {
3791                 # Unknown type!
3792                 print $fh "0 Unknown PAM message type $type\n";
3793                 return 0;
3794                 }
3795         }
3796 }
3797
3798 # send_pam_answer(&conv, answer)
3799 # Sends a response from the user to the PAM sub-process
3800 sub send_pam_answer
3801 {
3802 local ($conf, $answer) = @_;
3803 local $pw = $conf->{'PAMINw'};
3804 $conf->{'last'} = time();
3805 print $pw "$answer\n";
3806 }
3807
3808 # end_pam_conversation(&conv)
3809 # Clean up PAM conversation pipes and processes
3810 sub end_pam_conversation
3811 {
3812 local ($conv) = @_;
3813 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3814 if ($conv->{'PAMINr'}) {
3815         close($conv->{'PAMINr'});
3816         close($conv->{'PAMOUTr'});
3817         close($conv->{'PAMINw'});
3818         close($conv->{'PAMOUTw'});
3819         }
3820 delete($conversations{$conv->{'cid'}});
3821 }
3822
3823 # get_ipkeys(&miniserv)
3824 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3825 sub get_ipkeys
3826 {
3827 local (@rv, $k);
3828 foreach $k (keys %{$_[0]}) {
3829         if ($k =~ /^ipkey_(\S+)/) {
3830                 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3831                                  'key' => $_[0]->{$k},
3832                                  'index' => scalar(@rv) };
3833                 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3834                 push(@rv, $ipkey);
3835                 }
3836         }
3837 return @rv;
3838 }
3839
3840 # create_ssl_context(keyfile, [certfile])
3841 sub create_ssl_context
3842 {
3843 local ($keyfile, $certfile) = @_;
3844 local $ssl_ctx;
3845 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3846 $ssl_ctx ||= Net::SSLeay::CTX_new();
3847 $ssl_ctx || die "Failed to create SSL context : $!";
3848 if ($client_certs) {
3849         Net::SSLeay::CTX_load_verify_locations(
3850                 $ssl_ctx, $config{'ca'}, "");
3851         Net::SSLeay::CTX_set_verify(
3852                 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3853         }
3854 if ($config{'extracas'}) {
3855         local $p;
3856         foreach $p (split(/\s+/, $config{'extracas'})) {
3857                 Net::SSLeay::CTX_load_verify_locations(
3858                         $ssl_ctx, $p, "");
3859                 }
3860         }
3861
3862 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3863         $ssl_ctx, $keyfile,
3864         &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3865 Net::SSLeay::CTX_use_certificate_file(
3866         $ssl_ctx, $certfile || $keyfile,
3867         &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3868
3869 return $ssl_ctx;
3870 }
3871
3872 # ssl_connection_for_ip(socket)
3873 # Returns a new SSL connection object for some socket, or undef if failed
3874 sub ssl_connection_for_ip
3875 {
3876 local ($sock) = @_;
3877 local $sn = getsockname($sock);
3878 if (!$sn) {
3879         print STDERR "Failed to get address for socket $sock\n";
3880         return undef;
3881         }
3882 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3883 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3884 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3885 if ($config{'ssl_cipher_list'}) {
3886         # Force use of ciphers
3887         eval "Net::SSLeay::set_cipher_list(
3888                         \$ssl_con, \$config{'ssl_cipher_list'})";
3889         if ($@) {
3890                 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3891                              "$@\n";
3892                 }
3893         else {
3894                 }
3895         }
3896 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3897 if (!Net::SSLeay::accept($ssl_con)) {
3898         print STDERR "Failed to initialize SSL connection\n";
3899         return undef;
3900         }
3901 return $ssl_con;
3902 }
3903
3904 # login_redirect(username, password, host)
3905 # Calls the login redirect script (if configured), which may output a URL to
3906 # re-direct a user to after logging in.
3907 sub login_redirect
3908 {
3909 return undef if (!$config{'login_redirect'});
3910 local $quser = quotemeta($_[0]);
3911 local $qpass = quotemeta($_[1]);
3912 local $qhost = quotemeta($_[2]);
3913 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3914 chop($url);
3915 return $url;
3916 }
3917
3918 # reload_config_file()
3919 # Re-read %config, and call post-config actions
3920 sub reload_config_file
3921 {
3922 &log_error("Reloading configuration");
3923 %config = &read_config_file($config_file);
3924 &update_vital_config();
3925 &read_users_file();
3926 &read_mime_types();
3927 &build_config_mappings();
3928 &read_webmin_crons();
3929 if ($config{'session'}) {
3930         dbmclose(%sessiondb);
3931         dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3932         }
3933 }
3934
3935 # read_config_file(file)
3936 # Reads the given config file, and returns a hash of values
3937 sub read_config_file
3938 {
3939 local %rv;
3940 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3941 while(<CONF>) {
3942         s/\r|\n//g;
3943         if (/^#/ || !/\S/) { next; }
3944         /^([^=]+)=(.*)$/;
3945         $name = $1; $val = $2;
3946         $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3947         $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3948         $rv{$name} = $val;
3949         }
3950 close(CONF);
3951 return %rv;
3952 }
3953
3954 # update_vital_config()
3955 # Updates %config with defaults, and dies if something vital is missing
3956 sub update_vital_config
3957 {
3958 my %vital = ("port", 80,
3959           "root", "./",
3960           "server", "MiniServ/0.01",
3961           "index_docs", "index.html index.htm index.cgi index.php",
3962           "addtype_html", "text/html",
3963           "addtype_txt", "text/plain",
3964           "addtype_gif", "image/gif",
3965           "addtype_jpg", "image/jpeg",
3966           "addtype_jpeg", "image/jpeg",
3967           "realm", "MiniServ",
3968           "session_login", "/session_login.cgi",
3969           "pam_login", "/pam_login.cgi",
3970           "password_form", "/password_form.cgi",
3971           "password_change", "/password_change.cgi",
3972           "maxconns", 50,
3973           "pam", "webmin",
3974           "sidname", "sid",
3975           "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\$",
3976           "max_post", 10000,
3977           "expires", 7*24*60*60,
3978           "pam_test_user", "root",
3979          );
3980 foreach my $v (keys %vital) {
3981         if (!$config{$v}) {
3982                 if ($vital{$v} eq "") {
3983                         die "Missing config option $v";
3984                         }
3985                 $config{$v} = $vital{$v};
3986                 }
3987         }
3988 if (!$config{'sessiondb'}) {
3989         $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3990         $config{'sessiondb'} = "$1/sessiondb";
3991         }
3992 if (!$config{'errorlog'}) {
3993         $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3994         $config{'errorlog'} = "$1/miniserv.error";
3995         }
3996 if (!$config{'tempbase'}) {
3997         $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3998         $config{'tempbase'} = "$1/cgitemp";
3999         }
4000 if (!$config{'blockedfile'}) {
4001         $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4002         $config{'blockedfile'} = "$1/blocked";
4003         }
4004 if (!$config{'webmincron_dir'}) {
4005         $config_file =~ /^(.*)\/[^\/]+$/;
4006         $config{'webmincron_dir'} = "$1/webmincron/crons";
4007         }
4008 if (!$config{'webmincron_last'}) {
4009         $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4010         $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4011         }
4012 if (!$config{'webmincron_wrapper'}) {
4013         $config{'webmincron_wrapper'} = $config{'root'}.
4014                                         "/webmincron/webmincron.pl";
4015         }
4016 }
4017
4018 # read_users_file()
4019 # Fills the %users and %certs hashes from the users file in %config
4020 sub read_users_file
4021 {
4022 undef(%users);
4023 undef(%certs);
4024 undef(%allow);
4025 undef(%deny);
4026 undef(%allowdays);
4027 undef(%allowhours);
4028 undef(%lastchanges);
4029 undef(%nochange);
4030 undef(%temppass);
4031 if ($config{'userfile'}) {
4032         open(USERS, $config{'userfile'});
4033         while(<USERS>) {
4034                 s/\r|\n//g;
4035                 local @user = split(/:/, $_, -1);
4036                 $users{$user[0]} = $user[1];
4037                 $certs{$user[0]} = $user[3] if ($user[3]);
4038                 if ($user[4] =~ /^allow\s+(.*)/) {
4039                         $allow{$user[0]} = $config{'alwaysresolve'} ?
4040                                 [ split(/\s+/, $1) ] :
4041                                 [ &to_ipaddress(split(/\s+/, $1)) ];
4042                         }
4043                 elsif ($user[4] =~ /^deny\s+(.*)/) {
4044                         $deny{$user[0]} = $config{'alwaysresolve'} ?
4045                                 [ split(/\s+/, $1) ] :
4046                                 [ &to_ipaddress(split(/\s+/, $1)) ];
4047                         }
4048                 if ($user[5] =~ /days\s+(\S+)/) {
4049                         $allowdays{$user[0]} = [ split(/,/, $1) ];
4050                         }
4051                 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4052                         $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4053                         }
4054                 $lastchanges{$user[0]} = $user[6];
4055                 $nochange{$user[0]} = $user[9];
4056                 $temppass{$user[0]} = $user[10];
4057                 }
4058         close(USERS);
4059         }
4060 }
4061
4062 # get_user_details(username)
4063 # Returns a hash ref of user details, either from config files or the user DB
4064 # XXX fix all other user of %allow / etc to use this function
4065 sub get_user_details
4066 {
4067 my ($username) = @_;
4068 if (exists($users{$username})) {
4069         # In local files
4070         return { 'name' => $username,
4071                  'pass' => $users{$username},
4072                  'certs' => $certs{$username},
4073                  'allow' => $allow{$username},
4074                  'deny' => $deny{$username},
4075                  'allowdays' => $allowdays{$username},
4076                  'allowhours' => $allowhours{$username},
4077                  'lastchanges' => $lastchanges{$username},
4078                  'nochange' => $nochange{$username},
4079                  'temppass' => $temppass{$username},
4080                };
4081         }
4082 if ($config{'userdb'}) {
4083         # Try querying user database
4084         print DEBUG "get_user_details: Connecting to user database\n";
4085         my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4086         my $user;
4087         if (!ref($dbh)) {
4088                 print DEBUG "get_user_details: Failed : $dbh\n";
4089                 print STDERR "Failed to connect to user database : $dbh\n";
4090                 }
4091         elsif ($proto eq "mysql" || $proto eq "postgresql") {
4092                 # Fetch user ID and password with SQL
4093                 print DEBUG "get_user_details: Looking for $username\n";
4094                 my $cmd = $dbh->prepare(
4095                         "select id,pass from webmin_user where name = ?");
4096                 if (!$cmd || !$cmd->execute($username)) {
4097                         print STDERR "Failed to lookup user : ",
4098                                      $dbh->errstr,"\n";
4099                         return undef;
4100                         }
4101                 my ($id, $pass) = $cmd->fetchrow();
4102                 $cmd->finish();
4103                 if (!$id) {
4104                         &disconnect_userdb($config{'userdb'}, $dbh);
4105                         print DEBUG "get_user_details: User not found\n";
4106                         return undef;
4107                         }
4108                 print DEBUG "get_user_details: id=$id pass=$pass\n";
4109
4110                 # Fetch attributes and add to user object
4111                 print DEBUG "get_user_details: finding user attributes\n";
4112                 my $cmd = $dbh->prepare(
4113                         "select attr,value from webmin_user_attr where id = ?");
4114                 if (!$cmd || !$cmd->execute($id)) {
4115                         print STDERR "Failed to lookup user attrs : ",
4116                                      $dbh->errstr,"\n";
4117                         return undef;
4118                         }
4119                 $user = { 'name' => $username,
4120                           'id' => $id,
4121                           'pass' => $pass,
4122                           'proto' => $proto };
4123                 my %attrs;
4124                 while(my ($attr, $value) = $cmd->fetchrow()) {
4125                         $attrs{$attr} = $value;
4126                         }
4127                 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4128                             " attributes\n";
4129                 $cmd->finish();
4130                 $user->{'certs'} = $attrs{'cert'};
4131                 if ($attrs{'allow'}) {
4132                         $user->{'allow'} = $config{'alwaysresolve'} ?
4133                                 [ split(/\s+/, $attrs{'allow'}) ] :
4134                                 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4135                         }
4136                 if ($attrs{'deny'}) {
4137                         $user->{'deny'} = $config{'alwaysresolve'} ?
4138                                 [ split(/\s+/, $attrs{'deny'}) ] :
4139                                 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4140                         }
4141                 if ($attr{'days'}) {
4142                         $user->{'allowdays'} = [ split(/,/, $attr{'days'}) ];
4143                         }
4144                 if ($attr{'hoursfrom'} && $attr{'hoursto'}) {
4145                         my ($hf, $mf) = split(/\./, $attr{'hoursfrom'});
4146                         my ($ht, $mt) = split(/\./, $attr{'hoursto'});
4147                         $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4148                         }
4149                 $user->{'lastchanges'} = $attr{'lastchange'};
4150                 $user->{'nochange'} = $attr{'nochange'};
4151                 $user->{'temppass'} = $attr{'temppass'};
4152                 }
4153         elsif ($proto eq "ldap") {
4154                 # Fetch with LDAP
4155                 # XXX
4156                 }
4157         &disconnect_userdb($config{'userdb'}, $dbh);
4158         return $user;
4159         }
4160 return undef;
4161 }
4162
4163 # connect_userdb(string)
4164 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4165 # On failure returns an error message string. In an array context, returns the
4166 # protocol type too.
4167 sub connect_userdb
4168 {
4169 my ($str) = @_;
4170 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4171 if ($proto eq "mysql") {
4172         # Connect to MySQL with DBI
4173         my $drh = eval "use DBI; DBI->install_driver('mysql');";
4174         $drh || return $text{'sql_emysqldriver'};
4175         my ($host, $port) = split(/:/, $host);
4176         my $cstr = "database=$prefix;host=$host";
4177         $cstr .= ";port=$port" if ($port);
4178         print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4179         my $dbh = $drh->connect($cstr, $user, $pass, { });
4180         $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4181         print DEBUG "connect_userdb: Connected OK\n";
4182         return wantarray ? ($dbh, $proto) : $dbh;
4183         }
4184 elsif ($proto eq "postgresql") {
4185         # Connect to PostgreSQL with DBI
4186         my $drh = eval "use DBI; DBI->install_driver('Pg');";
4187         $drh || return $text{'sql_epostgresqldriver'};
4188         my ($host, $port) = split(/:/, $host);
4189         my $cstr = "dbname=$prefix;host=$host";
4190         $cstr .= ";port=$port" if ($port);
4191         print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4192         my $dbh = $drh->connect($cstr, $user, $pass);
4193         $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4194         print DEBUG "connect_userdb: Connected OK\n";
4195         return wantarray ? ($dbh, $proto) : $dbh;
4196         }
4197 elsif ($proto eq "ldap") {
4198         # XXX
4199         return "LDAP not done yet";
4200         }
4201 else {
4202         return "Unknown protocol $proto";
4203         }
4204 }
4205
4206 # split_userdb_string(string)
4207 # Converts a string like mysql://user:pass@host/db into separate parts
4208 sub split_userdb_string
4209 {
4210 my ($str) = @_;
4211 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4212         my ($proto, $user, $pass, $host, $prefix, $argstr) =
4213                 ($1, $2, $3, $4, $5, $7);
4214         my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4215         return ($proto, $user, $pass, $host, $prefix, \%args);
4216         }
4217 return ( );
4218 }
4219
4220 # disconnect_userdb(string, &handle)
4221 # Closes a handle opened by connect_userdb
4222 sub disconnect_userdb
4223 {
4224 my ($str, $h) = @_;
4225 if ($str =~ /^(mysql|postgresql):/) {
4226         # DBI disconnnect
4227         $h->disconnect();
4228         }
4229 elsif ($str =~ /^ldap:/) {
4230         # LDAP disconnect
4231         $h->disconnect();
4232         }
4233 }
4234
4235 # read_mime_types()
4236 # Fills %mime with entries from file in %config and extra settings in %config
4237 sub read_mime_types
4238 {
4239 undef(%mime);
4240 if ($config{"mimetypes"} ne "") {
4241         open(MIME, $config{"mimetypes"});
4242         while(<MIME>) {
4243                 chop; s/#.*$//;
4244                 if (/^(\S+)\s+(.*)$/) {
4245                         my $type = $1;
4246                         my @exts = split(/\s+/, $2);
4247                         foreach my $ext (@exts) {
4248                                 $mime{$ext} = $type;
4249                                 }
4250                         }
4251                 }
4252         close(MIME);
4253         }
4254 foreach my $k (keys %config) {
4255         if ($k !~ /^addtype_(.*)$/) { next; }
4256         $mime{$1} = $config{$k};
4257         }
4258 }
4259
4260 # build_config_mappings()
4261 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4262 # redirect mapping and allow and deny lists from %config
4263 sub build_config_mappings
4264 {
4265 # build anonymous access list
4266 undef(%anonymous);
4267 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4268         if ($a =~ /^([^=]+)=(\S+)$/) {
4269                 $anonymous{$1} = $2;
4270                 }
4271         }
4272
4273 # build IP access list
4274 undef(%ipaccess);
4275 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4276         if ($a =~ /^([^=]+)=(\S+)$/) {
4277                 $ipaccess{$1} = $2;
4278                 }
4279         }
4280
4281 # build unauthenticated URLs list
4282 @unauth = split(/\s+/, $config{'unauth'});
4283
4284 # build redirect mapping
4285 undef(%redirect);
4286 foreach my $r (split(/\s+/, $config{'redirect'})) {
4287         if ($r =~ /^([^=]+)=(\S+)$/) {
4288                 $redirect{$1} = $2;
4289                 }
4290         }
4291
4292 # build prefixes to be stripped
4293 undef(@strip_prefix);
4294 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4295         push(@strip_prefix, $r);
4296         }
4297
4298 # Init allow and deny lists
4299 @deny = split(/\s+/, $config{"deny"});
4300 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4301 @allow = split(/\s+/, $config{"allow"});
4302 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4303 undef(@allowusers);
4304 undef(@denyusers);
4305 if ($config{'allowusers'}) {
4306         @allowusers = split(/\s+/, $config{'allowusers'});
4307         }
4308 elsif ($config{'denyusers'}) {
4309         @denyusers = split(/\s+/, $config{'denyusers'});
4310         }
4311
4312 # Build list of unixauth mappings
4313 undef(%unixauth);
4314 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4315         if ($ua =~ /^(\S+)=(\S+)$/) {
4316                 $unixauth{$1} = $2;
4317                 }
4318         else {
4319                 $unixauth{"*"} = $ua;
4320                 }
4321         }
4322
4323 # Build list of non-session-auth pages
4324 undef(%sessiononly);
4325 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4326         $sessiononly{$sp} = 1;
4327         }
4328
4329 # Build list of logout times
4330 undef(@logouttimes);
4331 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4332         if ($a =~ /^([^=]+)=(\S+)$/) {
4333                 push(@logouttimes, [ $1, $2 ]);
4334                 }
4335         }
4336 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4337
4338 # Build list of DAV pathss
4339 undef(@davpaths);
4340 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4341         push(@davpaths, $d);
4342         }
4343 @davusers = split(/\s+/, $config{'dav_users'});
4344
4345 # Mobile agent substrings and hostname prefixes
4346 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4347 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4348
4349 # Open debug log
4350 close(DEBUG);
4351 if ($config{'debug'}) {
4352         open(DEBUG, ">>$config{'debug'}");
4353         }
4354 else {
4355         open(DEBUG, ">/dev/null");
4356         }
4357
4358 # Reset cache of sudo checks
4359 undef(%sudocache);
4360 }
4361
4362 # is_group_member(&uinfo, groupname)
4363 # Returns 1 if some user is a primary or secondary member of a group
4364 sub is_group_member
4365 {
4366 local ($uinfo, $group) = @_;
4367 local @ginfo = getgrnam($group);
4368 return 0 if (!@ginfo);
4369 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4370 foreach my $m (split(/\s+/, $ginfo[3])) {
4371         return 1 if ($m eq $uinfo->[0]);
4372         }
4373 return 0;
4374 }
4375
4376 # prefix_to_mask(prefix)
4377 # Converts a number like 24 to a mask like 255.255.255.0
4378 sub prefix_to_mask
4379 {
4380 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4381        $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4382        $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4383                      (256-(2 ** (8-$_[0]))).".0.0.0";
4384 }
4385
4386 # get_logout_time(user, session-id)
4387 # Given a username, returns the idle time before he will be logged out
4388 sub get_logout_time
4389 {
4390 local ($user, $sid) = @_;
4391 if (!defined($logout_time_cache{$user,$sid})) {
4392         local $time;
4393         foreach my $l (@logouttimes) {
4394                 if ($l->[0] =~ /^\@(.*)$/) {
4395                         # Check group membership
4396                         local @uinfo = getpwnam($user);
4397                         if (@uinfo && &is_group_member(\@uinfo, $1)) {
4398                                 $time = $l->[1];
4399                                 }
4400                         }
4401                 elsif ($l->[0] =~ /^\//) {
4402                         # Check file contents
4403                         open(FILE, $l->[0]);
4404                         while(<FILE>) {
4405                                 s/\r|\n//g;
4406                                 s/^\s*#.*$//;
4407                                 if ($user eq $_) {
4408                                         $time = $l->[1];
4409                                         last;
4410                                         }
4411                                 }
4412                         close(FILE);
4413                         }
4414                 elsif (!$l->[0]) {
4415                         # Always match
4416                         $time = $l->[1];
4417                         }
4418                 else {
4419                         # Check username
4420                         if ($l->[0] eq $user) {
4421                                 $time = $l->[1];
4422                                 }
4423                         }
4424                 last if (defined($time));
4425                 }
4426         $logout_time_cache{$user,$sid} = $time;
4427         }
4428 return $logout_time_cache{$user,$sid};
4429 }
4430
4431 # password_crypt(password, salt)
4432 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4433 # of a password. Otherwise, do Unix crypt.
4434 sub password_crypt
4435 {
4436 local ($pass, $salt) = @_;
4437 if ($salt =~ /^\$1\$/ && $use_md5) {
4438         return &encrypt_md5($pass, $salt);
4439         }
4440 else {
4441         return &unix_crypt($pass, $salt);
4442         }
4443 }
4444
4445 # unix_crypt(password, salt)
4446 # Performs standard Unix hashing for a password
4447 sub unix_crypt
4448 {
4449 local ($pass, $salt) = @_;
4450 if ($use_perl_crypt) {
4451         return Crypt::UnixCrypt::crypt($pass, $salt);
4452         }
4453 else {
4454         return crypt($pass, $salt);
4455         }
4456 }
4457
4458 # handle_dav_request(davpath)
4459 # Pass a request on to the Net::DAV::Server module
4460 sub handle_dav_request
4461 {
4462 local ($path) = @_;
4463 eval "use Filesys::Virtual::Plain";
4464 eval "use Net::DAV::Server";
4465 eval "use HTTP::Request";
4466 eval "use HTTP::Headers";
4467
4468 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4469         delete $Net::DAV::Server::implemented{lock};
4470         delete $Net::DAV::Server::implemented{unlock};
4471         }
4472
4473 # Read in request data
4474 if (!$posted_data) {
4475         local $clen = $header{"content-length"};
4476         while(length($posted_data) < $clen) {
4477                 $buf = &read_data($clen - length($posted_data));
4478                 if (!length($buf)) {
4479                         &http_error(500, "Failed to read POST request");
4480                         }
4481                 $posted_data .= $buf;
4482                 }
4483         }
4484
4485 # For subsequent logging
4486 open(MINISERVLOG, ">>$config{'logfile'}");
4487
4488 # Switch to user
4489 local $root;
4490 local @u = getpwnam($authuser);
4491 if ($config{'dav_remoteuser'} && !$< && $validated) {
4492         if (@u) {
4493                 if ($u[2] != 0) {
4494                         $( = $u[3]; $) = "$u[3] $u[3]";
4495                         ($>, $<) = ($u[2], $u[2]);
4496                         }
4497                 if ($config{'dav_root'} eq '*') {
4498                         $root = $u[7];
4499                         }
4500                 }
4501         else {
4502                 &http_error(500, "Unix user $authuser does not exist");
4503                 return 0;
4504                 }
4505         }
4506 $root ||= $config{'dav_root'};
4507 $root ||= "/";
4508
4509 # Check if this user can use DAV
4510 if (@davusers) {
4511         &users_match(\@u, @davusers) ||
4512                 &http_error(500, "You are not allowed to access DAV");
4513         }
4514
4515 # Create DAV server
4516 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4517 my $webdav = Net::DAV::Server->new();
4518 $webdav->filesys($filesys);
4519
4520 # Make up a request object, and feed to DAV
4521 local $ho = HTTP::Headers->new;
4522 foreach my $h (keys %header) {
4523         next if (lc($h) eq "connection");
4524         $ho->header($h => $header{$h});
4525         }
4526 if ($path ne "/") {
4527         $request_uri =~ s/^\Q$path\E//;
4528         $request_uri = "/" if ($request_uri eq "");
4529         }
4530 my $request = HTTP::Request->new($method, $request_uri, $ho,
4531                                  $posted_data);
4532 if ($config{'dav_debug'}) {
4533         print STDERR "DAV request :\n";
4534         print STDERR "---------------------------------------------\n";
4535         print STDERR $request->as_string();
4536         print STDERR "---------------------------------------------\n";
4537         }
4538 my $response = $webdav->run($request);
4539
4540 # Send back the reply
4541 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4542 local $content = $response->content();
4543 if ($path ne "/") {
4544         $content =~ s|href>/(.+)<|href>$path/$1<|g;
4545         $content =~ s|href>/<|href>$path<|g;
4546         }
4547 foreach my $h ($response->header_field_names) {
4548         next if (lc($h) eq "connection" || lc($h) eq "content-length");
4549         &write_data("$h: ",$response->header($h),"\r\n");
4550         }
4551 &write_data("Content-length: ",length($content),"\r\n");
4552 local $rv = &write_keep_alive(0);
4553 &write_data("\r\n");
4554 &write_data($content);
4555
4556 if ($config{'dav_debug'}) {
4557         print STDERR "DAV reply :\n";
4558         print STDERR "---------------------------------------------\n";
4559         print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4560         foreach my $h ($response->header_field_names) {
4561                 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4562                 print STDERR "$h: ",$response->header($h),"\r\n";
4563                 }
4564         print STDERR "Content-length: ",length($content),"\r\n";
4565         print STDERR "\r\n";
4566         print STDERR $content;
4567         print STDERR "---------------------------------------------\n";
4568         }
4569
4570 # Log it
4571 &log_request($acpthost, $authuser, $reqline, $response->code(), 
4572              length($response->content()));
4573 }
4574
4575 # get_system_hostname()
4576 # Returns the hostname of this system, for reporting to listeners
4577 sub get_system_hostname
4578 {
4579 # On Windows, try computername environment variable
4580 return $ENV{'computername'} if ($ENV{'computername'});
4581 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4582
4583 # If a specific command is set, use it first
4584 if ($config{'hostname_command'}) {
4585         local $out = `($config{'hostname_command'}) 2>&1`;
4586         if (!$?) {
4587                 $out =~ s/\r|\n//g;
4588                 return $out;
4589                 }
4590         }
4591
4592 # First try the hostname command
4593 local $out = `hostname 2>&1`;
4594 if (!$? && $out =~ /\S/) {
4595         $out =~ s/\r|\n//g;
4596         return $out;
4597         }
4598
4599 # Try the Sys::Hostname module
4600 eval "use Sys::Hostname";
4601 if (!$@) {
4602         local $rv = eval "hostname()";
4603         if (!$@ && $rv) {
4604                 return $rv;
4605                 }
4606         }
4607
4608 # Must use net name on Windows
4609 local $out = `net name 2>&1`;
4610 if ($out =~ /\-+\r?\n(\S+)/) {
4611         return $1;
4612         }
4613
4614 return undef;
4615 }
4616
4617 # indexof(string, array)
4618 # Returns the index of some value in an array, or -1
4619 sub indexof {
4620   local($i);
4621   for($i=1; $i <= $#_; $i++) {
4622     if ($_[$i] eq $_[0]) { return $i - 1; }
4623   }
4624   return -1;
4625 }
4626
4627
4628 # has_command(command)
4629 # Returns the full path if some command is in the path, undef if not
4630 sub has_command
4631 {
4632 local($d);
4633 if (!$_[0]) { return undef; }
4634 if (exists($has_command_cache{$_[0]})) {
4635         return $has_command_cache{$_[0]};
4636         }
4637 local $rv = undef;
4638 if ($_[0] =~ /^\//) {
4639         $rv = -x $_[0] ? $_[0] : undef;
4640         }
4641 else {
4642         local $sp = $on_windows ? ';' : ':';
4643         foreach $d (split($sp, $ENV{PATH})) {
4644                 if (-x "$d/$_[0]") {
4645                         $rv = "$d/$_[0]";
4646                         last;
4647                         }
4648                 if ($on_windows) {
4649                         foreach my $sfx (".exe", ".com", ".bat") {
4650                                 if (-r "$d/$_[0]".$sfx) {
4651                                         $rv = "$d/$_[0]".$sfx;
4652                                         last;
4653                                         }
4654                                 }
4655                         }
4656                 }
4657         }
4658 $has_command_cache{$_[0]} = $rv;
4659 return $rv;
4660 }
4661
4662 # check_sudo_permissions(user, pass)
4663 # Returns 1 if some user can run any command via sudo
4664 sub check_sudo_permissions
4665 {
4666 local ($user, $pass) = @_;
4667
4668 # First try the pipes
4669 if ($PASSINw) {
4670         print DEBUG "check_sudo_permissions: querying cache for $user\n";
4671         print $PASSINw "readsudo $user\n";
4672         local $can = <$PASSOUTr>;
4673         chop($can);
4674         print DEBUG "check_sudo_permissions: cache said $can\n";
4675         if ($can =~ /^\d+$/ && $can != 2) {
4676                 return int($can);
4677                 }
4678         }
4679
4680 local $ptyfh = new IO::Pty;
4681 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4682 if (!$ptyfh) {
4683         print STDERR "Failed to create new PTY with IO::Pty\n";
4684         return 0;
4685         }
4686 local @uinfo = getpwnam($user);
4687 if (!@uinfo) {
4688         print STDERR "Unix user $user does not exist for sudo\n";
4689         return 0;
4690         }
4691
4692 # Execute sudo in a sub-process, via a pty
4693 local $ttyfh = $ptyfh->slave();
4694 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4695 local $tty = $ptyfh->ttyname();
4696 print DEBUG "check_sudo_permissions: tty=$tty\n";
4697 chown($uinfo[2], $uinfo[3], $tty);
4698 pipe(SUDOr, SUDOw);
4699 print DEBUG "check_sudo_permissions: about to fork..\n";
4700 local $pid = fork();
4701 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4702 if ($pid < 0) {
4703         print STDERR "fork for sudo failed : $!\n";
4704         return 0;
4705         }
4706 if (!$pid) {
4707         setsid();
4708         $ptyfh->make_slave_controlling_terminal();
4709         close(STDIN); close(STDOUT); close(STDERR);
4710         untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4711         close($PASSINw); close($PASSOUTr);
4712         $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4713         ($>, $<) = ($uinfo[2], $uinfo[2]);
4714
4715         close(SUDOw);
4716         close(SOCK);
4717         close(MAIN);
4718         open(STDIN, "<&SUDOr");
4719         open(STDOUT, ">$tty");
4720         open(STDERR, ">&STDOUT");
4721         close($ptyfh);
4722         exec("sudo -l -S");
4723         print "Exec failed : $!\n";
4724         exit 1;
4725         }
4726 print DEBUG "check_sudo_permissions: pid=$pid\n";
4727 close(SUDOr);
4728 $ptyfh->close_slave();
4729
4730 # Send password, and get back response
4731 local $oldfh = select(SUDOw);
4732 $| = 1;
4733 select($oldfh);
4734 print DEBUG "check_sudo_permissions: about to send pass\n";
4735 local $SIG{'PIPE'} = 'ignore';  # Sometimes sudo doesn't ask for a password
4736 print SUDOw $pass,"\n";
4737 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4738 close(SUDOw);
4739 local $out;
4740 while(<$ptyfh>) {
4741         print DEBUG "check_sudo_permissions: got $_";
4742         $out .= $_;
4743         }
4744 close($ptyfh);
4745 kill('KILL', $pid);
4746 waitpid($pid, 0);
4747 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4748
4749 # Update cache
4750 if ($PASSINw) {
4751         print $PASSINw "writesudo $user $ok\n";
4752         }
4753
4754 return $ok;
4755 }
4756
4757 # is_mobile_useragent(agent)
4758 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4759 # such as a treo.
4760 sub is_mobile_useragent
4761 {
4762 local ($agent) = @_;
4763 local @prefixes = ( 
4764     "UP.Link",    # Openwave
4765     "Nokia",      # All Nokias start with Nokia
4766     "MOT-",       # All Motorola phones start with MOT-
4767     "SAMSUNG",    # Samsung browsers
4768     "Samsung",    # Samsung browsers
4769     "SEC-",       # Samsung browsers
4770     "AU-MIC",     # Samsung browsers
4771     "AUDIOVOX",   # Audiovox
4772     "BlackBerry", # BlackBerry
4773     "hiptop",     # Danger hiptop Sidekick
4774     "SonyEricsson", # Sony Ericsson
4775     "Ericsson",     # Old Ericsson browsers , mostly WAP
4776     "Mitsu/1.1.A",  # Mitsubishi phones
4777     "Panasonic WAP", # Panasonic old WAP phones
4778     "DoCoMo",     # DoCoMo phones
4779     "Lynx",       # Lynx text-mode linux browser
4780     "Links",      # Another text-mode linux browser
4781     );
4782 local @substrings = (
4783     "UP.Browser",         # Openwave
4784     "MobilePhone",        # NetFront
4785     "AU-MIC-A700",        # Samsung A700 Obigo browsers
4786     "Danger hiptop",      # Danger Sidekick hiptop
4787     "Windows CE",         # Windows CE Pocket PC
4788     "IEMobile",           # Windows mobile browser
4789     "Blazer",             # Palm Treo Blazer
4790     "BlackBerry",         # BlackBerries can emulate other browsers, but
4791                           # they still keep this string in the UserAgent
4792     "SymbianOS",          # New Series60 browser has safari in it and
4793                           # SymbianOS is the only distinguishing string
4794     "iPhone",             # Apple iPhone KHTML browser
4795     "iPod",               # iPod touch browser
4796     "MobileSafari",       # HTTP client in iPhone
4797     "Android",            # gPhone
4798     "Opera Mini",         # Opera Mini
4799     "HTC_P3700",          # HTC mobile device
4800     "Pre/",               # Palm Pre
4801     "webOS/",             # Palm WebOS
4802     "Nintendo DS",        # DSi / DSi-XL
4803     );
4804 foreach my $p (@prefixes) {
4805         return 1 if ($agent =~ /^\Q$p\E/);
4806         }
4807 foreach my $s (@substrings, @mobile_agents) {
4808         return 1 if ($agent =~ /\Q$s\E/);
4809         }
4810 return 0;
4811 }
4812
4813 # write_blocked_file()
4814 # Writes out a text file of blocked hosts and users
4815 sub write_blocked_file
4816 {
4817 open(BLOCKED, ">$config{'blockedfile'}");
4818 foreach my $d (grep { $hostfail{$_} } @deny) {
4819         print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4820         }
4821 foreach my $d (grep { $userfail{$_} } @denyusers) {
4822         print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4823         }
4824 close(BLOCKED);
4825 chmod(0700, $config{'blockedfile'});
4826 }
4827
4828 sub write_pid_file
4829 {
4830 open(PIDFILE, ">$config{'pidfile'}");
4831 printf PIDFILE "%d\n", getpid();
4832 close(PIDFILE);
4833 $miniserv_main_pid = getpid();
4834 }
4835
4836 # lock_user_password(user)
4837 # Updates a user's password file entry to lock it, both in memory and on disk.
4838 # Returns 1 if done, -1 if no such user, 0 if already locked
4839 sub lock_user_password
4840 {
4841 local ($user) = @_;
4842 if ($users{$user}) {
4843         if ($users{$user} !~ /^\!/) {
4844                 # Lock the password
4845                 # XXX update user DB
4846                 $users{$user} = "!".$users{$user};
4847                 open(USERS, $config{'userfile'});
4848                 local @ufile = <USERS>;
4849                 close(USERS);
4850                 foreach my $u (@ufile) {
4851                         local @uinfo = split(/:/, $u);
4852                         if ($uinfo[0] eq $user) {
4853                                 $uinfo[1] = $users{$user};
4854                                 }
4855                         $u = join(":", @uinfo);
4856                         }
4857                 open(USERS, ">$config{'userfile'}");
4858                 print USERS @ufile;
4859                 close(USERS);
4860                 return 1;
4861                 }
4862         return 0;
4863         }
4864 return -1;
4865 }
4866
4867 # hash_session_id(sid)
4868 # Returns an MD5 or Unix-crypted session ID
4869 sub hash_session_id
4870 {
4871 local ($sid) = @_;
4872 if (!$hash_session_id_cache{$sid}) {
4873         if ($use_md5) {
4874                 # Take MD5 hash
4875                 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4876                 }
4877         else {
4878                 # Unix crypt
4879                 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4880                 }
4881         }
4882 return $hash_session_id_cache{$sid};
4883 }
4884
4885 # encrypt_md5(string, [salt])
4886 # Returns a string encrypted in MD5 format
4887 sub encrypt_md5
4888 {
4889 local ($passwd, $salt) = @_;
4890 local $magic = '$1$';
4891 if ($salt =~ /^\$1\$([^\$]+)/) {
4892         # Extract actual salt from already encrypted password
4893         $salt = $1;
4894         }
4895
4896 # Add the password
4897 local $ctx = eval "new $use_md5";
4898 $ctx->add($passwd);
4899 if ($salt) {
4900         $ctx->add($magic);
4901         $ctx->add($salt);
4902         }
4903
4904 # Add some more stuff from the hash of the password and salt
4905 local $ctx1 = eval "new $use_md5";
4906 $ctx1->add($passwd);
4907 if ($salt) {
4908         $ctx1->add($salt);
4909         }
4910 $ctx1->add($passwd);
4911 local $final = $ctx1->digest();
4912 for($pl=length($passwd); $pl>0; $pl-=16) {
4913         $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4914         }
4915
4916 # This piece of code seems rather pointless, but it's in the C code that
4917 # does MD5 in PAM so it has to go in!
4918 local $j = 0;
4919 local ($i, $l);
4920 for($i=length($passwd); $i; $i >>= 1) {
4921         if ($i & 1) {
4922                 $ctx->add("\0");
4923                 }
4924         else {
4925                 $ctx->add(substr($passwd, $j, 1));
4926                 }
4927         }
4928 $final = $ctx->digest();
4929
4930 if ($salt) {
4931         # This loop exists only to waste time
4932         for($i=0; $i<1000; $i++) {
4933                 $ctx1 = eval "new $use_md5";
4934                 $ctx1->add($i & 1 ? $passwd : $final);
4935                 $ctx1->add($salt) if ($i % 3);
4936                 $ctx1->add($passwd) if ($i % 7);
4937                 $ctx1->add($i & 1 ? $final : $passwd);
4938                 $final = $ctx1->digest();
4939                 }
4940         }
4941
4942 # Convert the 16-byte final string into a readable form
4943 local $rv;
4944 local @final = map { ord($_) } split(//, $final);
4945 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4946 $rv .= &to64($l, 4);
4947 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4948 $rv .= &to64($l, 4);
4949 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4950 $rv .= &to64($l, 4);
4951 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4952 $rv .= &to64($l, 4);
4953 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4954 $rv .= &to64($l, 4);
4955 $l = $final[11];
4956 $rv .= &to64($l, 2);
4957
4958 # Add salt if needed
4959 if ($salt) {
4960         return $magic.$salt.'$'.$rv;
4961         }
4962 else {
4963         return $rv;
4964         }
4965 }
4966
4967 sub to64
4968 {
4969 local ($v, $n) = @_;
4970 local $r;
4971 while(--$n >= 0) {
4972         $r .= $itoa64[$v & 0x3f];
4973         $v >>= 6;
4974         }
4975 return $r;
4976 }
4977
4978 # read_file(file, &assoc, [&order], [lowercase])
4979 # Fill an associative array with name=value pairs from a file
4980 sub read_file
4981 {
4982 open(ARFILE, $_[0]) || return 0;
4983 while(<ARFILE>) {
4984         s/\r|\n//g;
4985         if (!/^#/ && /^([^=]*)=(.*)$/) {
4986                 $_[1]->{$_[3] ? lc($1) : $1} = $2;
4987                 push(@{$_[2]}, $1) if ($_[2]);
4988                 }
4989         }
4990 close(ARFILE);
4991 return 1;
4992 }
4993  
4994 # write_file(file, array)
4995 # Write out the contents of an associative array as name=value lines
4996 sub write_file
4997 {
4998 local(%old, @order);
4999 &read_file($_[0], \%old, \@order);
5000 open(ARFILE, ">$_[0]");
5001 foreach $k (@order) {
5002         print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5003         }
5004 foreach $k (keys %{$_[1]}) {
5005         print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5006         }
5007 close(ARFILE);
5008 }
5009
5010 # execute_ready_webmin_crons()
5011 # Find and run any cron jobs that are due, based on their last run time and
5012 # execution interval
5013 sub execute_ready_webmin_crons
5014 {
5015 my $now = time();
5016 my $changed = 0;
5017 foreach my $cron (@webmincrons) {
5018         my $run = 0;
5019         if (!$webmincron_last{$cron->{'id'}}) {
5020                 # If not ever run before, don't run right away
5021                 $webmincron_last{$cron->{'id'}} = $now;
5022                 $changed = 1;
5023                 }
5024         elsif ($cron->{'interval'} &&
5025                $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5026                 # Older than interval .. time to run
5027                 $run = 1;
5028                 }
5029         elsif ($cron->{'mins'}) {
5030                 # Check if current time matches spec, and we haven't run in the
5031                 # last minute
5032                 my @tm = localtime($now);
5033                 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5034                     &matches_cron($cron->{'hours'}, $tm[2]) &&
5035                     &matches_cron($cron->{'days'}, $tm[3]) &&
5036                     &matches_cron($cron->{'months'}, $tm[4]+1) &&
5037                     &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5038                     $now - $webmincron_last{$cron->{'id'}} > 60) {
5039                         $run = 1;
5040                         }
5041                 }
5042
5043         if ($run) {
5044                 print DEBUG "Running cron id=$cron->{'id'} ".
5045                             "module=$cron->{'module'} func=$cron->{'func'}\n";
5046                 $webmincron_last{$cron->{'id'}} = $now;
5047                 $changed = 1;
5048                 my $pid = fork();
5049                 if (!$pid) {
5050                         # Run via a wrapper command, which we run like a CGI
5051
5052                         # Setup CGI-like environment
5053                         $envtz = $ENV{"TZ"};
5054                         $envuser = $ENV{"USER"};
5055                         $envpath = $ENV{"PATH"};
5056                         $envlang = $ENV{"LANG"};
5057                         $envroot = $ENV{"SystemRoot"};
5058                         $envperllib = $ENV{'PERLLIB'};
5059                         foreach my $k (keys %ENV) {
5060                                 delete($ENV{$k});
5061                                 }
5062                         $ENV{"PATH"} = $envpath if ($envpath);
5063                         $ENV{"TZ"} = $envtz if ($envtz);
5064                         $ENV{"USER"} = $envuser if ($envuser);
5065                         $ENV{"OLD_LANG"} = $envlang if ($envlang);
5066                         $ENV{"SystemRoot"} = $envroot if ($envroot);
5067                         $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5068                         $ENV{"HOME"} = $user_homedir;
5069                         $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5070                         $ENV{"SERVER_ADMIN"} = $config{"email"};
5071                         $root0 = $roots[0];
5072                         $ENV{"SERVER_ROOT"} = $root0;
5073                         $ENV{"SERVER_REALROOT"} = $root0;
5074                         $ENV{"SERVER_PORT"} = $config{'port'};
5075                         $ENV{"WEBMIN_CRON"} = 1;
5076                         $ENV{"DOCUMENT_ROOT"} = $root0;
5077                         $ENV{"DOCUMENT_REALROOT"} = $root0;
5078                         $ENV{"MINISERV_CONFIG"} = $config_file;
5079                         $ENV{"HTTPS"} = "ON" if ($use_ssl);
5080                         $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5081                         $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5082                         if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5083                                 $ENV{"SCRIPT_NAME"} = $1;
5084                                 }
5085                         $config{'webmincron_wrapper'} =~ /^(.*)\//;
5086                         $ENV{"PWD"} = $1;
5087                         foreach $k (keys %config) {
5088                                 if ($k =~ /^env_(\S+)$/) {
5089                                         $ENV{$1} = $config{$k};
5090                                         }
5091                                 }
5092                         chdir($ENV{"PWD"});
5093                         $SIG{'CHLD'} = 'DEFAULT';
5094                         eval {
5095                                 # Have SOCK closed if the perl exec's something
5096                                 use Fcntl;
5097                                 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5098                                 };
5099
5100                         # Run the wrapper script by evaling it
5101                         $pkg = "webmincron";
5102                         $0 = $config{'webmincron_wrapper'};
5103                         @ARGV = ( $cron );
5104                         $main_process_id = $$;
5105                         eval "
5106                                 \%pkg::ENV = \%ENV;
5107                                 package $pkg;
5108                                 do \$miniserv::config{'webmincron_wrapper'};
5109                                 die \$@ if (\$@);
5110                                 ";
5111                         if ($@) {
5112                                 print STDERR "Perl cron failure : $@\n";
5113                                 }
5114
5115                         exit(0);
5116                         }
5117                 push(@childpids, $pid);
5118                 }
5119         }
5120 if ($changed) {
5121         # Write out file containing last run times
5122         &write_file($config{'webmincron_last'}, \%webmincron_last);
5123         }
5124 }
5125
5126 # matches_cron(cron-spec, time)
5127 # Checks if some minute or hour matches some cron spec, which can be * or a list
5128 # of numbers.
5129 sub matches_cron
5130 {
5131 my ($spec, $tm) = @_;
5132 if ($spec eq '*') {
5133         return 1;
5134         }
5135 else {
5136         foreach my $s (split(/,/, $spec)) {
5137                 if ($s == $tm ||
5138                     $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5139                         return 1;
5140                         }
5141                 }
5142         return 0;
5143         }
5144 }
5145
5146 # read_webmin_crons()
5147 # Read all scheduled webmin cron functions and store them in the @webmincrons
5148 # global list
5149 sub read_webmin_crons
5150 {
5151 @webmincrons = ( );
5152 opendir(CRONS, $config{'webmincron_dir'});
5153 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5154 foreach my $f (readdir(CRONS)) {
5155         if ($f =~ /^(\d+)\.cron$/) {
5156                 my %cron;
5157                 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5158                 $cron{'id'} = $1;
5159                 my $broken = 0;
5160                 foreach my $n ('module', 'func') {
5161                         if (!$cron{$n}) {
5162                                 print STDERR "Cron $1 missing $n\n";
5163                                 $broken = 1;
5164                                 }
5165                         }
5166                 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5167                         print STDERR "Cron $1 missing any time spec\n";
5168                         $broken = 1;
5169                         }
5170                 if ($cron{'special'} eq 'hourly') {
5171                         # Run every hour on the hour
5172                         $cron{'mins'} = 0;
5173                         $cron{'hours'} = '*';
5174                         $cron{'days'} = '*';
5175                         $cron{'months'} = '*';
5176                         $cron{'weekdays'} = '*';
5177                         }
5178                 elsif ($cron{'special'} eq 'daily') {
5179                         # Run every day at midnight
5180                         $cron{'mins'} = 0;
5181                         $cron{'hours'} = '0';
5182                         $cron{'days'} = '*';
5183                         $cron{'months'} = '*';
5184                         $cron{'weekdays'} = '*';
5185                         }
5186                 elsif ($cron{'special'} eq 'monthly') {
5187                         # Run every month on the 1st
5188                         $cron{'mins'} = 0;
5189                         $cron{'hours'} = '0';
5190                         $cron{'days'} = '1';
5191                         $cron{'months'} = '*';
5192                         $cron{'weekdays'} = '*';
5193                         }
5194                 elsif ($cron{'special'} eq 'weekly') {
5195                         # Run every month on the 1st
5196                         $cron{'mins'} = 0;
5197                         $cron{'hours'} = '0';
5198                         $cron{'days'} = '*';
5199                         $cron{'months'} = '*';
5200                         $cron{'weekdays'} = '0';
5201                         }
5202                 elsif ($cron{'special'} eq 'yearly' ||
5203                        $cron{'special'} eq 'annually') {
5204                         # Run every year on 1st january
5205                         $cron{'mins'} = 0;
5206                         $cron{'hours'} = '0';
5207                         $cron{'days'} = '1';
5208                         $cron{'months'} = '1';
5209                         $cron{'weekdays'} = '*';
5210                         }
5211                 elsif ($cron{'special'}) {
5212                         print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5213                         $broken = 1;
5214                         }
5215                 if ($cron{'special'}) {
5216                         delete($cron{'special'});
5217                         }
5218                 if (!$broken) {
5219                         print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5220                         push(@webmincrons, \%cron);
5221                         }
5222                 }
5223         }
5224 }