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