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