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