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