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