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