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