1 =head1 web-lib-funcs.pl
3 Common functions for Webmin CGI scripts. This file gets in-directly included
4 by all scripts that use web-lib.pl.
9 ui_print_header(undef, 'My Module', '');
10 print 'This is Webmin version ',get_webmin_version(),'<p>\n';
18 use vars qw($user_risk_level $loaded_theme_library $wait_for_input
19 $done_webmin_header $trust_unknown_referers $unsafe_index_cgi
20 %done_foreign_require $webmin_feedback_address
21 $user_skill_level $pragma_no_cache $foreign_args);
23 =head2 read_file(file, &hash, [&order], [lowercase], [split-char])
25 Fill the given hash reference with name=value pairs from a file. The required
28 =item file - The file to head, which must be text with each line like name=value
30 =item hash - The hash reference to add values read from the file to.
32 =item order - If given, an array reference to add names to in the order they were read
34 =item lowercase - If set to 1, names are converted to lower case
36 =item split-char - If set, names and values are split on this character instead of =
42 my $split = defined($_[4]) ? $_[4] : "=";
43 my $realfile = &translate_filename($_[0]);
44 &open_readfile(ARFILE, $_[0]) || return 0;
47 my $hash = index($_, "#");
48 my $eq = index($_, $split);
49 if ($hash != 0 && $eq >= 0) {
50 my $n = substr($_, 0, $eq);
51 my $v = substr($_, $eq+1);
53 $_[1]->{$_[3] ? lc($n) : $n} = $v;
54 push(@{$_[2]}, $n) if ($_[2]);
58 $main::read_file_missing{$realfile} = 0; # It exists now
59 if (defined($main::read_file_cache{$realfile})) {
60 %{$main::read_file_cache{$realfile}} = %{$_[1]};
65 =head2 read_file_cached(file, &hash, [&order], [lowercase], [split-char])
67 Like read_file, but reads from an in-memory cache if the file has already been
68 read in this Webmin script. Recommended, as it behaves exactly the same as
69 read_file, but can be much faster.
74 my $realfile = &translate_filename($_[0]);
75 if (defined($main::read_file_cache{$realfile})) {
77 %{$_[1]} = ( %{$_[1]}, %{$main::read_file_cache{$realfile}} );
80 elsif ($main::read_file_missing{$realfile}) {
81 # Doesn't exist, so don't re-try read
85 # Actually read the file
87 if (&read_file($_[0], \%d, $_[2], $_[3], $_[4])) {
88 %{$main::read_file_cache{$realfile}} = %d;
89 %{$_[1]} = ( %{$_[1]}, %d );
93 # Flag as non-existant
94 $main::read_file_missing{$realfile} = 1;
100 =head2 write_file(file, &hash, [join-char])
102 Write out the contents of a hash as name=value lines. The parameters are :
104 =item file - Full path to write to
106 =item hash - A hash reference containing names and values to output
108 =item join-char - If given, names and values are separated by this instead of =
114 my $join = defined($_[2]) ? $_[2] : "=";
115 my $realfile = &translate_filename($_[0]);
116 &read_file($_[0], \%old, \@order);
117 &open_tempfile(ARFILE, ">$_[0]");
118 foreach $k (@order) {
119 if (exists($_[1]->{$k})) {
120 (print ARFILE $k,$join,$_[1]->{$k},"\n") ||
121 &error(&text("efilewrite", $realfile, $!));
124 foreach $k (keys %{$_[1]}) {
125 if (!exists($old{$k})) {
126 (print ARFILE $k,$join,$_[1]->{$k},"\n") ||
127 &error(&text("efilewrite", $realfile, $!));
130 &close_tempfile(ARFILE);
131 if (defined($main::read_file_cache{$realfile})) {
132 %{$main::read_file_cache{$realfile}} = %{$_[1]};
134 if (defined($main::read_file_missing{$realfile})) {
135 $main::read_file_missing{$realfile} = 0;
139 =head2 html_escape(string)
141 Converts &, < and > codes in text to HTML entities, and returns the new string.
142 This should be used when including data read from other sources in HTML pages.
151 $tmp =~ s/\"/"/g;
152 $tmp =~ s/\'/'/g;
157 =head2 quote_escape(string, [only-quote])
159 Converts ' and " characters in a string into HTML entities, and returns it.
160 Useful for outputing HTML tag values.
165 my ($tmp, $only) = @_;
166 if ($tmp !~ /\&[a-zA-Z]+;/ && $tmp !~ /\&#/) {
167 # convert &, unless it is part of &#nnn; or &foo;
168 $tmp =~ s/&([^#])/&$1/g;
170 $tmp =~ s/&$/&/g;
171 $tmp =~ s/\"/"/g if ($only eq '' || $only eq '"');
172 $tmp =~ s/\'/'/g if ($only eq '' || $only eq "'");
176 =head2 tempname([filename])
178 Returns a mostly random temporary file name, typically under the /tmp/.webmin
179 directory. If filename is given, this will be the base name used. Otherwise
180 a unique name is selected randomly.
185 my $tmp_base = $gconfig{'tempdir_'.&get_module_name()} ?
186 $gconfig{'tempdir_'.&get_module_name()} :
187 $gconfig{'tempdir'} ? $gconfig{'tempdir'} :
188 $ENV{'TEMP'} ? $ENV{'TEMP'} :
189 $ENV{'TMP'} ? $ENV{'TMP'} :
190 -d "c:/temp" ? "c:/temp" : "/tmp/.webmin";
191 my $tmp_dir = -d $remote_user_info[7] && !$gconfig{'nohometemp'} ?
192 "$remote_user_info[7]/.tmp" :
193 @remote_user_info ? $tmp_base."-".$remote_user :
194 $< != 0 ? $tmp_base."-".getpwuid($<) :
196 if ($gconfig{'os_type'} eq 'windows' || $tmp_dir =~ /^[a-z]:/i) {
197 # On Windows system, just create temp dir if missing
199 mkdir($tmp_dir, 0755) ||
200 &error("Failed to create temp directory $tmp_dir : $!");
204 # On Unix systems, need to make sure temp dir is valid
206 while($tries++ < 10) {
207 my @st = lstat($tmp_dir);
208 last if ($st[4] == $< && (-d _) && ($st[2] & 0777) == 0755);
210 unlink($tmp_dir) || rmdir($tmp_dir) ||
211 system("/bin/rm -rf ".quotemeta($tmp_dir));
213 mkdir($tmp_dir, 0755) || next;
214 chown($<, $(, $tmp_dir);
215 chmod(0755, $tmp_dir);
218 my @st = lstat($tmp_dir);
219 &error("Failed to create temp directory $tmp_dir : uid=$st[4] mode=$st[2]");
223 if (defined($_[0]) && $_[0] !~ /\.\./) {
224 $rv = "$tmp_dir/$_[0]";
227 $main::tempfilecount++;
229 $rv = $tmp_dir."/".int(rand(1000000))."_".
230 $main::tempfilecount."_".$scriptname;
235 =head2 transname([filename])
237 Behaves exactly like tempname, but records the temp file for deletion when the
238 current Webmin script process exits.
243 my $rv = &tempname(@_);
244 push(@main::temporary_files, $rv);
248 =head2 trunc(string, maxlen)
250 Truncates a string to the shortest whole word less than or equal to the
251 given width. Useful for word wrapping.
256 if (length($_[0]) <= $_[1]) {
259 my $str = substr($_[0],0,$_[1]);
268 =head2 indexof(string, value, ...)
270 Returns the index of some value in an array of values, or -1 if it was not
276 for(my $i=1; $i <= $#_; $i++) {
277 if ($_[$i] eq $_[0]) { return $i - 1; }
282 =head2 indexoflc(string, value, ...)
284 Like indexof, but does a case-insensitive match
289 my $str = lc(shift(@_));
290 my @arr = map { lc($_) } @_;
291 return &indexof($str, @arr);
294 =head2 sysprint(handle, [string]+)
296 Outputs some strings to a file handle, but bypassing IO buffering. Can be used
297 as a replacement for print when writing to pipes or sockets.
302 my $fh = &callers_package($_[0]);
303 my $str = join('', @_[1..$#_]);
304 syswrite $fh, $str, length($str);
307 =head2 check_ipaddress(ip)
309 Check if some IPv4 address is properly formatted, returning 1 if so or 0 if not.
314 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
315 $1 >= 0 && $1 <= 255 &&
316 $2 >= 0 && $2 <= 255 &&
317 $3 >= 0 && $3 <= 255 &&
318 $4 >= 0 && $4 <= 255;
321 =head2 check_ip6address(ip)
323 Check if some IPv6 address is properly formatted, and returns 1 if so.
328 my @blocks = split(/:/, $_[0]);
329 return 0 if (@blocks == 0 || @blocks > 8);
331 # The address/netmask format is accepted. So we're looking for a "/" to isolate a possible netmask.
332 # After that, we delete the netmask to control the address only format, but we verify whether the netmask
333 # value is in [0;128].
335 my $where = index($blocks[$ib],"/");
338 my $b = substr($blocks[$ib],0,$where);
339 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
343 # The netmask must take its value in [0;128]
344 return 0 if ($m <0 || $m >128);
346 # Check the different blocks of the address : 16 bits block in hexa notation.
347 # Possibility of 1 empty block or 2 if the address begins with "::".
350 foreach $b (@blocks) {
351 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
352 $empty++ if ($b eq "");
354 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
360 =head2 generate_icon(image, title, link, [href], [width], [height], [before-title], [after-title])
362 Prints HTML for an icon image. The parameters are :
364 =item image - URL for the image, like images/foo.gif
366 =item title - Text to appear under the icon
368 =item link - Optional destination for the icon's link
370 =item href - Other HTML attributes to be added to the <a href> for the link
372 =item width - Optional width of the icon
374 =item height - Optional height of the icon
376 =item before-title - HTML to appear before the title link, but which is not actually in the link
378 =item after-title - HTML to appear after the title link, but which is not actually in the link
383 &load_theme_library();
384 if (defined(&theme_generate_icon)) {
385 &theme_generate_icon(@_);
388 my $w = !defined($_[4]) ? "width=48" : $_[4] ? "width=$_[4]" : "";
389 my $h = !defined($_[5]) ? "height=48" : $_[5] ? "height=$_[5]" : "";
390 if ($tconfig{'noicons'}) {
392 print "$_[6]<a href=\"$_[2]\" $_[3]>$_[1]</a>$_[7]\n";
395 print "$_[6]$_[1]$_[7]\n";
399 print "<table border><tr><td width=48 height=48>\n",
400 "<a href=\"$_[2]\" $_[3]><img src=\"$_[0]\" alt=\"\" border=0 ",
401 "$w $h></a></td></tr></table>\n";
402 print "$_[6]<a href=\"$_[2]\" $_[3]>$_[1]</a>$_[7]\n";
405 print "<table border><tr><td width=48 height=48>\n",
406 "<img src=\"$_[0]\" alt=\"\" border=0 $w $h>",
407 "</td></tr></table>\n$_[6]$_[1]$_[7]\n";
413 Converts a string to a form ok for putting in a URL, using % escaping.
419 $rv =~ s/([^A-Za-z0-9])/sprintf("%%%2.2X", ord($1))/ge;
423 =head2 un_urlize(string)
425 Converts a URL-encoded string to it's original contents - the reverse of the
433 $rv =~ s/%(..)/pack("c",hex($1))/ge;
437 =head2 include(filename)
439 Read and output the contents of the given file.
445 open(INCLUDE, &translate_filename($_[0])) || return 0;
453 =head2 copydata(in-handle, out-handle)
455 Read from one file handle and write to another, until there is no more to read.
461 $in = &callers_package($in);
462 $out = &callers_package($out);
464 while(read($in, $buf, 1024) > 0) {
465 (print $out $buf) || return 0;
470 =head2 ReadParseMime([maximum], [&cbfunc, &cbargs])
472 Read data submitted via a POST request using the multipart/form-data coding,
473 and store it in the global %in hash. The optional parameters are :
475 =item maximum - If the number of bytes of input exceeds this number, stop reading and call error.
477 =item cbfunc - A function reference to call after reading each block of data.
479 =item cbargs - Additional parameters to the callback function.
484 my ($max, $cbfunc, $cbargs) = @_;
485 my ($boundary, $line, $foo, $name, $got, $file);
486 my $err = &text('readparse_max', $max);
487 $ENV{'CONTENT_TYPE'} =~ /boundary=(.*)$/ || &error($text{'readparse_enc'});
488 if ($ENV{'CONTENT_LENGTH'} && $max && $ENV{'CONTENT_LENGTH'} > $max) {
491 &$cbfunc(0, $ENV{'CONTENT_LENGTH'}, $file, @$cbargs) if ($cbfunc);
493 <STDIN>; # skip first boundary
496 # Read section headers
500 $got += length($line);
501 &$cbfunc($got, $ENV{'CONTENT_LENGTH'}, @$cbargs) if ($cbfunc);
502 if ($max && $got > $max) {
507 if ($line =~ /^(\S+):\s*(.*)$/) {
508 $header{$lastheader = lc($1)} = $2;
510 elsif ($line =~ /^\s+(.*)$/) {
511 $header{$lastheader} .= $line;
515 # Parse out filename and type
516 if ($header{'content-disposition'} =~ /^form-data(.*)/) {
518 while ($rest =~ /([a-zA-Z]*)=\"([^\"]*)\"(.*)/) {
523 $foo = $name . "_$1";
530 &error($text{'readparse_cdheader'});
532 if ($header{'content-type'} =~ /^([^\s;]+)/) {
533 $foo = $name . "_content_type";
536 $file = $in{$name."_filename"};
539 $in{$name} .= "\0" if (defined($in{$name}));
542 $got += length($line);
543 &$cbfunc($got, $ENV{'CONTENT_LENGTH'}, $file, @$cbargs)
545 if ($max && $got > $max) {
546 #print STDERR "over limit of $max\n";
551 &$cbfunc(-1, $ENV{'CONTENT_LENGTH'}, $file, @$cbargs)
556 $ptline =~ s/[^a-zA-Z0-9\-]/\./g;
557 if (index($line, $boundary) != -1) { last; }
560 chop($in{$name}); chop($in{$name});
561 if (index($line,"$boundary--") != -1) { last; }
563 &$cbfunc(-1, $ENV{'CONTENT_LENGTH'}, $file, @$cbargs) if ($cbfunc);
566 =head2 ReadParse([&hash], [method], [noplus])
568 Fills the given hash reference with CGI parameters, or uses the global hash
569 %in if none is given. Also sets the global variables $in and @in. The other
572 =item method - For use of this HTTP method, such as GET
574 =item noplus - Don't convert + in parameters to spaces.
579 my $a = $_[0] || \%in;
581 my $meth = $_[1] ? $_[1] : $ENV{'REQUEST_METHOD'};
583 if ($meth eq 'POST') {
584 my $clen = $ENV{'CONTENT_LENGTH'};
585 &read_fully(STDIN, \$in, $clen) == $clen ||
586 &error("Failed to read POST input : $!");
588 if ($ENV{'QUERY_STRING'}) {
589 if ($in) { $in .= "&".$ENV{'QUERY_STRING'}; }
590 else { $in = $ENV{'QUERY_STRING'}; }
592 @in = split(/\&/, $in);
593 foreach my $i (@in) {
594 my ($k, $v) = split(/=/, $i, 2);
599 $k =~ s/%(..)/pack("c",hex($1))/ge;
600 $v =~ s/%(..)/pack("c",hex($1))/ge;
601 $a->{$k} = defined($a->{$k}) ? $a->{$k}."\0".$v : $v;
605 =head2 read_fully(fh, &buffer, length)
607 Read data from some file handle up to the given length, even in the face
608 of partial reads. Reads the number of bytes read. Stores received data in the
609 string pointed to be the buffer reference.
614 my ($fh, $buf, $len) = @_;
615 $fh = &callers_package($fh);
618 my $r = read(STDIN, $$buf, $len-$got, $got);
625 =head2 read_parse_mime_callback(size, totalsize, upload-id)
627 Called by ReadParseMime as new data arrives from a form-data POST. Only updates
628 the file on every 1% change though. For internal use by the upload progress
632 sub read_parse_mime_callback
634 my ($size, $totalsize, $filename, $id) = @_;
635 return if ($gconfig{'no_upload_tracker'});
638 # Create the upload tracking directory - if running as non-root, this has to
639 # be under the user's home
642 my @uinfo = @remote_user_info ? @remote_user_info : getpwuid($<);
643 $vardir = "$uinfo[7]/.tmp";
646 $vardir = $ENV{'WEBMIN_VAR'};
649 &make_dir($vardir, 0755);
652 # Remove any upload.* files more than 1 hour old
653 if (!$main::read_parse_mime_callback_flushed) {
655 opendir(UPDIR, $vardir);
656 foreach my $f (readdir(UPDIR)) {
657 next if ($f !~ /^upload\./);
658 my @st = stat("$vardir/$f");
659 if ($st[9] < $now-3600) {
660 unlink("$vardir/$f");
664 $main::read_parse_mime_callback_flushed++;
667 # Only update file once per percent
668 my $upfile = "$vardir/upload.$id";
669 if ($totalsize && $size >= 0) {
670 my $pc = int(100 * $size / $totalsize);
671 if ($pc <= $main::read_parse_mime_callback_pc{$upfile}) {
674 $main::read_parse_mime_callback_pc{$upfile} = $pc;
678 &open_tempfile(UPFILE, ">$upfile");
679 print UPFILE $size,"\n";
680 print UPFILE $totalsize,"\n";
681 print UPFILE $filename,"\n";
682 &close_tempfile(UPFILE);
685 =head2 read_parse_mime_javascript(upload-id, [&fields])
687 Returns an onSubmit= Javascript statement to popup a window for tracking
688 an upload with the given ID. For internal use by the upload progress tracker.
691 sub read_parse_mime_javascript
693 my ($id, $fields) = @_;
694 return "" if ($gconfig{'no_upload_tracker'});
695 my $opener = "window.open(\"$gconfig{'webprefix'}/uptracker.cgi?id=$id&uid=$<\", \"uptracker\", \"toolbar=no,menubar=no,scrollbars=no,width=500,height=100\");";
697 my $if = join(" || ", map { "typeof($_) != \"undefined\" && $_.value != \"\"" } @$fields);
698 return "onSubmit='if ($if) { $opener }'";
701 return "onSubmit='$opener'";
705 =head2 PrintHeader(charset)
707 Outputs the HTTP headers for an HTML page. The optional charset parameter
708 can be used to set a character set. Normally this function is not called
709 directly, but is rather called by ui_print_header or header.
714 if ($pragma_no_cache || $gconfig{'pragma_no_cache'}) {
715 print "pragma: no-cache\n";
716 print "Expires: Thu, 1 Jan 1970 00:00:00 GMT\n";
717 print "Cache-Control: no-store, no-cache, must-revalidate\n";
718 print "Cache-Control: post-check=0, pre-check=0\n";
720 if (defined($_[0])) {
721 print "Content-type: text/html; Charset=$_[0]\n\n";
724 print "Content-type: text/html\n\n";
728 =head2 header(title, image, [help], [config], [nomodule], [nowebmin], [rightside], [head-stuff], [body-stuff], [below])
730 Outputs a Webmin HTML page header with a title, including HTTP headers. The
733 =item title - The text to show at the top of the page
735 =item image - An image to show instead of the title text. This is typically left blank.
737 =item help - If set, this is the name of a help page that will be linked to in the title.
739 =item config - If set to 1, the title will contain a link to the module's config page.
741 =item nomodule - If set to 1, there will be no link in the title section to the module's index.
743 =item nowebmin - If set to 1, there will be no link in the title section to the Webmin index.
745 =item rightside - HTML to be shown on the right-hand side of the title. Can contain multiple lines, separated by <br>. Typically this is used for links to stop, start or restart servers.
747 =item head-stuff - HTML to be included in the <head> section of the page.
749 =item body-stuff - HTML attributes to be include in the <body> tag.
751 =item below - HTML to be displayed below the title. Typically this is used for application or server version information.
756 return if ($main::done_webmin_header++);
758 my $charset = defined($main::force_charset) ? $main::force_charset
760 &PrintHeader($charset);
761 &load_theme_library();
762 if (defined(&theme_header)) {
763 $module_name = &get_module_name();
767 print "<!doctype html public \"-//W3C//DTD HTML 3.2 Final//EN\">\n";
770 if (defined(&theme_prehead)) {
774 print "<meta http-equiv=\"Content-Type\" ",
775 "content=\"text/html; Charset="."e_escape($charset)."\">\n";
778 my $title = &get_html_title($_[0]);
779 print "<title>$title</title>\n";
780 print $_[7] if ($_[7]);
781 print &get_html_status_line(0);
783 print "$tconfig{'headhtml'}\n" if ($tconfig{'headhtml'});
784 if ($tconfig{'headinclude'}) {
786 open(INC, "$theme_root_directory/$tconfig{'headinclude'}");
793 my $bgcolor = defined($tconfig{'cs_page'}) ? $tconfig{'cs_page'} :
794 defined($gconfig{'cs_page'}) ? $gconfig{'cs_page'} : "ffffff";
795 my $link = defined($tconfig{'cs_link'}) ? $tconfig{'cs_link'} :
796 defined($gconfig{'cs_link'}) ? $gconfig{'cs_link'} : "0000ee";
797 my $text = defined($tconfig{'cs_text'}) ? $tconfig{'cs_text'} :
798 defined($gconfig{'cs_text'}) ? $gconfig{'cs_text'} : "000000";
799 my $bgimage = defined($tconfig{'bgimage'}) ? "background=$tconfig{'bgimage'}"
801 my $dir = $current_lang_info->{'dir'} ? "dir=\"$current_lang_info->{'dir'}\""
803 print "<body bgcolor=#$bgcolor link=#$link vlink=#$link text=#$text ",
804 "$bgimage $tconfig{'inbody'} $dir $_[8]>\n";
805 if (defined(&theme_prebody)) {
808 my $hostname = &get_display_hostname();
809 my $version = &get_webmin_version();
810 my $prebody = $tconfig{'prebody'};
812 $prebody =~ s/%HOSTNAME%/$hostname/g;
813 $prebody =~ s/%VERSION%/$version/g;
814 $prebody =~ s/%USER%/$remote_user/g;
815 $prebody =~ s/%OS%/$os_type $os_version/g;
818 if ($tconfig{'prebodyinclude'}) {
820 open(INC, "$theme_root_directory/$tconfig{'prebodyinclude'}");
827 print $tconfig{'preheader'};
828 my %this_module_info = &get_module_info(&get_module_name());
829 print "<table class='header' width=100%><tr>\n";
830 if ($gconfig{'sysinfo'} == 2 && $remote_user) {
831 print "<td id='headln1' colspan=3 align=center>\n";
832 print &get_html_status_line(1);
833 print "</td></tr> <tr>\n";
835 print "<td id='headln2l' width=15% valign=top align=left>";
836 if ($ENV{'HTTP_WEBMIN_SERVERS'} && !$tconfig{'framed'}) {
837 print "<a href='$ENV{'HTTP_WEBMIN_SERVERS'}'>",
838 "$text{'header_servers'}</a><br>\n";
840 if (!$_[5] && !$tconfig{'noindex'}) {
841 my @avail = &get_available_module_infos(1);
842 my $nolo = $ENV{'ANONYMOUS_USER'} ||
843 $ENV{'SSL_USER'} || $ENV{'LOCAL_USER'} ||
844 $ENV{'HTTP_USER_AGENT'} =~ /webmin/i;
845 if ($gconfig{'gotoone'} && $main::session_id && @avail == 1 &&
847 print "<a href='$gconfig{'webprefix'}/session_login.cgi?logout=1'>",
848 "$text{'main_logout'}</a><br>";
850 elsif ($gconfig{'gotoone'} && @avail == 1 && !$nolo) {
851 print "<a href=$gconfig{'webprefix'}/switch_user.cgi>",
852 "$text{'main_switch'}</a><br>";
854 elsif (!$gconfig{'gotoone'} || @avail > 1) {
855 print "<a href='$gconfig{'webprefix'}/?cat=",
856 $this_module_info{'category'},
857 "'>$text{'header_webmin'}</a><br>\n";
860 if (!$_[4] && !$tconfig{'nomoduleindex'}) {
861 my $idx = $this_module_info{'index_link'};
862 my $mi = $module_index_link || "/".&get_module_name()."/$idx";
863 my $mt = $module_index_name || $text{'header_module'};
864 print "<a href=\"$gconfig{'webprefix'}$mi\">$mt</a><br>\n";
866 if (ref($_[2]) eq "ARRAY" && !$ENV{'ANONYMOUS_USER'} &&
867 !$tconfig{'nohelp'}) {
868 print &hlink($text{'header_help'}, $_[2]->[0], $_[2]->[1]),
871 elsif (defined($_[2]) && !$ENV{'ANONYMOUS_USER'} &&
872 !$tconfig{'nohelp'}) {
873 print &hlink($text{'header_help'}, $_[2]),"<br>\n";
876 my %access = &get_module_acl();
877 if (!$access{'noconfig'} && !$config{'noprefs'}) {
878 my $cprog = $user_module_config_directory ?
879 "uconfig.cgi" : "config.cgi";
880 print "<a href=\"$gconfig{'webprefix'}/$cprog?",
881 &get_module_name()."\">",
882 $text{'header_config'},"</a><br>\n";
887 # Title is a single image
888 print "<td id='headln2c' align=center width=70%>",
889 "<img alt=\"$_[0]\" src=\"$_[1]\"></td>\n";
893 my $ts = defined($tconfig{'titlesize'}) ?
894 $tconfig{'titlesize'} : "+2";
895 print "<td id='headln2c' align=center width=70%>",
896 ($ts ? "<font size=$ts>" : ""),$_[0],
897 ($ts ? "</font>" : "");
898 print "<br>$_[9]\n" if ($_[9]);
901 print "<td id='headln2r' width=15% valign=top align=right>";
903 print "</td></tr></table>\n";
904 print $tconfig{'postheader'};
908 =head2 get_html_title(title)
910 Returns the full string to appear in the HTML <title> block.
917 my $os_type = $gconfig{'real_os_type'} || $gconfig{'os_type'};
918 my $os_version = $gconfig{'real_os_version'} || $gconfig{'os_version'};
919 if ($gconfig{'sysinfo'} == 1 && $remote_user) {
920 $title = sprintf "%s : %s on %s (%s %s)\n",
921 $msg, $remote_user, &get_display_hostname(),
922 $os_type, $os_version;
924 elsif ($gconfig{'sysinfo'} == 4 && $remote_user) {
925 $title = sprintf "%s on %s (%s %s)\n",
926 $remote_user, &get_display_hostname(),
927 $os_type, $os_version;
932 if ($gconfig{'showlogin'} && $remote_user) {
933 $title = $remote_user." : ".$title;
938 =head2 get_html_framed_title
940 Returns the title text for a framed theme main page.
943 sub get_html_framed_title
946 my $os_type = $gconfig{'real_os_type'} || $gconfig{'os_type'};
947 my $os_version = $gconfig{'real_os_version'} || $gconfig{'os_version'};
949 if (($gconfig{'sysinfo'} == 4 || $gconfig{'sysinfo'} == 1) && $remote_user) {
950 # Alternate title mode requested
951 $title = sprintf "%s on %s (%s %s)\n",
952 $remote_user, &get_display_hostname(),
953 $os_type, $os_version;
956 # Title like 'Webmin x.yy on hostname (Linux 6)'
957 if ($os_version eq "*") {
961 $ostr = "$os_type $os_version";
963 my $host = &get_display_hostname();
964 $title = $gconfig{'nohostname'} ? $text{'main_title2'} :
965 &text('main_title', &get_webmin_version(), $host, $ostr);
966 if ($gconfig{'showlogin'}) {
967 $title = $remote_user." : ".$title;
973 =head2 get_html_status_line(text-only)
975 Returns HTML for a script block that sets the status line, or if text-only
976 is set to 1, just return the status line text.
979 sub get_html_status_line
982 if (($gconfig{'sysinfo'} != 0 || !$remote_user) && !$textonly) {
983 # Disabled in this mode
986 my $os_type = $gconfig{'real_os_type'} || $gconfig{'os_type'};
987 my $os_version = $gconfig{'real_os_version'} || $gconfig{'os_version'};
988 my $line = &text('header_statusmsg',
989 ($ENV{'ANONYMOUS_USER'} ? "Anonymous user"
991 ($ENV{'SSL_USER'} ? " (SSL certified)" :
992 $ENV{'LOCAL_USER'} ? " (Local user)" : ""),
993 $text{'programname'},
994 &get_webmin_version(),
995 &get_display_hostname(),
996 $os_type.($os_version eq "*" ? "" :" $os_version"));
1001 $line =~ s/\r|\n//g;
1002 return "<script language=JavaScript type=text/javascript>\n".
1003 "defaultStatus=\""."e_escape($line)."\";\n".
1008 =head2 popup_header([title], [head-stuff], [body-stuff])
1010 Outputs a page header, suitable for a popup window. If no title is given,
1011 absolutely no decorations are output. Also useful in framesets. The parameters
1014 =item title - Title text for the popup window.
1016 =item head-stuff - HTML to appear in the <head> section.
1018 =item body-stuff - HTML attributes to be include in the <body> tag.
1023 return if ($main::done_webmin_header++);
1025 my $charset = defined($main::force_charset) ? $main::force_charset
1027 &PrintHeader($charset);
1028 &load_theme_library();
1029 if (defined(&theme_popup_header)) {
1030 &theme_popup_header(@_);
1033 print "<!doctype html public \"-//W3C//DTD HTML 3.2 Final//EN\">\n";
1036 if (defined(&theme_popup_prehead)) {
1037 &theme_popup_prehead(@_);
1039 print "<title>$_[0]</title>\n";
1041 print "$tconfig{'headhtml'}\n" if ($tconfig{'headhtml'});
1042 if ($tconfig{'headinclude'}) {
1044 open(INC, "$theme_root_directory/$tconfig{'headinclude'}");
1051 my $bgcolor = defined($tconfig{'cs_page'}) ? $tconfig{'cs_page'} :
1052 defined($gconfig{'cs_page'}) ? $gconfig{'cs_page'} : "ffffff";
1053 my $link = defined($tconfig{'cs_link'}) ? $tconfig{'cs_link'} :
1054 defined($gconfig{'cs_link'}) ? $gconfig{'cs_link'} : "0000ee";
1055 my $text = defined($tconfig{'cs_text'}) ? $tconfig{'cs_text'} :
1056 defined($gconfig{'cs_text'}) ? $gconfig{'cs_text'} : "000000";
1057 my $bgimage = defined($tconfig{'bgimage'}) ? "background=$tconfig{'bgimage'}"
1059 print "<body id='popup' bgcolor=#$bgcolor link=#$link vlink=#$link ",
1060 "text=#$text $bgimage $tconfig{'inbody'} $_[2]>\n";
1061 if (defined(&theme_popup_prebody)) {
1062 &theme_popup_prebody(@_);
1066 =head2 footer([page, name]+, [noendbody])
1068 Outputs the footer for a Webmin HTML page, possibly with links back to other
1069 pages. The links are specified by pairs of parameters, the first of which is
1070 a link destination, and the second the link text. For example :
1072 footer('/', 'Webmin index', '', 'Module menu');
1077 &load_theme_library();
1078 my %this_module_info = &get_module_info(&get_module_name());
1079 if (defined(&theme_footer)) {
1080 $module_name = &get_module_name(); # Old themes use these
1081 %module_info = %this_module_info;
1085 for(my $i=0; $i+1<@_; $i+=2) {
1087 if ($url ne '/' || !$tconfig{'noindex'}) {
1089 $url = "/?cat=$this_module_info{'category'}";
1091 elsif ($url eq '' && &get_module_name()) {
1092 $url = "/".&get_module_name()."/".
1093 $this_module_info{'index_link'};
1095 elsif ($url =~ /^\?/ && &get_module_name()) {
1096 $url = "/".&get_module_name()."/$url";
1098 $url = "$gconfig{'webprefix'}$url" if ($url =~ /^\//);
1100 print "<a href=\"$url\"><img alt=\"<-\" align=middle border=0 src=$gconfig{'webprefix'}/images/left.gif></a>\n";
1105 print " <a href=\"$url\">",&text('main_return', $_[$i+1]),"</a>\n";
1110 my $postbody = $tconfig{'postbody'};
1112 my $hostname = &get_display_hostname();
1113 my $version = &get_webmin_version();
1114 my $os_type = $gconfig{'real_os_type'} ||
1115 $gconfig{'os_type'};
1116 my $os_version = $gconfig{'real_os_version'} ||
1117 $gconfig{'os_version'};
1118 $postbody =~ s/%HOSTNAME%/$hostname/g;
1119 $postbody =~ s/%VERSION%/$version/g;
1120 $postbody =~ s/%USER%/$remote_user/g;
1121 $postbody =~ s/%OS%/$os_type $os_version/g;
1122 print "$postbody\n";
1124 if ($tconfig{'postbodyinclude'}) {
1126 open(INC, "$theme_root_directory/$tconfig{'postbodyinclude'}");
1132 if (defined(&theme_postbody)) {
1133 &theme_postbody(@_);
1135 print "</body></html>\n";
1141 Outputs html for a footer for a popup window, started by popup_header.
1146 &load_theme_library();
1147 if (defined(&theme_popup_footer)) {
1148 &theme_popup_footer(@_);
1151 print "</body></html>\n";
1154 =head2 load_theme_library
1156 Immediately loads the current theme's theme.pl file. Not generally useful for
1157 most module developers, as this is called automatically by the header function.
1160 sub load_theme_library
1162 return if (!$current_theme || $loaded_theme_library++);
1163 for(my $i=0; $i<@theme_root_directories; $i++) {
1164 if ($theme_configs[$i]->{'functions'}) {
1165 do $theme_root_directories[$i]."/".
1166 $theme_configs[$i]->{'functions'};
1171 =head2 redirect(url)
1173 Output HTTP headers to redirect the browser to some page. The url parameter is
1174 typically a relative URL like index.cgi or list_users.cgi.
1179 my $port = $ENV{'SERVER_PORT'} == 443 && uc($ENV{'HTTPS'}) eq "ON" ? "" :
1180 $ENV{'SERVER_PORT'} == 80 && uc($ENV{'HTTPS'}) ne "ON" ? "" :
1181 ":$ENV{'SERVER_PORT'}";
1182 my $prot = uc($ENV{'HTTPS'}) eq "ON" ? "https" : "http";
1183 my $wp = $gconfig{'webprefixnoredir'} ? undef : $gconfig{'webprefix'};
1185 if ($_[0] =~ /^(http|https|ftp|gopher):/) {
1186 # Absolute URL (like http://...)
1189 elsif ($_[0] =~ /^\//) {
1190 # Absolute path (like /foo/bar.cgi)
1191 $url = "$prot://$ENV{'SERVER_NAME'}$port$wp$_[0]";
1193 elsif ($ENV{'SCRIPT_NAME'} =~ /^(.*)\/[^\/]*$/) {
1194 # Relative URL (like foo.cgi)
1195 $url = "$prot://$ENV{'SERVER_NAME'}$port$wp$1/$_[0]";
1198 $url = "$prot://$ENV{'SERVER_NAME'}$port/$wp$_[0]";
1200 &load_theme_library();
1201 if (defined(&theme_redirect)) {
1202 $module_name = &get_module_name(); # Old themes use these
1203 %module_info = &get_module_info($module_name);
1204 &theme_redirect($_[0], $url);
1207 print "Location: $url\n\n";
1211 =head2 kill_byname(name, signal)
1213 Finds a process whose command line contains the given name (such as httpd), and
1214 sends some signal to it. The signal can be numeric (like 9) or named
1220 my @pids = &find_byname($_[0]);
1221 return scalar(@pids) if (&is_readonly_mode());
1222 &webmin_debug_log('KILL', "signal=$_[1] name=$_[0]")
1223 if ($gconfig{'debug_what_procs'});
1224 if (@pids) { kill($_[1], @pids); return scalar(@pids); }
1228 =head2 kill_byname_logged(name, signal)
1230 Like kill_byname, but also logs the killing.
1233 sub kill_byname_logged
1235 my @pids = &find_byname($_[0]);
1236 return scalar(@pids) if (&is_readonly_mode());
1237 if (@pids) { &kill_logged($_[1], @pids); return scalar(@pids); }
1241 =head2 find_byname(name)
1243 Finds processes searching for the given name in their command lines, and
1244 returns a list of matching PIDs.
1249 if ($gconfig{'os_type'} =~ /-linux$/ && -r "/proc/$$/cmdline") {
1250 # Linux with /proc filesystem .. use cmdline files, as this is
1251 # faster than forking
1253 opendir(PROCDIR, "/proc");
1254 foreach my $f (readdir(PROCDIR)) {
1255 if ($f eq int($f) && $f != $$) {
1256 my $line = &read_file_contents("/proc/$f/cmdline");
1257 if ($line =~ /$_[0]/) {
1266 if (&foreign_check("proc")) {
1267 # Call the proc module
1268 &foreign_require("proc", "proc-lib.pl");
1269 if (defined(&proc::list_processes)) {
1270 my @procs = &proc::list_processes();
1272 foreach my $p (@procs) {
1273 if ($p->{'args'} =~ /$_[0]/) {
1274 push(@pids, $p->{'pid'});
1277 @pids = grep { $_ != $$ } @pids;
1282 # Fall back to running a command
1284 $cmd = $gconfig{'find_pid_command'};
1285 $cmd =~ s/NAME/"$_[0]"/g;
1286 $cmd = &translate_command($cmd);
1287 @pids = split(/\n/, `($cmd) <$null_file 2>$null_file`);
1288 @pids = grep { $_ != $$ } @pids;
1292 =head2 error([message]+)
1294 Display an error message and exit. This should be used by CGI scripts that
1295 encounter a fatal error or invalid user input to notify users of the problem.
1296 If error_setup has been called, the displayed error message will be prefixed
1297 by the message setup using that function.
1302 my $msg = join("", @_);
1303 $msg =~ s/<[^>]*>//g;
1304 if (!$main::error_must_die) {
1305 print STDERR "Error: ",$msg,"\n";
1307 &load_theme_library();
1308 if ($main::error_must_die) {
1309 if ($gconfig{'error_stack'}) {
1310 print STDERR "Error: ",$msg,"\n";
1311 for(my $i=0; my @stack = caller($i); $i++) {
1312 print STDERR "File: $stack[1] Line: $stack[2] ",
1313 "Function: $stack[3]\n";
1318 elsif (!$ENV{'REQUEST_METHOD'}) {
1319 # Show text-only error
1320 print STDERR "$text{'error'}\n";
1321 print STDERR "-----\n";
1322 print STDERR ($main::whatfailed ? "$main::whatfailed : " : ""),
1324 print STDERR "-----\n";
1325 if ($gconfig{'error_stack'}) {
1327 print STDERR $text{'error_stack'},"\n";
1328 for(my $i=0; my @stack = caller($i); $i++) {
1329 print STDERR &text('error_stackline',
1330 $stack[1], $stack[2], $stack[3]),"\n";
1335 elsif (defined(&theme_error)) {
1339 &header($text{'error'}, "");
1341 print "<h3>",($main::whatfailed ? "$main::whatfailed : " : ""),
1343 if ($gconfig{'error_stack'}) {
1345 print "<h3>$text{'error_stack'}</h3>\n";
1347 print "<tr> <td><b>$text{'error_file'}</b></td> ",
1348 "<td><b>$text{'error_line'}</b></td> ",
1349 "<td><b>$text{'error_sub'}</b></td> </tr>\n";
1350 for($i=0; my @stack = caller($i); $i++) {
1352 print "<td>$stack[1]</td>\n";
1353 print "<td>$stack[2]</td>\n";
1354 print "<td>$stack[3]</td>\n";
1360 if ($ENV{'HTTP_REFERER'} && $main::completed_referers_check) {
1361 &footer($ENV{'HTTP_REFERER'}, $text{'error_previous'});
1367 &unlock_all_files();
1368 &cleanup_tempnames();
1372 =head2 popup_error([message]+)
1374 This function is almost identical to error, but displays the message with HTML
1375 headers suitable for a popup window.
1380 &load_theme_library();
1381 if ($main::error_must_die) {
1384 elsif (defined(&theme_popup_error)) {
1385 &theme_popup_error(@_);
1388 &popup_header($text{'error'}, "");
1389 print "<h3>",($main::whatfailed ? "$main::whatfailed : " : ""),@_,"</h3>\n";
1392 &unlock_all_files();
1393 &cleanup_tempnames();
1397 =head2 error_setup(message)
1399 Registers a message to be prepended to all error messages displayed by the
1405 $main::whatfailed = $_[0];
1408 =head2 wait_for(handle, regexp, regexp, ...)
1410 Reads from the input stream until one of the regexps matches, and returns the
1411 index of the matching regexp, or -1 if input ended before any matched. This is
1412 very useful for parsing the output of interactive programs, and can be used with
1413 a two-way pipe to feed input to a program in response to output matched by
1416 If the matching regexp contains bracketed sub-expressions, their values will
1417 be placed in the global array @matches, indexed starting from 1. You cannot
1418 use the Perl variables $1, $2 and so on to capture matches.
1422 $rv = wait_for($loginfh, "username:");
1424 error("Didn't get username prompt");
1426 print $loginfh "joe\n";
1427 $rv = wait_for($loginfh, "password:");
1429 error("Didn't get password prompt");
1431 print $loginfh "smeg\n";
1436 my ($c, $i, $sw, $rv, $ha);
1437 undef($wait_for_input);
1438 if ($wait_for_debug) {
1439 print STDERR "wait_for(",join(",", @_),")\n";
1441 $ha = &callers_package($_[0]);
1442 if ($wait_for_debug) {
1443 print STDERR "File handle=$ha fd=",fileno($ha),"\n";
1448 " if ((\$c = getc(\$ha)) eq \"\") { return -1; }\n".
1449 " \$wait_for_input .= \$c;\n";
1450 if ($wait_for_debug) {
1451 $codes .= "print STDERR \$wait_for_input,\"\\n\";";
1453 for($i=1; $i<@_; $i++) {
1454 $sw = $i>1 ? "elsif" : "if";
1455 $codes .= " $sw (\$wait_for_input =~ /$_[$i]/i) { \$hit = $i-1; }\n";
1458 " if (defined(\$hit)) {\n".
1459 " \@matches = (-1, \$1, \$2, \$3, \$4, \$5, \$6, \$7, \$8, \$9);\n".
1465 &error("wait_for error : $@\n");
1470 =head2 fast_wait_for(handle, string, string, ...)
1472 This function behaves very similar to wait_for (documented above), but instead
1473 of taking regular expressions as parameters, it takes strings. As soon as the
1474 input contains one of them, it will return the index of the matching string.
1475 If the input ends before any match, it returns -1.
1480 my ($inp, $maxlen, $ha, $i, $c, $inpl);
1481 for($i=1; $i<@_; $i++) {
1482 $maxlen = length($_[$i]) > $maxlen ? length($_[$i]) : $maxlen;
1486 if (($c = getc($ha)) eq "") {
1487 &error("fast_wait_for read error : $!");
1490 if (length($inp) > $maxlen) {
1491 $inp = substr($inp, length($inp)-$maxlen);
1493 $inpl = length($inp);
1494 for($i=1; $i<@_; $i++) {
1495 if ($_[$i] eq substr($inp, $inpl-length($_[$i]))) {
1502 =head2 has_command(command)
1504 Returns the full path to the executable if some command is in the path, or
1505 undef if not found. If the given command is already an absolute path and
1506 exists, then the same path will be returned.
1511 if (!$_[0]) { return undef; }
1512 if (exists($main::has_command_cache{$_[0]})) {
1513 return $main::has_command_cache{$_[0]};
1516 my $slash = $gconfig{'os_type'} eq 'windows' ? '\\' : '/';
1517 if ($_[0] =~ /^\// || $_[0] =~ /^[a-z]:[\\\/]/i) {
1518 # Absolute path given - just use it
1519 my $t = &translate_filename($_[0]);
1520 $rv = (-x $t && !-d _) ? $_[0] : undef;
1523 # Check each directory in the path
1525 foreach my $d (split($path_separator, $ENV{'PATH'})) {
1526 next if ($donedir{$d}++);
1527 $d =~ s/$slash$// if ($d ne $slash);
1528 my $t = &translate_filename("$d/$_[0]");
1529 if (-x $t && !-d _) {
1530 $rv = $d.$slash.$_[0];
1533 if ($gconfig{'os_type'} eq 'windows') {
1534 foreach my $sfx (".exe", ".com", ".bat") {
1535 my $t = &translate_filename("$d/$_[0]").$sfx;
1536 if (-r $t && !-d _) {
1537 $rv = $d.$slash.$_[0].$sfx;
1544 $main::has_command_cache{$_[0]} = $rv;
1548 =head2 make_date(seconds, [date-only], [fmt])
1550 Converts a Unix date/time in seconds to a human-readable form, by default
1551 formatted like dd/mmm/yyyy hh:mm:ss. Parameters are :
1553 =item seconds - Unix time is seconds to convert.
1555 =item date-only - If set to 1, exclude the time from the returned string.
1557 =item fmt - Optional, one of dd/mon/yyyy, dd/mm/yyyy, mm/dd/yyyy or yyyy/mm/dd
1562 my ($secs, $only, $fmt) = @_;
1563 my @tm = localtime($secs);
1566 $fmt = $gconfig{'dateformat'} || 'dd/mon/yyyy';
1568 if ($fmt eq 'dd/mon/yyyy') {
1569 $date = sprintf "%2.2d/%s/%4.4d",
1570 $tm[3], $text{"smonth_".($tm[4]+1)}, $tm[5]+1900;
1572 elsif ($fmt eq 'dd/mm/yyyy') {
1573 $date = sprintf "%2.2d/%2.2d/%4.4d", $tm[3], $tm[4]+1, $tm[5]+1900;
1575 elsif ($fmt eq 'mm/dd/yyyy') {
1576 $date = sprintf "%2.2d/%2.2d/%4.4d", $tm[4]+1, $tm[3], $tm[5]+1900;
1578 elsif ($fmt eq 'yyyy/mm/dd') {
1579 $date = sprintf "%4.4d/%2.2d/%2.2d", $tm[5]+1900, $tm[4]+1, $tm[3];
1582 $date .= sprintf " %2.2d:%2.2d", $tm[2], $tm[1];
1587 =head2 file_chooser_button(input, type, [form], [chroot], [addmode])
1589 Return HTML for a button that pops up a file chooser when clicked, and places
1590 the selected filename into another HTML field. The parameters are :
1592 =item input - Name of the form field to store the filename in.
1594 =item type - 0 for file or directory chooser, or 1 for directory only.
1596 =item form - Index of the form containing the button.
1598 =item chroot - If set to 1, the chooser will be limited to this directory.
1600 =item addmode - If set to 1, the selected filename will be appended to the text box instead of replacing it's contents.
1603 sub file_chooser_button
1605 return &theme_file_chooser_button(@_)
1606 if (defined(&theme_file_chooser_button));
1607 my $form = defined($_[2]) ? $_[2] : 0;
1608 my $chroot = defined($_[3]) ? $_[3] : "/";
1609 my $add = int($_[4]);
1610 my ($w, $h) = (400, 300);
1611 if ($gconfig{'db_sizefile'}) {
1612 ($w, $h) = split(/x/, $gconfig{'db_sizefile'});
1614 return "<input type=button onClick='ifield = form.$_[0]; chooser = window.open(\"$gconfig{'webprefix'}/chooser.cgi?add=$add&type=$_[1]&chroot=$chroot&file=\"+escape(ifield.value), \"chooser\", \"toolbar=no,menubar=no,scrollbars=no,resizable=yes,width=$w,height=$h\"); chooser.ifield = ifield; window.ifield = ifield' value=\"...\">\n";
1617 =head2 popup_window_button(url, width, height, scrollbars?, &field-mappings)
1619 Returns HTML for a button that will popup a chooser window of some kind. The
1622 =item url - Base URL of the popup window's contents
1624 =item width - Width of the window in pixels
1626 =item height - Height in pixels
1628 =item scrollbars - Set to 1 if the window should have scrollbars
1630 The field-mappings parameter is an array ref of array refs containing
1632 =item - Attribute to assign field to in the popup window
1634 =item - Form field name
1636 =item - CGI parameter to URL for value, if any
1639 sub popup_window_button
1641 return &theme_popup_window_button(@_) if (defined(&theme_popup_window_button));
1642 my ($url, $w, $h, $scroll, $fields) = @_;
1643 my $scrollyn = $scroll ? "yes" : "no";
1644 my $rv = "<input type=button onClick='";
1645 foreach my $m (@$fields) {
1646 $rv .= "$m->[0] = form.$m->[1]; ";
1648 my $sep = $url =~ /\?/ ? "&" : "?";
1649 $rv .= "chooser = window.open(\"$url\"";
1650 foreach my $m (@$fields) {
1652 $rv .= "+\"$sep$m->[2]=\"+escape($m->[0].value)";
1656 $rv .= ", \"chooser\", \"toolbar=no,menubar=no,scrollbars=$scrollyn,resizable=yes,width=$w,height=$h\"); ";
1657 foreach my $m (@$fields) {
1658 $rv .= "chooser.$m->[0] = $m->[0]; ";
1659 $rv .= "window.$m->[0] = $m->[0]; ";
1661 $rv .= "' value=\"...\">";
1665 =head2 read_acl(&user-module-hash, &user-list-hash)
1667 Reads the Webmin acl file into the given hash references. The first is indexed
1668 by a combined key of username,module , with the value being set to 1 when
1669 the user has access to that module. The second is indexed by username, with
1670 the value being an array ref of allowed modules.
1672 This function is deprecated in favour of foreign_available, which performs a
1673 more comprehensive check of module availability.
1678 if (!defined(%main::acl_hash_cache)) {
1680 open(ACL, &acl_filename());
1682 if (/^([^:]+):\s*(.*)/) {
1684 my @mods = split(/\s+/, $2);
1685 foreach my $m (@mods) {
1686 $main::acl_hash_cache{$user,$m}++;
1688 $main::acl_array_cache{$user} = \@mods;
1693 if ($_[0]) { %{$_[0]} = %main::acl_hash_cache; }
1694 if ($_[1]) { %{$_[1]} = %main::acl_array_cache; }
1699 Returns the file containing the webmin ACL, which is usually
1700 /etc/webmin/webmin.acl.
1705 return "$config_directory/webmin.acl";
1710 Does nothing, but kept around for compatability.
1717 =head2 get_miniserv_config(&hash)
1719 Reads the Webmin webserver's (miniserv.pl) configuration file, usually located
1720 at /etc/webmin/miniserv.conf, and stores its names and values in the given
1724 sub get_miniserv_config
1726 return &read_file_cached(
1727 $ENV{'MINISERV_CONFIG'} || "$config_directory/miniserv.conf", $_[0]);
1730 =head2 put_miniserv_config(&hash)
1732 Writes out the Webmin webserver configuration file from the contents of
1733 the given hash ref. This should be initially populated by get_miniserv_config,
1736 get_miniserv_config(\%miniserv);
1737 $miniserv{'port'} = 10005;
1738 put_miniserv_config(\%miniserv);
1742 sub put_miniserv_config
1744 &write_file($ENV{'MINISERV_CONFIG'} || "$config_directory/miniserv.conf",
1748 =head2 restart_miniserv([nowait])
1750 Kill the old miniserv process and re-start it, then optionally waits for
1751 it to restart. This will apply all configuration settings.
1754 sub restart_miniserv
1757 return undef if (&is_readonly_mode());
1759 &get_miniserv_config(\%miniserv) || return;
1762 if ($gconfig{'os_type'} ne 'windows') {
1763 # On Unix systems, we can restart with a signal
1764 my ($pid, $addr, $i);
1765 $miniserv{'inetd'} && return;
1766 my @oldst = stat($miniserv{'pidfile'});
1767 open(PID, $miniserv{'pidfile'}) || &error("Failed to open PID file");
1770 if (!$pid) { &error("Invalid PID file"); }
1772 # Just signal miniserv to restart
1773 &kill_logged('HUP', $pid) || &error("Incorrect Webmin PID $pid");
1775 # Wait till new PID is written, indicating a restart
1776 for($i=0; $i<60; $i++) {
1778 my @newst = stat($miniserv{'pidfile'});
1779 last if ($newst[9] != $oldst[9]);
1781 $i < 60 || &error("Webmin server did not write new PID file");
1783 ## Totally kill the process and re-run it
1784 #$SIG{'TERM'} = 'IGNORE';
1785 #&kill_logged('TERM', $pid);
1786 #&system_logged("$config_directory/start >/dev/null 2>&1 </dev/null");
1789 # On Windows, we need to use the flag file
1790 open(TOUCH, ">$miniserv{'restartflag'}");
1795 # wait for miniserv to come back up
1796 $addr = inet_aton($miniserv{'bind'} ? $miniserv{'bind'} : "127.0.0.1");
1798 for($i=0; $i<20; $i++) {
1800 socket(STEST, PF_INET, SOCK_STREAM, getprotobyname("tcp"));
1801 my $rv = connect(STEST,
1802 pack_sockaddr_in($miniserv{'port'}, $addr));
1804 last if ($rv && ++$ok >= 2);
1806 $i < 20 || &error("Failed to restart Webmin server!");
1810 =head2 reload_miniserv
1812 Sends a USR1 signal to the miniserv process, telling it to read-read it's
1813 configuration files. Not all changes will be applied though, such as the
1814 IP addresses and ports to accept connections on.
1819 return undef if (&is_readonly_mode());
1821 &get_miniserv_config(\%miniserv) || return;
1823 if ($gconfig{'os_type'} ne 'windows') {
1824 # Send a USR1 signal to re-read the config
1825 my ($pid, $addr, $i);
1826 $miniserv{'inetd'} && return;
1827 open(PID, $miniserv{'pidfile'}) || &error("Failed to open PID file");
1830 if (!$pid) { &error("Invalid PID file"); }
1831 &kill_logged('USR1', $pid) || &error("Incorrect Webmin PID $pid");
1833 # Make sure this didn't kill Webmin!
1835 if (!kill(0, $pid)) {
1836 print STDERR "USR1 signal killed Webmin - restarting\n";
1837 &system_logged("$config_directory/start >/dev/null 2>&1 </dev/null");
1841 # On Windows, we need to use the flag file
1842 open(TOUCH, ">$miniserv{'reloadflag'}");
1847 =head2 check_os_support(&minfo, [os-type, os-version], [api-only])
1849 Returns 1 if some module is supported on the current operating system, or the
1850 OS supplies as parameters. The parameters are :
1852 =item minfo - A hash ref of module information, as returned by get_module_info
1854 =item os-type - The Webmin OS code to use instead of the system's real OS, such as redhat-linux
1856 =item os-version - The Webmin OS version to use, such as 13.0
1858 =item api-only - If set to 1, considers a module supported if it provides an API to other modules on this OS, even if the majority of its functionality is not supported.
1861 sub check_os_support
1863 my $oss = $_[0]->{'os_support'};
1864 if ($_[3] && $oss && $_[0]->{'api_os_support'}) {
1865 # May provide usable API
1866 $oss .= " ".$_[0]->{'api_os_support'};
1868 if ($_[0]->{'nozone'} && &running_in_zone()) {
1869 # Not supported in a Solaris Zone
1872 if ($_[0]->{'novserver'} && &running_in_vserver()) {
1873 # Not supported in a Linux vserver
1876 return 1 if (!$oss || $oss eq '*');
1877 my $osver = $_[2] || $gconfig{'os_version'};
1878 my $ostype = $_[1] || $gconfig{'os_type'};
1881 my ($os, $ver, $codes);
1882 my ($neg) = ($oss =~ s/^!//); # starts with !
1883 $anyneg++ if ($neg);
1884 if ($oss =~ /^([^\/\s]+)\/([^\{\s]+)\{([^\}]*)\}\s*(.*)$/) {
1886 $os = $1; $ver = $2; $codes = $3; $oss = $4;
1888 elsif ($oss =~ /^([^\/\s]+)\/([^\/\s]+)\s*(.*)$/) {
1890 $os = $1; $ver = $2; $oss = $3;
1892 elsif ($oss =~ /^([^\{\s]+)\{([^\}]*)\}\s*(.*)$/) {
1894 $os = $1; $codes = $2; $oss = $3;
1896 elsif ($oss =~ /^\{([^\}]*)\}\s*(.*)$/) {
1898 $codes = $1; $oss = $2;
1900 elsif ($oss =~ /^(\S+)\s*(.*)$/) {
1902 $os = $1; $oss = $2;
1905 next if ($os && !($os eq $ostype ||
1906 $ostype =~ /^(\S+)-(\S+)$/ && $os eq "*-$2"));
1907 if ($ver =~ /^([0-9\.]+)\-([0-9\.]+)$/) {
1908 next if ($osver < $1 || $osver > $2);
1910 elsif ($ver =~ /^([0-9\.]+)\-\*$/) {
1911 next if ($osver < $1);
1913 elsif ($ver =~ /^\*\-([0-9\.]+)$/) {
1914 next if ($osver > $1);
1917 next if ($ver ne $osver);
1919 next if ($codes && !eval $codes);
1925 =head2 http_download(host, port, page, destfile, [&error], [&callback], [sslmode], [user, pass], [timeout], [osdn-convert], [no-cache], [&headers])
1927 Downloads data from a HTTP url to a local file or string. The parameters are :
1929 =item host - The hostname part of the URL, such as www.google.com
1931 =item port - The HTTP port number, such as 80
1933 =item page - The filename part of the URL, like /index.html
1935 =item destfile - The local file to save the URL data to, like /tmp/index.html. This can also be a scalar reference, in which case the data will be appended to that scalar.
1937 =item error - If set to a scalar ref, the function will store any error message in this scalar and return 0 on failure, or 1 on success. If not set, it will simply call the error function if the download fails.
1939 =item callback - If set to a function ref, it will be called after each block of data is received. This is typically set to \&progress_callback, for printing download progress.
1941 =item sslmode - If set to 1, an HTTPS connection is used instead of HTTP.
1943 =item user - If set, HTTP authentication is done with this username.
1945 =item pass - The HTTP password to use with the username above.
1947 =item timeout - A timeout in seconds to wait for the TCP connection to be established before failing.
1949 =item osdn-convert - If set to 1, URL for downloads from sourceforge are converted to use an appropriate mirror site.
1951 =item no-cache - If set to 1, Webmin's internal caching for this URL is disabled.
1953 =item headers - If set to a hash ref of additional HTTP headers, they will be added to the request.
1958 my ($host, $port, $page, $dest, $error, $cbfunc, $ssl, $user, $pass,
1959 $timeout, $osdn, $nocache, $headers) = @_;
1960 if ($gconfig{'debug_what_net'}) {
1961 &webmin_debug_log('HTTP', "host=$host port=$port page=$page ssl=$ssl".
1962 ($user ? " user=$user pass=$pass" : "").
1963 (ref($dest) ? "" : " dest=$dest"));
1966 # Convert OSDN URL first
1967 my $prot = $ssl ? "https://" : "http://";
1968 my $portstr = $ssl && $port == 443 ||
1969 !$ssl && $port == 80 ? "" : ":$port";
1970 ($host, $port, $page, $ssl) = &parse_http_url(
1971 &convert_osdn_url($prot.$host.$portstr.$page));
1974 # Check if we already have cached the URL
1975 my $url = ($ssl ? "https://" : "http://").$host.":".$port.$page;
1976 my $cfile = &check_in_http_cache($url);
1977 if ($cfile && !$nocache) {
1978 # Yes! Copy to dest file or variable
1979 &$cbfunc(6, $url) if ($cbfunc);
1981 &open_readfile(CACHEFILE, $cfile);
1983 $$dest = <CACHEFILE>;
1987 ©_source_dest($cfile, $dest);
1994 push(@headers, [ "Host", $host ]);
1995 push(@headers, [ "User-agent", "Webmin" ]);
1997 my $auth = &encode_base64("$user:$pass");
1998 $auth =~ tr/\r\n//d;
1999 push(@headers, [ "Authorization", "Basic $auth" ]);
2001 foreach my $hname (keys %$headers) {
2002 push(@headers, [ $hname, $headers->{$hname} ]);
2005 # Actually download it
2006 $main::download_timed_out = undef;
2007 local $SIG{ALRM} = \&download_timeout;
2008 alarm($timeout || 60);
2009 my $h = &make_http_connection($host, $port, $ssl, "GET", $page, \@headers);
2011 $h = $main::download_timed_out if ($main::download_timed_out);
2013 if ($error) { $$error = $h; return; }
2014 else { &error($h); }
2016 &complete_http_download($h, $dest, $error, $cbfunc, $osdn, $host, $port,
2018 if ((!$error || !$$error) && !$nocache) {
2019 &write_to_http_cache($url, $dest);
2023 =head2 complete_http_download(handle, destfile, [&error], [&callback], [osdn], [oldhost], [oldport], [&send-headers], [old-ssl])
2025 Do a HTTP download, after the headers have been sent. For internal use only,
2026 typically called by http_download.
2029 sub complete_http_download
2031 local ($line, %header, @headers, $s); # Kept local so that callback funcs
2037 ($line = &read_http_connection($_[0])) =~ tr/\r\n//d;
2038 if ($line !~ /^HTTP\/1\..\s+(200|30[0-9])(\s+|$)/) {
2040 if ($_[2]) { ${$_[2]} = $line; return; }
2041 else { &error("Download failed : $line"); }
2044 &$cbfunc(1, $rcode >= 300 && $rcode < 400 ? 1 : 0)
2047 $line = &read_http_connection($_[0]);
2048 $line =~ tr/\r\n//d;
2049 $line =~ /^(\S+):\s+(.*)$/ || last;
2050 $header{lc($1)} = $2;
2051 push(@headers, [ lc($1), $2 ]);
2054 if ($main::download_timed_out) {
2055 if ($_[2]) { ${$_[2]} = $main::download_timed_out; return 0; }
2056 else { &error($main::download_timed_out); }
2058 &$cbfunc(2, $header{'content-length'}) if ($cbfunc);
2059 if ($rcode >= 300 && $rcode < 400) {
2060 # follow the redirect
2061 &$cbfunc(5, $header{'location'}) if ($cbfunc);
2062 my ($host, $port, $page, $ssl);
2063 if ($header{'location'} =~ /^(http|https):\/\/([^:]+):(\d+)(\/.*)?$/) {
2064 $ssl = $1 eq 'https' ? 1 : 0;
2065 $host = $2; $port = $3; $page = $4 || "/";
2067 elsif ($header{'location'} =~ /^(http|https):\/\/([^:\/]+)(\/.*)?$/) {
2068 $ssl = $1 eq 'https' ? 1 : 0;
2069 $host = $2; $port = 80; $page = $3 || "/";
2071 elsif ($header{'location'} =~ /^\// && $_[5]) {
2072 # Relative to same server
2076 $page = $header{'location'};
2078 elsif ($header{'location'}) {
2079 # Assume relative to same dir .. not handled
2080 if ($_[2]) { ${$_[2]} = "Invalid Location header $header{'location'}"; return; }
2081 else { &error("Invalid Location header $header{'location'}"); }
2084 if ($_[2]) { ${$_[2]} = "Missing Location header"; return; }
2085 else { &error("Missing Location header"); }
2087 &http_download($host, $port, $page, $_[1], $_[2], $cbfunc, $ssl,
2088 undef, undef, undef, $_[4], 0, $_[7]);
2093 # Append to a variable
2094 while(defined($buf = &read_http_connection($_[0], 1024))) {
2096 &$cbfunc(3, length(${$_[1]})) if ($cbfunc);
2102 if (!&open_tempfile(PFILE, ">$_[1]", 1)) {
2103 if ($_[2]) { ${$_[2]} = "Failed to write to $_[1] : $!"; return; }
2104 else { &error("Failed to write to $_[1] : $!"); }
2106 binmode(PFILE); # For windows
2107 while(defined($buf = &read_http_connection($_[0], 1024))) {
2108 &print_tempfile(PFILE, $buf);
2109 $got += length($buf);
2110 &$cbfunc(3, $got) if ($cbfunc);
2112 &close_tempfile(PFILE);
2113 if ($header{'content-length'} &&
2114 $got != $header{'content-length'}) {
2115 if ($_[2]) { ${$_[2]} = "Download incomplete"; return; }
2116 else { &error("Download incomplete"); }
2119 &$cbfunc(4) if ($cbfunc);
2121 &close_http_connection($_[0]);
2125 =head2 ftp_download(host, file, destfile, [&error], [&callback], [user, pass], [port])
2127 Download data from an FTP site to a local file. The parameters are :
2129 =item host - FTP server hostname
2131 =item file - File on the FTP server to download
2133 =item destfile - File on the Webmin system to download data to
2135 =item error - If set to a string ref, any error message is written into this string and the function returns 0 on failure, 1 on success. Otherwise, error is called on failure.
2137 =item callback - If set to a function ref, it will be called after each block of data is received. This is typically set to \&progress_callback, for printing download progress.
2139 =item user - Username to login to the FTP server as. If missing, Webmin will login as anonymous.
2141 =item pass - Password for the username above.
2143 =item port - FTP server port number, which defaults to 21 if not set.
2148 my ($host, $file, $dest, $error, $cbfunc, $user, $pass, $port) = @_;
2150 if ($gconfig{'debug_what_net'}) {
2151 &webmin_debug_log('FTP', "host=$host port=$port file=$file".
2152 ($user ? " user=$user pass=$pass" : "").
2153 (ref($dest) ? "" : " dest=$dest"));
2157 if (&is_readonly_mode()) {
2158 if ($_[3]) { ${$_[3]} = "FTP connections not allowed in readonly mode";
2160 else { &error("FTP connections not allowed in readonly mode"); }
2163 # Check if we already have cached the URL
2164 my $url = "ftp://".$host.$file;
2165 my $cfile = &check_in_http_cache($url);
2167 # Yes! Copy to dest file or variable
2168 &$cbfunc(6, $url) if ($cbfunc);
2170 &open_readfile(CACHEFILE, $cfile);
2172 $$dest = <CACHEFILE>;
2176 ©_source_dest($cfile, $dest);
2181 # Actually download it
2182 $main::download_timed_out = undef;
2183 local $SIG{ALRM} = \&download_timeout;
2186 if ($gconfig{'ftp_proxy'} =~ /^http:\/\/(\S+):(\d+)/ && !&no_proxy($_[0])) {
2187 # download through http-style proxy
2189 if (&open_socket($1, $2, "SOCK", \$error)) {
2191 if ($main::download_timed_out) {
2193 if ($_[3]) { ${$_[3]} = $main::download_timed_out; return 0; }
2194 else { &error($main::download_timed_out); }
2196 my $esc = $_[1]; $esc =~ s/ /%20/g;
2197 my $up = "$_[5]:$_[6]\@" if ($_[5]);
2198 my $portstr = $port == 21 ? "" : ":$port";
2199 print SOCK "GET ftp://$up$_[0]$portstr$esc HTTP/1.0\r\n";
2200 print SOCK "User-agent: Webmin\r\n";
2201 if ($gconfig{'proxy_user'}) {
2202 my $auth = &encode_base64(
2203 "$gconfig{'proxy_user'}:$gconfig{'proxy_pass'}");
2204 $auth =~ tr/\r\n//d;
2205 print SOCK "Proxy-Authorization: Basic $auth\r\n";
2208 &complete_http_download({ 'fh' => "SOCK" }, $_[2], $_[3], $_[4]);
2211 elsif (!$gconfig{'proxy_fallback'}) {
2213 if ($error) { $$error = $main::download_timed_out; return 0; }
2214 else { &error($main::download_timed_out); }
2219 # connect to host and login with real FTP protocol
2220 &open_socket($_[0], $port, "SOCK", $_[3]) || return 0;
2222 if ($main::download_timed_out) {
2223 if ($_[3]) { ${$_[3]} = $main::download_timed_out; return 0; }
2224 else { &error($main::download_timed_out); }
2226 &ftp_command("", 2, $_[3]) || return 0;
2228 # Login as supplied user
2229 my @urv = &ftp_command("USER $_[5]", [ 2, 3 ], $_[3]);
2231 if (int($urv[1]/100) == 3) {
2232 &ftp_command("PASS $_[6]", 2, $_[3]) || return 0;
2236 # Login as anonymous
2237 my @urv = &ftp_command("USER anonymous", [ 2, 3 ], $_[3]);
2239 if (int($urv[1]/100) == 3) {
2240 &ftp_command("PASS root\@".&get_system_hostname(), 2,
2244 &$cbfunc(1, 0) if ($cbfunc);
2247 # get the file size and tell the callback
2248 &ftp_command("TYPE I", 2, $_[3]) || return 0;
2249 my $size = &ftp_command("SIZE $_[1]", 2, $_[3]);
2250 defined($size) || return 0;
2252 &$cbfunc(2, int($size));
2256 my $pasv = &ftp_command("PASV", 2, $_[3]);
2257 defined($pasv) || return 0;
2258 $pasv =~ /\(([0-9,]+)\)/;
2259 @n = split(/,/ , $1);
2260 &open_socket("$n[0].$n[1].$n[2].$n[3]",
2261 $n[4]*256 + $n[5], "CON", $_[3]) || return 0;
2262 &ftp_command("RETR $_[1]", 1, $_[3]) || return 0;
2266 &open_tempfile(PFILE, ">$_[2]", 1);
2267 while(read(CON, $buf, 1024) > 0) {
2268 &print_tempfile(PFILE, $buf);
2269 $got += length($buf);
2270 &$cbfunc(3, $got) if ($cbfunc);
2272 &close_tempfile(PFILE);
2274 if ($got != $size) {
2275 if ($_[3]) { ${$_[3]} = "Download incomplete"; return 0; }
2276 else { &error("Download incomplete"); }
2278 &$cbfunc(4) if ($cbfunc);
2280 &ftp_command("", 2, $_[3]) || return 0;
2284 &ftp_command("QUIT", 2, $_[3]) || return 0;
2288 &write_to_http_cache($url, $dest);
2292 =head2 ftp_upload(host, file, srcfile, [&error], [&callback], [user, pass], [port])
2294 Upload data from a local file to an FTP site. The parameters are :
2296 =item host - FTP server hostname
2298 =item file - File on the FTP server to write to
2300 =item srcfile - File on the Webmin system to upload data from
2302 =item error - If set to a string ref, any error message is written into this string and the function returns 0 on failure, 1 on success. Otherwise, error is called on failure.
2304 =item callback - If set to a function ref, it will be called after each block of data is received. This is typically set to \&progress_callback, for printing upload progress.
2306 =item user - Username to login to the FTP server as. If missing, Webmin will login as anonymous.
2308 =item pass - Password for the username above.
2310 =item port - FTP server port number, which defaults to 21 if not set.
2317 if (&is_readonly_mode()) {
2318 if ($_[3]) { ${$_[3]} = "FTP connections not allowed in readonly mode";
2320 else { &error("FTP connections not allowed in readonly mode"); }
2323 $main::download_timed_out = undef;
2324 local $SIG{ALRM} = \&download_timeout;
2327 # connect to host and login
2328 &open_socket($_[0], $_[7] || 21, "SOCK", $_[3]) || return 0;
2330 if ($main::download_timed_out) {
2331 if ($_[3]) { ${$_[3]} = $main::download_timed_out; return 0; }
2332 else { &error($main::download_timed_out); }
2334 &ftp_command("", 2, $_[3]) || return 0;
2336 # Login as supplied user
2337 my @urv = &ftp_command("USER $_[5]", [ 2, 3 ], $_[3]);
2339 if (int($urv[1]/100) == 3) {
2340 &ftp_command("PASS $_[6]", 2, $_[3]) || return 0;
2344 # Login as anonymous
2345 my @urv = &ftp_command("USER anonymous", [ 2, 3 ], $_[3]);
2347 if (int($urv[1]/100) == 3) {
2348 &ftp_command("PASS root\@".&get_system_hostname(), 2,
2352 &$cbfunc(1, 0) if ($cbfunc);
2354 &ftp_command("TYPE I", 2, $_[3]) || return 0;
2356 # get the file size and tell the callback
2357 my @st = stat($_[2]);
2359 &$cbfunc(2, $st[7]);
2363 my $pasv = &ftp_command("PASV", 2, $_[3]);
2364 defined($pasv) || return 0;
2365 $pasv =~ /\(([0-9,]+)\)/;
2366 @n = split(/,/ , $1);
2367 &open_socket("$n[0].$n[1].$n[2].$n[3]", $n[4]*256 + $n[5], "CON", $_[3]) || return 0;
2368 &ftp_command("STOR $_[1]", 1, $_[3]) || return 0;
2373 while(read(PFILE, $buf, 1024) > 0) {
2375 $got += length($buf);
2376 &$cbfunc(3, $got) if ($cbfunc);
2380 if ($got != $st[7]) {
2381 if ($_[3]) { ${$_[3]} = "Upload incomplete"; return 0; }
2382 else { &error("Upload incomplete"); }
2384 &$cbfunc(4) if ($cbfunc);
2387 &ftp_command("", 2, $_[3]) || return 0;
2388 &ftp_command("QUIT", 2, $_[3]) || return 0;
2394 =head2 no_proxy(host)
2396 Checks if some host is on the no proxy list. For internal use by the
2397 http_download and ftp_download functions.
2402 my $ip = &to_ipaddress($_[0]);
2403 foreach my $n (split(/\s+/, $gconfig{'noproxy'})) {
2404 return 1 if ($_[0] =~ /\Q$n\E/ ||
2410 =head2 open_socket(host, port, handle, [&error])
2412 Open a TCP connection to some host and port, using a file handle. The
2415 =item host - Hostname or IP address to connect to.
2417 =item port - TCP port number.
2419 =item handle - A file handle name to use for the connection.
2421 =item error - A string reference to write any error message into. If not set, the error function is called on failure.
2426 my ($host, $port, $fh, $err) = @_;
2427 $fh = &callers_package($fh);
2429 if ($gconfig{'debug_what_net'}) {
2430 &webmin_debug_log('TCP', "host=$host port=$port");
2432 if (!socket($fh, PF_INET, SOCK_STREAM, getprotobyname("tcp"))) {
2433 if ($err) { $$err = "Failed to create socket : $!"; return 0; }
2434 else { &error("Failed to create socket : $!"); }
2437 if (!($addr = inet_aton($host))) {
2438 if ($err) { $$err = "Failed to lookup IP address for $host"; return 0; }
2439 else { &error("Failed to lookup IP address for $host"); }
2441 if ($gconfig{'bind_proxy'}) {
2442 if (!bind($fh,pack_sockaddr_in(0, inet_aton($gconfig{'bind_proxy'})))) {
2443 if ($err) { $$err = "Failed to bind to source address : $!"; return 0; }
2444 else { &error("Failed to bind to source address : $!"); }
2447 if (!connect($fh, pack_sockaddr_in($port, $addr))) {
2448 if ($err) { $$err = "Failed to connect to $host:$port : $!"; return 0; }
2449 else { &error("Failed to connect to $host:$port : $!"); }
2451 my $old = select($fh); $| =1; select($old);
2455 =head2 download_timeout
2457 Called when a download times out. For internal use only.
2460 sub download_timeout
2462 $main::download_timed_out = "Download timed out";
2465 =head2 ftp_command(command, expected, [&error], [filehandle])
2467 Send an FTP command, and die if the reply is not what was expected. Mainly
2468 for internal use by the ftp_download and ftp_upload functions.
2473 my ($cmd, $expect, $err, $fh) = @_;
2475 $fh = &callers_package($fh);
2478 my $what = $cmd ne "" ? "<i>$cmd</i>" : "initial connection";
2480 print $fh "$cmd\r\n";
2483 if (!($line = <$fh>)) {
2485 if ($err) { $$err = "Failed to read reply to $what"; return undef; }
2486 else { &error("Failed to read reply to $what"); }
2488 $line =~ /^(...)(.)(.*)$/;
2491 foreach my $c (@$expect) {
2492 $found++ if (int($1/100) == $c);
2496 $found++ if (int($1/100) == $_[1]);
2500 if ($err) { $$err = "$what failed : $3"; return undef; }
2501 else { &error("$what failed : $3"); }
2506 # Need to skip extra stuff..
2508 if (!($line = <$fh>)) {
2510 if ($$err) { $$err = "Failed to read reply to $what";
2512 else { &error("Failed to read reply to $what"); }
2514 $line =~ /^(....)(.*)$/; $reply .= $2;
2515 if ($1 eq "$rcode ") { last; }
2519 return wantarray ? ($reply, $rcode) : $reply;
2522 =head2 to_ipaddress(hostname)
2524 Converts a hostname to an a.b.c.d format IP address, or returns undef if
2525 it cannot be resolved.
2530 if (&check_ipaddress($_[0])) {
2534 my $hn = gethostbyname($_[0]);
2535 return undef if (!$hn);
2536 local @ip = unpack("CCCC", $hn);
2537 return join("." , @ip);
2541 =head2 icons_table(&links, &titles, &icons, [columns], [href], [width], [height], &befores, &afters)
2543 Renders a 4-column table of icons. The useful parameters are :
2545 =item links - An array ref of link destination URLs for the icons.
2547 =item titles - An array ref of titles to appear under the icons.
2549 =item icons - An array ref of URLs for icon images.
2551 =item columns - Number of columns to layout the icons with. Defaults to 4.
2556 &load_theme_library();
2557 if (defined(&theme_icons_table)) {
2558 &theme_icons_table(@_);
2562 my $cols = $_[3] ? $_[3] : 4;
2563 my $per = int(100.0 / $cols);
2564 print "<table class='icons_table' width=100% cellpadding=5>\n";
2565 for(my $i=0; $i<@{$_[0]}; $i++) {
2566 if ($i%$cols == 0) { print "<tr>\n"; }
2567 print "<td width=$per% align=center valign=top>\n";
2568 &generate_icon($_[2]->[$i], $_[1]->[$i], $_[0]->[$i],
2569 ref($_[4]) ? $_[4]->[$i] : $_[4], $_[5], $_[6],
2570 $_[7]->[$i], $_[8]->[$i]);
2572 if ($i%$cols == $cols-1) { print "</tr>\n"; }
2574 while($i++%$cols) { print "<td width=$per%></td>\n"; $need_tr++; }
2575 print "</tr>\n" if ($need_tr);
2579 =head2 replace_file_line(file, line, [newline]*)
2581 Replaces one line in some file with 0 or more new lines. The parameters are :
2583 =item file - Full path to some file, like /etc/hosts.
2585 =item line - Line number to replace, starting from 0.
2587 =item newline - Zero or more lines to put into the file at the given line number. These must be newline-terminated strings.
2590 sub replace_file_line
2593 my $realfile = &translate_filename($_[0]);
2594 open(FILE, $realfile);
2597 if (@_ > 2) { splice(@lines, $_[1], 1, @_[2..$#_]); }
2598 else { splice(@lines, $_[1], 1); }
2599 &open_tempfile(FILE, ">$realfile");
2600 &print_tempfile(FILE, @lines);
2601 &close_tempfile(FILE);
2604 =head2 read_file_lines(file, [readonly])
2606 Returns a reference to an array containing the lines from some file. This
2607 array can be modified, and will be written out when flush_file_lines()
2608 is called. The parameters are :
2610 =item file - Full path to the file to read.
2612 =item readonly - Should be set 1 if the caller is only going to read the lines, and never write it out.
2616 $lref = read_file_lines("/etc/hosts");
2617 push(@$lref, "127.0.0.1 localhost");
2618 flush_file_lines("/etc/hosts");
2624 my ($package, $filename, $line) = caller;
2625 print STDERR "Missing file to read at ${package}::${filename} line $line\n";
2627 my $realfile = &translate_filename($_[0]);
2628 if (!$main::file_cache{$realfile}) {
2631 &webmin_debug_log('READ', $_[0]) if ($gconfig{'debug_what_read'});
2632 open(READFILE, $realfile);
2635 $eol = /\r\n$/ ? "\r\n" : "\n";
2641 $main::file_cache{$realfile} = \@lines;
2642 $main::file_cache_noflush{$realfile} = $_[1];
2643 $main::file_cache_eol{$realfile} = $eol || "\n";
2646 # Make read-write if currently readonly
2648 $main::file_cache_noflush{$realfile} = 0;
2651 return $main::file_cache{$realfile};
2654 =head2 flush_file_lines([file], [eol])
2656 Write out to a file previously read by read_file_lines to disk (except
2657 for those marked readonly). The parameters are :
2659 =item file - The file to flush out.
2661 =item eof - End-of-line character for each line. Defaults to \n.
2664 sub flush_file_lines
2668 local $trans = &translate_filename($_[0]);
2669 $main::file_cache{$trans} ||
2670 &error("flush_file_lines called on non-loaded file $trans");
2671 push(@files, $trans);
2674 @files = ( keys %main::file_cache );
2676 foreach my $f (@files) {
2677 my $eol = $_[1] || $main::file_cache_eol{$f} || "\n";
2678 if (!$main::file_cache_noflush{$f}) {
2679 &open_tempfile(FLUSHFILE, ">$f");
2680 foreach my $line (@{$main::file_cache{$f}}) {
2681 (print FLUSHFILE $line,$eol) ||
2682 &error(&text("efilewrite", $f, $!));
2684 &close_tempfile(FLUSHFILE);
2686 delete($main::file_cache{$f});
2687 delete($main::file_cache_noflush{$f});
2691 =head2 unflush_file_lines(file)
2693 Clear the internal cache of some given file, previously read by read_file_lines.
2696 sub unflush_file_lines
2698 my $realfile = &translate_filename($_[0]);
2699 delete($main::file_cache{$realfile});
2700 delete($main::file_cache_noflush{$realfile});
2703 =head2 unix_user_input(fieldname, user, [form])
2705 Returns HTML for an input to select a Unix user. By default this is a text
2706 box with a user popup button next to it.
2711 if (defined(&theme_unix_user_input)) {
2712 return &theme_unix_user_input(@_);
2714 return "<input name=$_[0] size=13 value=\"$_[1]\"> ".
2715 &user_chooser_button($_[0], 0, $_[2] || 0)."\n";
2718 =head2 unix_group_input(fieldname, user, [form])
2720 Returns HTML for an input to select a Unix group. By default this is a text
2721 box with a group popup button next to it.
2724 sub unix_group_input
2726 if (defined(&theme_unix_group_input)) {
2727 return &theme_unix_group_input(@_);
2729 return "<input name=$_[0] size=13 value=\"$_[1]\"> ".
2730 &group_chooser_button($_[0], 0, $_[2] || 0)."\n";
2733 =head2 hlink(text, page, [module], [width], [height])
2735 Returns HTML for a link that when clicked on pops up a window for a Webmin
2736 help page. The parameters are :
2738 =item text - Text for the link.
2740 =item page - Help page code, such as 'intro'.
2742 =item module - Module the help page is in. Defaults to the current module.
2744 =item width - Width of the help popup window. Defaults to 600 pixels.
2746 =item height - Height of the help popup window. Defaults to 400 pixels.
2748 The actual help pages are in each module's help sub-directory, in files with
2754 if (defined(&theme_hlink)) {
2755 return &theme_hlink(@_);
2757 my $mod = $_[2] ? $_[2] : &get_module_name();
2758 my $width = $_[3] || $tconfig{'help_width'} || $gconfig{'help_width'} || 600;
2759 my $height = $_[4] || $tconfig{'help_height'} || $gconfig{'help_height'} || 400;
2760 return "<a onClick='window.open(\"$gconfig{'webprefix'}/help.cgi/$mod/$_[1]\", \"help\", \"toolbar=no,menubar=no,scrollbars=yes,width=$width,height=$height,resizable=yes\"); return false' href=\"$gconfig{'webprefix'}/help.cgi/$mod/$_[1]\">$_[0]</a>";
2763 =head2 user_chooser_button(field, multiple, [form])
2765 Returns HTML for a javascript button for choosing a Unix user or users.
2766 The parameters are :
2768 =item field - Name of the HTML field to place the username into.
2770 =item multiple - Set to 1 if multiple users can be selected.
2772 =item form - Index of the form on the page.
2775 sub user_chooser_button
2777 return undef if (!&supports_users());
2778 return &theme_user_chooser_button(@_)
2779 if (defined(&theme_user_chooser_button));
2780 my $form = defined($_[2]) ? $_[2] : 0;
2781 my $w = $_[1] ? 500 : 300;
2783 if ($_[1] && $gconfig{'db_sizeusers'}) {
2784 ($w, $h) = split(/x/, $gconfig{'db_sizeusers'});
2786 elsif (!$_[1] && $gconfig{'db_sizeuser'}) {
2787 ($w, $h) = split(/x/, $gconfig{'db_sizeuser'});
2789 return "<input type=button onClick='ifield = form.$_[0]; chooser = window.open(\"$gconfig{'webprefix'}/user_chooser.cgi?multi=$_[1]&user=\"+escape(ifield.value), \"chooser\", \"toolbar=no,menubar=no,scrollbars=yes,resizable=yes,width=$w,height=$h\"); chooser.ifield = ifield; window.ifield = ifield' value=\"...\">\n";
2792 =head2 group_chooser_button(field, multiple, [form])
2794 Returns HTML for a javascript button for choosing a Unix group or groups
2795 The parameters are :
2797 =item field - Name of the HTML field to place the group name into.
2799 =item multiple - Set to 1 if multiple groups can be selected.
2801 =item form - Index of the form on the page.
2804 sub group_chooser_button
2806 return undef if (!&supports_users());
2807 return &theme_group_chooser_button(@_)
2808 if (defined(&theme_group_chooser_button));
2809 my $form = defined($_[2]) ? $_[2] : 0;
2810 my $w = $_[1] ? 500 : 300;
2812 if ($_[1] && $gconfig{'db_sizeusers'}) {
2813 ($w, $h) = split(/x/, $gconfig{'db_sizeusers'});
2815 elsif (!$_[1] && $gconfig{'db_sizeuser'}) {
2816 ($w, $h) = split(/x/, $gconfig{'db_sizeuser'});
2818 return "<input type=button onClick='ifield = form.$_[0]; chooser = window.open(\"$gconfig{'webprefix'}/group_chooser.cgi?multi=$_[1]&group=\"+escape(ifield.value), \"chooser\", \"toolbar=no,menubar=no,scrollbars=yes,resizable=yes,width=$w,height=$h\"); chooser.ifield = ifield; window.ifield = ifield' value=\"...\">\n";
2821 =head2 foreign_check(module, [api-only])
2823 Checks if some other module exists and is supported on this OS. The parameters
2826 =item module - Name of the module to check.
2828 =item api-only - Set to 1 if you just want to check if the module provides an API that others can call, instead of the full web UI.
2833 my ($mod, $api) = @_;
2835 my $mdir = &module_root_directory($mod);
2836 &read_file_cached("$mdir/module.info", \%minfo) || return 0;
2837 return &check_os_support(\%minfo, undef, undef, $api);
2840 =head2 foreign_exists(module)
2842 Checks if some other module exists. The module parameter is the short module
2848 my $mdir = &module_root_directory($_[0]);
2849 return -r "$mdir/module.info";
2852 =head2 foreign_available(module)
2854 Returns 1 if some module is installed, and acessible to the current user. The
2855 module parameter is the module directory name.
2858 sub foreign_available
2860 return 0 if (!&foreign_check($_[0]) &&
2861 !$gconfig{'available_even_if_no_support'});
2862 my %foreign_module_info = &get_module_info($_[0]);
2864 # Check list of allowed modules
2866 &read_acl(\%acl, undef);
2867 return 0 if (!$acl{$base_remote_user,$_[0]} &&
2868 !$acl{$base_remote_user,'*'});
2870 # Check for usermod restrictions
2871 my @usermods = &list_usermods();
2872 return 0 if (!&available_usermods( [ \%foreign_module_info ], \@usermods));
2874 if (&get_product_name() eq "webmin") {
2875 # Check if the user has any RBAC privileges in this module
2876 if (&supports_rbac($_[0]) &&
2877 &use_rbac_module_acl(undef, $_[0])) {
2878 # RBAC is enabled for this user and module - check if he
2880 my $rbacs = &get_rbac_module_acl($remote_user, $_[0]);
2881 return 0 if (!$rbacs);
2883 elsif ($gconfig{'rbacdeny_'.$u}) {
2884 # If denying access to modules not specifically allowed by
2885 # RBAC, then prevent access
2890 # Check readonly support
2891 if (&is_readonly_mode()) {
2892 return 0 if (!$foreign_module_info{'readonly'});
2895 # Check if theme vetos
2896 if (defined(&theme_foreign_available)) {
2897 return 0 if (!&theme_foreign_available($_[0]));
2900 # Check if licence module vetos
2901 if ($main::licence_module) {
2902 return 0 if (!&foreign_call($main::licence_module,
2903 "check_module_licence", $_[0]));
2909 =head2 foreign_require(module, [file], [package])
2911 Brings in functions from another module, and places them in the Perl namespace
2912 with the same name as the module. The parameters are :
2914 =item module - The source module's directory name, like sendmail.
2916 =item file - The API file in that module, like sendmail-lib.pl. If missing, all API files are loaded.
2918 =item package - Perl package to place the module's functions and global variables in.
2920 If the original module name contains dashes, they will be replaced with _ in
2926 my ($mod, $file, $pkg) = @_;
2927 $pkg ||= $mod || "global";
2928 $pkg =~ s/[^A-Za-z0-9]/_/g;
2931 push(@files, $file);
2935 my %minfo = &get_module_info($mod);
2936 if ($minfo{'library'}) {
2937 @files = split(/\s+/, $minfo{'library'});
2940 @files = ( $mod."-lib.pl" );
2943 my @files = grep { !$main::done_foreign_require{$pkg,$_} } @files;
2944 return 1 if (!@files);
2945 foreach my $f (@files) {
2946 $main::done_foreign_require{$pkg,$f}++;
2949 my $mdir = &module_root_directory($mod);
2950 @INC = &unique($mdir, @INC);
2951 -d $mdir || &error("Module $mod does not exist");
2952 if (!&get_module_name() && $mod) {
2955 my $old_fmn = $ENV{'FOREIGN_MODULE_NAME'};
2956 my $old_frd = $ENV{'FOREIGN_ROOT_DIRECTORY'};
2957 my $code = "package $pkg; ".
2958 "\$ENV{'FOREIGN_MODULE_NAME'} = '$mod'; ".
2959 "\$ENV{'FOREIGN_ROOT_DIRECTORY'} = '$root_directory'; ";
2960 foreach my $f (@files) {
2961 $code .= "do '$mdir/$f' || die \$@; ";
2964 if (defined($old_fmn)) {
2965 $ENV{'FOREIGN_MODULE_NAME'} = $old_fmn;
2968 delete($ENV{'FOREIGN_MODULE_NAME'});
2970 if (defined($old_frd)) {
2971 $ENV{'FOREIGN_ROOT_DIRECTORY'} = $old_frd;
2974 delete($ENV{'FOREIGN_ROOT_DIRECTORY'});
2977 if ($@) { &error("Require $mod/$files[0] failed : <pre>$@</pre>"); }
2981 =head2 foreign_call(module, function, [arg]*)
2983 Call a function in another module. The module parameter is the target module
2984 directory name, function is the perl sub to call, and the remaining parameters
2985 are the arguments. However, unless you need to call a function whose name
2986 is dynamic, it is better to use Perl's cross-module function call syntax
2987 like module::function(args).
2992 my $pkg = $_[0] || "global";
2993 $pkg =~ s/[^A-Za-z0-9]/_/g;
2994 my @args = @_[2 .. @_-1];
2995 $main::foreign_args = \@args;
2996 my @rv = eval <<EOF;
2998 &$_[1](\@{\$main::foreign_args});
3000 if ($@) { &error("$_[0]::$_[1] failed : $@"); }
3001 return wantarray ? @rv : $rv[0];
3004 =head2 foreign_config(module, [user-config])
3006 Get the configuration from another module, and return it as a hash. If the
3007 user-config parameter is set to 1, returns the Usermin user-level preferences
3008 for the current user instead.
3013 my ($mod, $uc) = @_;
3016 &read_file_cached("$root_directory/$mod/defaultuconfig", \%fconfig);
3017 &read_file_cached("$config_directory/$mod/uconfig", \%fconfig);
3018 &read_file_cached("$user_config_directory/$mod/config", \%fconfig);
3021 &read_file_cached("$config_directory/$mod/config", \%fconfig);
3026 =head2 foreign_installed(module, mode)
3028 Checks if the server for some module is installed, and possibly also checks
3029 if the module has been configured by Webmin.
3030 For mode 1, returns 2 if the server is installed and configured for use by
3031 Webmin, 1 if installed but not configured, or 0 otherwise.
3032 For mode 0, returns 1 if installed, 0 if not.
3033 If the module does not provide an install_check.pl script, assumes that
3034 the server is installed.
3037 sub foreign_installed
3039 my ($mod, $configured) = @_;
3040 if (defined($main::foreign_installed_cache{$mod,$configured})) {
3042 return $main::foreign_installed_cache{$mod,$configured};
3046 if (!&foreign_check($mod)) {
3051 my $mdir = &module_root_directory($mod);
3052 if (!-r "$mdir/install_check.pl") {
3053 # Not known, assume OK
3054 $rv = $configured ? 2 : 1;
3057 # Call function to check
3058 &foreign_require($mod, "install_check.pl");
3059 $rv = &foreign_call($mod, "is_installed", $configured);
3062 $main::foreign_installed_cache{$mod,$configured} = $rv;
3067 =head2 foreign_defined(module, function)
3069 Returns 1 if some function is defined in another module. In general, it is
3070 simpler to use the syntax &defined(module::function) instead.
3076 $pkg =~ s/[^A-Za-z0-9]/_/g;
3077 my $func = "${pkg}::$_[1]";
3078 return defined(&$func);
3081 =head2 get_system_hostname([short])
3083 Returns the hostname of this system. If the short parameter is set to 1,
3084 then the domain name is not prepended - otherwise, Webmin will attempt to get
3085 the fully qualified hostname, like foo.example.com.
3088 sub get_system_hostname
3091 if (!$main::get_system_hostname[$m]) {
3092 if ($gconfig{'os_type'} ne 'windows') {
3093 # Try some common Linux hostname files first
3095 if ($gconfig{'os_type'} eq 'redhat-linux') {
3097 &read_env_file("/etc/sysconfig/network", \%nc);
3098 if ($nc{'HOSTNAME'}) {
3099 $fromfile = $nc{'HOSTNAME'};
3102 elsif ($gconfig{'os_type'} eq 'debian-linux') {
3103 my $hn = &read_file_contents("/etc/hostname");
3109 elsif ($gconfig{'os_type'} eq 'open-linux') {
3110 my $hn = &read_file_contents("/etc/HOSTNAME");
3116 elsif ($gconfig{'os_type'} eq 'solaris') {
3117 my $hn = &read_file_contents("/etc/nodename");
3124 # If we found a hostname, use it if value
3125 if ($fromfile && ($m || $fromfile =~ /\./)) {
3127 $fromfile =~ s/\..*$//;
3129 $main::get_system_hostname[$m] = $fromfile;
3133 # Can use hostname command on Unix
3134 &execute_command("hostname", undef,
3135 \$main::get_system_hostname[$m], undef, 0, 1);
3136 chop($main::get_system_hostname[$m]);
3138 eval "use Sys::Hostname";
3140 $main::get_system_hostname[$m] = eval "hostname()";
3142 if ($@ || !$main::get_system_hostname[$m]) {
3143 $main::get_system_hostname[$m] = "UNKNOWN";
3146 elsif ($main::get_system_hostname[$m] !~ /\./ &&
3147 $gconfig{'os_type'} =~ /linux$/ &&
3148 !$gconfig{'no_hostname_f'} && !$_[0]) {
3149 # Try with -f flag to get fully qualified name
3151 my $ex = &execute_command("hostname -f", undef, \$flag,
3154 if ($ex || $flag eq "") {
3155 # -f not supported! We have probably set the
3156 # hostname to just '-f'. Fix the problem
3159 &execute_command("hostname ".
3160 quotemeta($main::get_system_hostname[$m]),
3161 undef, undef, undef, 0, 1);
3165 $main::get_system_hostname[$m] = $flag;
3170 # On Windows, try computername environment variable
3171 return $ENV{'computername'} if ($ENV{'computername'});
3172 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
3174 # Fall back to net name command
3175 my $out = `net name 2>&1`;
3176 if ($out =~ /\-+\r?\n(\S+)/) {
3177 $main::get_system_hostname[$m] = $1;
3180 $main::get_system_hostname[$m] = "windows";
3184 return $main::get_system_hostname[$m];
3187 =head2 get_webmin_version
3189 Returns the version of Webmin currently being run, such as 1.450.
3192 sub get_webmin_version
3194 if (!$get_webmin_version) {
3195 open(VERSION, "$root_directory/version") || return 0;
3196 ($get_webmin_version = <VERSION>) =~ tr/\r|\n//d;
3199 return $get_webmin_version;
3202 =head2 get_module_acl([user], [module], [no-rbac], [no-default])
3204 Returns a hash containing access control options for the given user and module.
3205 By default the current username and module name are used. If the no-rbac flag
3206 is given, the permissions will not be updated based on the user's RBAC role
3207 (as seen on Solaris). If the no-default flag is given, default permissions for
3208 the module will not be included.
3213 my $u = defined($_[0]) ? $_[0] : $base_remote_user;
3214 my $m = defined($_[1]) ? $_[1] : &get_module_name();
3215 my $mdir = &module_root_directory($m);
3218 # Read default ACL first, to be overridden by per-user settings
3219 &read_file_cached("$mdir/defaultacl", \%rv);
3221 # If this isn't a master admin user, apply the negative permissions
3222 # so that he doesn't un-expectedly gain access to new features
3224 &read_file_cached("$config_directory/$u.acl", \%gaccess);
3225 if ($gaccess{'negative'}) {
3226 &read_file_cached("$mdir/negativeacl", \%rv);
3230 if (!$_[2] && &supports_rbac($m) && &use_rbac_module_acl($u, $m)) {
3231 # RBAC overrides exist for this user in this module
3232 my $rbac = &get_rbac_module_acl(
3233 defined($_[0]) ? $_[0] : $remote_user, $m);
3234 foreach my $r (keys %$rbac) {
3235 $rv{$r} = $rbac->{$r};
3238 elsif ($gconfig{"risk_$u"} && $m) {
3239 # ACL is defined by user's risk level
3240 my $rf = $gconfig{"risk_$u"}.'.risk';
3241 &read_file_cached("$mdir/$rf", \%rv);
3243 my $sf = $gconfig{"skill_$u"}.'.skill';
3244 &read_file_cached("$mdir/$sf", \%rv);
3247 # Use normal Webmin ACL, if a user is set
3248 &read_file_cached("$config_directory/$m/$u.acl", \%rv);
3249 if ($remote_user ne $base_remote_user && !defined($_[0])) {
3250 &read_file_cached("$config_directory/$m/$remote_user.acl",\%rv);
3253 if ($tconfig{'preload_functions'}) {
3254 &load_theme_library();
3256 if (defined(&theme_get_module_acl)) {
3257 %rv = &theme_get_module_acl($u, $m, \%rv);
3262 =head2 get_group_module_acl(group, [module])
3264 Returns the ACL for a Webmin group, in an optional module (which defaults to
3265 the current module).
3268 sub get_group_module_acl
3271 my $m = defined($_[1]) ? $_[1] : &get_module_name();
3272 my $mdir = &module_root_directory($m);
3274 &read_file_cached("$mdir/defaultacl", \%rv);
3275 &read_file_cached("$config_directory/$m/$g.gacl", \%rv);
3276 if (defined(&theme_get_module_acl)) {
3277 %rv = &theme_get_module_acl($g, $m, \%rv);
3282 =head2 save_module_acl(&acl, [user], [module])
3284 Updates the acl hash for some user and module. The parameters are :
3286 =item acl - Hash reference for the new access control options.
3288 =item user - User to update, defaulting to the current user.
3290 =item module - Module to update, defaulting to the caller.
3295 my $u = defined($_[1]) ? $_[1] : $base_remote_user;
3296 my $m = defined($_[2]) ? $_[2] : &get_module_name();
3297 if (&foreign_check("acl")) {
3298 # Check if this user is a member of a group, and if he gets the
3299 # module from a group. If so, update its ACL as well
3300 &foreign_require("acl", "acl-lib.pl");
3302 foreach my $g (&acl::list_groups()) {
3303 if (&indexof($u, @{$g->{'members'}}) >= 0 &&
3304 &indexof($m, @{$g->{'modules'}}) >= 0) {
3310 &save_group_module_acl($_[0], $group->{'name'}, $m);
3313 if (!-d "$config_directory/$m") {
3314 mkdir("$config_directory/$m", 0755);
3316 &write_file("$config_directory/$m/$u.acl", $_[0]);
3319 =head2 save_group_module_acl(&acl, group, [module])
3321 Updates the acl hash for some group and module. The parameters are :
3323 =item acl - Hash reference for the new access control options.
3325 =item group - Group name to update.
3327 =item module - Module to update, defaulting to the caller.
3330 sub save_group_module_acl
3333 my $m = defined($_[2]) ? $_[2] : &get_module_name();
3334 if (&foreign_check("acl")) {
3335 # Check if this group is a member of a group, and if it gets the
3336 # module from a group. If so, update the parent ACL as well
3337 &foreign_require("acl", "acl-lib.pl");
3339 foreach my $pg (&acl::list_groups()) {
3340 if (&indexof('@'.$g, @{$pg->{'members'}}) >= 0 &&
3341 &indexof($m, @{$pg->{'modules'}}) >= 0) {
3347 &save_group_module_acl($_[0], $group->{'name'}, $m);
3350 if (!-d "$config_directory/$m") {
3351 mkdir("$config_directory/$m", 0755);
3353 &write_file("$config_directory/$m/$g.gacl", $_[0]);
3358 This function must be called by all Webmin CGI scripts, either directly or
3359 indirectly via a per-module lib.pl file. It performs a number of initialization
3360 and housekeeping tasks, such as working out the module name, checking that the
3361 current user has access to the module, and populating global variables. Some
3362 of the variables set include :
3364 =item $config_directory - Base Webmin config directory, typically /etc/webmin
3366 =item $var_directory - Base logs directory, typically /var/webmin
3368 =item %config - Per-module configuration.
3370 =item %gconfig - Global configuration.
3372 =item $scriptname - Base name of the current perl script.
3374 =item $module_name - The name of the current module.
3376 =item $module_config_directory - The config directory for this module.
3378 =item $module_config_file - The config file for this module.
3380 =item $module_root_directory - This module's code directory.
3382 =item $webmin_logfile - The detailed logfile for webmin.
3384 =item $remote_user - The actual username used to login to webmin.
3386 =item $base_remote_user - The username whose permissions are in effect.
3388 =item $current_theme - The theme currently in use.
3390 =item $root_directory - The first root directory of this webmin install.
3392 =item @root_directories - All root directories for this webmin install.
3397 # Record first process ID that called this, so we know when it exited to clean
3399 $main::initial_process_id ||= $$;
3401 # Configuration and spool directories
3402 if (!defined($ENV{'WEBMIN_CONFIG'})) {
3403 die "WEBMIN_CONFIG not set";
3405 $config_directory = $ENV{'WEBMIN_CONFIG'};
3406 if (!defined($ENV{'WEBMIN_VAR'})) {
3407 open(VARPATH, "$config_directory/var-path");
3408 chop($var_directory = <VARPATH>);
3412 $var_directory = $ENV{'WEBMIN_VAR'};
3414 $main::http_cache_directory = $ENV{'WEBMIN_VAR'}."/cache";
3415 $main::default_debug_log_file = $ENV{'WEBMIN_VAR'}."/webmin.debug";
3417 if ($ENV{'SESSION_ID'}) {
3418 # Hide this variable from called programs, but keep it for internal use
3419 $main::session_id = $ENV{'SESSION_ID'};
3420 delete($ENV{'SESSION_ID'});
3422 if ($ENV{'REMOTE_PASS'}) {
3423 # Hide the password too
3424 $main::remote_pass = $ENV{'REMOTE_PASS'};
3425 delete($ENV{'REMOTE_PASS'});
3428 if ($> == 0 && $< != 0 && !$ENV{'FOREIGN_MODULE_NAME'}) {
3429 # Looks like we are running setuid, but the real UID hasn't been set.
3430 # Do so now, so that executed programs don't get confused
3435 # Read the webmin global config file. This contains the OS type and version,
3436 # OS specific configuration and global options such as proxy servers
3437 $config_file = "$config_directory/config";
3439 &read_file_cached($config_file, \%gconfig);
3440 $null_file = $gconfig{'os_type'} eq 'windows' ? "NUL" : "/dev/null";
3441 $path_separator = $gconfig{'os_type'} eq 'windows' ? ';' : ':';
3443 # If debugging is enabled, open the debug log
3444 if ($gconfig{'debug_enabled'} && !$main::opened_debug_log++) {
3445 my $dlog = $gconfig{'debug_file'} || $main::default_debug_log_file;
3446 if ($gconfig{'debug_size'}) {
3447 my @st = stat($dlog);
3448 if ($st[7] > $gconfig{'debug_size'}) {
3449 rename($dlog, $dlog.".0");
3452 open(main::DEBUGLOG, ">>$dlog");
3453 $main::opened_debug_log = 1;
3455 if ($gconfig{'debug_what_start'}) {
3456 my $script_name = $0 =~ /([^\/]+)$/ ? $1 : '-';
3457 $main::debug_log_start_time = time();
3458 &webmin_debug_log("START", "script=$script_name");
3459 $main::debug_log_start_module = $module_name;
3463 # Set PATH and LD_LIBRARY_PATH
3464 if ($gconfig{'path'}) {
3465 if ($gconfig{'syspath'}) {
3467 $ENV{'PATH'} = $gconfig{'path'};
3471 $ENV{'PATH'} = $gconfig{'path'}.$path_separator.$ENV{'PATH'};
3474 $ENV{$gconfig{'ld_env'}} = $gconfig{'ld_path'} if ($gconfig{'ld_env'});
3476 # Set http_proxy and ftp_proxy environment variables, based on Webmin settings
3477 if ($gconfig{'http_proxy'}) {
3478 $ENV{'http_proxy'} = $gconfig{'http_proxy'};
3480 if ($gconfig{'ftp_proxy'}) {
3481 $ENV{'ftp_proxy'} = $gconfig{'ftp_proxy'};
3483 if ($gconfig{'noproxy'}) {
3484 $ENV{'no_proxy'} = $gconfig{'noproxy'};
3487 # Find all root directories
3489 if (&get_miniserv_config(\%miniserv)) {
3490 @root_directories = ( $miniserv{'root'} );
3491 for($i=0; defined($miniserv{"extraroot_$i"}); $i++) {
3492 push(@root_directories, $miniserv{"extraroot_$i"});
3496 # Work out which module we are in, and read the per-module config file
3497 $0 =~ s/\\/\//g; # Force consistent path on Windows
3498 if (defined($ENV{'FOREIGN_MODULE_NAME'})) {
3499 # In a foreign call - use the module name given
3500 $root_directory = $ENV{'FOREIGN_ROOT_DIRECTORY'};
3501 $module_name = $ENV{'FOREIGN_MODULE_NAME'};
3502 @root_directories = ( $root_directory ) if (!@root_directories);
3504 elsif ($ENV{'SCRIPT_NAME'}) {
3505 my $sn = $ENV{'SCRIPT_NAME'};
3506 $sn =~ s/^$gconfig{'webprefix'}//
3507 if (!$gconfig{'webprefixnoredir'});
3508 if ($sn =~ /^\/([^\/]+)\//) {
3509 # Get module name from CGI path
3512 if ($ENV{'SERVER_ROOT'}) {
3513 $root_directory = $ENV{'SERVER_ROOT'};
3515 elsif ($ENV{'SCRIPT_FILENAME'}) {
3516 $root_directory = $ENV{'SCRIPT_FILENAME'};
3517 $root_directory =~ s/$sn$//;
3519 @root_directories = ( $root_directory ) if (!@root_directories);
3522 # Get root directory from miniserv.conf, and deduce module name from $0
3523 $root_directory = $root_directories[0];
3525 foreach my $r (@root_directories) {
3526 if ($0 =~ /^$r\/([^\/]+)\/[^\/]+$/i) {
3527 # Under a module directory
3532 elsif ($0 =~ /^$root_directory\/[^\/]+$/i) {
3538 &error("Script was not run with full path (failed to find $0 under $root_directory)") if (!$rok);
3541 # Work out of this is a web, command line or cron job
3542 if (!$main::webmin_script_type) {
3543 if ($ENV{'SCRIPT_NAME'}) {
3545 $main::webmin_script_type = 'web';
3548 # Cron jobs have no TTY
3549 if ($gconfig{'os_type'} eq 'windows' ||
3550 open(DEVTTY, ">/dev/tty")) {
3551 $main::webmin_script_type = 'cmd';
3555 $main::webmin_script_type = 'cron';
3560 # Set the umask based on config
3561 if ($gconfig{'umask'} && !$main::umask_already++) {
3562 umask(oct($gconfig{'umask'}));
3565 # If this is a cron job or other background task, set the nice level
3566 if (!$main::nice_already && $main::webmin_script_type eq 'cron') {
3568 if ($gconfig{'nice'}) {
3569 eval 'POSIX::nice($gconfig{\'nice\'});';
3572 # Set IO scheduling class and priority
3573 if ($gconfig{'sclass'} ne '' || $gconfig{'sprio'} ne '') {
3575 $cmd .= " -c ".quotemeta($gconfig{'sclass'})
3576 if ($gconfig{'sclass'} ne '');
3577 $cmd .= " -n ".quotemeta($gconfig{'sprio'})
3578 if ($gconfig{'sprio'} ne '');
3580 &execute_command("$cmd >/dev/null 2>&1");
3583 $main::nice_already++;
3586 my $u = $ENV{'BASE_REMOTE_USER'} || $ENV{'REMOTE_USER'};
3587 $base_remote_user = $u;
3588 $remote_user = $ENV{'REMOTE_USER'};
3591 # Find and load the configuration file for this module
3592 my (@ruinfo, $rgroup);
3593 $module_config_directory = "$config_directory/$module_name";
3594 if (&get_product_name() eq "usermin" &&
3595 -r "$module_config_directory/config.$remote_user") {
3597 $module_config_file = "$module_config_directory/config.$remote_user";
3599 elsif (&get_product_name() eq "usermin" &&
3600 (@ruinfo = getpwnam($remote_user)) &&
3601 ($rgroup = getgrgid($ruinfo[3])) &&
3602 -r "$module_config_directory/config.\@$rgroup") {
3603 # Based on group name
3604 $module_config_file = "$module_config_directory/config.\@$rgroup";
3608 $module_config_file = "$module_config_directory/config";
3611 &read_file_cached($module_config_file, \%config);
3613 # Fix up windows-specific substitutions in values
3614 foreach my $k (keys %config) {
3615 if ($config{$k} =~ /\$\{systemroot\}/) {
3616 my $root = &get_windows_root();
3617 $config{$k} =~ s/\$\{systemroot\}/$root/g;
3622 # Record the initial module
3623 $main::initial_module_name ||= $module_name;
3625 # Set some useful variables
3627 $current_themes = $ENV{'MOBILE_DEVICE'} && defined($gconfig{'mobile_theme'}) ?
3628 $gconfig{'mobile_theme'} :
3629 defined($gconfig{'theme_'.$remote_user}) ?
3630 $gconfig{'theme_'.$remote_user} :
3631 defined($gconfig{'theme_'.$base_remote_user}) ?
3632 $gconfig{'theme_'.$base_remote_user} :
3634 @current_themes = split(/\s+/, $current_themes);
3635 $current_theme = $current_themes[0];
3636 @theme_root_directories = map { "$root_directory/$_" } @current_themes;
3637 $theme_root_directory = $theme_root_directories[0];
3638 @theme_configs = ( );
3639 foreach my $troot (@theme_root_directories) {
3641 &read_file_cached("$troot/config", \%onetconfig);
3642 &read_file_cached("$troot/config", \%tconfig);
3643 push(@theme_configs, \%onetconfig);
3645 $tb = defined($tconfig{'cs_header'}) ? "bgcolor=#$tconfig{'cs_header'}" :
3646 defined($gconfig{'cs_header'}) ? "bgcolor=#$gconfig{'cs_header'}" :
3648 $cb = defined($tconfig{'cs_table'}) ? "bgcolor=#$tconfig{'cs_table'}" :
3649 defined($gconfig{'cs_table'}) ? "bgcolor=#$gconfig{'cs_table'}" :
3651 $tb .= ' '.$tconfig{'tb'} if ($tconfig{'tb'});
3652 $cb .= ' '.$tconfig{'cb'} if ($tconfig{'cb'});
3653 if ($tconfig{'preload_functions'}) {
3654 # Force load of theme functions right now, if requested
3655 &load_theme_library();
3657 if ($tconfig{'oofunctions'} && !$main::loaded_theme_oo_library++) {
3658 # Load the theme's Webmin:: package classes
3659 do "$theme_root_directory/$tconfig{'oofunctions'}";
3664 $webmin_logfile = $gconfig{'webmin_log'} ? $gconfig{'webmin_log'}
3665 : "$var_directory/webmin.log";
3667 # Load language strings into %text
3668 my @langs = &list_languages();
3670 if ($gconfig{'acceptlang'}) {
3671 foreach my $a (split(/,/, $ENV{'HTTP_ACCEPT_LANGUAGE'})) {
3672 my ($al) = grep { $_->{'lang'} eq $a } @langs;
3674 $accepted_lang = $al->{'lang'};
3679 $current_lang = $force_lang ? $force_lang :
3680 $accepted_lang ? $accepted_lang :
3681 $gconfig{"lang_$remote_user"} ? $gconfig{"lang_$remote_user"} :
3682 $gconfig{"lang_$base_remote_user"} ? $gconfig{"lang_$base_remote_user"} :
3683 $gconfig{"lang"} ? $gconfig{"lang"} : $default_lang;
3684 foreach my $l (@langs) {
3685 $current_lang_info = $l if ($l->{'lang'} eq $current_lang);
3687 @lang_order_list = &unique($default_lang,
3688 split(/:/, $current_lang_info->{'fallback'}),
3690 %text = &load_language($module_name);
3691 %text || &error("Failed to determine Webmin root from SERVER_ROOT, SCRIPT_FILENAME or the full command line");
3693 # Get the %module_info for this module
3695 my ($mi) = grep { $_->{'dir'} eq $module_name }
3696 &get_all_module_infos(2);
3697 %module_info = %$mi;
3698 $module_root_directory = &module_root_directory($module_name);
3701 if ($module_name && !$main::no_acl_check &&
3702 !defined($ENV{'FOREIGN_MODULE_NAME'})) {
3703 # Check if the HTTP user can access this module
3704 if (!&foreign_available($module_name)) {
3705 if (!&foreign_check($module_name)) {
3706 &error(&text('emodulecheck',
3707 "<i>$module_info{'desc'}</i>"));
3710 &error(&text('emodule', "<i>$u</i>",
3711 "<i>$module_info{'desc'}</i>"));
3714 $main::no_acl_check++;
3717 # Check the Referer: header for nasty redirects
3718 my @referers = split(/\s+/, $gconfig{'referers'});
3720 if ($ENV{'HTTP_REFERER'} =~/^(http|https|ftp):\/\/([^:\/]+:[^@\/]+@)?([^\/:@]+)/) {
3723 my $http_host = $ENV{'HTTP_HOST'};
3724 $http_host =~ s/:\d+$//;
3726 ($ENV{'SCRIPT_NAME'} !~ /^\/(index.cgi)?$/ || $unsafe_index_cgi) &&
3727 ($ENV{'SCRIPT_NAME'} !~ /^\/([a-z0-9\_\-]+)\/(index.cgi)?$/i ||
3728 $unsafe_index_cgi) &&
3729 $0 !~ /(session_login|pam_login)\.cgi$/ && !$gconfig{'referer'} &&
3730 $ENV{'MINISERV_CONFIG'} && !$main::no_referers_check &&
3731 $ENV{'HTTP_USER_AGENT'} !~ /^Webmin/i &&
3732 ($referer_site && $referer_site ne $http_host &&
3733 &indexof($referer_site, @referers) < 0 ||
3734 !$referer_site && $gconfig{'referers_none'}) &&
3735 !$trust_unknown_referers &&
3736 !&get_module_variable('$trust_unknown_referers')) {
3737 # Looks like a link from elsewhere .. show an error
3738 &header($text{'referer_title'}, "", undef, 0, 1, 1);
3740 $prot = lc($ENV{'HTTPS'}) eq 'on' ? "https" : "http";
3741 my $url = "<tt>".&html_escape("$prot://$ENV{'HTTP_HOST'}$ENV{'REQUEST_URI'}")."</tt>";
3742 if ($referer_site) {
3744 print &text('referer_warn',
3745 "<tt>".&html_escape($ENV{'HTTP_REFERER'})."</tt>", $url);
3747 print &text('referer_fix1', &html_escape($http_host)),"<p>\n";
3748 print &text('referer_fix2', &html_escape($http_host)),"<p>\n";
3751 # No referer info given
3752 print &text('referer_warn_unknown', $url),"<p>\n";
3753 print &text('referer_fix1u'),"<p>\n";
3754 print &text('referer_fix2u'),"<p>\n";
3758 &footer("/", $text{'index'});
3761 $main::no_referers_check++;
3762 $main::completed_referers_check++;
3764 # Call theme post-init
3765 if (defined(&theme_post_init_config)) {
3766 &theme_post_init_config(@_);
3769 # Record that we have done the calling library in this package
3770 my ($callpkg, $lib) = caller();
3772 $main::done_foreign_require{$callpkg,$lib} = 1;
3774 # If a licence checking is enabled, do it now
3775 if ($gconfig{'licence_module'} && !$main::done_licence_module_check &&
3776 &foreign_check($gconfig{'licence_module'}) &&
3777 -r "$root_directory/$gconfig{'licence_module'}/licence_check.pl") {
3778 my $oldpwd = &get_current_dir();
3779 $main::done_licence_module_check++;
3780 $main::licence_module = $gconfig{'licence_module'};
3781 &foreign_require($main::licence_module, "licence_check.pl");
3782 ($main::licence_status, $main::licence_message) =
3783 &foreign_call($main::licence_module, "check_licence");
3787 # Export global variables to caller
3788 if ($main::export_to_caller) {
3789 foreach my $v ('$config_file', '%gconfig', '$null_file',
3790 '$path_separator', '@root_directories',
3791 '$root_directory', '$module_name',
3792 '$base_remote_user', '$remote_user',
3793 '$module_config_directory', '$module_config_file',
3794 '%config', '@current_themes', '$current_theme',
3795 '@theme_root_directories', '$theme_root_directory',
3796 '%tconfig','@theme_configs', '$tb', '$cb', '$scriptname',
3797 '$webmin_logfile', '$current_lang',
3798 '$current_lang_info', '@lang_order_list', '%text',
3799 '%module_info', '$module_root_directory') {
3800 my ($vt, $vn) = split('', $v, 2);
3801 eval "${vt}${callpkg}::${vn} = ${vt}${vn}";
3808 =head2 load_language([module], [directory])
3810 Returns a hashtable mapping text codes to strings in the appropriate language,
3811 based on the $current_lang global variable, which is in turn set based on
3812 the Webmin user's selection. The optional module parameter tells the function
3813 which module to load strings for, and defaults to the calling module. The
3814 optional directory parameter can be used to load strings from a directory
3817 In regular module development you will never need to call this function
3818 directly, as init_config calls it for you, and places the module's strings
3819 into the %text hash.
3825 my $root = $root_directory;
3826 my $ol = $gconfig{'overlang'};
3827 my ($dir) = ($_[1] || "lang");
3829 # Read global lang files
3830 foreach my $o (@lang_order_list) {
3831 my $ok = &read_file_cached("$root/$dir/$o", \%text);
3832 return () if (!$ok && $o eq $default_lang);
3835 foreach my $o (@lang_order_list) {
3836 &read_file_cached("$root/$ol/$o", \%text);
3839 &read_file_cached("$config_directory/custom-lang", \%text);
3842 # Read module's lang files
3843 my $mdir = &module_root_directory($_[0]);
3844 foreach my $o (@lang_order_list) {
3845 &read_file_cached("$mdir/$dir/$o", \%text);
3848 foreach $o (@lang_order_list) {
3849 &read_file_cached("$mdir/$ol/$o", \%text);
3852 &read_file_cached("$config_directory/$_[0]/custom-lang", \%text);
3854 foreach $k (keys %text) {
3855 $text{$k} =~ s/\$(\{([^\}]+)\}|([A-Za-z0-9\.\-\_]+))/text_subs($2 || $3,\%text)/ge;
3858 if (defined(&theme_load_language)) {
3859 &theme_load_language(\%text, $_[0]);
3864 =head2 text_subs(string)
3866 Used internally by load_language to expand $code substitutions in language
3872 if (substr($_[0], 0, 8) eq "include:") {
3875 open(INCLUDE, substr($_[0], 8));
3883 my $t = $_[1]->{$_[0]};
3884 return defined($t) ? $t : '$'.$_[0];
3888 =head2 text(message, [substitute]+)
3890 Returns a translated message from %text, but with $1, $2, etc.. replaced with
3891 the substitute parameters. This makes it easy to use strings with placeholders
3892 that get replaced with programmatically generated text. For example :
3894 print &text('index_hello', $remote_user),"<p>\n";
3899 my $t = &get_module_variable('%text', 1);
3900 my $rv = exists($t->{$_[0]}) ? $t->{$_[0]} : $text{$_[0]};
3901 for(my $i=1; $i<@_; $i++) {
3902 $rv =~ s/\$$i/$_[$i]/g;
3907 =head2 encode_base64(string)
3909 Encodes a string into base64 format, for use in MIME email or HTTP
3910 authorization headers.
3916 pos($_[0]) = 0; # ensure start at the beginning
3917 while ($_[0] =~ /(.{1,57})/gs) {
3918 $res .= substr(pack('u57', $1), 1)."\n";
3921 $res =~ tr|\` -_|AA-Za-z0-9+/|;
3922 my $padding = (3 - length($_[0]) % 3) % 3;
3923 $res =~ s/.{$padding}$/'=' x $padding/e if ($padding);
3927 =head2 decode_base64(string)
3929 Converts a base64-encoded string into plain text. The opposite of encode_base64.
3936 $str =~ tr|A-Za-z0-9+=/||cd; # remove non-base64 chars
3937 if (length($str) % 4) {
3940 $str =~ s/=+$//; # remove padding
3941 $str =~ tr|A-Za-z0-9+/| -_|; # convert to uuencoded format
3942 while ($str =~ /(.{1,60})/gs) {
3943 my $len = chr(32 + length($1)*3/4); # compute length byte
3944 $res .= unpack("u", $len . $1 ); # uudecode
3949 =head2 get_module_info(module, [noclone], [forcache])
3951 Returns a hash containg details of the given module. Some useful keys are :
3953 =item dir - The module directory, like sendmail.
3955 =item desc - Human-readable description, in the current users' language.
3957 =item version - Optional module version number.
3959 =item os_support - List of supported operating systems and versions.
3961 =item category - Category on Webmin's left menu, like net.
3966 return () if ($_[0] =~ /^\./);
3967 my (%rv, $clone, $o);
3968 my $mdir = &module_root_directory($_[0]);
3969 &read_file_cached("$mdir/module.info", \%rv) || return ();
3971 foreach $o (@lang_order_list) {
3972 $rv{"desc"} = $rv{"desc_$o"} if ($rv{"desc_$o"});
3973 $rv{"longdesc"} = $rv{"longdesc_$o"} if ($rv{"longdesc_$o"});
3975 if ($clone && !$_[1] && $config_directory) {
3976 $rv{'clone'} = $rv{'desc'};
3977 &read_file("$config_directory/$_[0]/clone", \%rv);
3980 my %module_categories;
3981 &read_file_cached("$config_directory/webmin.cats", \%module_categories);
3982 my $pn = &get_product_name();
3983 if (defined($rv{'category_'.$pn})) {
3984 # Can override category for webmin/usermin
3985 $rv{'category'} = $rv{'category_'.$pn};
3987 $rv{'realcategory'} = $rv{'category'};
3988 $rv{'category'} = $module_categories{$_[0]}
3989 if (defined($module_categories{$_[0]}));
3991 # Apply description overrides
3992 $rv{'realdesc'} = $rv{'desc'};
3994 &read_file_cached("$config_directory/webmin.descs", \%descs);
3995 if ($descs{$_[0]." ".$current_lang}) {
3996 $rv{'desc'} = $descs{$_[0]." ".$current_lang};
3998 elsif ($descs{$_[0]}) {
3999 $rv{'desc'} = $descs{$_[0]};
4003 # Apply per-user description overridde
4004 my %gaccess = &get_module_acl(undef, "");
4005 if ($gaccess{'desc_'.$_[0]}) {
4006 $rv{'desc'} = $gaccess{'desc_'.$_[0]};
4010 if ($rv{'longdesc'}) {
4011 # All standard modules have an index.cgi
4012 $rv{'index_link'} = 'index.cgi';
4015 # Call theme-specific override function
4016 if (defined(&theme_get_module_info)) {
4017 %rv = &theme_get_module_info(\%rv, $_[0], $_[1], $_[2]);
4023 =head2 get_all_module_infos(cachemode)
4025 Returns a list contains the information on all modules in this webmin
4026 install, including clones. Uses caching to reduce the number of module.info
4027 files that need to be read. Each element of the array is a hash reference
4028 in the same format as returned by get_module_info. The cache mode flag can be :
4029 0 = read and write, 1 = don't read or write, 2 = read only
4032 sub get_all_module_infos
4036 # Is the cache out of date? (ie. have any of the root's changed?)
4037 my $cache_file = "$config_directory/module.infos.cache";
4039 if (&read_file_cached($cache_file, \%cache)) {
4040 foreach my $r (@root_directories) {
4042 if ($st[9] != $cache{'mtime_'.$r}) {
4052 if ($_[0] != 1 && !$changed && $cache{'lang'} eq $current_lang) {
4053 # Can use existing module.info cache
4055 foreach my $k (keys %cache) {
4056 if ($k =~ /^(\S+) (\S+)$/) {
4057 $mods{$1}->{$2} = $cache{$k};
4060 @rv = map { $mods{$_} } (keys %mods) if (%mods);
4063 # Need to rebuild cache
4065 foreach my $r (@root_directories) {
4067 foreach my $m (readdir(DIR)) {
4068 next if ($m =~ /^(config-|\.)/ || $m =~ /\.(cgi|pl)$/);
4069 my %minfo = &get_module_info($m, 0, 1);
4070 next if (!%minfo || !$minfo{'dir'});
4072 foreach $k (keys %minfo) {
4073 $cache{"${m} ${k}"} = $minfo{$k};
4078 $cache{'mtime_'.$r} = $st[9];
4080 $cache{'lang'} = $current_lang;
4081 &write_file($cache_file, \%cache) if (!$_[0] && $< == 0 && $> == 0);
4084 # Override descriptions for modules for current user
4085 my %gaccess = &get_module_acl(undef, "");
4086 foreach my $m (@rv) {
4087 if ($gaccess{"desc_".$m->{'dir'}}) {
4088 $m->{'desc'} = $gaccess{"desc_".$m->{'dir'}};
4092 # Apply installed flags
4094 &read_file_cached("$config_directory/installed.cache", \%installed);
4095 foreach my $m (@rv) {
4096 $m->{'installed'} = $installed{$m->{'dir'}};
4102 =head2 get_theme_info(theme)
4104 Returns a hash containing a theme's details, taken from it's theme.info file.
4105 Some useful keys are :
4107 =item dir - The theme directory, like blue-theme.
4109 =item desc - Human-readable description, in the current users' language.
4111 =item version - Optional module version number.
4113 =item os_support - List of supported operating systems and versions.
4118 return () if ($_[0] =~ /^\./);
4120 my $tdir = &module_root_directory($_[0]);
4121 &read_file("$tdir/theme.info", \%rv) || return ();
4122 foreach my $o (@lang_order_list) {
4123 $rv{"desc"} = $rv{"desc_$o"} if ($rv{"desc_$o"});
4129 =head2 list_languages
4131 Returns an array of supported languages, taken from Webmin's os_list.txt file.
4132 Each is a hash reference with the following keys :
4134 =item lang - The short language code, like es for Spanish.
4136 =item desc - A human-readable description, in English.
4138 =item charset - An optional character set to use when displaying the language.
4140 =item titles - Set to 1 only if Webmin has title images for the language.
4142 =item fallback - The code for another language to use if a string does not exist in this one. For all languages, English is the ultimate fallback.
4147 if (!@main::list_languages_cache) {
4150 open(LANG, "$root_directory/lang_list.txt");
4152 if (/^(\S+)\s+(.*)/) {
4153 my $l = { 'desc' => $2 };
4154 foreach $o (split(/,/, $1)) {
4155 if ($o =~ /^([^=]+)=(.*)$/) {
4159 $l->{'index'} = scalar(@rv);
4160 push(@main::list_languages_cache, $l);
4164 @main::list_languages_cache = sort { $a->{'desc'} cmp $b->{'desc'} }
4165 @main::list_languages_cache;
4167 return @main::list_languages_cache;
4170 =head2 read_env_file(file, &hash)
4172 Similar to Webmin's read_file function, but handles files containing shell
4173 environment variables formatted like :
4178 The file parameter is the full path to the file to read, and hash a Perl hash
4179 ref to read names and values into.
4185 &open_readfile(FILE, $_[0]) || return 0;
4188 if (/^\s*(export\s*)?([A-Za-z0-9_\.]+)\s*=\s*"(.*)"/i ||
4189 /^\s*(export\s*)?([A-Za-z0-9_\.]+)\s*=\s*'(.*)'/i ||
4190 /^\s*(export\s*)?([A-Za-z0-9_\.]+)\s*=\s*(.*)/i) {
4198 =head2 write_env_file(file, &hash, [export])
4200 Writes out a hash to a file in name='value' format, suitable for use in a shell
4201 script. The parameters are :
4203 =item file - Full path for a file to write to
4205 =item hash - Hash reference of names and values to write.
4207 =item export - If set to 1, preceed each variable setting with the word 'export'.
4212 my $exp = $_[2] ? "export " : "";
4213 &open_tempfile(FILE, ">$_[0]");
4214 foreach my $k (keys %{$_[1]}) {
4215 my $v = $_[1]->{$k};
4216 if ($v =~ /^\S+$/) {
4217 &print_tempfile(FILE, "$exp$k=$v\n");
4220 &print_tempfile(FILE, "$exp$k=\"$v\"\n");
4223 &close_tempfile(FILE);
4226 =head2 lock_file(filename, [readonly], [forcefile])
4228 Lock a file for exclusive access. If the file is already locked, spin
4229 until it is freed. Uses a .lock file, which is not 100% reliable, but seems
4230 to work OK. The parameters are :
4232 =item filename - File or directory to lock.
4234 =item readonly - If set, the lock is for reading the file only. More than one script can have a readonly lock, but only one can hold a write lock.
4236 =item forcefile - Force the file to be considered as a real file and not a symlink for Webmin actions logging purposes.
4241 my $realfile = &translate_filename($_[0]);
4242 return 0 if (!$_[0] || defined($main::locked_file_list{$realfile}));
4243 my $no_lock = !&can_lock_file($realfile);
4244 my $lock_tries_count = 0;
4247 if (!$no_lock && open(LOCKING, "$realfile.lock")) {
4252 if ($no_lock || !$pid || !kill(0, $pid) || $pid == $$) {
4255 # Create the .lock file
4256 open(LOCKING, ">$realfile.lock") || return 0;
4257 my $lck = eval "flock(LOCKING, 2+4)";
4259 # Lock of lock file failed! Wait till later
4262 print LOCKING $$,"\n";
4263 eval "flock(LOCKING, 8)";
4266 $main::locked_file_list{$realfile} = int($_[1]);
4267 push(@main::temporary_files, "$realfile.lock");
4268 if (($gconfig{'logfiles'} || $gconfig{'logfullfiles'}) &&
4269 !&get_module_variable('$no_log_file_changes') &&
4271 # Grab a copy of this file for later diffing
4273 $main::locked_file_data{$realfile} = undef;
4275 $main::locked_file_type{$realfile} = 1;
4276 $main::locked_file_data{$realfile} = '';
4278 elsif (!$_[2] && ($lnk = readlink($realfile))) {
4279 $main::locked_file_type{$realfile} = 2;
4280 $main::locked_file_data{$realfile} = $lnk;
4282 elsif (open(ORIGFILE, $realfile)) {
4283 $main::locked_file_type{$realfile} = 0;
4284 $main::locked_file_data{$realfile} = '';
4287 $main::locked_file_data{$realfile} .=$_;
4296 if ($lock_tries_count++ > 5*60) {
4297 # Give up after 5 minutes
4298 &error(&text('elock_tries', "<tt>$realfile</tt>", 5));
4304 =head2 unlock_file(filename)
4306 Release a lock on a file taken out by lock_file. If Webmin actions logging of
4307 file changes is enabled, then at unlock file a diff will be taken between the
4308 old and new contents, and stored under /var/webmin/diffs when webmin_log is
4309 called. This can then be viewed in the Webmin Actions Log module.
4314 my $realfile = &translate_filename($_[0]);
4315 return if (!$_[0] || !defined($main::locked_file_list{$realfile}));
4316 unlink("$realfile.lock") if (&can_lock_file($realfile));
4317 delete($main::locked_file_list{$realfile});
4318 if (exists($main::locked_file_data{$realfile})) {
4319 # Diff the new file with the old
4321 my $lnk = readlink($realfile);
4322 my $type = -d _ ? 1 : $lnk ? 2 : 0;
4323 my $oldtype = $main::locked_file_type{$realfile};
4324 my $new = !defined($main::locked_file_data{$realfile});
4325 if ($new && !-e _) {
4326 # file doesn't exist, and never did! do nothing ..
4328 elsif ($new && $type == 1 || !$new && $oldtype == 1) {
4329 # is (or was) a directory ..
4330 if (-d _ && !defined($main::locked_file_data{$realfile})) {
4331 push(@main::locked_file_diff,
4332 { 'type' => 'mkdir', 'object' => $realfile });
4334 elsif (!-d _ && defined($main::locked_file_data{$realfile})) {
4335 push(@main::locked_file_diff,
4336 { 'type' => 'rmdir', 'object' => $realfile });
4339 elsif ($new && $type == 2 || !$new && $oldtype == 2) {
4340 # is (or was) a symlink ..
4341 if ($lnk && !defined($main::locked_file_data{$realfile})) {
4342 push(@main::locked_file_diff,
4343 { 'type' => 'symlink', 'object' => $realfile,
4346 elsif (!$lnk && defined($main::locked_file_data{$realfile})) {
4347 push(@main::locked_file_diff,
4348 { 'type' => 'unsymlink', 'object' => $realfile,
4349 'data' => $main::locked_file_data{$realfile} });
4351 elsif ($lnk ne $main::locked_file_data{$realfile}) {
4352 push(@main::locked_file_diff,
4353 { 'type' => 'resymlink', 'object' => $realfile,
4358 # is a file, or has changed type?!
4359 my ($diff, $delete_file);
4360 my $type = "modify";
4362 open(NEWFILE, ">$realfile");
4367 if (!defined($main::locked_file_data{$realfile})) {
4370 open(ORIGFILE, ">$realfile.webminorig");
4371 print ORIGFILE $main::locked_file_data{$realfile};
4373 $diff = &backquote_command(
4374 "diff ".quotemeta("$realfile.webminorig")." ".
4375 quotemeta($realfile)." 2>/dev/null");
4376 push(@main::locked_file_diff,
4377 { 'type' => $type, 'object' => $realfile,
4378 'data' => $diff } ) if ($diff);
4379 unlink("$realfile.webminorig");
4380 unlink($realfile) if ($delete_file);
4383 if ($gconfig{'logfullfiles'}) {
4384 # Add file details to list of those to fully log
4385 $main::orig_file_data{$realfile} ||=
4386 $main::locked_file_data{$realfile};
4387 $main::orig_file_type{$realfile} ||=
4388 $main::locked_file_type{$realfile};
4391 delete($main::locked_file_data{$realfile});
4392 delete($main::locked_file_type{$realfile});
4396 =head2 test_lock(file)
4398 Returns 1 if some file is currently locked, 0 if not.
4403 my $realfile = &translate_filename($_[0]);
4404 return 0 if (!$_[0]);
4405 return 1 if (defined($main::locked_file_list{$realfile}));
4406 return 0 if (!&can_lock_file($realfile));
4408 if (open(LOCKING, "$realfile.lock")) {
4413 return $pid && kill(0, $pid);
4416 =head2 unlock_all_files
4418 Unlocks all files locked by the current script.
4421 sub unlock_all_files
4423 foreach $f (keys %main::locked_file_list) {
4428 =head2 can_lock_file(file)
4430 Returns 1 if some file should be locked, based on the settings in the
4431 Webmin Configuration module. For internal use by lock_file only.
4436 if (&is_readonly_mode()) {
4437 return 0; # never lock in read-only mode
4439 elsif ($gconfig{'lockmode'} == 0) {
4442 elsif ($gconfig{'lockmode'} == 1) {
4446 # Check if under any of the directories
4448 foreach my $d (split(/\t+/, $gconfig{'lockdirs'})) {
4449 if (&same_file($d, $_[0]) ||
4450 &is_under_directory($d, $_[0])) {
4454 return $gconfig{'lockmode'} == 2 ? $match : !$match;
4458 =head2 webmin_log(action, type, object, ¶ms, [module], [host, script-on-host, client-ip])
4460 Log some action taken by a user. This is typically called at the end of a
4461 script, once all file changes are complete and all commands run. The
4464 =item action - A short code for the action being performed, like 'create'.
4466 =item type - A code for the type of object the action is performed to, like 'user'.
4468 =item object - A short name for the object, like 'joe' if the Unix user 'joe' was just created.
4470 =item params - A hash ref of additional information about the action.
4472 =item module - Name of the module in which the action was performed, which defaults to the current module.
4474 =item host - Remote host on which the action was performed. You should never need to set this (or the following two parameters), as they are used only for remote Webmin logging.
4476 =item script-on-host - Script name like create_user.cgi on the host the action was performed on.
4478 =item client-ip - IP address of the browser that performed the action.
4483 return if (!$gconfig{'log'} || &is_readonly_mode());
4484 my $m = $_[4] ? $_[4] : &get_module_name();
4486 if ($gconfig{'logclear'}) {
4487 # check if it is time to clear the log
4488 my @st = stat("$webmin_logfile.time");
4489 my $write_logtime = 0;
4491 if ($st[9]+$gconfig{'logtime'}*60*60 < time()) {
4492 # clear logfile and all diff files
4493 &unlink_file("$ENV{'WEBMIN_VAR'}/diffs");
4494 &unlink_file("$ENV{'WEBMIN_VAR'}/files");
4495 &unlink_file("$ENV{'WEBMIN_VAR'}/annotations");
4496 unlink($webmin_logfile);
4503 if ($write_logtime) {
4504 open(LOGTIME, ">$webmin_logfile.time");
4505 print LOGTIME time(),"\n";
4510 # If an action script directory is defined, call the appropriate scripts
4511 if ($gconfig{'action_script_dir'}) {
4512 my ($action, $type, $object) = ($_[0], $_[1], $_[2]);
4513 my ($basedir) = $gconfig{'action_script_dir'};
4515 for my $dir ($basedir/$type/$action, $basedir/$type, $basedir) {
4518 opendir(DIR, $dir) or die "Can't open $dir: $!";
4519 while (defined($file = readdir(DIR))) {
4520 next if ($file =~ /^\.\.?$/); # skip '.' and '..'
4521 if (-x "$dir/$file") {
4522 # Call a script notifying it of the action
4524 $ENV{'ACTION_MODULE'} = &get_module_name();
4525 $ENV{'ACTION_ACTION'} = $_[0];
4526 $ENV{'ACTION_TYPE'} = $_[1];
4527 $ENV{'ACTION_OBJECT'} = $_[2];
4528 $ENV{'ACTION_SCRIPT'} = $script_name;
4529 foreach my $p (keys %param) {
4530 $ENV{'ACTION_PARAM_'.uc($p)} = $param{$p};
4532 system("$dir/$file", @_,
4533 "<$null_file", ">$null_file", "2>&1");
4541 # should logging be done at all?
4542 return if ($gconfig{'logusers'} && &indexof($base_remote_user,
4543 split(/\s+/, $gconfig{'logusers'})) < 0);
4544 return if ($gconfig{'logmodules'} && &indexof($m,
4545 split(/\s+/, $gconfig{'logmodules'})) < 0);
4549 my @tm = localtime($now);
4550 my $script_name = $0 =~ /([^\/]+)$/ ? $1 : '-';
4551 my $id = sprintf "%d.%d.%d", $now, $$, $main::action_id_count;
4552 $main::action_id_count++;
4553 my $line = sprintf "%s [%2.2d/%s/%4.4d %2.2d:%2.2d:%2.2d] %s %s %s %s %s \"%s\" \"%s\" \"%s\"",
4554 $id, $tm[3], $text{"smonth_".($tm[4]+1)}, $tm[5]+1900,
4555 $tm[2], $tm[1], $tm[0],
4556 $remote_user || '-',
4557 $main::session_id || '-',
4558 $_[7] || $ENV{'REMOTE_HOST'} || '-',
4559 $m, $_[5] ? "$_[5]:$_[6]" : $script_name,
4560 $_[0], $_[1] ne '' ? $_[1] : '-', $_[2] ne '' ? $_[2] : '-';
4562 foreach my $k (sort { $a cmp $b } keys %{$_[3]}) {
4563 my $v = $_[3]->{$k};
4569 elsif (ref($v) eq 'ARRAY') {
4573 $vv =~ s/(['"\\\r\n\t\%])/sprintf("%%%2.2X",ord($1))/ge;
4574 $line .= " $k='$vv'";
4578 foreach $vv (split(/\0/, $v)) {
4580 $vv =~ s/(['"\\\r\n\t\%])/sprintf("%%%2.2X",ord($1))/ge;
4581 $line .= " $k='$vv'";
4584 $param{$k} = join(" ", @pv);
4586 open(WEBMINLOG, ">>$webmin_logfile");
4587 print WEBMINLOG $line,"\n";
4589 if ($gconfig{'logperms'}) {
4590 chmod(oct($gconfig{'logperms'}), $webmin_logfile);
4593 chmod(0600, $webmin_logfile);
4596 if ($gconfig{'logfiles'} && !&get_module_variable('$no_log_file_changes')) {
4597 # Find and record the changes made to any locked files, or commands run
4599 mkdir("$ENV{'WEBMIN_VAR'}/diffs", 0700);
4600 foreach my $d (@main::locked_file_diff) {
4601 mkdir("$ENV{'WEBMIN_VAR'}/diffs/$id", 0700);
4602 open(DIFFLOG, ">$ENV{'WEBMIN_VAR'}/diffs/$id/$i");
4603 print DIFFLOG "$d->{'type'} $d->{'object'}\n";
4604 print DIFFLOG $d->{'data'};
4606 if ($d->{'input'}) {
4607 open(DIFFLOG, ">$ENV{'WEBMIN_VAR'}/diffs/$id/$i.input");
4608 print DIFFLOG $d->{'input'};
4611 if ($gconfig{'logperms'}) {
4612 chmod(oct($gconfig{'logperms'}),
4613 "$ENV{'WEBMIN_VAR'}/diffs/$id/$i",
4614 "$ENV{'WEBMIN_VAR'}/diffs/$id/$i.input");
4618 @main::locked_file_diff = undef;
4620 if ($gconfig{'logfullfiles'}) {
4621 # Save the original contents of any modified files
4623 mkdir("$ENV{'WEBMIN_VAR'}/files", 0700);
4624 foreach my $f (keys %main::orig_file_data) {
4625 mkdir("$ENV{'WEBMIN_VAR'}/files/$id", 0700);
4626 open(ORIGLOG, ">$ENV{'WEBMIN_VAR'}/files/$id/$i");
4627 if (!defined($main::orig_file_type{$f})) {
4628 print ORIGLOG -1," ",$f,"\n";
4631 print ORIGLOG $main::orig_file_type{$f}," ",$f,"\n";
4633 print ORIGLOG $main::orig_file_data{$f};
4635 if ($gconfig{'logperms'}) {
4636 chmod(oct($gconfig{'logperms'}),
4637 "$ENV{'WEBMIN_VAR'}/files/$id.$i");
4641 %main::orig_file_data = undef;
4642 %main::orig_file_type = undef;
4646 if ($gconfig{'logsyslog'}) {
4647 eval 'use Sys::Syslog qw(:DEFAULT setlogsock);
4648 openlog(&get_product_name(), "cons,pid,ndelay", "daemon");
4649 setlogsock("inet");';
4651 # Syslog module is installed .. try to convert to a
4652 # human-readable form
4654 my $mod = &get_module_name();
4655 my $mdir = module_root_directory($mod);
4656 if (-r "$mdir/log_parser.pl") {
4657 &foreign_require($mod, "log_parser.pl");
4659 foreach my $k (keys %{$_[3]}) {
4660 my $v = $_[3]->{$k};
4661 if (ref($v) eq 'ARRAY') {
4662 $params{$k} = join("\0", @$v);
4668 $msg = &foreign_call($mod, "parse_webmin_log",
4669 $remote_user, $script_name,
4670 $_[0], $_[1], $_[2], \%params);
4671 $msg =~ s/<[^>]*>//g; # Remove tags
4673 elsif ($_[0] eq "_config_") {
4674 my %wtext = &load_language("webminlog");
4675 $msg = $wtext{'search_config'};
4677 $msg ||= "$_[0] $_[1] $_[2]";
4678 my %info = &get_module_info($m);
4679 eval { syslog("info", "%s", "[$info{'desc'}] $msg"); };
4684 =head2 additional_log(type, object, data, [input])
4686 Records additional log data for an upcoming call to webmin_log, such
4687 as a command that was run or SQL that was executed. Typically you will never
4688 need to call this function directory.
4693 if ($gconfig{'logfiles'} && !&get_module_variable('$no_log_file_changes')) {
4694 push(@main::locked_file_diff,
4695 { 'type' => $_[0], 'object' => $_[1], 'data' => $_[2],
4696 'input' => $_[3] } );
4700 =head2 webmin_debug_log(type, message)
4702 Write something to the Webmin debug log. For internal use only.
4705 sub webmin_debug_log
4707 my ($type, $msg) = @_;
4708 return 0 if (!$main::opened_debug_log);
4709 return 0 if ($gconfig{'debug_no'.$main::webmin_script_type});
4711 my @tm = localtime($now);
4713 "%s [%2.2d/%s/%4.4d %2.2d:%2.2d:%2.2d] %s %s %s %s \"%s\"",
4714 $$, $tm[3], $text{"smonth_".($tm[4]+1)}, $tm[5]+1900,
4715 $tm[2], $tm[1], $tm[0],
4716 $remote_user || "-",
4717 $ENV{'REMOTE_HOST'} || "-",
4718 &get_module_name() || "-",
4721 seek(main::DEBUGLOG, 0, 2);
4722 print main::DEBUGLOG $line."\n";
4726 =head2 system_logged(command)
4728 Just calls the Perl system() function, but also logs the command run.
4733 if (&is_readonly_mode()) {
4734 print STDERR "Vetoing command $_[0]\n";
4737 my @realcmd = ( &translate_command($_[0]), @_[1..$#_] );
4738 my $cmd = join(" ", @realcmd);
4740 if ($cmd =~ s/(\s*&\s*)$//) {
4743 while($cmd =~ s/(\d*)(<|>)((\/(tmp|dev)\S+)|&\d+)\s*$//) { }
4744 $cmd =~ s/^\((.*)\)\s*$/$1/;
4746 &additional_log('exec', undef, $cmd);
4747 return system(@realcmd);
4750 =head2 backquote_logged(command)
4752 Executes a command and returns the output (like `command`), but also logs it.
4755 sub backquote_logged
4757 if (&is_readonly_mode()) {
4759 print STDERR "Vetoing command $_[0]\n";
4762 my $realcmd = &translate_command($_[0]);
4765 if ($cmd =~ s/(\s*&\s*)$//) {
4768 while($cmd =~ s/(\d*)(<|>)((\/(tmp\/.webmin|dev)\S+)|&\d+)\s*$//) { }
4769 $cmd =~ s/^\((.*)\)\s*$/$1/;
4771 &additional_log('exec', undef, $cmd);
4772 &webmin_debug_log('CMD', "cmd=$cmd") if ($gconfig{'debug_what_cmd'});
4776 =head2 backquote_with_timeout(command, timeout, safe?, [maxlines])
4778 Runs some command, waiting at most the given number of seconds for it to
4779 complete, and returns the output. The maxlines parameter sets the number
4780 of lines of output to capture. The safe parameter should be set to 1 if the
4781 command is safe for read-only mode users to run.
4784 sub backquote_with_timeout
4786 my $realcmd = &translate_command($_[0]);
4787 &webmin_debug_log('CMD', "cmd=$realcmd timeout=$_[1]")
4788 if ($gconfig{'debug_what_cmd'});
4790 my $pid = &open_execute_command(OUT, "($realcmd) <$null_file", 1, $_[2]);
4795 my $elapsed = time() - $start;
4796 last if ($elapsed > $_[1]);
4798 vec($rmask, fileno(OUT), 1) = 1;
4799 my $sel = select($rmask, undef, undef, $_[1] - $elapsed);
4800 last if (!$sel || $sel < 0);
4802 last if (!defined($line));
4805 if ($_[3] && $linecount >= $_[3]) {
4810 if (kill('TERM', $pid) && time() - $start >= $_[1]) {
4814 return wantarray ? ($out, $timed_out) : $out;
4817 =head2 backquote_command(command, safe?)
4819 Executes a command and returns the output (like `command`), subject to
4820 command translation. The safe parameter should be set to 1 if the command
4821 is safe for read-only mode users to run.
4824 sub backquote_command
4826 if (&is_readonly_mode() && !$_[1]) {
4827 print STDERR "Vetoing command $_[0]\n";
4831 my $realcmd = &translate_command($_[0]);
4832 &webmin_debug_log('CMD', "cmd=$realcmd") if ($gconfig{'debug_what_cmd'});
4836 =head2 kill_logged(signal, pid, ...)
4838 Like Perl's built-in kill function, but also logs the fact that some process
4839 was killed. On Windows, falls back to calling process.exe to terminate a
4845 return scalar(@_)-1 if (&is_readonly_mode());
4846 &webmin_debug_log('KILL', "signal=$_[0] pids=".join(" ", @_[1..@_-1]))
4847 if ($gconfig{'debug_what_procs'});
4848 &additional_log('kill', $_[0], join(" ", @_[1..@_-1])) if (@_ > 1);
4849 if ($gconfig{'os_type'} eq 'windows') {
4850 # Emulate some kills with process.exe
4851 my $arg = $_[0] eq "KILL" ? "-k" :
4852 $_[0] eq "TERM" ? "-q" :
4853 $_[0] eq "STOP" ? "-s" :
4854 $_[0] eq "CONT" ? "-r" : undef;
4856 foreach my $p (@_[1..@_-1]) {
4858 $ok ||= kill($_[0], $p);
4861 &execute_command("process $arg $p");
4873 =head2 rename_logged(old, new)
4875 Re-names a file and logs the rename. If the old and new files are on different
4876 filesystems, calls mv or the Windows rename function to do the job.
4881 &additional_log('rename', $_[0], $_[1]) if ($_[0] ne $_[1]);
4882 return &rename_file($_[0], $_[1]);
4885 =head2 rename_file(old, new)
4887 Renames a file or directory. If the old and new files are on different
4888 filesystems, calls mv or the Windows rename function to do the job.
4893 if (&is_readonly_mode()) {
4894 print STDERR "Vetoing rename from $_[0] to $_[1]\n";
4897 my $src = &translate_filename($_[0]);
4898 my $dst = &translate_filename($_[1]);
4899 &webmin_debug_log('RENAME', "src=$src dst=$dst")
4900 if ($gconfig{'debug_what_ops'});
4901 my $ok = rename($src, $dst);
4902 if (!$ok && $! !~ /permission/i) {
4903 # Try the mv command, in case this is a cross-filesystem rename
4904 if ($gconfig{'os_type'} eq 'windows') {
4905 # Need to use rename
4906 my $out = &backquote_command("rename ".quotemeta($_[0]).
4907 " ".quotemeta($_[1])." 2>&1");
4909 $! = $out if (!$ok);
4913 my $out = &backquote_command("mv ".quotemeta($_[0]).
4914 " ".quotemeta($_[1])." 2>&1");
4916 $! = $out if (!$ok);
4922 =head2 symlink_logged(src, dest)
4924 Create a symlink, and logs it. Effectively does the same thing as the Perl
4931 my $rv = &symlink_file($_[0], $_[1]);
4932 &unlock_file($_[1]);
4936 =head2 symlink_file(src, dest)
4938 Creates a soft link, unless in read-only mode. Effectively does the same thing
4939 as the Perl symlink function.
4944 if (&is_readonly_mode()) {
4945 print STDERR "Vetoing symlink from $_[0] to $_[1]\n";
4948 my $src = &translate_filename($_[0]);
4949 my $dst = &translate_filename($_[1]);
4950 &webmin_debug_log('SYMLINK', "src=$src dst=$dst")
4951 if ($gconfig{'debug_what_ops'});
4952 return symlink($src, $dst);
4955 =head2 link_file(src, dest)
4957 Creates a hard link, unless in read-only mode. The existing new link file
4958 will be deleted if necessary. Effectively the same as Perl's link function.
4963 if (&is_readonly_mode()) {
4964 print STDERR "Vetoing link from $_[0] to $_[1]\n";
4967 my $src = &translate_filename($_[0]);
4968 my $dst = &translate_filename($_[1]);
4969 &webmin_debug_log('LINK', "src=$src dst=$dst")
4970 if ($gconfig{'debug_what_ops'});
4971 unlink($dst); # make sure link works
4972 return link($src, $dst);
4975 =head2 make_dir(dir, perms, recursive)
4977 Creates a directory and sets permissions on it, unless in read-only mode.
4978 The perms parameter sets the octal permissions to apply, which unlike Perl's
4979 mkdir will really get set. The recursive flag can be set to 1 to have the
4980 function create parent directories too.
4985 my ($dir, $perms, $recur) = @_;
4986 if (&is_readonly_mode()) {
4987 print STDERR "Vetoing directory $dir\n";
4990 $dir = &translate_filename($dir);
4991 my $exists = -d $dir ? 1 : 0;
4992 return 1 if ($exists && $recur); # already exists
4993 &webmin_debug_log('MKDIR', $dir) if ($gconfig{'debug_what_ops'});
4994 my $rv = mkdir($dir, $perms);
4995 if (!$rv && $recur) {
4996 # Failed .. try mkdir -p
4997 my $param = $gconfig{'os_type'} eq 'windows' ? "" : "-p";
4998 my $ex = &execute_command("mkdir $param "."e_path($dir));
5004 chmod($perms, $dir);
5009 =head2 set_ownership_permissions(user, group, perms, file, ...)
5011 Sets the user, group owner and permissions on some files. The parameters are :
5013 =item user - UID or username to change the file owner to. If undef, then the owner is not changed.
5015 =item group - GID or group name to change the file group to. If undef, then the group is set to the user's primary group.
5017 =item perms - Octal permissions set to set on the file. If undef, they are left alone.
5019 =item file - One or more files or directories to modify.
5022 sub set_ownership_permissions
5024 my ($user, $group, $perms, @files) = @_;
5025 if (&is_readonly_mode()) {
5026 print STDERR "Vetoing permission changes on ",join(" ", @files),"\n";
5029 @files = map { &translate_filename($_) } @files;
5030 if ($gconfig{'debug_what_ops'}) {
5031 foreach my $f (@files) {
5032 &webmin_debug_log('PERMS',
5033 "file=$f user=$user group=$group perms=$perms");
5037 if (defined($user)) {
5038 my $uid = $user !~ /^\d+$/ ? getpwnam($user) : $user;
5040 if (defined($group)) {
5041 $gid = $group !~ /^\d+$/ ? getgrnam($group) : $group;
5044 my @uinfo = getpwuid($uid);
5047 $rv = chown($uid, $gid, @files);
5049 if ($rv && defined($perms)) {
5050 $rv = chmod($perms, @files);
5055 =head2 unlink_logged(file, ...)
5057 Like Perl's unlink function, but locks the files beforehand and un-locks them
5058 after so that the deletion is logged by Webmin.
5064 foreach my $f (@_) {
5065 if (!&test_lock($f)) {
5070 my @rv = &unlink_file(@_);
5071 foreach my $f (@_) {
5076 return wantarray ? @rv : $rv[0];
5079 =head2 unlink_file(file, ...)
5081 Deletes some files or directories. Like Perl's unlink function, but also
5082 recursively deletes directories with the rm command if needed.
5087 return 1 if (&is_readonly_mode());
5090 foreach my $f (@_) {
5091 my $realf = &translate_filename($f);
5092 &webmin_debug_log('UNLINK', $realf) if ($gconfig{'debug_what_ops'});
5094 if (!rmdir($realf)) {
5095 if ($gconfig{'os_type'} eq 'windows') {
5096 # Call del and rmdir commands
5099 my $out = `del /q "$qm" 2>&1`;
5101 $out = `rmdir "$qm" 2>&1`;
5106 my $qm = quotemeta($realf);
5107 my $out = `rm -rf $qm 2>&1`;
5116 if (!unlink($realf)) {
5122 return wantarray ? ($rv, $err) : $rv;
5125 =head2 copy_source_dest(source, dest)
5127 Copy some file or directory to a new location. Returns 1 on success, or 0
5128 on failure - also sets $! on failure. If the source is a directory, uses
5129 piped tar commands to copy a whole directory structure including permissions
5133 sub copy_source_dest
5135 return (1, undef) if (&is_readonly_mode());
5136 my ($src, $dst) = @_;
5139 &webmin_debug_log('COPY', "src=$src dst=$dst")
5140 if ($gconfig{'debug_what_ops'});
5141 if ($gconfig{'os_type'} eq 'windows') {
5142 # No tar or cp on windows, so need to use copy command
5146 $out = &backquote_logged("xcopy \"$src\" \"$dst\" /Y /E /I 2>&1");
5149 $out = &backquote_logged("copy /Y \"$src\" \"$dst\" 2>&1");
5157 # A directory .. need to copy with tar command
5158 my @st = stat($src);
5161 &set_ownership_permissions($st[4], $st[5], $st[2], $dst);
5162 $out = &backquote_logged("(cd ".quotemeta($src)." ; tar cf - . | (cd ".quotemeta($dst)." ; tar xf -)) 2>&1");
5169 # Can just copy with cp
5170 my $out = &backquote_logged("cp -p ".quotemeta($src).
5171 " ".quotemeta($dst)." 2>&1");
5177 return wantarray ? ($ok, $err) : $ok;
5180 =head2 remote_session_name(host|&server)
5182 Generates a session ID for some server. For this server, this will always
5183 be an empty string. For a server object it will include the hostname and
5184 port and PID. For a server name, it will include the hostname and PID. For
5188 sub remote_session_name
5190 return ref($_[0]) && $_[0]->{'host'} && $_[0]->{'port'} ?
5191 "$_[0]->{'host'}:$_[0]->{'port'}.$$" :
5192 $_[0] eq "" || ref($_[0]) && $_[0]->{'id'} == 0 ? "" :
5193 ref($_[0]) ? "" : "$_[0].$$";
5196 =head2 remote_foreign_require(server, module, file)
5198 Connects to rpc.cgi on a remote webmin server and have it open a session
5199 to a process that will actually do the require and run functions. This is the
5200 equivalent for foreign_require, but for a remote Webmin system. The server
5201 parameter can either be a hostname of a system registered in the Webmin
5202 Servers Index module, or a hash reference for a system from that module.
5205 sub remote_foreign_require
5207 my $call = { 'action' => 'require',
5210 my $sn = &remote_session_name($_[0]);
5211 if ($remote_session{$sn}) {
5212 $call->{'session'} = $remote_session{$sn};
5215 $call->{'newsession'} = 1;
5217 my $rv = &remote_rpc_call($_[0], $call);
5218 if ($rv->{'session'}) {
5219 $remote_session{$sn} = $rv->{'session'};
5220 $remote_session_server{$sn} = $_[0];
5224 =head2 remote_foreign_call(server, module, function, [arg]*)
5226 Call a function on a remote server. Must have been setup first with
5227 remote_foreign_require for the same server and module. Equivalent to
5228 foreign_call, but with the extra server parameter to specify the remote
5232 sub remote_foreign_call
5234 return undef if (&is_readonly_mode());
5235 my $sn = &remote_session_name($_[0]);
5236 return &remote_rpc_call($_[0], { 'action' => 'call',
5239 'session' => $remote_session{$sn},
5240 'args' => [ @_[3 .. $#_] ] } );
5243 =head2 remote_foreign_check(server, module, [api-only])
5245 Checks if some module is installed and supported on a remote server. Equivilant
5246 to foreign_check, but for the remote Webmin system specified by the server
5250 sub remote_foreign_check
5252 return &remote_rpc_call($_[0], { 'action' => 'check',
5257 =head2 remote_foreign_config(server, module)
5259 Gets the configuration for some module from a remote server, as a hash.
5260 Equivalent to foreign_config, but for a remote system.
5263 sub remote_foreign_config
5265 return &remote_rpc_call($_[0], { 'action' => 'config',
5266 'module' => $_[1] });
5269 =head2 remote_eval(server, module, code)
5271 Evaluates some perl code in the context of a module on a remote webmin server.
5272 The server parameter must be the hostname of a remote system, module must
5273 be a module directory name, and code a string of Perl code to run. This can
5274 only be called after remote_foreign_require for the same server and module.
5279 return undef if (&is_readonly_mode());
5280 my $sn = &remote_session_name($_[0]);
5281 return &remote_rpc_call($_[0], { 'action' => 'eval',
5284 'session' => $remote_session{$sn} });
5287 =head2 remote_write(server, localfile, [remotefile], [remotebasename])
5289 Transfers some local file to another server via Webmin's RPC protocol, and
5290 returns the resulting remote filename. If the remotefile parameter is given,
5291 that is the destination filename which will be used. Otherwise a randomly
5292 selected temporary filename will be used, and returned by the function.
5297 return undef if (&is_readonly_mode());
5299 my $sn = &remote_session_name($_[0]);
5300 if (!$_[0] || $remote_server_version{$sn} >= 0.966) {
5301 # Copy data over TCP connection
5302 my $rv = &remote_rpc_call($_[0], { 'action' => 'tcpwrite',
5304 'name' => $_[3] } );
5306 my $serv = ref($_[0]) ? $_[0]->{'host'} : $_[0];
5307 &open_socket($serv || "localhost", $rv->[1], TWRITE, \$error);
5308 return &$main::remote_error_handler("Failed to transfer file : $error")
5311 while(read(FILE, $got, 1024) > 0) {
5315 shutdown(TWRITE, 1);
5317 if ($error && $error !~ /^OK/) {
5318 # Got back an error!
5319 return &$main::remote_error_handler("Failed to transfer file : $error");
5325 # Just pass file contents as parameters
5327 while(read(FILE, $got, 1024) > 0) {
5331 return &remote_rpc_call($_[0], { 'action' => 'write',
5334 'session' => $remote_session{$sn} });
5338 =head2 remote_read(server, localfile, remotefile)
5340 Transfers a file from a remote server to this system, using Webmin's RPC
5341 protocol. The server parameter must be the hostname of a system registered
5342 in the Webmin Servers Index module, localfile is the destination path on this
5343 system, and remotefile is the file to fetch from the remote server.
5348 my $sn = &remote_session_name($_[0]);
5349 if (!$_[0] || $remote_server_version{$sn} >= 0.966) {
5350 # Copy data over TCP connection
5351 my $rv = &remote_rpc_call($_[0], { 'action' => 'tcpread',
5352 'file' => $_[2] } );
5354 return &$main::remote_error_handler("Failed to transfer file : $rv->[1]");
5357 my $serv = ref($_[0]) ? $_[0]->{'host'} : $_[0];
5358 &open_socket($serv || "localhost", $rv->[1], TREAD, \$error);
5359 return &$main::remote_error_handler("Failed to transfer file : $error")
5362 open(FILE, ">$_[1]");
5363 while(read(TREAD, $got, 1024) > 0) {
5370 # Just get data as return value
5371 my $d = &remote_rpc_call($_[0], { 'action' => 'read',
5373 'session' => $remote_session{$sn} });
5374 open(FILE, ">$_[1]");
5380 =head2 remote_finished
5382 Close all remote sessions. This happens automatically after a while
5383 anyway, but this function should be called to clean things up faster.
5388 foreach my $sn (keys %remote_session) {
5389 my $server = $remote_session_server{$sn};
5390 &remote_rpc_call($server, { 'action' => 'quit',
5391 'session' => $remote_session{$sn} } );
5392 delete($remote_session{$sn});
5393 delete($remote_session_server{$sn});
5395 foreach $fh (keys %fast_fh_cache) {
5397 delete($fast_fh_cache{$fh});
5401 =head2 remote_error_setup(&function)
5403 Sets a function to be called instead of &error when a remote RPC operation
5404 fails. Useful if you want to have more control over your remote operations.
5407 sub remote_error_setup
5409 $main::remote_error_handler = $_[0] || \&error;
5412 =head2 remote_rpc_call(server, structure)
5414 Calls rpc.cgi on some server and passes it a perl structure (hash,array,etc)
5415 and then reads back a reply structure. This is mainly for internal use only,
5416 and is called by the other remote_* functions.
5422 my $sn = &remote_session_name($_[0]); # Will be undef for local connection
5424 # Server structure was given
5426 $serv->{'user'} || $serv->{'id'} == 0 ||
5427 return &$main::remote_error_handler(
5428 "No Webmin login set for server");
5431 # lookup the server in the webmin servers module if needed
5432 if (!defined(%main::remote_servers_cache)) {
5433 &foreign_require("servers", "servers-lib.pl");
5434 foreach $s (&foreign_call("servers", "list_servers")) {
5435 $main::remote_servers_cache{$s->{'host'}} = $s;
5436 $main::remote_servers_cache{$s->{'host'}.":".$s->{'port'}} = $s;
5439 $serv = $main::remote_servers_cache{$_[0]};
5440 $serv || return &$main::remote_error_handler(
5441 "No Webmin Servers entry for $_[0]");
5442 $serv->{'user'} || return &$main::remote_error_handler(
5443 "No login set for server $_[0]");
5446 # Work out the username and password
5448 if ($serv->{'sameuser'}) {
5449 $user = $remote_user;
5450 defined($main::remote_pass) || return &$main::remote_error_handler(
5451 "Password for this server is not available");
5452 $pass = $main::remote_pass;
5455 $user = $serv->{'user'};
5456 $pass = $serv->{'pass'};
5459 if ($serv->{'fast'} || !$sn) {
5460 # Make TCP connection call to fastrpc.cgi
5461 if (!$fast_fh_cache{$sn} && $sn) {
5462 # Need to open the connection
5463 my $con = &make_http_connection(
5464 $serv->{'host'}, $serv->{'port'}, $serv->{'ssl'},
5465 "POST", "/fastrpc.cgi");
5466 return &$main::remote_error_handler(
5467 "Failed to connect to $serv->{'host'} : $con")
5469 &write_http_connection($con, "Host: $serv->{'host'}\r\n");
5470 &write_http_connection($con, "User-agent: Webmin\r\n");
5471 my $auth = &encode_base64("$user:$pass");
5473 &write_http_connection($con, "Authorization: basic $auth\r\n");
5474 &write_http_connection($con, "Content-length: ",
5475 length($tostr),"\r\n");
5476 &write_http_connection($con, "\r\n");
5477 &write_http_connection($con, $tostr);
5479 # read back the response
5480 my $line = &read_http_connection($con);
5481 $line =~ tr/\r\n//d;
5482 if ($line =~ /^HTTP\/1\..\s+401\s+/) {
5483 return &$main::remote_error_handler("Login to RPC server as $user rejected");
5485 $line =~ /^HTTP\/1\..\s+200\s+/ ||
5486 return &$main::remote_error_handler("HTTP error : $line");
5488 $line = &read_http_connection($con);
5489 $line =~ tr/\r\n//d;
5491 $line = &read_http_connection($con);
5492 if ($line =~ /^0\s+(.*)/) {
5493 return &$main::remote_error_handler("RPC error : $1");
5495 elsif ($line =~ /^1\s+(\S+)\s+(\S+)\s+(\S+)/ ||
5496 $line =~ /^1\s+(\S+)\s+(\S+)/) {
5497 # Started ok .. connect and save SID
5498 &close_http_connection($con);
5499 my ($port, $sid, $version, $error) = ($1, $2, $3);
5500 &open_socket($serv->{'host'}, $port, $sid, \$error);
5501 return &$main::remote_error_handler("Failed to connect to fastrpc.cgi : $error")
5503 $fast_fh_cache{$sn} = $sid;
5504 $remote_server_version{$sn} = $version;
5507 while($stuff = &read_http_connection($con)) {
5510 return &$main::remote_error_handler("Bad response from fastrpc.cgi : $line");
5513 elsif (!$fast_fh_cache{$sn}) {
5514 # Open the connection by running fastrpc.cgi locally
5515 pipe(RPCOUTr, RPCOUTw);
5519 open(STDOUT, ">&RPCOUTw");
5523 $ENV{'REQUEST_METHOD'} = 'GET';
5524 $ENV{'SCRIPT_NAME'} = '/fastrpc.cgi';
5525 $ENV{'SERVER_ROOT'} ||= $root_directory;
5527 if ($base_remote_user ne 'root' &&
5528 $base_remote_user ne 'admin') {
5529 # Need to fake up a login for the CGI!
5530 &read_acl(undef, \%acl);
5531 $ENV{'BASE_REMOTE_USER'} =
5532 $ENV{'REMOTE_USER'} =
5533 $acl{'root'} ? 'root' : 'admin';
5535 delete($ENV{'FOREIGN_MODULE_NAME'});
5536 delete($ENV{'FOREIGN_ROOT_DIRECTORY'});
5537 chdir($root_directory);
5538 if (!exec("$root_directory/fastrpc.cgi")) {
5539 print "exec failed : $!\n";
5546 ($line = <RPCOUTr>) =~ tr/\r\n//d;
5550 if ($line =~ /^0\s+(.*)/) {
5551 return &$main::remote_error_handler("RPC error : $2");
5553 elsif ($line =~ /^1\s+(\S+)\s+(\S+)/) {
5554 # Started ok .. connect and save SID
5556 my ($port, $sid, $error) = ($1, $2, undef);
5557 &open_socket("localhost", $port, $sid, \$error);
5558 return &$main::remote_error_handler("Failed to connect to fastrpc.cgi : $error") if ($error);
5559 $fast_fh_cache{$sn} = $sid;
5566 &error("Bad response from fastrpc.cgi : $line");
5569 # Got a connection .. send off the request
5570 my $fh = $fast_fh_cache{$sn};
5571 my $tostr = &serialise_variable($_[1]);
5572 print $fh length($tostr)," $fh\n";
5574 my $rlen = int(<$fh>);
5575 my ($fromstr, $got);
5576 while(length($fromstr) < $rlen) {
5577 return &$main::remote_error_handler("Failed to read from fastrpc.cgi")
5578 if (read($fh, $got, $rlen - length($fromstr)) <= 0);
5581 my $from = &unserialise_variable($fromstr);
5583 return &$main::remote_error_handler("Remote Webmin error");
5585 if (defined($from->{'arv'})) {
5586 return @{$from->{'arv'}};
5589 return $from->{'rv'};
5593 # Call rpc.cgi on remote server
5594 my $tostr = &serialise_variable($_[1]);
5596 my $con = &make_http_connection($serv->{'host'}, $serv->{'port'},
5597 $serv->{'ssl'}, "POST", "/rpc.cgi");
5598 return &$main::remote_error_handler("Failed to connect to $serv->{'host'} : $con") if (!ref($con));
5600 &write_http_connection($con, "Host: $serv->{'host'}\r\n");
5601 &write_http_connection($con, "User-agent: Webmin\r\n");
5602 my $auth = &encode_base64("$user:$pass");
5604 &write_http_connection($con, "Authorization: basic $auth\r\n");
5605 &write_http_connection($con, "Content-length: ",length($tostr),"\r\n");
5606 &write_http_connection($con, "\r\n");
5607 &write_http_connection($con, $tostr);
5609 # read back the response
5610 my $line = &read_http_connection($con);
5611 $line =~ tr/\r\n//d;
5612 if ($line =~ /^HTTP\/1\..\s+401\s+/) {
5613 return &$main::remote_error_handler("Login to RPC server as $user rejected");
5615 $line =~ /^HTTP\/1\..\s+200\s+/ || return &$main::remote_error_handler("RPC HTTP error : $line");
5617 $line = &read_http_connection($con);
5618 $line =~ tr/\r\n//d;
5621 while($line = &read_http_connection($con)) {
5625 my $from = &unserialise_variable($fromstr);
5626 return &$main::remote_error_handler("Invalid RPC login to $serv->{'host'}") if (!$from->{'status'});
5627 if (defined($from->{'arv'})) {
5628 return @{$from->{'arv'}};
5631 return $from->{'rv'};
5636 =head2 remote_multi_callback(&servers, parallel, &function, arg|&args, &returns, &errors, [module, library])
5638 Executes some function in parallel on multiple servers at once. Fills in
5639 the returns and errors arrays respectively. If the module and library
5640 parameters are given, that module is remotely required on the server first,
5641 to check if it is connectable. The parameters are :
5643 =item servers - A list of Webmin system hash references.
5645 =item parallel - Number of parallel operations to perform.
5647 =item function - Reference to function to call for each system.
5649 =item args - Additional parameters to the function.
5651 =item returns - Array ref to place return values into, in same order as servers.
5653 =item errors - Array ref to place error messages into.
5655 =item module - Optional module to require on the remote system first.
5657 =item library - Optional library to require in the module.
5660 sub remote_multi_callback
5662 my ($servs, $parallel, $func, $args, $rets, $errs, $mod, $lib) = @_;
5663 &remote_error_setup(\&remote_multi_callback_error);
5665 # Call the functions
5667 foreach my $g (@$servs) {
5673 $remote_multi_callback_err = undef;
5675 # Require the remote lib
5676 &remote_foreign_require($g->{'host'}, $mod, $lib);
5677 if ($remote_multi_callback_err) {
5678 # Failed .. return error
5679 print $wh &serialise_variable(
5680 [ undef, $remote_multi_callback_err ]);
5686 my $a = ref($args) ? $args->[$p] : $args;
5687 my $rv = &$func($g, $a);
5690 print $wh &serialise_variable(
5691 [ $rv, $remote_multi_callback_err ]);
5699 # Read back the results
5701 foreach my $g (@$servs) {
5705 $errs->[$p] = "Failed to read response from $g->{'host'}";
5708 my $rv = &unserialise_variable($line);
5710 $rets->[$p] = $rv->[0];
5711 $errs->[$p] = $rv->[1];
5716 &remote_error_setup(undef);
5719 sub remote_multi_callback_error
5721 $remote_multi_callback_err = $_[0];
5724 =head2 serialise_variable(variable)
5726 Converts some variable (maybe a scalar, hash ref, array ref or scalar ref)
5727 into a url-encoded string. In the cases of arrays and hashes, it is recursively
5728 called on each member to serialize the entire object.
5731 sub serialise_variable
5733 if (!defined($_[0])) {
5739 $rv = &urlize($_[0]);
5741 elsif ($r eq 'SCALAR') {
5742 $rv = &urlize(${$_[0]});
5744 elsif ($r eq 'ARRAY') {
5745 $rv = join(",", map { &urlize(&serialise_variable($_)) } @{$_[0]});
5747 elsif ($r eq 'HASH') {
5748 $rv = join(",", map { &urlize(&serialise_variable($_)).",".
5749 &urlize(&serialise_variable($_[0]->{$_})) }
5752 elsif ($r eq 'REF') {
5753 $rv = &serialise_variable(${$_[0]});
5755 elsif ($r eq 'CODE') {
5760 # An object - treat as a hash
5761 $r = "OBJECT ".&urlize($r);
5762 $rv = join(",", map { &urlize(&serialise_variable($_)).",".
5763 &urlize(&serialise_variable($_[0]->{$_})) }
5766 return ($r ? $r : 'VAL').",".$rv;
5769 =head2 unserialise_variable(string)
5771 Converts a string created by serialise_variable() back into the original
5772 scalar, hash ref, array ref or scalar ref. If the original variable was a Perl
5773 object, the same class is used on this system, if available.
5776 sub unserialise_variable
5778 my @v = split(/,/, $_[0]);
5780 if ($v[0] eq 'VAL') {
5781 @v = split(/,/, $_[0], -1);
5782 $rv = &un_urlize($v[1]);
5784 elsif ($v[0] eq 'SCALAR') {
5785 local $r = &un_urlize($v[1]);
5788 elsif ($v[0] eq 'ARRAY') {
5790 for(my $i=1; $i<@v; $i++) {
5791 push(@$rv, &unserialise_variable(&un_urlize($v[$i])));
5794 elsif ($v[0] eq 'HASH') {
5796 for(my $i=1; $i<@v; $i+=2) {
5797 $rv->{&unserialise_variable(&un_urlize($v[$i]))} =
5798 &unserialise_variable(&un_urlize($v[$i+1]));
5801 elsif ($v[0] eq 'REF') {
5802 local $r = &unserialise_variable($v[1]);
5805 elsif ($v[0] eq 'UNDEF') {
5808 elsif ($v[0] =~ /^OBJECT\s+(.*)$/) {
5809 # An object hash that we have to re-bless
5812 for(my $i=1; $i<@v; $i+=2) {
5813 $rv->{&unserialise_variable(&un_urlize($v[$i]))} =
5814 &unserialise_variable(&un_urlize($v[$i+1]));
5822 =head2 other_groups(user)
5824 Returns a list of secondary groups a user is a member of, as a list of
5833 while(my @g = getgrent()) {
5834 my @m = split(/\s+/, $g[3]);
5835 push(@rv, $g[2]) if (&indexof($user, @m) >= 0);
5837 endgrent() if ($gconfig{'os_type'} ne 'hpux');
5841 =head2 date_chooser_button(dayfield, monthfield, yearfield)
5843 Returns HTML for a button that pops up a data chooser window. The parameters
5846 =item dayfield - Name of the text field to place the day of the month into.
5848 =item monthfield - Name of the select field to select the month of the year in, indexed from 1.
5850 =item yearfield - Name of the text field to place the year into.
5853 sub date_chooser_button
5855 return &theme_date_chooser_button(@_)
5856 if (defined(&theme_date_chooser_button));
5857 my ($w, $h) = (250, 225);
5858 if ($gconfig{'db_sizedate'}) {
5859 ($w, $h) = split(/x/, $gconfig{'db_sizedate'});
5861 return "<input type=button onClick='window.dfield = form.$_[0]; window.mfield = form.$_[1]; window.yfield = form.$_[2]; window.open(\"$gconfig{'webprefix'}/date_chooser.cgi?day=\"+escape(dfield.value)+\"&month=\"+escape(mfield.selectedIndex)+\"&year=\"+yfield.value, \"chooser\", \"toolbar=no,menubar=no,scrollbars=yes,width=$w,height=$h\")' value=\"...\">\n";
5864 =head2 help_file(module, file)
5866 Returns the path to a module's help file of some name, typically under the
5867 help directory with a .html extension.
5872 my $mdir = &module_root_directory($_[0]);
5873 my $dir = "$mdir/help";
5874 foreach my $o (@lang_order_list) {
5875 my $lang = "$dir/$_[1].$current_lang.html";
5876 return $lang if (-r $lang);
5878 return "$dir/$_[1].html";
5883 Seeds the random number generator, if not already done in this script. On Linux
5884 this makes use of the current time, process ID and a read from /dev/urandom.
5885 On other systems, only the current time and process ID are used.
5890 if (!$main::done_seed_random) {
5891 if (open(RANDOM, "/dev/urandom")) {
5893 read(RANDOM, $buf, 4);
5895 srand(time() ^ $$ ^ $buf);
5900 $main::done_seed_random = 1;
5904 =head2 disk_usage_kb(directory)
5906 Returns the number of kB used by some directory and all subdirs. Implemented
5907 by calling the C<du -k> command.
5912 my $dir = &translate_filename($_[0]);
5914 my $ex = &execute_command("du -sk ".quotemeta($dir), undef, \$out, undef, 0, 1);
5916 &execute_command("du -s ".quotemeta($dir), undef, \$out, undef, 0, 1);
5918 return $out =~ /^([0-9]+)/ ? $1 : "???";
5921 =head2 recursive_disk_usage(directory)
5923 Returns the number of bytes taken up by all files in some directory and all
5924 sub-directories, by summing up their lengths. The disk_usage_kb is more
5925 reflective of reality, as the filesystem typically pads file sizes to 1k or
5929 sub recursive_disk_usage
5931 my $dir = &translate_filename($_[0]);
5936 my @st = stat($dir);
5942 my @files = readdir(DIR);
5944 foreach my $f (@files) {
5945 next if ($f eq "." || $f eq "..");
5946 $rv += &recursive_disk_usage("$dir/$f");
5952 =head2 help_search_link(term, [ section, ... ] )
5954 Returns HTML for a link to the man module for searching local and online
5955 docs for various search terms. The term parameter can either be a single
5956 word like 'bind', or a space-separated list of words. This function is typically
5957 used by modules that want to refer users to additional documentation in man
5958 pages or local system doc files.
5961 sub help_search_link
5963 if (&foreign_available("man") && !$tconfig{'nosearch'}) {
5964 my $for = &urlize(shift(@_));
5965 return "<a href='$gconfig{'webprefix'}/man/search.cgi?".
5966 join("&", map { "section=$_" } @_)."&".
5967 "for=$for&exact=1&check=".&get_module_name()."'>".
5968 $text{'helpsearch'}."</a>\n";
5975 =head2 make_http_connection(host, port, ssl, method, page, [&headers])
5977 Opens a connection to some HTTP server, maybe through a proxy, and returns
5978 a handle object. The handle can then be used to send additional headers
5979 and read back a response. If anything goes wrong, returns an error string.
5980 The parameters are :
5982 =item host - Hostname or IP address of the webserver to connect to.
5984 =item port - HTTP port number to connect to.
5986 =item ssl - Set to 1 to connect in SSL mode.
5988 =item method - HTTP method, like GET or POST.
5990 =item page - Page to request on the webserver, like /foo/index.html
5992 =item headers - Array ref of additional HTTP headers, each of which is a 2-element array ref.
5995 sub make_http_connection
5997 my ($host, $port, $ssl, $method, $page, $headers) = @_;
6000 foreach my $h (@$headers) {
6001 $htxt .= $h->[0].": ".$h->[1]."\r\n";
6005 if (&is_readonly_mode()) {
6006 return "HTTP connections not allowed in readonly mode";
6008 my $rv = { 'fh' => time().$$ };
6011 eval "use Net::SSLeay";
6012 $@ && return $text{'link_essl'};
6013 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
6014 eval "Net::SSLeay::load_error_strings()";
6015 $rv->{'ssl_ctx'} = Net::SSLeay::CTX_new() ||
6016 return "Failed to create SSL context";
6017 $rv->{'ssl_con'} = Net::SSLeay::new($rv->{'ssl_ctx'}) ||
6018 return "Failed to create SSL connection";
6020 if ($gconfig{'http_proxy'} =~ /^http:\/\/(\S+):(\d+)/ &&
6021 !&no_proxy($host)) {
6024 &open_socket($1, $2, $rv->{'fh'}, \$error);
6027 my $fh = $rv->{'fh'};
6028 print $fh "CONNECT $host:$port HTTP/1.0\r\n";
6029 if ($gconfig{'proxy_user'}) {
6030 my $auth = &encode_base64(
6031 "$gconfig{'proxy_user'}:".
6032 "$gconfig{'proxy_pass'}");
6033 $auth =~ tr/\r\n//d;
6034 print $fh "Proxy-Authorization: Basic $auth\r\n";
6038 if ($line =~ /^HTTP(\S+)\s+(\d+)\s+(.*)/) {
6039 return "Proxy error : $3" if ($2 != 200);
6042 return "Proxy error : $line";
6047 elsif (!$gconfig{'proxy_fallback'}) {
6048 # Connection to proxy failed - give up
6055 &open_socket($host, $port, $rv->{'fh'}, \$error);
6056 return $error if ($error);
6058 Net::SSLeay::set_fd($rv->{'ssl_con'}, fileno($rv->{'fh'}));
6059 Net::SSLeay::connect($rv->{'ssl_con'}) ||
6060 return "SSL connect() failed";
6061 my $rtxt = "$method $page HTTP/1.0\r\n".$htxt;
6062 Net::SSLeay::write($rv->{'ssl_con'}, $rtxt);
6065 # Plain HTTP request
6067 if ($gconfig{'http_proxy'} =~ /^http:\/\/(\S+):(\d+)/ &&
6068 !&no_proxy($host)) {
6071 &open_socket($1, $2, $rv->{'fh'}, \$error);
6075 my $fh = $rv->{'fh'};
6076 my $rtxt = $method." ".
6077 "http://$host:$port$page HTTP/1.0\r\n";
6078 if ($gconfig{'proxy_user'}) {
6079 my $auth = &encode_base64(
6080 "$gconfig{'proxy_user'}:".
6081 "$gconfig{'proxy_pass'}");
6082 $auth =~ tr/\r\n//d;
6083 $rtxt .= "Proxy-Authorization: Basic $auth\r\n";
6088 elsif (!$gconfig{'proxy_fallback'}) {
6093 # Connecting directly
6095 &open_socket($host, $port, $rv->{'fh'}, \$error);
6096 return $error if ($error);
6097 my $fh = $rv->{'fh'};
6098 my $rtxt = "$method $page HTTP/1.0\r\n".$htxt;
6105 =head2 read_http_connection(&handle, [bytes])
6107 Reads either one line or up to the specified number of bytes from the handle,
6108 originally supplied by make_http_connection.
6111 sub read_http_connection
6115 if ($h->{'ssl_con'}) {
6118 while(($idx = index($h->{'buffer'}, "\n")) < 0) {
6119 # need to read more..
6120 if (!($more = Net::SSLeay::read($h->{'ssl_con'}))) {
6122 $rv = $h->{'buffer'};
6123 delete($h->{'buffer'});
6126 $h->{'buffer'} .= $more;
6128 $rv = substr($h->{'buffer'}, 0, $idx+1);
6129 $h->{'buffer'} = substr($h->{'buffer'}, $idx+1);
6132 if (length($h->{'buffer'})) {
6133 $rv = $h->{'buffer'};
6134 delete($h->{'buffer'});
6137 $rv = Net::SSLeay::read($h->{'ssl_con'}, $_[1]);
6143 read($h->{'fh'}, $rv, $_[1]) > 0 || return undef;
6146 my $fh = $h->{'fh'};
6150 $rv = undef if ($rv eq "");
6154 =head2 write_http_connection(&handle, [data+])
6156 Writes the given data to the given HTTP connection handle.
6159 sub write_http_connection
6162 my $fh = $h->{'fh'};
6164 if ($h->{'ssl_ctx'}) {
6165 foreach my $s (@_) {
6166 my $ok = Net::SSLeay::write($h->{'ssl_con'}, $s);
6167 $allok = 0 if (!$ok);
6171 my $ok = (print $fh @_);
6172 $allok = 0 if (!$ok);
6177 =head2 close_http_connection(&handle)
6179 Closes a connection to an HTTP server, identified by the given handle.
6182 sub close_http_connection
6187 =head2 clean_environment
6189 Deletes any environment variables inherited from miniserv so that they
6190 won't be passed to programs started by webmin. This is useful when calling
6191 programs that check for CGI-related environment variables and modify their
6192 behaviour, and to avoid passing sensitive variables to un-trusted programs.
6195 sub clean_environment
6197 %UNCLEAN_ENV = %ENV;
6198 foreach my $k (keys %ENV) {
6199 if ($k =~ /^(HTTP|VIRTUALSERVER|QUOTA|USERADMIN)_/) {
6203 foreach my $e ('WEBMIN_CONFIG', 'SERVER_NAME', 'CONTENT_TYPE', 'REQUEST_URI',
6204 'PATH_INFO', 'WEBMIN_VAR', 'REQUEST_METHOD', 'GATEWAY_INTERFACE',
6205 'QUERY_STRING', 'REMOTE_USER', 'SERVER_SOFTWARE', 'SERVER_PROTOCOL',
6206 'REMOTE_HOST', 'SERVER_PORT', 'DOCUMENT_ROOT', 'SERVER_ROOT',
6207 'MINISERV_CONFIG', 'SCRIPT_NAME', 'SERVER_ADMIN', 'CONTENT_LENGTH',
6208 'HTTPS', 'FOREIGN_MODULE_NAME', 'FOREIGN_ROOT_DIRECTORY',
6209 'SCRIPT_FILENAME', 'PATH_TRANSLATED', 'BASE_REMOTE_USER',
6210 'DOCUMENT_REALROOT', 'MINISERV_CONFIG', 'MYSQL_PWD') {
6215 =head2 reset_environment
6217 Puts the environment back how it was before clean_environment was callled.
6220 sub reset_environment
6222 if (defined(%UNCLEAN_ENV)) {
6223 foreach my $k (keys %UNCLEAN_ENV) {
6224 $ENV{$k} = $UNCLEAN_ENV{$k};
6226 undef(%UNCLEAN_ENV);
6230 =head2 progress_callback
6232 Never called directly, but useful for passing to &http_download to print
6233 out progress of an HTTP request.
6236 sub progress_callback
6238 if (defined(&theme_progress_callback)) {
6239 # Call the theme override
6240 return &theme_progress_callback(@_);
6244 print $progress_callback_prefix;
6246 $progress_size = $_[1];
6247 $progress_step = int($_[1] / 10);
6248 print &text('progress_size', $progress_callback_url,
6249 $progress_size),"<br>\n";
6252 print &text('progress_nosize', $progress_callback_url),"<br>\n";
6254 $last_progress_time = $last_progress_size = undef;
6256 elsif ($_[0] == 3) {
6258 my $sp = $progress_callback_prefix.(" " x 5);
6259 if ($progress_size) {
6260 # And we have a size to compare against
6261 my $st = int(($_[1] * 10) / $progress_size);
6262 my $time_now = time();
6263 if ($st != $progress_step ||
6264 $time_now - $last_progress_time > 60) {
6265 # Show progress every 10% or 60 seconds
6266 print $sp,&text('progress_data', $_[1], int($_[1]*100/$progress_size)),"<br>\n";
6267 $last_progress_time = $time_now;
6269 $progress_step = $st;
6272 # No total size .. so only show in 100k jumps
6273 if ($_[1] > $last_progress_size+100*1024) {
6274 print $sp,&text('progress_data2', $_[1]),"<br>\n";
6275 $last_progress_size = $_[1];
6279 elsif ($_[0] == 4) {
6280 # All done downloading
6281 print $progress_callback_prefix,&text('progress_done'),"<br>\n";
6283 elsif ($_[0] == 5) {
6284 # Got new location after redirect
6285 $progress_callback_url = $_[1];
6287 elsif ($_[0] == 6) {
6289 $progress_callback_url = $_[1];
6290 print &text('progress_incache', $progress_callback_url),"<br>\n";
6294 =head2 switch_to_remote_user
6296 Changes the user and group of the current process to that of the unix user
6297 with the same name as the current webmin login, or fails if there is none.
6298 This should be called by Usermin module scripts that only need to run with
6299 limited permissions.
6302 sub switch_to_remote_user
6304 @remote_user_info = $remote_user ? getpwnam($remote_user) :
6306 @remote_user_info || &error(&text('switch_remote_euser', $remote_user));
6307 &create_missing_homedir(\@remote_user_info);
6309 &switch_to_unix_user(\@remote_user_info);
6310 $ENV{'USER'} = $ENV{'LOGNAME'} = $remote_user;
6311 $ENV{'HOME'} = $remote_user_info[7];
6313 # Export global variables to caller
6314 if ($main::export_to_caller) {
6315 my ($callpkg) = caller();
6316 eval "\@${callpkg}::remote_user_info = \@remote_user_info";
6320 =head2 switch_to_unix_user(&user-details)
6322 Switches the current process to the UID and group ID from the given list
6323 of user details, which must be in the format returned by getpwnam.
6326 sub switch_to_unix_user
6329 if (!defined($uinfo->[0])) {
6330 # No username given, so just use given GID
6331 ($(, $)) = ( $uinfo->[3], "$uinfo->[3] $uinfo->[3]" );
6334 # Use all groups from user
6335 ($(, $)) = ( $uinfo->[3],
6336 "$uinfo->[3] ".join(" ", $uinfo->[3],
6337 &other_groups($uinfo->[0])) );
6340 POSIX::setuid($uinfo->[2]);
6342 if ($< != $uinfo->[2] || $> != $uinfo->[2]) {
6343 ($>, $<) = ( $uinfo->[2], $uinfo->[2] );
6347 =head2 eval_as_unix_user(username, &code)
6349 Runs some code fragment with the effective UID and GID switch to that
6350 of the given Unix user, so that file IO takes place with his permissions.
6354 sub eval_as_unix_user
6356 my ($user, $code) = @_;
6357 my @uinfo = getpwnam($user);
6358 defined(@uinfo) || &error("eval_as_unix_user called with invalid user $user");
6359 $) = $uinfo[3]." ".join(" ", $uinfo[3], &other_groups($user));
6363 local $main::error_must_die = 1;
6370 $err =~ s/\s+at\s+(\/\S+)\s+line\s+(\d+)\.?//;
6373 return wantarray ? @rv : $rv[0];
6376 =head2 create_user_config_dirs
6378 Creates per-user config directories and sets $user_config_directory and
6379 $user_module_config_directory to them. Also reads per-user module configs
6380 into %userconfig. This should be called by Usermin module scripts that need
6381 to store per-user preferences or other settings.
6384 sub create_user_config_dirs
6386 return if (!$gconfig{'userconfig'});
6387 my @uinfo = @remote_user_info ? @remote_user_info : getpwnam($remote_user);
6388 return if (!@uinfo || !$uinfo[7]);
6389 &create_missing_homedir(\@uinfo);
6390 $user_config_directory = "$uinfo[7]/$gconfig{'userconfig'}";
6391 if (!-d $user_config_directory) {
6392 mkdir($user_config_directory, 0700) ||
6393 &error("Failed to create $user_config_directory : $!");
6394 if ($< == 0 && $uinfo[2]) {
6395 chown($uinfo[2], $uinfo[3], $user_config_directory);
6398 if (&get_module_name()) {
6399 $user_module_config_directory = $user_config_directory."/".
6401 if (!-d $user_module_config_directory) {
6402 mkdir($user_module_config_directory, 0700) ||
6403 &error("Failed to create $user_module_config_directory : $!");
6404 if ($< == 0 && $uinfo[2]) {
6405 chown($uinfo[2], $uinfo[3], $user_config_directory);
6409 &read_file_cached("$module_root_directory/defaultuconfig",
6411 &read_file_cached("$module_config_directory/uconfig", \%userconfig);
6412 &read_file_cached("$user_module_config_directory/config",
6416 # Export global variables to caller
6417 if ($main::export_to_caller) {
6418 my ($callpkg) = caller();
6419 foreach my $v ('$user_config_directory',
6420 '$user_module_config_directory', '%userconfig') {
6421 my ($vt, $vn) = split('', $v, 2);
6422 eval "${vt}${callpkg}::${vn} = ${vt}${vn}";
6427 =head2 create_missing_homedir(&uinfo)
6429 If auto homedir creation is enabled, create one for this user if needed.
6430 For internal use only.
6433 sub create_missing_homedir
6436 if (!-e $uinfo->[7] && $gconfig{'create_homedir'}) {
6437 # Use has no home dir .. make one
6438 system("mkdir -p ".quotemeta($uinfo->[7]));
6439 chown($uinfo->[2], $uinfo->[3], $uinfo->[7]);
6440 if ($gconfig{'create_homedir_perms'} ne '') {
6441 chmod(oct($gconfig{'create_homedir_perms'}), $uinfo->[7]);
6446 =head2 filter_javascript(text)
6448 Disables all javascript <script>, onClick= and so on tags in the given HTML,
6449 and returns the new HTML. Useful for displaying HTML from an un-trusted source.
6452 sub filter_javascript
6455 $rv =~ s/<\s*script[^>]*>([\000-\377]*?)<\s*\/script\s*>//gi;
6456 $rv =~ s/(on(Abort|Blur|Change|Click|DblClick|DragDrop|Error|Focus|KeyDown|KeyPress|KeyUp|Load|MouseDown|MouseMove|MouseOut|MouseOver|MouseUp|Move|Reset|Resize|Select|Submit|Unload)=)/x$1/gi;
6457 $rv =~ s/(javascript:)/x$1/gi;
6458 $rv =~ s/(vbscript:)/x$1/gi;
6462 =head2 resolve_links(path)
6464 Given a path that may contain symbolic links, returns the real path.
6470 $path =~ s/\/+/\//g;
6471 $path =~ s/\/$// if ($path ne "/");
6472 my @p = split(/\/+/, $path);
6474 for(my $i=0; $i<@p; $i++) {
6475 my $sofar = "/".join("/", @p[0..$i]);
6476 my $lnk = readlink($sofar);
6477 if ($lnk =~ /^\//) {
6478 # Link is absolute..
6479 return &resolve_links($lnk."/".join("/", @p[$i+1 .. $#p]));
6483 return &resolve_links("/".join("/", @p[0..$i-1])."/".$lnk."/".join("/", @p[$i+1 .. $#p]));
6489 =head2 simplify_path(path, bogus)
6491 Given a path, maybe containing elements ".." and "." , convert it to a
6492 clean, absolute form. Returns undef if this is not possible.
6500 my @bits = split(/\/+/, $dir);
6503 foreach my $b (@bits) {
6507 elsif ($b eq "..") {
6509 if (scalar(@fixedbits) == 0) {
6510 # Cannot! Already at root!
6517 push(@fixedbits, $b);
6520 return "/".join('/', @fixedbits);
6523 =head2 same_file(file1, file2)
6525 Returns 1 if two files are actually the same
6530 return 1 if ($_[0] eq $_[1]);
6531 return 0 if ($_[0] !~ /^\// || $_[1] !~ /^\//);
6532 my @stat1 = $stat_cache{$_[0]} ? @{$stat_cache{$_[0]}}
6533 : (@{$stat_cache{$_[0]}} = stat($_[0]));
6534 my @stat2 = $stat_cache{$_[1]} ? @{$stat_cache{$_[1]}}
6535 : (@{$stat_cache{$_[1]}} = stat($_[1]));
6536 return 0 if (!@stat1 || !@stat2);
6537 return $stat1[0] == $stat2[0] && $stat1[1] == $stat2[1];
6540 =head2 flush_webmin_caches
6542 Clears all in-memory and on-disk caches used by Webmin.
6545 sub flush_webmin_caches
6547 undef(%main::read_file_cache);
6548 undef(%main::acl_hash_cache);
6549 undef(%main::acl_array_cache);
6550 undef(%main::has_command_cache);
6551 undef(@main::list_languages_cache);
6552 undef($main::got_list_usermods_cache);
6553 undef(@main::list_usermods_cache);
6554 undef(%main::foreign_installed_cache);
6555 unlink("$config_directory/module.infos.cache");
6556 &get_all_module_infos();
6559 =head2 list_usermods
6561 Returns a list of additional module restrictions. For internal use in
6567 if (!$main::got_list_usermods_cache) {
6568 @main::list_usermods_cache = ( );
6570 open(USERMODS, "$config_directory/usermin.mods");
6572 if (/^([^:]+):(\+|-|):(.*)/) {
6573 push(@main::list_usermods_cache,
6574 [ $1, $2, [ split(/\s+/, $3) ] ]);
6578 $main::got_list_usermods_cache = 1;
6580 return @main::list_usermods_cache;
6583 =head2 available_usermods(&allmods, &usermods)
6585 Returns a list of modules that are available to the given user, based
6586 on usermod additional/subtractions. For internal use by Usermin only.
6589 sub available_usermods
6591 return @{$_[0]} if (!@{$_[1]});
6593 my %mods = map { $_->{'dir'}, 1 } @{$_[0]};
6594 my @uinfo = @remote_user_info;
6595 @uinfo = getpwnam($remote_user) if (!@uinfo);
6596 foreach my $u (@{$_[1]}) {
6598 if ($u->[0] eq "*" || $u->[0] eq $remote_user) {
6601 elsif ($u->[0] =~ /^\@(.*)$/) {
6602 # Check for group membership
6603 my @ginfo = getgrnam($1);
6604 $applies++ if (@ginfo && ($ginfo[2] == $uinfo[3] ||
6605 &indexof($remote_user, split(/\s+/, $ginfo[3])) >= 0));
6607 elsif ($u->[0] =~ /^\//) {
6608 # Check users and groups in file
6610 open(USERFILE, $u->[0]);
6613 if ($_ eq $remote_user) {
6616 elsif (/^\@(.*)$/) {
6617 my @ginfo = getgrnam($1);
6619 if (@ginfo && ($ginfo[2] == $uinfo[3] ||
6620 &indexof($remote_user,
6621 split(/\s+/, $ginfo[3])) >= 0));
6628 if ($u->[1] eq "+") {
6629 map { $mods{$_}++ } @{$u->[2]};
6631 elsif ($u->[1] eq "-") {
6632 map { delete($mods{$_}) } @{$u->[2]};
6636 map { $mods{$_}++ } @{$u->[2]};
6640 return grep { $mods{$_->{'dir'}} } @{$_[0]};
6643 =head2 get_available_module_infos(nocache)
6645 Returns a list of modules available to the current user, based on
6646 operating system support, access control and usermod restrictions. Useful
6647 in themes that need to display a list of modules the user can use.
6648 Each element of the returned array is a hash reference in the same format as
6649 returned by get_module_info.
6652 sub get_available_module_infos
6655 &read_acl(\%acl, \%uacl);
6656 my $risk = $gconfig{'risk_'.$base_remote_user};
6658 foreach my $minfo (&get_all_module_infos($_[0])) {
6659 next if (!&check_os_support($minfo));
6661 # Check module risk level
6662 next if ($risk ne 'high' && $minfo->{'risk'} &&
6663 $minfo->{'risk'} !~ /$risk/);
6667 next if (!$acl{$base_remote_user,$minfo->{'dir'}} &&
6668 !$acl{$base_remote_user,"*"});
6670 next if (&is_readonly_mode() && !$minfo->{'readonly'});
6674 # Check usermod restrictions
6675 my @usermods = &list_usermods();
6676 @rv = sort { $a->{'desc'} cmp $b->{'desc'} }
6677 &available_usermods(\@rv, \@usermods);
6679 # Check RBAC restrictions
6681 foreach my $m (@rv) {
6682 if (&supports_rbac($m->{'dir'}) &&
6683 &use_rbac_module_acl(undef, $m->{'dir'})) {
6684 local $rbacs = &get_rbac_module_acl($remote_user,
6692 # Module or system doesn't support RBAC
6693 push(@rbacrv, $m) if (!$gconfig{'rbacdeny_'.$base_remote_user});
6699 if (defined(&theme_foreign_available)) {
6700 foreach my $m (@rbacrv) {
6701 if (&theme_foreign_available($m->{'dir'})) {
6710 # Check licence module vetos
6712 if ($main::licence_module) {
6713 foreach my $m (@themerv) {
6714 if (&foreign_call($main::licence_module,
6715 "check_module_licence", $m->{'dir'})) {
6727 =head2 get_visible_module_infos(nocache)
6729 Like get_available_module_infos, but excludes hidden modules from the list.
6730 Each element of the returned array is a hash reference in the same format as
6731 returned by get_module_info.
6734 sub get_visible_module_infos
6737 my $pn = &get_product_name();
6738 return grep { !$_->{'hidden'} &&
6739 !$_->{$pn.'_hidden'} } &get_available_module_infos($nocache);
6742 =head2 get_visible_modules_categories(nocache)
6744 Returns a list of Webmin module categories, each of which is a hash ref
6745 with 'code', 'desc' and 'modules' keys. The modules value is an array ref
6746 of modules in the category, in the format returned by get_module_info.
6747 Un-used modules are automatically assigned to the 'unused' category, and
6748 those with no category are put into 'others'.
6751 sub get_visible_modules_categories
6754 my @mods = &get_visible_module_infos($nocache);
6756 if (&get_product_name() eq 'webmin') {
6757 @unmods = grep { $_->{'installed'} eq '0' } @mods;
6758 @mods = grep { $_->{'installed'} ne '0' } @mods;
6760 my %cats = &list_categories(\@mods);
6762 foreach my $c (keys %cats) {
6763 my $cat = { 'code' => $c || 'other',
6764 'desc' => $cats{$c} };
6765 $cat->{'modules'} = [ grep { $_->{'category'} eq $c } @mods ];
6768 @rv = sort { ($b->{'code'} eq "others" ? "" : $b->{'code'}) cmp
6769 ($a->{'code'} eq "others" ? "" : $a->{'code'}) } @rv;
6771 # Add un-installed modules in magic category
6772 my $cat = { 'code' => 'unused',
6773 'desc' => $text{'main_unused'},
6775 'modules' => \@unmods };
6781 =head2 is_under_directory(directory, file)
6783 Returns 1 if the given file is under the specified directory, 0 if not.
6784 Symlinks are taken into account in the file to find it's 'real' location.
6787 sub is_under_directory
6789 my ($dir, $file) = @_;
6790 return 1 if ($dir eq "/");
6791 return 0 if ($file =~ /\.\./);
6792 my $ld = &resolve_links($dir);
6794 return &is_under_directory($ld, $file);
6796 my $lp = &resolve_links($file);
6798 return &is_under_directory($dir, $lp);
6800 return 0 if (length($file) < length($dir));
6801 return 1 if ($dir eq $file);
6803 return substr($file, 0, length($dir)) eq $dir;
6806 =head2 parse_http_url(url, [basehost, baseport, basepage, basessl])
6808 Given an absolute URL, returns the host, port, page and ssl flag components.
6809 Relative URLs can also be parsed, if the base information is provided.
6814 if ($_[0] =~ /^(http|https):\/\/([^:\/]+)(:(\d+))?(\/\S*)?$/) {
6816 my $ssl = $1 eq 'https';
6817 return ($2, $3 ? $4 : $ssl ? 443 : 80, $5 || "/", $ssl);
6823 elsif ($_[0] =~ /^\/\S*$/) {
6824 # A relative to the server URL
6825 return ($_[1], $_[2], $_[0], $_[4]);
6828 # A relative to the directory URL
6830 $page =~ s/[^\/]+$//;
6831 return ($_[1], $_[2], $page.$_[0], $_[4]);
6835 =head2 check_clicks_function
6837 Returns HTML for a JavaScript function called check_clicks that returns
6838 true when first called, but false subsequently. Useful on onClick for
6839 critical buttons. Deprecated, as this method of preventing duplicate actions
6843 sub check_clicks_function
6848 function check_clicks(form)
6855 for(i=0; i<form.length; i++)
6856 form.elements[i].disabled = true;
6865 =head2 load_entities_map
6867 Returns a hash ref containing mappings between HTML entities (like ouml) and
6868 ascii values (like 246). Mainly for internal use.
6871 sub load_entities_map
6873 if (!defined(%entities_map_cache)) {
6875 open(EMAP, "$root_directory/entities_map.txt");
6877 if (/^(\d+)\s+(\S+)/) {
6878 $entities_map_cache{$2} = $1;
6883 return \%entities_map_cache;
6886 =head2 entities_to_ascii(string)
6888 Given a string containing HTML entities like ö and 7, replace them
6889 with their ASCII equivalents.
6892 sub entities_to_ascii
6895 my $emap = &load_entities_map();
6896 $str =~ s/&([a-z]+);/chr($emap->{$1})/ge;
6897 $str =~ s/&#(\d+);/chr($1)/ge;
6901 =head2 get_product_name
6903 Returns either 'webmin' or 'usermin', depending on which program the current
6904 module is in. Useful for modules that can be installed into either.
6907 sub get_product_name
6909 return $gconfig{'product'} if (defined($gconfig{'product'}));
6910 return defined($gconfig{'userconfig'}) ? 'usermin' : 'webmin';
6915 Returns the character set for the current language, such as iso-8859-1.
6920 my $charset = defined($gconfig{'charset'}) ? $gconfig{'charset'} :
6921 $current_lang_info->{'charset'} ?
6922 $current_lang_info->{'charset'} : $default_charset;
6926 =head2 get_display_hostname
6928 Returns the system's hostname for UI display purposes. This may be different
6929 from the actual hostname if you administrator has configured it so in the
6930 Webmin Configuration module.
6933 sub get_display_hostname
6935 if ($gconfig{'hostnamemode'} == 0) {
6936 return &get_system_hostname();
6938 elsif ($gconfig{'hostnamemode'} == 3) {
6939 return $gconfig{'hostnamedisplay'};
6942 my $h = $ENV{'HTTP_HOST'};
6944 if ($gconfig{'hostnamemode'} == 2) {
6945 $h =~ s/^(www|ftp|mail)\.//i;
6951 =head2 save_module_config([&config], [modulename])
6953 Saves the configuration for some module. The config parameter is an optional
6954 hash reference of names and values to save, which defaults to the global
6955 %config hash. The modulename parameter is the module to update the config
6956 file, which defaults to the current module.
6959 sub save_module_config
6961 my $c = $_[0] || { &get_module_variable('%config') };
6962 my $m = defined($_[1]) ? $_[1] : &get_module_name();
6963 &write_file("$config_directory/$m/config", $c);
6966 =head2 save_user_module_config([&config], [modulename])
6968 Saves the user's Usermin preferences for some module. The config parameter is
6969 an optional hash reference of names and values to save, which defaults to the
6970 global %userconfig hash. The modulename parameter is the module to update the
6971 config file, which defaults to the current module.
6974 sub save_user_module_config
6976 my $c = $_[0] || { &get_module_variable('%userconfig') };
6977 my $m = $_[1] || &get_module_name();
6978 my $ucd = $user_config_directory;
6980 my @uinfo = @remote_user_info ? @remote_user_info
6981 : getpwnam($remote_user);
6982 return if (!@uinfo || !$uinfo[7]);
6983 $ucd = "$uinfo[7]/$gconfig{'userconfig'}";
6985 &write_file("$ucd/$m/config", $c);
6988 =head2 nice_size(bytes, [min])
6990 Converts a number of bytes into a number followed by a suffix like GB, MB
6991 or kB. Rounding is to two decimal digits. The optional min parameter sets the
6992 smallest units to use - so you could pass 1024*1024 to never show bytes or kB.
6997 my ($units, $uname);
6998 if (abs($_[0]) > 1024*1024*1024*1024 || $_[1] >= 1024*1024*1024*1024) {
6999 $units = 1024*1024*1024*1024;
7002 elsif (abs($_[0]) > 1024*1024*1024 || $_[1] >= 1024*1024*1024) {
7003 $units = 1024*1024*1024;
7006 elsif (abs($_[0]) > 1024*1024 || $_[1] >= 1024*1024) {
7010 elsif (abs($_[0]) > 1024 || $_[1] >= 1024) {
7018 my $sz = sprintf("%.2f", ($_[0]*1.0 / $units));
7020 return $sz." ".$uname;
7023 =head2 get_perl_path
7025 Returns the path to Perl currently in use, such as /usr/bin/perl.
7030 if (open(PERL, "$config_directory/perl-path")) {
7036 return $^X if (-x $^X);
7037 return &has_command("perl");
7040 =head2 get_goto_module([&mods])
7042 Returns the details of a module that the current user should be re-directed
7043 to after logging in, or undef if none. Useful for themes.
7048 my @mods = $_[0] ? @{$_[0]} : &get_visible_module_infos();
7049 if ($gconfig{'gotomodule'}) {
7050 my ($goto) = grep { $_->{'dir'} eq $gconfig{'gotomodule'} } @mods;
7051 return $goto if ($goto);
7053 if (@mods == 1 && $gconfig{'gotoone'}) {
7059 =head2 select_all_link(field, form, [text])
7061 Returns HTML for a 'Select all' link that uses Javascript to select
7062 multiple checkboxes with the same name. The parameters are :
7064 =item field - Name of the checkbox inputs.
7066 =item form - Index of the form on the page.
7068 =item text - Message for the link, defaulting to 'Select all'.
7073 return &theme_select_all_link(@_) if (defined(&theme_select_all_link));
7074 my ($field, $form, $text) = @_;
7076 $text ||= $text{'ui_selall'};
7077 return "<a class='select_all' href='#' onClick='document.forms[$form].$field.checked = true; for(i=0; i<document.forms[$form].$field.length; i++) { document.forms[$form].${field}[i].checked = true; } return false'>$text</a>";
7080 =head2 select_invert_link(field, form, text)
7082 Returns HTML for an 'Invert selection' link that uses Javascript to invert the
7083 selection on multiple checkboxes with the same name. The parameters are :
7085 =item field - Name of the checkbox inputs.
7087 =item form - Index of the form on the page.
7089 =item text - Message for the link, defaulting to 'Invert selection'.
7092 sub select_invert_link
7094 return &theme_select_invert_link(@_) if (defined(&theme_select_invert_link));
7095 my ($field, $form, $text) = @_;
7097 $text ||= $text{'ui_selinv'};
7098 return "<a class='select_invert' href='#' onClick='document.forms[$form].$field.checked = !document.forms[$form].$field.checked; for(i=0; i<document.forms[$form].$field.length; i++) { document.forms[$form].${field}[i].checked = !document.forms[$form].${field}[i].checked; } return false'>$text</a>";
7101 =head2 select_rows_link(field, form, text, &rows)
7103 Returns HTML for a link that uses Javascript to select rows with particular
7104 values for their checkboxes. The parameters are :
7106 =item field - Name of the checkbox inputs.
7108 =item form - Index of the form on the page.
7110 =item text - Message for the link, de
7112 =item rows - Reference to an array of 1 or 0 values, indicating which rows to check.
7115 sub select_rows_link
7117 return &theme_select_rows_link(@_) if (defined(&theme_select_rows_link));
7118 my ($field, $form, $text, $rows) = @_;
7120 my $js = "var sel = { ".join(",", map { "\""."e_escape($_)."\":1" } @$rows)." }; ";
7121 $js .= "for(var i=0; i<document.forms[$form].${field}.length; i++) { var r = document.forms[$form].${field}[i]; r.checked = sel[r.value]; } ";
7122 $js .= "return false;";
7123 return "<a href='#' onClick='$js'>$text</a>";
7126 =head2 check_pid_file(file)
7128 Given a pid file, returns the PID it contains if the process is running.
7133 open(PIDFILE, $_[0]) || return undef;
7134 my $pid = <PIDFILE>;
7136 $pid =~ /^\s*(\d+)/ || return undef;
7137 kill(0, $1) || return undef;
7143 Return the local os-specific library name to this module. For internal use only.
7148 my $mn = &get_module_name();
7149 my $md = &module_root_directory($mn);
7150 if (-r "$md/$mn-$gconfig{'os_type'}-$gconfig{'os_version'}-lib.pl") {
7151 return "$mn-$gconfig{'os_type'}-$gconfig{'os_version'}-lib.pl";
7153 elsif (-r "$md/$mn-$gconfig{'os_type'}-lib.pl") {
7154 return "$mn-$gconfig{'os_type'}-lib.pl";
7156 elsif (-r "$md/$mn-generic-lib.pl") {
7157 return "$mn-generic-lib.pl";
7164 =head2 module_root_directory(module)
7166 Given a module name, returns its root directory. On a typical Webmin install,
7167 all modules are under the same directory - but it is theoretically possible to
7171 sub module_root_directory
7173 my $d = ref($_[0]) ? $_[0]->{'dir'} : $_[0];
7174 if (@root_directories > 1) {
7175 foreach my $r (@root_directories) {
7181 return "$root_directories[0]/$d";
7184 =head2 list_mime_types
7186 Returns a list of all known MIME types and their extensions, as a list of hash
7187 references with keys :
7189 =item type - The MIME type, like text/plain.
7191 =item exts - A list of extensions, like .doc and .avi.
7193 =item desc - A human-readable description for the MIME type.
7198 if (!@list_mime_types_cache) {
7200 open(MIME, "$root_directory/mime.types");
7204 if (s/#\s*(.*)$//g) {
7207 my ($type, @exts) = split(/\s+/);
7209 push(@list_mime_types_cache, { 'type' => $type,
7216 return @list_mime_types_cache;
7219 =head2 guess_mime_type(filename, [default])
7221 Given a file name like xxx.gif or foo.html, returns a guessed MIME type.
7222 The optional default parameter sets a default type of use if none is found,
7223 which defaults to application/octet-stream.
7228 if ($_[0] =~ /\.([A-Za-z0-9\-]+)$/) {
7230 foreach my $t (&list_mime_types()) {
7231 foreach my $e (@{$t->{'exts'}}) {
7232 return $t->{'type'} if (lc($e) eq lc($ext));
7236 return @_ > 1 ? $_[1] : "application/octet-stream";
7239 =head2 open_tempfile([handle], file, [no-error], [no-tempfile], [safe?])
7241 Opens a file handle for writing to a temporary file, which will only be
7242 renamed over the real file when the handle is closed. This allows critical
7243 files like /etc/shadow to be updated safely, even if writing fails part way
7244 through due to lack of disk space. The parameters are :
7246 =item handle - File handle to open, as you would use in Perl's open function.
7248 =item file - Full path to the file to write, prefixed by > or >> to indicate over-writing or appending. In append mode, no temp file is used.
7250 =item no-error - By default, this function will call error if the open fails. Setting this parameter to 1 causes it to return 0 on failure, and set $! with the error code.
7252 =item no-tempfile - If set to 1, writing will be direct to the file instead of using a temporary file.
7254 =item safe - Indicates to users in read-only mode that this write is safe and non-destructive.
7260 # Just getting a temp file
7261 if (!defined($main::open_tempfiles{$_[0]})) {
7262 $_[0] =~ /^(.*)\/(.*)$/ || return $_[0];
7263 my $dir = $1 || "/";
7264 my $tmp = "$dir/$2.webmintmp.$$";
7265 $main::open_tempfiles{$_[0]} = $tmp;
7266 push(@main::temporary_files, $tmp);
7268 return $main::open_tempfiles{$_[0]};
7272 my ($fh, $file, $noerror, $notemp, $safe) = @_;
7273 $fh = &callers_package($fh);
7275 my %gaccess = &get_module_acl(undef, "");
7276 my $db = $gconfig{'debug_what_write'};
7277 if ($file =~ /\r|\n|\0/) {
7278 if ($noerror) { return 0; }
7279 else { &error("Filename contains invalid characters"); }
7281 if (&is_readonly_mode() && $file =~ />/ && !$safe) {
7282 # Read-only mode .. veto all writes
7283 print STDERR "vetoing write to $file\n";
7284 return open($fh, ">$null_file");
7286 elsif ($file =~ /^(>|>>|)nul$/i) {
7287 # Write to Windows null device
7288 &webmin_debug_log($1 eq ">" ? "WRITE" :
7289 $l eq ">>" ? "APPEND" : "READ", "nul") if ($db);
7291 elsif ($file =~ /^(>|>>)(\/dev\/.*)/ || lc($file) eq "nul") {
7292 # Writes to /dev/null or TTYs don't need to be handled
7293 &webmin_debug_log($1 eq ">" ? "WRITE" : "APPEND", $2) if ($db);
7294 return open($fh, $file);
7296 elsif ($file =~ /^>\s*(([a-zA-Z]:)?\/.*)$/ && !$notemp) {
7297 &webmin_debug_log("WRITE", $1) if ($db);
7298 # Over-writing a file, via a temp file
7300 $file = &translate_filename($file);
7302 # Open the link target instead
7303 $file = &resolve_links($file);
7306 # Cannot open a directory!
7307 if ($noerror) { return 0; }
7308 else { &error("Cannot write to directory $file"); }
7310 my $tmp = &open_tempfile($file);
7311 my $ex = open($fh, ">$tmp");
7312 if (!$ex && $! =~ /permission/i) {
7313 # Could not open temp file .. try opening actual file
7315 $ex = open($fh, ">$file");
7316 delete($main::open_tempfiles{$file});
7319 $main::open_temphandles{$fh} = $file;
7322 if (!$ex && !$noerror) {
7323 &error(&text("efileopen", $file, $!));
7327 elsif ($file =~ /^>\s*(([a-zA-Z]:)?\/.*)$/ && $notemp) {
7328 # Just writing direct to a file
7329 &webmin_debug_log("WRITE", $1) if ($db);
7331 $file = &translate_filename($file);
7332 my @old_attributes = &get_clear_file_attributes($file);
7333 my $ex = open($fh, ">$file");
7334 &reset_file_attributes($file, \@old_attributes);
7335 $main::open_temphandles{$fh} = $file;
7336 if (!$ex && !$noerror) {
7337 &error(&text("efileopen", $file, $!));
7342 elsif ($file =~ /^>>\s*(([a-zA-Z]:)?\/.*)$/) {
7343 # Appending to a file .. nothing special to do
7344 &webmin_debug_log("APPEND", $1) if ($db);
7346 $file = &translate_filename($file);
7347 my @old_attributes = &get_clear_file_attributes($file);
7348 my $ex = open($fh, ">>$file");
7349 &reset_file_attributes($file, \@old_attributes);
7350 $main::open_temphandles{$fh} = $file;
7351 if (!$ex && !$noerror) {
7352 &error(&text("efileopen", $file, $!));
7357 elsif ($file =~ /^([a-zA-Z]:)?\//) {
7358 # Read mode .. nothing to do here
7359 &webmin_debug_log("READ", $file) if ($db);
7360 $file = &translate_filename($file);
7361 return open($fh, $file);
7363 elsif ($file eq ">" || $file eq ">>") {
7364 my ($package, $filename, $line) = caller;
7365 if ($noerror) { return 0; }
7366 else { &error("Missing file to open at ${package}::${filename} line $line"); }
7369 my ($package, $filename, $line) = caller;
7370 &error("Unsupported file or mode $file at ${package}::${filename} line $line");
7375 =head2 close_tempfile(file|handle)
7377 Copies a temp file to the actual file, assuming that all writes were
7378 successful. The handle must have been one passed to open_tempfile.
7384 my $fh = &callers_package($_[0]);
7386 if (defined($file = $main::open_temphandles{$fh})) {
7388 close($fh) || &error(&text("efileclose", $file, $!));
7389 delete($main::open_temphandles{$fh});
7390 return &close_tempfile($file);
7392 elsif (defined($main::open_tempfiles{$_[0]})) {
7394 &webmin_debug_log("CLOSE", $_[0]) if ($gconfig{'debug_what_write'});
7395 my @st = stat($_[0]);
7396 if (&is_selinux_enabled() && &has_command("chcon")) {
7397 # Set original security context
7398 system("chcon --reference=".quotemeta($_[0]).
7399 " ".quotemeta($main::open_tempfiles{$_[0]}).
7400 " >/dev/null 2>&1");
7402 my @old_attributes = &get_clear_file_attributes($_[0]);
7403 rename($main::open_tempfiles{$_[0]}, $_[0]) || &error("Failed to replace $_[0] with $main::open_tempfiles{$_[0]} : $!");
7405 # Set original permissions and ownership
7406 chmod($st[2], $_[0]);
7407 chown($st[4], $st[5], $_[0]);
7409 &reset_file_attributes($_[0], \@old_attributes);
7410 delete($main::open_tempfiles{$_[0]});
7411 @main::temporary_files = grep { $_ ne $main::open_tempfiles{$_[0]} } @main::temporary_files;
7412 if ($main::open_templocks{$_[0]}) {
7413 &unlock_file($_[0]);
7414 delete($main::open_templocks{$_[0]});
7419 # Must be closing a handle not associated with a file
7425 =head2 print_tempfile(handle, text, ...)
7427 Like the normal print function, but calls &error on failure. Useful when
7428 combined with open_tempfile, to ensure that a criticial file is never
7429 only partially written.
7434 my ($fh, @args) = @_;
7435 $fh = &callers_package($fh);
7436 (print $fh @args) || &error(&text("efilewrite",
7437 $main::open_temphandles{$fh} || $fh, $!));
7440 =head2 is_selinux_enabled
7442 Returns 1 if SElinux is supported on this system and enabled, 0 if not.
7445 sub is_selinux_enabled
7447 if (!defined($main::selinux_enabled_cache)) {
7449 if ($gconfig{'os_type'} !~ /-linux$/) {
7450 # Not on linux, so no way
7451 $main::selinux_enabled_cache = 0;
7453 elsif (&read_env_file("/etc/selinux/config", \%seconfig)) {
7454 # Use global config file
7455 $main::selinux_enabled_cache =
7456 $seconfig{'SELINUX'} eq 'disabled' ||
7457 !$seconfig{'SELINUX'} ? 0 : 1;
7460 # Use selinuxenabled command
7461 #$selinux_enabled_cache =
7462 # system("selinuxenabled >/dev/null 2>&1") ? 0 : 1;
7463 $main::selinux_enabled_cache = 0;
7466 return $main::selinux_enabled_cache;
7469 =head2 get_clear_file_attributes(file)
7471 Finds file attributes that may prevent writing, clears them and returns them
7472 as a list. May call error. Mainly for internal use by open_tempfile and
7476 sub get_clear_file_attributes
7480 if ($gconfig{'chattr'}) {
7481 # Get original immutable bit
7482 my $out = &backquote_command(
7483 "lsattr ".quotemeta($file)." 2>/dev/null");
7485 $out =~ s/\s\S+\n//;
7486 @old_attributes = grep { $_ ne '-' } split(//, $out);
7488 if (&indexof("i", @old_attributes) >= 0) {
7489 my $err = &backquote_logged(
7490 "chattr -i ".quotemeta($file)." 2>&1");
7492 &error("Failed to remove immutable bit on ".
7497 return @old_attributes;
7500 =head2 reset_file_attributes(file, &attributes)
7502 Put back cleared attributes on some file. May call error. Mainly for internal
7503 use by close_tempfile.
7506 sub reset_file_attributes
7508 my ($file, $old_attributes) = @_;
7509 if (&indexof("i", @$old_attributes) >= 0) {
7510 my $err = &backquote_logged(
7511 "chattr +i ".quotemeta($file)." 2>&1");
7513 &error("Failed to restore immutable bit on ".
7519 =head2 cleanup_tempnames
7521 Remove all temporary files generated using transname. Typically only called
7522 internally when a Webmin script exits.
7525 sub cleanup_tempnames
7527 foreach my $t (@main::temporary_files) {
7530 @main::temporary_files = ( );
7533 =head2 open_lock_tempfile([handle], file, [no-error])
7535 Returns a temporary file for writing to some actual file, and also locks it.
7536 Effectively the same as calling lock_file and open_tempfile on the same file,
7537 but calls the unlock for you automatically when it is closed.
7540 sub open_lock_tempfile
7542 my ($fh, $file, $noerror, $notemp, $safe) = @_;
7543 $fh = &callers_package($fh);
7544 my $lockfile = $file;
7545 $lockfile =~ s/^[^\/]*//;
7546 if ($lockfile =~ /^\//) {
7547 $main::open_templocks{$lockfile} = &lock_file($lockfile);
7549 return &open_tempfile($fh, $file, $noerror, $notemp, $safe);
7554 $main::end_exit_status ||= $?;
7555 if ($$ == $main::initial_process_id) {
7556 # Exiting from initial process
7557 &cleanup_tempnames();
7558 if ($gconfig{'debug_what_start'} && $main::debug_log_start_time &&
7559 $main::debug_log_start_module eq &get_module_name()) {
7560 my $len = time() - $main::debug_log_start_time;
7561 &webmin_debug_log("STOP", "runtime=$len");
7562 $main::debug_log_start_time = 0;
7564 if (!$ENV{'SCRIPT_NAME'} &&
7565 $main::initial_module_name eq &get_module_name()) {
7566 # In a command-line script - call the real exit, so that the
7567 # exit status gets properly propogated. In some cases this
7568 # was not happening.
7569 exit($main::end_exit_status);
7574 =head2 month_to_number(month)
7576 Converts a month name like feb to a number like 1.
7581 return $month_to_number_map{lc(substr($_[0], 0, 3))};
7584 =head2 number_to_month(number)
7586 Converts a number like 1 to a month name like Feb.
7591 return ucfirst($number_to_month_map{$_[0]});
7594 =head2 get_rbac_module_acl(user, module)
7596 Returns a hash reference of RBAC overrides ACLs for some user and module.
7597 May return undef if none exist (indicating access denied), or the string *
7598 if full access is granted.
7601 sub get_rbac_module_acl
7603 my ($user, $mod) = @_;
7604 eval "use Authen::SolarisRBAC";
7605 return undef if ($@);
7608 if (Authen::SolarisRBAC::chkauth("webmin.$mod.admin", $user)) {
7609 # Automagic webmin.modulename.admin authorization exists .. allow access
7611 if (!Authen::SolarisRBAC::chkauth("webmin.$mod.config", $user)) {
7612 %rv = ( 'noconfig' => 1 );
7619 open(RBAC, &module_root_directory($mod)."/rbac-mapping");
7623 my ($auths, $acls) = split(/\s+/, $_);
7624 my @auths = split(/,/, $auths);
7626 my ($merge) = ($acls =~ s/^\+//);
7628 if ($auths eq "*") {
7629 # These ACLs apply to all RBAC users.
7630 # Only if there is some that match a specific authorization
7631 # later will they be used though.
7634 # Check each of the RBAC authorizations
7635 foreach my $a (@auths) {
7636 if (!Authen::SolarisRBAC::chkauth($a, $user)) {
7641 $foundany++ if ($gotall);
7644 # Found an RBAC authorization - return the ACLs
7645 return "*" if ($acls eq "*");
7646 my %acl = map { split(/=/, $_, 2) } split(/,/, $acls);
7648 # Just add to current set
7649 foreach my $a (keys %acl) {
7660 return !$foundany ? undef : defined(%rv) ? \%rv : undef;
7663 =head2 supports_rbac([module])
7665 Returns 1 if RBAC client support is available, such as on Solaris.
7670 return 0 if ($gconfig{'os_type'} ne 'solaris');
7671 eval "use Authen::SolarisRBAC";
7674 #return 0 if (!-r &module_root_directory($_[0])."/rbac-mapping");
7679 =head2 use_rbac_module_acl(user, module)
7681 Returns 1 if some user should use RBAC to get permissions for a module
7684 sub use_rbac_module_acl
7686 my $u = defined($_[0]) ? $_[0] : $base_remote_user;
7687 my $m = defined($_[1]) ? $_[1] : &get_module_name();
7688 return 1 if ($gconfig{'rbacdeny_'.$u}); # RBAC forced for user
7689 my %access = &get_module_acl($u, $m, 1);
7690 return $access{'rbac'} ? 1 : 0;
7693 =head2 execute_command(command, stdin, stdout, stderr, translate-files?, safe?)
7695 Runs some command, possibly feeding it input and capturing output to the
7696 give files or scalar references. The parameters are :
7698 =item command - Full command to run, possibly including shell meta-characters.
7700 =item stdin - File to read input from, or a scalar ref containing input, or undef if no input should be given.
7702 =item stdout - File to write output to, or a scalar ref into which output should be placed, or undef if the output is to be discarded.
7704 =item stderr - File to write error output to, or a scalar ref into which error output should be placed, or undef if the error output is to be discarded.
7706 =item translate-files - Set to 1 to apply filename translation to any filenames. Usually has no effect.
7708 =item safe - Set to 1 if this command is safe and does not modify the state of the system.
7713 my ($cmd, $stdin, $stdout, $stderr, $trans, $safe) = @_;
7714 if (&is_readonly_mode() && !$safe) {
7715 print STDERR "Vetoing command $_[0]\n";
7719 my $cmd = &translate_command($cmd);
7721 # Use ` operator where possible
7722 if (!$stdin && ref($stdout) && !$stderr) {
7723 $cmd = "($cmd)" if ($gconfig{'os_type'} ne 'windows');
7724 $$stdout = `$cmd 2>$null_file`;
7727 elsif (!$stdin && ref($stdout) && $stdout eq $stderr) {
7728 $cmd = "($cmd)" if ($gconfig{'os_type'} ne 'windows');
7729 $$stdout = `$cmd 2>&1`;
7732 elsif (!$stdin && !$stdout && !$stderr) {
7733 $cmd = "($cmd)" if ($gconfig{'os_type'} ne 'windows');
7734 return system("$cmd >$null_file 2>$null_file <$null_file");
7736 &webmin_debug_log('CMD', "cmd=$cmd") if ($gconfig{'debug_what_cmd'});
7739 $| = 1; # needed on some systems to flush before forking
7740 pipe(EXECSTDINr, EXECSTDINw);
7741 pipe(EXECSTDOUTr, EXECSTDOUTw);
7742 pipe(EXECSTDERRr, EXECSTDERRw);
7744 if (!($pid = fork())) {
7748 open(STDIN, "<&EXECSTDINr");
7749 open(STDOUT, ">&EXECSTDOUTw");
7750 if (ref($stderr) && $stderr eq $stdout) {
7751 open(STDERR, ">&EXECSTDOUTw");
7754 open(STDERR, ">&EXECSTDERRw");
7761 my $fullcmd = "($cmd)";
7762 if ($stdin && !ref($stdin)) {
7763 $fullcmd .= " <$stdin";
7765 if ($stdout && !ref($stdout)) {
7766 $fullcmd .= " >$stdout";
7768 if ($stderr && !ref($stderr)) {
7769 if ($stderr eq $stdout) {
7770 $fullcmd .= " 2>&1";
7773 $fullcmd .= " 2>$stderr";
7776 if ($gconfig{'os_type'} eq 'windows') {
7780 exec("/bin/sh", "-c", $fullcmd);
7782 print "Exec failed : $!\n";
7789 # Feed input and capture output
7791 if ($stdin && ref($stdin)) {
7792 print EXECSTDINw $$stdin;
7795 if ($stdout && ref($stdout)) {
7797 while(<EXECSTDOUTr>) {
7802 if ($stderr && ref($stderr) && $stderr ne $stdout) {
7804 while(<EXECSTDERRr>) {
7815 =head2 open_readfile(handle, file)
7817 Opens some file for reading. Returns 1 on success, 0 on failure. Pretty much
7818 exactly the same as Perl's open function.
7823 my ($fh, $file) = @_;
7824 $fh = &callers_package($fh);
7825 my $realfile = &translate_filename($file);
7826 &webmin_debug_log('READ', $file) if ($gconfig{'debug_what_read'});
7827 return open($fh, "<".$realfile);
7830 =head2 open_execute_command(handle, command, output?, safe?)
7832 Runs some command, with the specified file handle set to either write to it if
7833 in-or-out is set to 0, or read to it if output is set to 1. The safe flag
7834 indicates if the command modifies the state of the system or not.
7837 sub open_execute_command
7839 my ($fh, $cmd, $mode, $safe) = @_;
7840 $fh = &callers_package($fh);
7841 my $realcmd = &translate_command($cmd);
7842 if (&is_readonly_mode() && !$safe) {
7843 # Don't actually run it
7844 print STDERR "vetoing command $cmd\n";
7847 return open($fh, ">$null_file");
7850 return open($fh, $null_file);
7854 &webmin_debug_log('CMD', "cmd=$realcmd mode=$mode")
7855 if ($gconfig{'debug_what_cmd'});
7857 return open($fh, "| $cmd");
7859 elsif ($mode == 1) {
7860 return open($fh, "$cmd 2>$null_file |");
7862 elsif ($mode == 2) {
7863 return open($fh, "$cmd 2>&1 |");
7867 =head2 translate_filename(filename)
7869 Applies all relevant registered translation functions to a filename. Mostly
7870 for internal use, and typically does nothing.
7873 sub translate_filename
7875 my ($realfile) = @_;
7876 my @funcs = grep { $_->[0] eq &get_module_name() ||
7877 !defined($_->[0]) } @main::filename_callbacks;
7878 foreach my $f (@funcs) {
7880 $realfile = &$func($realfile, @{$f->[2]});
7885 =head2 translate_command(filename)
7887 Applies all relevant registered translation functions to a command. Mostly
7888 for internal use, and typically does nothing.
7891 sub translate_command
7894 my @funcs = grep { $_->[0] eq &get_module_name() ||
7895 !defined($_->[0]) } @main::command_callbacks;
7896 foreach my $f (@funcs) {
7898 $realcmd = &$func($realcmd, @{$f->[2]});
7903 =head2 register_filename_callback(module|undef, &function, &args)
7905 Registers some function to be called when the specified module (or all
7906 modules) tries to open a file for reading and writing. The function must
7907 return the actual file to open. This allows you to override which files
7908 other code actually operates on, via the translate_filename function.
7911 sub register_filename_callback
7913 my ($mod, $func, $args) = @_;
7914 push(@main::filename_callbacks, [ $mod, $func, $args ]);
7917 =head2 register_command_callback(module|undef, &function, &args)
7919 Registers some function to be called when the specified module (or all
7920 modules) tries to execute a command. The function must return the actual
7921 command to run. This allows you to override which commands other other code
7922 actually runs, via the translate_command function.
7925 sub register_command_callback
7927 my ($mod, $func, $args) = @_;
7928 push(@main::command_callbacks, [ $mod, $func, $args ]);
7931 =head2 capture_function_output(&function, arg, ...)
7933 Captures output that some function prints to STDOUT, and returns it. Useful
7934 for functions outside your control that print data when you really want to
7935 manipulate it before output.
7938 sub capture_function_output
7940 my ($func, @args) = @_;
7941 socketpair(SOCKET2, SOCKET1, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
7942 my $old = select(SOCKET1);
7943 my @rv = &$func(@args);
7952 return wantarray ? ($out, \@rv) : $out;
7955 =head2 capture_function_output_tempfile(&function, arg, ...)
7957 Behaves the same as capture_function_output, but uses a temporary file
7958 to avoid buffer full problems.
7961 sub capture_function_output_tempfile
7963 my ($func, @args) = @_;
7964 my $temp = &transname();
7965 open(BUFFER, ">$temp");
7966 my $old = select(BUFFER);
7967 my @rv = &$func(@args);
7970 my $out = &read_file_contents($temp);
7971 &unlink_file($temp);
7972 return wantarray ? ($out, \@rv) : $out;
7975 =head2 modules_chooser_button(field, multiple, [form])
7977 Returns HTML for a button for selecting one or many Webmin modules.
7978 field - Name of the HTML field to place the module names into.
7979 multiple - Set to 1 if multiple modules can be selected.
7980 form - Index of the form on the page.
7983 sub modules_chooser_button
7985 return &theme_modules_chooser_button(@_)
7986 if (defined(&theme_modules_chooser_button));
7987 my $form = defined($_[2]) ? $_[2] : 0;
7988 my $w = $_[1] ? 700 : 500;
7990 if ($_[1] && $gconfig{'db_sizemodules'}) {
7991 ($w, $h) = split(/x/, $gconfig{'db_sizemodules'});
7993 elsif (!$_[1] && $gconfig{'db_sizemodule'}) {
7994 ($w, $h) = split(/x/, $gconfig{'db_sizemodule'});
7996 return "<input type=button onClick='ifield = document.forms[$form].$_[0]; chooser = window.open(\"$gconfig{'webprefix'}/module_chooser.cgi?multi=$_[1]&module=\"+escape(ifield.value), \"chooser\", \"toolbar=no,menubar=no,scrollbars=yes,width=$w,height=$h\"); chooser.ifield = ifield; window.ifield = ifield' value=\"...\">\n";
7999 =head2 substitute_template(text, &hash)
8001 Given some text and a hash reference, for each ocurrance of $FOO or ${FOO} in
8002 the text replaces it with the value of the hash key foo. Also supports blocks
8003 like ${IF-FOO} ... ${ENDIF-FOO}, whose contents are only included if foo is
8004 non-zero, and ${IF-FOO} ... ${ELSE-FOO} ... ${ENDIF-FOO}.
8007 sub substitute_template
8009 # Add some extra fixed parameters to the hash
8010 my %hash = %{$_[1]};
8011 $hash{'hostname'} = &get_system_hostname();
8012 $hash{'webmin_config'} = $config_directory;
8013 $hash{'webmin_etc'} = $config_directory;
8014 $hash{'module_config'} = &get_module_variable('$module_config_directory');
8015 $hash{'webmin_var'} = $var_directory;
8017 # Add time-based parameters, for use in DNS
8018 $hash{'current_time'} = time();
8019 my @tm = localtime($hash{'current_time'});
8020 $hash{'current_year'} = $tm[5]+1900;
8021 $hash{'current_month'} = sprintf("%2.2d", $tm[4]+1);
8022 $hash{'current_day'} = sprintf("%2.2d", $tm[3]);
8023 $hash{'current_hour'} = sprintf("%2.2d", $tm[2]);
8024 $hash{'current_minute'} = sprintf("%2.2d", $tm[1]);
8025 $hash{'current_second'} = sprintf("%2.2d", $tm[0]);
8027 # Actually do the substition
8029 foreach my $s (keys %hash) {
8030 next if ($s eq ''); # Prevent just $ from being subbed
8033 $rv =~ s/\$\{\Q$us\E\}/$sv/g;
8034 $rv =~ s/\$\Q$us\E/$sv/g;
8036 # Replace ${IF}..${ELSE}..${ENDIF} block with first value,
8037 # and ${IF}..${ENDIF} with value
8038 $rv =~ s/\$\{IF-\Q$us\E\}(\n?)([\000-\377]*?)\$\{ELSE-\Q$us\E\}(\n?)([\000-\377]*?)\$\{ENDIF-\Q$us\E\}(\n?)/\2/g;
8039 $rv =~ s/\$\{IF-\Q$us\E\}(\n?)([\000-\377]*?)\$\{ENDIF-\Q$us\E\}(\n?)/\2/g;
8041 # Replace $IF..$ELSE..$ENDIF block with first value,
8042 # and $IF..$ENDIF with value
8043 $rv =~ s/\$IF-\Q$us\E(\n?)([\000-\377]*?)\$ELSE-\Q$us\E(\n?)([\000-\377]*?)\$ENDIF-\Q$us\E(\n?)/\2/g;
8044 $rv =~ s/\$IF-\Q$us\E(\n?)([\000-\377]*?)\$ENDIF-\Q$us\E(\n?)/\2/g;
8046 # Replace ${IFEQ}..${ENDIFEQ} block with first value if
8047 # matching, nothing if not
8048 $rv =~ s/\$\{IFEQ-\Q$us\E-\Q$sv\E\}(\n?)([\000-\377]*?)\$\{ENDIFEQ-\Q$us\E-\Q$sv\E\}(\n?)/\2/g;
8049 $rv =~ s/\$\{IFEQ-\Q$us\E-[^\}]+}(\n?)([\000-\377]*?)\$\{ENDIFEQ-\Q$us\E-[^\}]+\}(\n?)//g;
8051 # Replace $IFEQ..$ENDIFEQ block with first value if
8052 # matching, nothing if not
8053 $rv =~ s/\$IFEQ-\Q$us\E-\Q$sv\E(\n?)([\000-\377]*?)\$ENDIFEQ-\Q$us\E-\Q$sv\E(\n?)/\2/g;
8054 $rv =~ s/\$IFEQ-\Q$us\E-\S+(\n?)([\000-\377]*?)\$ENDIFEQ-\Q$us\E-\S+(\n?)//g;
8057 # Replace ${IF}..${ELSE}..${ENDIF} block with second value,
8058 # and ${IF}..${ENDIF} with nothing
8059 $rv =~ s/\$\{IF-\Q$us\E\}(\n?)([\000-\377]*?)\$\{ELSE-\Q$us\E\}(\n?)([\000-\377]*?)\$\{ENDIF-\Q$us\E\}(\n?)/\4/g;
8060 $rv =~ s/\$\{IF-\Q$us\E\}(\n?)([\000-\377]*?)\$\{ENDIF-\Q$us\E\}(\n?)//g;
8062 # Replace $IF..$ELSE..$ENDIF block with second value,
8063 # and $IF..$ENDIF with nothing
8064 $rv =~ s/\$IF-\Q$us\E(\n?)([\000-\377]*?)\$ELSE-\Q$us\E(\n?)([\000-\377]*?)\$ENDIF-\Q$us\E(\n?)/\4/g;
8065 $rv =~ s/\$IF-\Q$us\E(\n?)([\000-\377]*?)\$ENDIF-\Q$us\E(\n?)//g;
8067 # Replace ${IFEQ}..${ENDIFEQ} block with nothing
8068 $rv =~ s/\$\{IFEQ-\Q$us\E-[^\}]+}(\n?)([\000-\377]*?)\$\{ENDIFEQ-\Q$us\E-[^\}]+\}(\n?)//g;
8069 $rv =~ s/\$IFEQ-\Q$us\E-\S+(\n?)([\000-\377]*?)\$ENDIFEQ-\Q$us\E-\S+(\n?)//g;
8073 # Now assume any $IF blocks whose variables are not present in the hash
8074 # evaluate to false.
8075 # $IF...$ELSE x $ENDIF => x
8076 $rv =~ s/\$\{IF\-([A-Z]+)\}.*?\$\{ELSE\-\1\}(.*?)\$\{ENDIF\-\1\}/$2/gs;
8077 # $IF...x...$ENDIF => (nothing)
8078 $rv =~ s/\$\{IF\-([A-Z]+)\}.*?\$\{ENDIF\-\1\}//gs;
8079 # ${var} => (nothing)
8080 $rv =~ s/\$\{[A-Z]+\}//g;
8085 =head2 running_in_zone
8087 Returns 1 if the current Webmin instance is running in a Solaris zone. Used to
8088 disable module and features that are not appropriate, like those that modify
8089 mounted filesystems.
8094 return 0 if ($gconfig{'os_type'} ne 'solaris' ||
8095 $gconfig{'os_version'} < 10);
8096 my $zn = `zonename 2>$null_file`;
8098 return $zn && $zn ne "global";
8101 =head2 running_in_vserver
8103 Returns 1 if the current Webmin instance is running in a Linux VServer.
8104 Used to disable modules and features that are not appropriate.
8107 sub running_in_vserver
8109 return 0 if ($gconfig{'os_type'} !~ /^\*-linux$/);
8112 open(MTAB, "/etc/mtab");
8114 my ($dev, $mp) = split(/\s+/, $_);
8115 if ($mp eq "/" && $dev =~ /^\/dev\/hdv/) {
8124 =head2 running_in_xen
8126 Returns 1 if Webmin is running inside a Xen instance, by looking
8127 at /proc/xen/capabilities.
8132 return 0 if (!-r "/proc/xen/capabilities");
8133 my $cap = &read_file_contents("/proc/xen/capabilities");
8134 return $cap =~ /control_d/ ? 0 : 1;
8137 =head2 list_categories(&modules, [include-empty])
8139 Returns a hash mapping category codes to names, including any custom-defined
8140 categories. The modules parameter must be an array ref of module hash objects,
8141 as returned by get_all_module_infos.
8146 my ($mods, $empty) = @_;
8147 my (%cats, %catnames);
8148 &read_file("$config_directory/webmin.catnames", \%catnames);
8149 foreach my $o (@lang_order_list) {
8150 &read_file("$config_directory/webmin.catnames.$o", \%catnames);
8155 foreach my $m (@$mods) {
8156 my $c = $m->{'category'};
8157 next if ($cats{$c});
8158 if (defined($catnames{$c})) {
8159 $cats{$c} = $catnames{$c};
8161 elsif ($text{"category_$c"}) {
8162 $cats{$c} = $text{"category_$c"};
8165 # try to get category name from module ..
8166 my %mtext = &load_language($m->{'dir'});
8167 if ($mtext{"category_$c"}) {
8168 $cats{$c} = $mtext{"category_$c"};
8171 $c = $m->{'category'} = "";
8172 $cats{$c} = $text{"category_$c"};
8179 =head2 is_readonly_mode
8181 Returns 1 if the current user is in read-only mode, and thus all writes
8182 to files and command execution should fail.
8185 sub is_readonly_mode
8187 if (!defined($main::readonly_mode_cache)) {
8188 my %gaccess = &get_module_acl(undef, "");
8189 $main::readonly_mode_cache = $gaccess{'readonly'} ? 1 : 0;
8191 return $main::readonly_mode_cache;
8194 =head2 command_as_user(user, with-env?, command, ...)
8196 Returns a command to execute some command as the given user, using the
8197 su statement. If on Linux, the /bin/sh shell is forced in case the user
8198 does not have a valid shell. If with-env is set to 1, the -s flag is added
8199 to the su command to read the user's .profile or .bashrc file.
8204 my ($user, $env, @args) = @_;
8205 my @uinfo = getpwnam($user);
8206 if ($uinfo[8] ne "/bin/sh" && $uinfo[8] !~ /\/bash$/) {
8207 # User shell doesn't appear to be valid
8208 if ($gconfig{'os_type'} =~ /-linux$/) {
8209 # Use -s /bin/sh to force it
8210 $shellarg = " -s /bin/sh";
8212 elsif ($gconfig{'os_type'} eq 'freebsd' ||
8213 $gconfig{'os_type'} eq 'solaris' &&
8214 $gconfig{'os_version'} >= 11 ||
8215 $gconfig{'os_type'} eq 'macos') {
8216 # Use -m and force /bin/sh
8217 @args = ( "/bin/sh", "-c", quotemeta(join(" ", @args)) );
8221 my $rv = "su".($env ? " -" : "").$shellarg.
8222 " ".quotemeta($user)." -c ".quotemeta(join(" ", @args));
8226 =head2 list_osdn_mirrors(project, file)
8228 Given a OSDN project and filename, returns a list of mirror URLs from
8229 which it can be downloaded. Mainly for internal use by the http_download
8233 sub list_osdn_mirrors
8235 my ($project, $file) = @_;
8237 # Convert the sourceforge project name to a group ID
8238 my ($idpage, $iderror);
8239 &http_download($osdn_download_host, $osdn_download_port,
8240 "/$project/", \$idpage, \$iderror,
8241 undef, 0, undef, undef, 0, 0, 1);
8243 if ($idpage =~ /showfiles.php\?group_id=(\d+)/) {
8247 # Query the mirror picker page
8248 my ($page, $error, @rv);
8250 &http_download($osdn_download_host, $osdn_download_port,
8251 "/project/mirror_picker.php?group_id=".&urlize($group_id).
8252 "&filename=".&urlize($file),
8253 \$page, \$error, undef, 0, undef, undef, 0, 0, 1,
8255 while($page =~ /<input[^>]*name="use_mirror"\s+value="(\S+)"[^>]*>([^,]+),\s*([^<]*)<([\000-\377]*)/i) {
8256 # Got a country and city
8257 push(@rv, { 'country' => $3,
8260 'url' => "http://$1.dl.sourceforge.net/sourceforge/$project/$file" });
8266 # None found! Try some known mirrors
8267 foreach my $m ("superb-east", "superb-west", "osdn", "downloads") {
8268 my $url = $m eq "downloads" ?
8269 "http://downloads.sourceforge.net/$project/$file" :
8270 "http://$m.dl.sourceforge.net/sourceforge/$project/$file";
8271 $main::download_timed_out = undef;
8272 local $SIG{ALRM} = \&download_timeout;
8274 my ($host, $port, $page, $ssl) = &parse_http_url($url);
8275 my $h = &make_http_connection(
8276 $host, $port, $ssl, "HEAD", $page);
8278 next if (!ref($h) || $main::download_timed_out);
8280 # Make a HEAD request
8281 &write_http_connection($h, "Host: $host\r\n");
8282 &write_http_connection($h, "User-agent: Webmin\r\n");
8283 &write_http_connection($h, "\r\n");
8284 $line = &read_http_connection($h);
8285 $line =~ s/\r|\n//g;
8286 &close_http_connection($h);
8287 if ($line =~ /^HTTP\/1\..\s+(200)\s+/) {
8288 push(@rv, { 'mirror' => $m,
8289 'default' => $m eq 'osdn',
8298 =head2 convert_osdn_url(url)
8300 Given a URL like http://osdn.dl.sourceforge.net/sourceforge/project/file.zip
8301 or http://prdownloads.sourceforge.net/project/file.zip , convert it
8302 to a real URL on the best mirror.
8305 sub convert_osdn_url
8308 if ($url =~ /^http:\/\/[^\.]+.dl.sourceforge.net\/sourceforge\/([^\/]+)\/(.*)$/ ||
8309 $url =~ /^http:\/\/prdownloads.sourceforge.net\/([^\/]+)\/(.*)$/) {
8311 my ($project, $file) = ($1, $2);
8312 my @mirrors = &list_osdn_mirrors($project, $file);
8313 my $pref = $gconfig{'osdn_mirror'};
8316 ($site) = grep { $_->{'mirror'} eq $pref } @mirrors;
8319 # Fall back to automatic mirror selection via Sourceforge
8321 $site = { 'url' => "http://prdownloads.sourceforge.net/sourceforge/$project/$file",
8324 return wantarray ? ( $site->{'url'}, $site->{'default'} )
8328 # Some other source .. don't change
8329 return wantarray ? ( $url, 2 ) : $url;
8333 =head2 get_current_dir
8335 Returns the directory the current process is running in.
8341 if ($gconfig{'os_type'} eq 'windows') {
8354 =head2 supports_users
8356 Returns 1 if the current OS supports Unix user concepts and functions like
8357 su , getpw* and so on. This will be true on Linux and other Unixes, but false
8363 return $gconfig{'os_type'} ne 'windows';
8366 =head2 supports_symlinks
8368 Returns 1 if the current OS supports symbolic and hard links. This will not
8369 be the case on Windows.
8372 sub supports_symlinks
8374 return $gconfig{'os_type'} ne 'windows';
8377 =head2 quote_path(path)
8379 Returns a path with safe quoting for the current operating system.
8385 if ($gconfig{'os_type'} eq 'windows' || $path =~ /^[a-z]:/i) {
8386 # Windows only supports "" style quoting
8390 return quotemeta($path);
8394 =head2 get_windows_root
8396 Returns the base windows system directory, like c:/windows.
8399 sub get_windows_root
8401 if ($ENV{'SystemRoot'}) {
8402 my $rv = $ENV{'SystemRoot'};
8407 return -d "c:/windows" ? "c:/windows" : "c:/winnt";
8411 =head2 read_file_contents(file)
8413 Given a filename, returns its complete contents as a string. Effectively
8414 the same as the Perl construct `cat file`.
8417 sub read_file_contents
8419 &open_readfile(FILE, $_[0]) || return undef;
8426 =head2 unix_crypt(password, salt)
8428 Performs Unix encryption on a password, using the built-in crypt function or
8429 the Crypt::UnixCrypt module if the former does not work. The salt parameter
8430 must be either an already-hashed password, or a two-character alpha-numeric
8436 my ($pass, $salt) = @_;
8437 return "" if ($salt !~ /^[a-zA-Z0-9\.\/]{2}/); # same as real crypt
8438 my $rv = eval "crypt(\$pass, \$salt)";
8440 return $rv if ($rv && !$@);
8441 eval "use Crypt::UnixCrypt";
8443 return Crypt::UnixCrypt::crypt($pass, $salt);
8446 &error("Failed to encrypt password : $err");
8450 =head2 split_quoted_string(string)
8452 Given a string like I<foo "bar baz" quux>, returns the array :
8456 sub split_quoted_string
8460 while($str =~ /^"([^"]*)"\s*([\000-\377]*)$/ ||
8461 $str =~ /^'([^']*)'\s*([\000-\377]*)$/ ||
8462 $str =~ /^(\S+)\s*([\000-\377]*)$/) {
8469 =head2 write_to_http_cache(url, file|&data)
8471 Updates the Webmin cache with the contents of the given file, possibly also
8472 clearing out old data. Mainly for internal use by http_download.
8475 sub write_to_http_cache
8477 my ($url, $file) = @_;
8478 return 0 if (!$gconfig{'cache_size'});
8480 # Don't cache downloads that look dynamic
8481 if ($url =~ /cgi-bin/ || $url =~ /\?/) {
8485 # Check if the current module should do caching
8486 if ($gconfig{'cache_mods'} =~ /^\!(.*)$/) {
8487 # Caching all except some modules
8488 my @mods = split(/\s+/, $1);
8489 return 0 if (&indexof(&get_module_name(), @mods) != -1);
8491 elsif ($gconfig{'cache_mods'}) {
8492 # Only caching some modules
8493 my @mods = split(/\s+/, $gconfig{'cache_mods'});
8494 return 0 if (&indexof(&get_module_name(), @mods) == -1);
8500 $size = length($$file);
8503 my @st = stat($file);
8507 if ($size > $gconfig{'cache_size'}) {
8508 # Bigger than the whole cache - so don't save it
8513 $cfile = "$main::http_cache_directory/$cfile";
8515 # See how much we have cached currently, clearing old files
8517 mkdir($main::http_cache_directory, 0700) if (!-d $main::http_cache_directory);
8518 opendir(CACHEDIR, $main::http_cache_directory);
8519 foreach my $f (readdir(CACHEDIR)) {
8520 next if ($f eq "." || $f eq "..");
8521 my $path = "$main::http_cache_directory/$f";
8522 my @st = stat($path);
8523 if ($gconfig{'cache_days'} &&
8524 time()-$st[9] > $gconfig{'cache_days'}*24*60*60) {
8525 # This file is too old .. trash it
8530 push(@cached, [ $path, $st[7], $st[9] ]);
8534 @cached = sort { $a->[2] <=> $b->[2] } @cached;
8535 while($total+$size > $gconfig{'cache_size'} && @cached) {
8536 # Cache is too big .. delete some files until the new one will fit
8537 unlink($cached[0]->[0]);
8538 $total -= $cached[0]->[1];
8542 # Finally, write out the new file
8544 &open_tempfile(CACHEFILE, ">$cfile");
8545 &print_tempfile(CACHEFILE, $$file);
8546 &close_tempfile(CACHEFILE);
8549 my ($ok, $err) = ©_source_dest($file, $cfile);
8555 =head2 check_in_http_cache(url)
8557 If some URL is in the cache and valid, return the filename for it. Mainly
8558 for internal use by http_download.
8561 sub check_in_http_cache
8564 return undef if (!$gconfig{'cache_size'});
8566 # Check if the current module should do caching
8567 if ($gconfig{'cache_mods'} =~ /^\!(.*)$/) {
8568 # Caching all except some modules
8569 my @mods = split(/\s+/, $1);
8570 return 0 if (&indexof(&get_module_name(), @mods) != -1);
8572 elsif ($gconfig{'cache_mods'}) {
8573 # Only caching some modules
8574 my @mods = split(/\s+/, $gconfig{'cache_mods'});
8575 return 0 if (&indexof(&get_module_name(), @mods) == -1);
8580 $cfile = "$main::http_cache_directory/$cfile";
8581 my @st = stat($cfile);
8582 return undef if (!@st || !$st[7]);
8583 if ($gconfig{'cache_days'} && time()-$st[9] > $gconfig{'cache_days'}*24*60*60) {
8588 open(TOUCH, ">>$cfile"); # Update the file time, to keep it in the cache
8593 =head2 supports_javascript
8595 Returns 1 if the current browser is assumed to support javascript.
8598 sub supports_javascript
8600 if (defined(&theme_supports_javascript)) {
8601 return &theme_supports_javascript();
8603 return $ENV{'MOBILE_DEVICE'} ? 0 : 1;
8606 =head2 get_module_name
8608 Returns the name of the Webmin module that called this function. For internal
8609 use only by other API functions.
8614 return &get_module_variable('$module_name');
8617 =head2 get_module_variable(name, [ref])
8619 Returns the value of some variable which is set in the caller's context, if
8620 using the new WebminCore package. For internal use only.
8623 sub get_module_variable
8625 my ($v, $wantref) = @_;
8626 my $slash = $wantref ? "\\" : "";
8627 my $thispkg = &web_libs_package();
8628 if ($thispkg eq 'WebminCore') {
8629 my ($vt, $vn) = split('', $v, 2);
8631 for(my $i=0; ($callpkg) = caller($i); $i++) {
8632 last if ($callpkg ne $thispkg);
8634 return eval "${slash}${vt}${callpkg}::${vn}";
8636 return eval "${slash}${v}";
8639 =head2 clear_time_locale()
8641 Temporarily force the locale to C, until reset_time_locale is called. This is
8642 useful if your code is going to call C<strftime> from the POSIX package, and
8643 you want to ensure that the output is in a consistent format.
8646 sub clear_time_locale
8648 if ($main::clear_time_locale_count == 0) {
8651 $main::clear_time_locale_old = POSIX::setlocale(POSIX::LC_TIME);
8652 POSIX::setlocale(POSIX::LC_TIME, "C");
8655 $main::clear_time_locale_count++;
8658 =head2 reset_time_locale()
8660 Revert the locale to whatever it was before clear_time_locale was called
8663 sub reset_time_locale
8665 if ($main::clear_time_locale_count == 1) {
8667 POSIX::setlocale(POSIX::LC_TIME, $main::clear_time_locale_old);
8668 $main::clear_time_locale_old = undef;
8671 $main::clear_time_locale_count--;
8674 =head2 callers_package(filehandle)
8676 Convert a non-module filehandle like FOO to one qualified with the
8677 caller's caller's package, like fsdump::FOO. For internal use only.
8683 my $callpkg = (caller(1))[0];
8684 my $thispkg = &web_libs_package();
8685 if (!ref($fh) && $fh !~ /::/ &&
8686 $callpkg ne $thispkg && $thispkg eq 'WebminCore') {
8687 $fh = $callpkg."::".$fh;
8692 =head2 web_libs_package()
8694 Returns the package this code is in. We can't always trust __PACKAGE__. For
8698 sub web_libs_package
8700 if ($called_from_webmin_core) {
8701 return "WebminCore";
8706 $done_web_lib_funcs = 1;