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