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