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