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