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