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