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