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