# stta-lib.pl
# STTA Rev. 1.3 Copyright (c) 2001-2003 Jess Prez Lorenzo  --- license GNU GPL 
# stta: (@#) 1.3pre1044444122- [2003_2_05_122202]
# Common functions 

do '../web-lib.pl';
do 'web-lib.pl';
do 'global-lib.pl';
do 'lists-lib.pl';
do 'html-lib.pl';
do 'ttasess-lib.pl';
do 'monitor-lib.pl';
do 'print-lib.pl';

&init_config();
&load_dataconf();

%access = &get_module_acl();
%ttaprops=();
@ttahosts=();
%sttaparams=();
$cginame= $0 =~ /([^\/]+)$/ ? $1 : '-';   
$ldap_ok=true;
$ldapcache_ok=true;
$tta_ok=true;
$remote_err_msg="";

@access_types = $access{'types'} eq '*' ? (0 .. 100)
				        : split(/\s+/, $access{'types'});
map { $access_types{$_}++ } @access_types;
$debug=$config{debug_code};

if ( -r "$config_directory/$module_name/.insupd.lock" ) {
           &redirect("/stta/stta_installupd.cgi?rd=stta"); }
if ( ! -d "$config_directory/$module_name/dataconf" ) {  # If no config Lock 
             &redirect("/stta/stta_installupd.cgi?lck=lockstta"); }
if ( $config{'tta_dir'} eq "" || !(-d $config{'tta_dir'})) { 
             &redirect("/stta/config.cgi?$module_name"); }

if (  $parse_webmin_log ne true ) {   
      &scan_cgiacl();
      if ( $config{check_services} eq "true" ) {
               &load_ttaprops();
               &scanSTTA_services("all"); 
      } 
      # now code for housekeeping  logs,  copies etc following config params
      if ( -r $config{'list_debuglogs_name'} ne "" ) { &check_logtime("debuglogs"); }
      if ( -r $config{'list_sttalogs_name'} ne "" )  { &check_logtime("sttalogs"); }
      if ( -r $config{'list_backups_name'} ne "" )   { &check_logtime("backups"); }
}
$mhost=$sttaparams{'tta'}{'masthost'};
if ( $debug gt 0 ) {
              $DebugFile="/tmp/log";
              open(DebugLog, ">$DebugFile");
}
     
sub scan_cgiacl
{
    local $cgi_obj=$cginame;
    local $no_acl="index tta_selusr cache_selobj tta_filter stta_warn tta_works license";
    local $tta_acl="tta_backup tta_ensbk tta_archive tta_status tta_passwdcache updldapcache tta_ensdump tta_ensload tta_ensrestore tta_ensrecreate";
    $cgi_obj=~ s/.cgi//;  

    if ( $no_acl =~ /$cgi_obj/ ) {
          return true;  
    } elsif ( $tta_acl =~ /$cgi_obj/  && $access{'backup'} && $access{'global'} ) {
          return true;  
    } elsif ( $cgi_obj =~ /test/ && $debug gt 0  ) {
          if  ( $access{'admin'} && $access{'global'} ) { return true; } 
    } elsif ( $cgi_obj =~ /installupd/ && $debug gt 0  ) {
          if  ( $access{'admin'} && $access{'global'} ) { return true; } 
    } elsif ( $cgi_obj =~ /replica/ ) {
          if  ( $access{'replicate'} && $access{'global'} ) { return true; } 
    } elsif ( $cgi_obj =~ /start/ ||  $cgi_obj =~ /stta_proc/ )  {
          if  ( $access{'stop'} && $access{'global'} ) { return true; } 
    } elsif ( $cgi_obj eq "tta_alivehosts" || $cgi_obj eq "stta_view") {
          if ($access{'alivehosts'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj eq "sttaconfig" || $cgi_obj eq "tta_loadusrs" || $cgi_obj eq "tta_loadous" ) {
          if ($access{'admin'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /cache_/ || $cgi_obj =~ /obj/ || $cgi_obj =~ /profcache/ ) {
          if ($access{'passwd'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /log/ ) {
          if ($access{'supervision'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /dir/ ) {
          if ($access{'supervision'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /ldap_/ ) {
          if ($access{'admin'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /acl/ ) {
          if ($access{'monitor'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /act/ || $cgi_obj eq "mon_script" ) {
          if ($access{'monitor'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /file/ ) {
          if ($access{'supervision'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /sess/ ) {
          if ($access{'sessions'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /update/ || $cgi_obj =~ /fix/ ) {
          if ($access{'admin'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /feedback/  && $access{'feedback'} ) {
          if ($access{'admin'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /stta_webhelp/) {
          if ($access{'admin'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /stta_checksync/) {
          if ($access{'admin'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /stta_report/) {
          if ($access{'admin'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /stta_synclist/) {
          if ($access{'admin'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } elsif ( $cgi_obj =~ /sysusers/) {
          if ($access{'admin'} eq 1 && $access{'global'} eq 1 ) { return true; }; 
    } else {
         $cgi_obj=~s/tta_/_/;  
         $cgi_obj=~s/cache_/_/;  
         $cgi_obj=~s/_sel/_add/;  
         $cgi_obj=~s/_//;  
         $cgi_obj=~s/^mod/add/;  
         if ( $access{$cgi_obj} eq "1" ) { return true } 
    }
    &redirect("stta_warn.cgi?cgi=$cginame"); 
}

# list_user_file(file, &user,  &pass)
sub list_user_file
{
local($_);
open(USERS, $_[0]);
while(<USERS>) {
	/^(\S+):(\S+)/;
	push(@{$_[1]}, $1); $_[2]->{$1} = $2;
	}
close(USERS);
}

#scan_objdescrip($pos,$tta3tier->{objetype}, $dn_t, $tta3tier->{target});
# it tries to get target "objdescrip" from "object list files" depending on type 
#
sub scan_objdescrip 
{
    local ($pos) = $_[0];
    local ($objetype) = $_[1];
    local ($target) = $_[2];
    local ($origin) = $_[3];
    local ($objdescrip) = "";
    local (%lista,@dn_lin);

    $target=~s/,$config{ldapcache_base}//; 
    if ( $origin ne "default") { $target=~s/$origin,//;}
    if ($objetype eq "" ) { $objtype=$objType; }
    if ($objetype eq "ou" ) {
        %lista= &list_ous($pos);
    } elsif ($objetype eq "host" ) {
        if ( $pos eq 2 ) { $pos=3 };
        %lista= &list_hosts($pos);
    } elsif ($objetype eq "grphosts" ) {
        %lista= &list_grphosts($pos);
    } elsif ($objetype eq "app" ) {
        if ( $pos eq 2 ) { $pos=3 };
        %lista= &list_apps($pos);
    } elsif ($objetype eq "grpapps" ) {
        %lista= &list_grpapps($pos);
    } elsif ($objetype eq "domain" ) {
        %lista= &list_domains($pos);
    }
    if ( $lista{$target}->{'obj'} eq $target ) {
         $objdescrip=$lista{$target}->{descrip};
         if ( "$objdescrip" eq "" ) { $objdescrip = $lista{$target}->{name} };
    }
#    print "$objetype --$pos --$lista{$target}->{'obj'} eq $target <br>";
#   print "<p>$objetype ..($origin)  - $pos-- ($target) -- [$objdescrip]<br>";
    return $objdescrip;
}

#set_tta3tier(origin,target,dn,action,objtype)
# Set %tta3tier values from Input $in{} and return 
sub set_tta3tier
{
   local (@tta3tier);
   local ($passwd_coded);

   $tta3tier->{origin} = $_[0];
   $tta3tier->{target} = $_[1];
   $tta3tier->{oudn} = $_[2];
   $tta3tier->{action} = $_[3];
   $tta3tier->{objetype} = $_[4];
   $tta3tier->{login} = $in{tta3tier_login};
   &cipher_text ( "code", $in{tta3tier_password}, \$passwd_coded);
   $tta3tier->{password} = $passwd_coded;
   $tta3tier->{title} = $in{tta3tier_title};
   $tta3tier->{stringcmd} = $in{tta3tier_stringcmd};
   $tta3tier->{domain} = $in{tta3tier_domain};
   $tta3tier->{appkey1} = $in{tta3tier_appkey1};
   $tta3tier->{appkey2} = $in{tta3tier_appkey2};
   $tta3tier->{appkey3} = $in{tta3tier_appkey3};
   $tta3tier->{appkey4} = $in{tta3tier_appkey4};
   $tta3tier->{appkey5} = $in{tta3tier_appkey5};
   $tta3tier->{maxsess} = $in{tta3tier_maxsess};
   $tta3tier->{ticketstatus} = $in{tta3tier_ticketstatus};
   $tta3tier->{ticketcounter} = $in{tta3tier_ticketcounter};
   $tta3tier->{endticket} = $in{tta3tier_endticket};
 
   return @tta3tier;
}

sub scan_dn_cache {
   local (@linUserName, @UserPath);
   local ($UserName) = @_ ;
   local ($lnumUser) = 0;

         @linUserName = split(/,/, $UserName);
	 $OuName="";
	 foreach $obj (@linUserName) {
              @UserPath= split(/=/,$obj);
              $lnumUser++;
              if ( $UserPath[0] eq "cn"  &&  $lnumUser eq 1 ) {
		   $NameUser=$UserPath[1];
                        last;
              } else {
                   if ( "$OuName" ne "" ) { $OuName=$OuName.","; }
		         $OuName=$OuName.$UserPath[0]."=".$UserPath[1];
	      }
          }
}

sub load_tta3tier_vars
{
   # This will fill variables with values from hash LDAP entry with DN eq $dn_cache
   # later with should use the hash and avoid more variables in memory 
   # but the point is to preserver original values content somewhere 
   # and to the changes for the presentation and data input. by example password uncipher
   my ($dnCache) = @_ ;
   local $status_con=0;

   # loading variables
   my $cur_entry=&sel_cache_obj($dnCache,"cn=*");
   if ( !defined($cur_entry)  ||  $cur_entry->dn ne $dnCache) {
          $str_cmds=$str_cmds."<tr><td> ".$text{'ldapcache_norecord'}."</td>";
          $status_con=1;
   } else {
          %entryObj=&get_cache_obj($dnCache,$cur_entry);
          $tta3tier_domain = $entryObj{tta3tierdomain};
          $tta3tier_login = $entryObj{tta3tierlogin};
          &cipher_text ( "decode",$entryObj{tta3tierpassword}, \$tta3tier_password);
          # $tta3tier_password = $entryObj{tta3tierpassword};
          $tta3tier_stringcmd = $entryObj{tta3tierstringcmd};
          $tta3tier_title = $entryObj{tta3tiertitle};
          $tta3tier_oudn = $entryObj{tta3tieroudn};
          $tta3tier_appkey1 = $entryObj{tta3tierappkey1};
          $tta3tier_appkey2 = $entryObj{tta3tierappkey2};
          $tta3tier_appkey3 = $entryObj{tta3tierappkey3};
          $tta3tier_appkey4 = $entryObj{tta3tierappkey4};
          $tta3tier_appkey5 = $entryObj{tta3tierappkey5};
          $tta3tier_appkey6 = $entryObj{tta3tierappkey6};
          $tta3tier_maxsess = $entryObj{tta3tiermaxsess};
          $tta3tier_ticketstatus = $entryObj{tta3tierticketstatus};
          $tta3tier_ticketcounter = $entryObj{tta3tierticketcounter};
          $tta3tier_endticket = $entryObj{tta3tierendticket};
          $tta3tier_doifendticket = $entryObj{tta3tierdoifendticket};
   }
   return $status_con
}

# As webmin_log mode check values for $_[0] and clean what is defined in files 
sub check_logtime
{
      local %listaf=();
      if ( $_[0] eq "" ) { return };   
      local $fname="list_".$_[0]."_name";
      local $ftime="list_".$_[0]."_delhours";
    
      if ( $ftime eq "" || $ftime le 0 ) { return };
      if ( $var_directory eq "" || ! -d $var_directory ) { return };
      $stta_logfiletime="$var_directory/stta_".$_[0]."_log.time";
      # check if it is time to clear logs
      local @st = stat("$stta_logfiletime");
      local $write_logtime = 0;
      if (@st) {
		if ($st[9]+$config{$ftime}*60*60 < time()) {
		    # clear log or dir file 
                    &read_file($config{$fname}, \%listaf);
                    foreach $f (keys (%listaf)) {
                       next if ( $f =~ /^#/ );
                       if ( -r $f ) { 
                                  system("echo >$f ") 
                       } else { 
                                  system("find $listaf{$f} ! -newer $stta_logfiletime -print | xargs rm -f 2>/dev/null");
                       }
                       &webmin_log($_[0], "$f", "clean $listaf{$f}");
                    }
	   	    $write_logtime = 1;
		}
      } else { $write_logtime = 1; }
      if ($write_logtime) {
		open(LOGTIME, ">$stta_logfiletime");
		print LOGTIME time(),"\n";
		close(LOGTIME);
      }
}

# Setup error handler for remote hosts commands
sub stta_sync_error
{
   $remote_err_msg=join("", @_);
}

sub remote_file_do
{
    local @sttahosts = split(/ /,$config{stta_hosts},-1);
    local %servers = &list_servers();
    locat $destf = $_[2] || $_[1];

    $remote_err_msg="";
    &remote_error_setup(\&stta_sync_error);
print "HOLA 
    foreach $h (@sttahosts) {
        local $shost=$servers{$h}{'host'};
        next if ( !$shost || $shost eq "" );
        &remote_foreign_require($shost, "stta", "sttaremote-lib.pl");
        if ($remote_err_msg) { 
               &webmin_log("$shost $_[1] sync", "remote_write", "$remote_err_msg");
               &html_errshow("sync",$remote_err_msg);
               return -1;
        }
        if ( $_[0] eq "read" ) {
    	         &remote_read($shost,$_[1],$destf);
                 if ($remote_err_msg) { 
                    &webmin_log("$shost $destf sync", "remote_read",
                                "$remote_err_msg");
                    &html_errshow("sync",$remote_err_msg);
                    return -1;
                 }
                 &webmin_log("$shost $_[1] sync", "remote_read", "$destf");
        }
        if ( $_[0] eq "write" ) {
                 $rfile = &remote_write($shost, $_[1],$destf);
                 if ($remote_err_msg) { 
                    &webmin_log("$shost $destf sync", "remote_write",
                                "$remote_err_msg");
                    &html_errshow("sync",$remote_err_msg);
                    return -1;
                 }
                 &webmin_log("$shost $_[1] sync", "remote_write","$destf");
                 if ( $debug gt 1 ) { print "<tr><td>$text{remote_sync} $shost"; }
        }
        &remote_finished();
    }
    if ( $debug gt 1 ) { print "</td></tr>"; }
    return;
}

sub remote_file
{
    return if ( $config{'stta_sync'} ne "true" );
    return if ( $config{'stta_hosts'} eq "" );
print "$config{list_to_sync} =~  $_[2]  <br>";
    if ( $config{list_to_sync} =~  /$_[2]/ ) {
         local @sttahosts = split(/ /,$config{stta_hosts},-1);
         local %servers = &list_servers();
    } else {
      return;       # request not in list_to_sync
    }
    
    $remote_err_msg="";
    &remote_error_setup(\&stta_sync_error);
    foreach $h (@sttahosts) {
print "$shost .... <br>";
        local $shost=$servers{$h}{'host'};
        next if ( !$shost || $shost eq "" );
        &remote_foreign_require($shost, "stta", "sttaremote-lib.pl");
        if ($remote_err_msg) { 
               &webmin_log("$shost $_[2] sync", "remote_write", "$remote_err_msg");
               &html_errshow("sync",$remote_err_msg);
               return -1;
        }
        local %remote_config=&remote_foreign_call($shost,"stta", "get_dataconfig");
        if ( $remote_config{$_[2]} && $remote_config{$_[2]} ne "" ) {
             if ( $_[0] eq "read" ) {
    	         &remote_read($shost, $_[1],$remote_config{$_[2]});
                 if ($remote_err_msg) { 
                    &webmin_log("$shost $_[2] sync", "remote_read",
                                "$remote_err_msg");
                    &html_errshow("sync",$remote_err_msg);
                    return -1;
                 }
                 &webmin_log("$shost $_[2] sync", "remote_read",
                             "$remote_config{$_[2]}");
             }
             if ( $_[0] eq "write" ) {
                 $rfile = &remote_write($shost, $_[1],$remote_config{$_[2]});
                 if ($remote_err_msg) { 
                    &webmin_log("$shost $_[2] sync", "remote_write",
                                "$remote_err_msg");
                    &html_errshow("sync",$remote_err_msg);
                    return -1;
                 }
                 &webmin_log("$shost $_[2] sync", "remote_write",
                             "$remote_config{$_[2]}");
                 if ( $debug gt 1 ) { print "<tr><td>$text{remote_sync} $shost"; }
             }
        }
        &remote_finished();
    }
    if ( $debug gt 1 ) { print "</td></tr>"; }
    return;
}

# make_remote_user $_[0] "add | modify | delete", $_[1]  username 
sub make_remote_user
{
    return if ( $config{'has_systemusers'} ne "true" );
    return if ( $config{'stta_hosts'} eq "" );
    local @sttahosts = split(/ /,$config{stta_hosts},-1);
    local %servers = &list_servers();
    &foreign_require("useradmin", "user-lib.pl");
    local @listUsers=&foreign_call("useradmin", "list_users");
    local %h_listUsers=();
    foreach $item (@listUsers) { $h_listUsers{$item->{user}} = $item  }
    
    $remote_err_msg="";
    &remote_error_setup(\&stta_sync_error);
    foreach $h (@sttahosts) {
        local $shost=$servers{$h}{'host'};
        next if ( !$shost || $shost eq "" );
        &remote_foreign_require($shost, "useradmin", "user-lib.pl");
        if ($remote_err_msg) { 
               &webmin_log("$shost $_[1] sync", "remote_sync $_[0]", "$remote_err_msg");
               &html_errshow("usersync",$remote_err_msg);
               return -1;
        }
        local @ulist=&remote_foreign_call($shost,"useradmin", "list_users");
        local %h_ulist=();
        foreach $item (@ulist) { $h_ulist{$item->{user}} = $item  }
#        print "<tr><td> $h_ulist{$u}{user} -- $u -- $item->{user} </td></tr>";


        if ( $_[0] eq "add" ) {
                 &remote_foreign_call($shost,"useradmin", "create_user",$h_listUsers{$_[1]});
                 if ($remote_err_msg) { 
                    &webmin_log("$shost $_[1] sync", "remote_user_add",
                                "$remote_err_msg");
                    &html_errshow("sync",$remote_err_msg);
                    return -1;
                 }
                 &webmin_log("$shost $_[1] sync", "remote_user_add",
                             "$h_listUsers{$_[1]}");
                 if ( $debug gt 1 ) { print "<tr><td>$text{remote_sync} $shost ($_[1]) $_[0]"; }
        } elsif ( $_[0] eq "modify" ) {
                 if ( defined $h_ulist{$_[1]} && $h_ulist{$_[1]}{user} eq $_[1] ) {
                    &remote_foreign_call($shost,"useradmin", "modify_user",$h_ulist{$_[1]},$h_listUsers{$_[1]});
                 } else {
                    &remote_foreign_call($shost,"useradmin", "create_user",$h_listUsers{$_[1]});
                 }
                 if ($remote_err_msg) { 
                    &webmin_log("$shost $_[1] sync", "remote_user_mod",
                                "$remote_err_msg");
                    &html_errshow("sync",$remote_err_msg);
                    return -1;
                 }
                 &webmin_log("$shost $_[1] sync", "remote_user_mod",
                             "$h_ulis{$_[1]}");
                 if ( $debug gt 1 ) { print "<tr><td>$text{remote_sync} $shost ($_[1]) $_[0]"; }
        } elsif ( $_[0] eq "delete" ) {
                 if ( defined $h_ulist{$_[1]} && $h_ulist{$_[1]}{user} eq $_[1] ) {
                    &remote_foreign_call($shost,"useradmin", "delete_user",$h_ulist{$_[1]});
                 } else {
                    return ;
                 }
                 if ($remote_err_msg) { 
                    &webmin_log("$shost $_[1] sync", "remote_user_del",
                                "$remote_err_msg");
                    &html_errshow("sync",$remote_err_msg);
                    return -1;
                 }
                 &webmin_log("$shost $_[1] sync", "remote_user_del",
                             "$h_ulist{$_[1]}");
                 if ( $debug gt 1 ) { print "<tr><td>$text{remote_sync} $shost ($_[1]) $_[0]"; }
        }
        &remote_finished();
    }
    if ( $debug gt 1 ) { print "</td></tr>"; }
    return;
}

sub get_num_user 
{
    local $num=0;

    &foreign_require("useradmin", "user-lib.pl");
    @listUsers=&foreign_call("useradmin", "list_users");
    foreach $item (@listUsers) {
         if ( $item->{user} eq $_[0] ) {
              $num=$item->{num};
              last;
         }
    }
    return $num;
}
1;  # Return true
