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