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