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