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