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