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