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