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