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