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