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