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