CHips L MINI SHELL

CHips L pro

Current Path : /proc/2/root/usr/local/rvglobalsoft/rvglobalsoft/auto/RVSInstaller/
Upload File :
Current File : //proc/2/root/usr/local/rvglobalsoft/rvglobalsoft/auto/RVSInstaller/Process.pm

#!/usr/bin/perl
##LICENSE##

package RVSInstaller::Process;

use strict;
use warnings;
use Carp;
use File::Basename;
use Cwd qw(realpath);
use Getopt::Long;

use File::Copy;
use Socket;
use IO::Socket;
use Digest::MD5 qw(md5_hex);
use MIME::Base64;

BEGIN {
    push(@INC, dirname(dirname(__FILE__)));
}

use vars qw( $VERSION @ISA @EXPORT_OK $NEWLINE $MAINIP);

if ( $ENV{'HTTP_USER_AGENT'} ) {
    $NEWLINE = "<br />\n";
}
else {
    $NEWLINE = "\n";
}

use Exporter;
use Digest::MD5 qw(md5_hex);
use MIME::Base64;

@ISA = qw( Exporter );

@EXPORT_OK = qw(
    ParseForm DisplayENV SerializerData UnSerializerData URLEncode getMainIP getAllIP getPerlPath 
    unlinkAll copyAll chmodAll chownAll rvsMD5File whmConnection ParseOpt
);

$VERSION = "0.01";

sub init{
    return 1;
}

sub ParseForm{
   my ($fh) = @_;
   my(@pairs, $name, $value, $pair, %FORM, $buffer, $item, $bound, $header, $filename, $rndfile, $random1, $random2);
   if ( defined($ENV{'CONTENT_LENGTH'}) && $ENV{'CONTENT_LENGTH'} > 1 ) {
      if ( defined($fh) ) {
         read($fh, $buffer, $ENV{'CONTENT_LENGTH'});
      } else {
         read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
      }
      if ( $buffer =~/^(.+)\r\n/ ) {
         $bound = $1;
         @pairs = split(/$bound/, $buffer);
         undef $buffer; 
         foreach $item (@pairs) {
            ($header, $value) = split(/\n\r/, $item, 2);
            if ( $header =~/^file-/ ) { 
                next; 
            } 
            $value =~s/^\n//g;
            $value =~s/\n$//g;
            if ( $header =~/filename=\"(.+)\"/ ) {
               $filename = $1;
               $filename =~s/\".*$//g;
               $rndfile = '';
               alarm(50);
               while ( length($rndfile) < 10 ) {
                  open(RANDOM, "/dev/urandom");
                  read RANDOM, $rndfile, 128;
                  close(RANDOM);
                  $rndfile =~ s/\W//g;
               }
               alarm(0);
               if ( ! -e "/tmp/cpanel3upload.$rndfile" ) {
                  open(TMP,">","/tmp/cpanel3upload.$rndfile"); 
                  $value =~ s/\r$//g;
                  print TMP "$value";
                  undef $value;
                  close(TMP);
                  $FORM{"file-$filename"} = "/tmp/cpanel3upload.$rndfile";
               }
            }
            if ($header =~ /name=\"(.+)\"/) {
               $name = $1;
               $name =~ s/\".*$//g;

               if ($FORM{$name} eq "") {
                  $FORM{$name} = $value;
               } else {
                  my $i = 0;
                  while(! $FORM{"$name-${i}"} eq "") {
                     $i++;
                  }
                  $FORM{"$name-${i}"} = $value;
               }
            }
         }
         undef $value;
         return(%FORM);
      }
      @pairs = split(/&/, $buffer);
   } else {
      @pairs = split(/&/, $ENV{'QUERY_STRING'});
   }
   foreach $pair (@pairs) {
      ($name,$value) = split(/=/, $pair, 2);
      if ($name =~ /^file-/) { 
          next; 
      } 
      $value =~ tr/+/ /;
      $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

      if (!defined($FORM{$name}) || $FORM{$name} eq "") {
         $FORM{$name} = $value;
      } 
      else {
         my $i = 0;
         while(! $FORM{"$name-${i}"} eq "") {
            $i++;
         }
         $FORM{"$name-${i}"} = $value;
      }
   }
   return %FORM;
}

sub DisplayENV{
    foreach ( keys %ENV) {
        print '$ENV{' . $_ . '} = ' . $ENV{$_} . $NEWLINE;
    }
}

sub URLEncode{
    my $theURL = $_[0];
    $theURL =~ s/([\W])/"%" . uc(sprintf("%2.2x",ord($1)))/eg;
    return $theURL;
}

sub SerializerData{
	eval {
	    return MIME::Base64::encode(RVSInstaller::Serialize::serialize($_[0]));
	};
}

sub UnSerializerData{
	eval {
    	return %{RVSInstaller::Serialize::unserialize(MIME::Base64::decode($_[0]))};
	};
}

sub getMainIP{
    if ( $MAINIP) {
        return $MAINIP;
    }
    else {
        my $cmd_uname = rvsWhich('uname');
        my ($system) = `$cmd_uname -s`;
        $system =~s/\n|\r//gi;
        my (@ethdev, $ips, @ListIPS);
        if ( -e '/etc/wwwacct.conf') {
            open(R,'/etc/wwwacct.conf');
            while (<R>) {
                #print "--wwwacct ".$_."\n";
                if ( $_ !~/^;/i && /ETHDEV/) {
                    @ethdev = split(' ', $_);
                    #print "--ip: ".$_."\n";
                }
            }
        }

        if ( $system =~/freebsd/i || !defined($ethdev['1'])) {
            $ips = `/sbin/ifconfig -a`;
        } 
        else {
            $ips = `/sbin/ifconfig $ethdev[1]`;
        }
        @ListIPS = split(/\n/,$ips);
        foreach (@ListIPS) {
            if ( /(\d*)\.(\d*)\.(\d*).(\d*)/) {
                if ( $1 ne '127' ) {
                    $MAINIP = $1 . '.' . $2 . '.' . $3 . '.' . $4;
                    return $1 . '.' . $2 . '.' . $3 . '.' . $4;
                }
            }
        }
        # <-- No Reached -->
        my $cmd_hostname = rvsWhich('hostname');
        my ($hostname) = `$cmd_hostname`;
        $hostname =~s/\n//gi;
        my ($hostIP) = gethostbyname($hostname);
        $MAINIP = $hostIP;
        return $hostIP;
    }
}

sub getAllIP{
    my $cmd_uname = rvsWhich('uname');
    my ($system) = `$cmd_uname -s`;
    my ( @allIPList);
    $system =~s/\n|\r//gi;
    my (@ethdev, $ips, @ListIPS);
    if ( -e '/etc/wwwacct.conf') {
        open(R,'/etc/wwwacct.conf');
        while (<R>) {
            if ( $_ !~/^;/i && /ETHDEV/) {
                @ethdev = split(' ', $_);
            }       
        }
    }

    if ( $system =~/freebsd/i || $ethdev['1'] eq '') {
        $ips = `/sbin/ifconfig -a`;
    } 
    else {
        $ips = `/sbin/ifconfig $ethdev[1]`;
    }
    @ListIPS = split('\n', $ips);
    foreach (@ListIPS) {
        if ( /(\d*)\.(\d*)\.(\d*).(\d*)/) {
            if ( $1 ne '127' ) {
                push(@allIPList, $1 . '.' . $2 . '.' . $3 . '.' . $4);
            }
        }
    }
# <-- No Reached -->
    if (@ListIPS <= 0 ) {
        my $cmd_hostname = rvsWhich('hostname');
        my ($hostname) = `$cmd_hostname`;
        $hostname =~s/\n//gi;
        my ($hostIP) = gethostbyname($hostname);
        push(@allIPList, $hostIP);
    }
    return @allIPList;
}

sub getAllIPnew{
    my $cmd_uname = rvsWhich('uname');
    my $system = callBackticks("$cmd_uname -s");
    my @allIPList = ();
    $system =~s/\n|\r//gi;
    my $ips = '';
    my @ListIPS = ();
    if ( $system =~/freebsd/i) {
        $ips = callBackticks('/sbin/ifconfig -a');
    } else {
        $ips = callBackticks("/sbin/ifconfig");
    }
    @ListIPS = split('\n', $ips);
    foreach (@ListIPS) {
        if ( /(\d*)\.(\d*)\.(\d*).(\d*)/) {
            if ( $1 ne '127' ) {
                push(@allIPList, $1 . '.' . $2 . '.' . $3 . '.' . $4);
            }
        }
    }
    return @allIPList;
}

sub getPerlPath{
    my ($perlpath);
    
    if ( -e '/usr/bin/perl') {
       $perlpath = '/usr/bin/perl';
    }
    elsif ( -e '/usr/local/bin/perl') {
        $perlpath = '/usr/local/bin/perl';
    }
    else {
        $perlpath = `which perl`;
        chomp ($perlpath);
        $perlpath =~s/\n|\r//gi;
    }
    return $perlpath;
}

sub getAllIPReal{
    my @allIPList = ();
    my (@ethdev, $ips, @ListIPS);

    $ips = `/sbin/ifconfig -a`;

    @ListIPS = split('\n', $ips);
    foreach (@ListIPS) {
        if ( /(\d*)\.(\d*)\.(\d*).(\d*)/) {
            if ( $1 ne '127' ) {
                push(@allIPList, $1 . '.' . $2 . '.' . $3 . '.' . $4);
            }
        }
    }
# <-- No Reached -->
    if (@ListIPS <= 0 ) {
        my $cmd_hostname = rvsWhich('hostname');
        my ($hostname) = `$cmd_hostname`;
        $hostname =~s/\n//gi;
        my ($hostIP) = gethostbyname($hostname);
        push(@allIPList, $hostIP);
    }
    return @allIPList;
}

sub unlinkAll{
    my ($dest) = @_;
    my $cmd_rm = rvsWhich('rm');
    system ($cmd_rm . ' -rf ' . $dest) if ($dest);
    return 1;
    if ( -f $dest ) {
        unlink($dest);
    } 
    elsif ( -d $dest ) {
        opendir(DIR, $dest); 
        my (@dirs) =    readdir(DIR); 
        closedir(DIR);
        my ($file);
        foreach $file ( @dirs ) {
            if ( $file eq '.' || $file eq '..' ) {
                next;
            } 
            elsif ( -d $dest . '/' . $file ) {
                RVSInstaller::Process::unlinkAll($dest . '/' . $file);
                rmdir($dest . '/' . $file);
            }
            elsif ( -e $dest . '/' . $file ) {
                RVSInstaller::Process::unlinkAll($dest . '/' . $file);
            }
            else {
                unlink($dest . '/' . $file);
            } 
        }
        rmdir($dest);
    }
    return 1;
}

sub copyAll{
    my ($dest, $target) = @_;
    if ( -f $dest ) {
        copy($dest, $target);
    } 
    elsif ( -d $dest ) {
        opendir(DIR, $dest); 
        my (@dirs) =    readdir(DIR);
        closedir(DIR);
        my ($file);

       foreach $file ( @dirs ) {
            if ( $file eq '.' || $file eq '..' ) {
                next;
            }
            elsif ( -f $dest . '/' . $file ) {
                RVSInstaller::Process::copyAll($dest . '/' . $file, $target . '/' . $file);
            }
            elsif ( -d $dest . '/' . $file ) {
                mkdir($target . '/' . $file);
                RVSInstaller::Process::copyAll($dest . '/' . $file, $target . '/' . $file);
            }
            else {
                symlink($dest . '/' . $file, $target . '/' . $file);
            } 
        }
    }
}

sub chmodAll{
    my ($dest, $mode) = @_;
    if ( -f $dest ) {
        chmod($mode, $dest);
    } 
    elsif ( -d $dest ) {
        opendir(DIR, $dest); 
        my (@dirs) =    readdir(DIR);
        closedir(DIR);
        my ($file);

       foreach $file ( @dirs ) {
            if ( $file eq '.' || $file eq '..' ) {
                next;
            }
            elsif ( -l $dest . '/' . $file ) {
                next;
            }   
            elsif ( -f $dest . '/' . $file ) {
                chmod($mode, $dest . '/' . $file);
                #RVSInstaller::Process::chmodAll($dest . '/' . $file, $mode);
            }
            elsif ( -d $dest . '/' . $file ) {
                RVSInstaller::Process::chmodAll($dest . '/' . $file, $mode);
                chmod($mode, $dest . '/' . $file);
            }
            else {
                next;
            } 
        }
        chmod($mode, $dest);
    }
}

sub chownAll{
    my ($dest, $uid, $gid) = @_;
    if ( -f $dest ) {
        chown $uid, $gid, $dest;
    } 
    elsif ( -d $dest ) {
        opendir(DIR, $dest); 
        my (@dirs) =    readdir(DIR);
        closedir(DIR);
        my ($file);

       foreach $file ( @dirs ) {
            if ( $file eq '.' || $file eq '..' ) {
                chown $uid, $gid, $dest . '/' . $file;
                next;
            }
            elsif ( -l $dest . '/' . $file ) {
                chown $uid, $gid, $dest . '/' . $file;
                next;
            } 
            elsif ( -f $dest . '/' . $file ) {
                chown $uid, $gid, $dest . '/' . $file;
                #RVSInstaller::Process::chownAll($dest . '/' . $file, $uid, $gid);
            }
            elsif ( -d $dest . '/' . $file ) {
                RVSInstaller::Process::chownAll($dest . '/' . $file, $uid, $gid);
                chown $uid, $gid, $dest . '/' . $file;
            }
            else {
                next;
            } 
        }
        chown $uid, $gid, $dest;
    }
}

sub getParentDir {
    my $dir = $_[0];
    my @splitPath = split('/', $dir);
    pop(@splitPath);
    my $parentPath = join('/', @splitPath);
    if (scalar(@splitPath) < 2) {
        $parentPath = '/'.$parentPath;
    }
    return $parentPath;
}

sub mkdirp {
    my $pathName = $_[0];
    my $permission = (defined $_[1]) ? oct($_[1]) : oct("0755");
    my @checkPath = split("/", $pathName);
    my $pathNow;
    my $ismkdir = 1;
    mkdir($pathName);
    for (my $countCheckPath=1;$countCheckPath < @checkPath; $countCheckPath++){
        $pathNow .= "/" . $checkPath[$countCheckPath];
        if (!-d $pathNow) {
            if (-w getParentDir($pathNow)) {
                mkdir($pathNow);
                chmod $permission, $pathNow;
            } else {
                $ismkdir = 0;
            }
        }
    }
    return $ismkdir;
}

sub rvsMD5File{
    my $file = $_[0];
    my $fmd5 = "";

    if (-f $file) {
        my $cmd_uname = rvsWhich('uname');
        my ($system) = callBackticks("uname -s");
        my $result = '';
        $system =~s/\n|\r//gi;
        if ( $system =~/freebsd/i ) {
            my $md5bin = rvsWhich('md5');
            $result =callBackticks("$md5bin $file");
            $result =~s/\n|\r//gi;
            my(@aResult)=split('=',$result);
            $aResult[1] =~s/\s*//gi;
            $fmd5 = $aResult[1];
        } else {
            my $md5sumbin =rvsWhich('md5sum');
            $result =callBackticks("$md5sumbin $file");
            $result =~s/\n|\r//gi;
            $result =~/(.*?) /i;
            $fmd5 = $1;
        }
    } else {
        print STDERR "md5: error opening source $file\n";
        return "";
    }
    
    return $fmd5;
}

sub rvsWhich {
    my ($cmd) = $_[0];
    return if ($cmd eq '');
    return if ($cmd =~/\//);
    my @binpathList = (
        '/bin',
        '/usr/bin',
        '/usr/local/bin',
        '/sbin',
        '/usr/sbin',
        '/usr/local/sbin'
    );
    my $whichCmd = '';
    foreach my $path(@binpathList) {
        if ( -x $path . '/' . 'which') {
            $whichCmd = $path . '/' . 'which';
            last;
        }  
    }
    if ($whichCmd eq '') {
        print STDERR "which command is not support.\n";
        return '';
    } 
    my $binpath = '';
    foreach my $path(@binpathList) {
        if ( -x $path . '/' . $cmd) {
            $binpath = $path . '/' . $cmd;
            last;
        }  
    }
    if ($binpath eq '') {
        $binpath = `$whichCmd $cmd`;
        chomp ($binpath);
        $binpath =~s/\n|\r//gi;
    }
    if ($binpath eq '') {
        print STDERR "$cmd command is not support.\n";
        return '';
    }
    return $binpath;
}

sub callBackticks{
    my $cmd = join(' ', @_);

    if (-f '/tmp/.rvsBackticks') {
        system('rm -f /tmp/.rvsBackticks');
    }

    my ($TestBackticks) = `echo 'RV Test Backticks'`;
    my ($skipBackticks) = 0;
    if ($TestBackticks !~/RV Test Backticks/) {
        $skipBackticks = 1;
    }
    if (-f '/tmp/.rvsBackticks' || $skipBackticks eq 1) {
        system("$cmd > /tmp/.rvsBackticks 2>&1");
    }
    my ($resuft);
    if (-f '/tmp/.rvsBackticks') {
        if (open(my $fd, '<', '/tmp/.rvsBackticks')) {
            $resuft = join('',<$fd>);
            close($fd);
        }
        system('rm -f /tmp/.rvsBackticks');
    } else {
        $resuft = `$cmd 2>&1`;
    }
 
    return $resuft;
}

sub getmycnfdata {
    my $file = '';
    
    my $suser = '';
    my $spass = '';
    my $shost = '';
    my $iport = '';
    
    my $cpanel = '/root/.my.cnf';
    my $plesk = '/etc/psa/.psa.shadow';
    my $directadmin = '/usr/local/directadmin/conf/mysql.conf';
    my $unknown = '/etc/dbconfig-common/phpmyadmin.conf';
    
    if (-e "/usr/local/cpanel/cpkeyclt") {
        #cPanel
        $file = $cpanel;
    } elsif (-e "/etc/psa/psa.key") {
        #Plesk
        $file = $plesk;
    } elsif (-e '/usr/local/directadmin/conf/license.key') {
        #DirectAdmin
        $file = $directadmin;
    } elsif (-e '/etc/dbconfig-common/phpmyadmin.conf') {
        #unknown
        $file = $unknown;
    }
    
    if ($file ne '') {
        if (open(my $rh, '<', $file)) {
            while(<$rh>) {
                if ($file eq $cpanel) {
                    #cPanel
                    if (/^user=(\S+)/) {
                        $suser = $1;
                        $suser =~ s/^\"|\"$//g;
                    } elsif (/^pass=(\S+)/) {
                        $spass = $1;
                        $spass =~ s/^\"|\"$//g;
                    } elsif (/^host=(\S+)/) {
                        $shost = $1;
                        $shost =~ s/^\"|\"$//g;
                    } elsif (/^port=(\S+)/) {
                        $iport = $1;
                        $iport =~ s/^\"|\"$//g;
                    }elsif(/^password=(\S+)/){
                    	$spass = $1;
                        $spass =~ s/^\"|\"$//g;
                        $spass =~ s/^\'|\'$//g;
                    }
                } elsif ($file eq $plesk) {
                    #Plesk
                    $suser = 'admin';
                    $shost = 'localhost';
                    $iport = 3306;
                    $spass = trim($_);
                    last;
                } elsif ($file eq $directadmin) {
                    #DirectAdmin
                    $suser = 'da_admin';
                    $shost = 'localhost';
                    $iport = 3306;
                    if (/^user=(\S+)/) {
                        $suser = $1;
                        $suser =~ s/^\"|\"$//g;
                        $suser =~ s/^\'|\'$//g;
                    } elsif (/^passwd=(\S+)/) {
                        $spass = $1;
                        $spass =~ s/^\"|\"$//g;
                        $spass =~ s/^\'|\'$//g;
                    } elsif (/^host=(\S+)/) {
                        $shost = $1;
                        $shost =~ s/^\"|\"$//g;
                        $shost =~ s/^\'|\'$//g;
                    } elsif (/^port=(\S+)/) {
                        $iport = $1;
                        $iport =~ s/^\"|\"$//g;
                        $iport =~ s/^\'|\'$//g;
                    }
                    
                } elsif ($file eq $unknown) {
                    #unknow
                    if (/^\dbc_dbuser=(\S+)/) {
                        $suser = $1;
                        $suser =~ s/^\'|\';$//g;
                    } elsif (/^\dbc_dbpass=(\S+)/) {
                        $spass = $1;
                        $spass =~ s/^\'|\';$//g;
                    } elsif (/^\dbc_dbserver=(\S+)/) {
                        $shost = $1;
                        $shost =~ s/^\'|\';$//g;
                    } elsif (/^\dbc_dbport=(\S+)/) {
                        $iport = $1;
                        $iport =~ s/^\'|\';$//g;
                    }
                }
            }
            close($rh);
        }
    }
    
    return ($suser, $spass, $shost, $iport);
}

sub genPasswd {
    my ($max) = shift;
    if (!defined($max)) {
        $max = 16
    } elsif (int $max <= 0) {
        $max = 16
    }
    my (@aChar) = ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9');
    my ($passwd) = '';
    my ($num) = scalar(@aChar) -1;
    for (my $loop =0; $loop < $max; $loop++) {
        my ($randnum) = rand($num);
        my ($text) = $aChar[$randnum];
        $passwd .= $text;
    }
    return $passwd;
}

sub whmConnection{
    my ($aKey, $request) = @_;
    my $authstr = "root:$aKey";
    my $proto = getprotobyname('tcp');
    my (@PAGE);
    socket(WHM, AF_INET, SOCK_STREAM, $proto) || print "socket error: $!\n";
    #my $iaddr = gethostbyname("localhost") || print "Unable to resolve localhost\n";
    my $iaddr =  pack("C4",127,0,0,1);
    my $port = 2086;
    my $sin = sockaddr_in($port, $iaddr);
    connect("WHM", $sin) || print "Unable to connect to WHM\n";
    send WHM, "GET $request HTTP/1.0\n", 0;
    send WHM, "Connection: close\n", 0;
    send WHM, "Authorization: WHM $authstr\n\n", 0;
    my $inheaders = 1;
    while(<WHM>) {
        push(@PAGE, $_) 
    }
    close(WHM);
    return @PAGE;
}

sub ParseOpt{
    my (%opts);
    GetOptions(
        'force' =>\$opts{'force'},
        'system' =>\$opts{'system'},
        'rollback=s' => \$opts{'rollback'},
        'getversion=s' => \$opts{'getversion'},
        'debug=s' => \$opts{'debug'},
        'help' => \$opts{'help'},
    );
    return %opts;
}

sub getRvCode {
    my $progName = shift;
    my $cpname = shift;
    #   primary-ip
    #   program
    #   all-ip
    
    my %rvcode = ();
    
    my $allIp = join(',', RVSInstaller::Process::getAllIP());
    $rvcode{'timestamp'} = time();
    $rvcode{'primary-ip'} = RVSInstaller::Process::getMainIP();
    $rvcode{'program'} = $progName;
    $rvcode{'all-ip'} = $allIp;
    $rvcode{'cp'} = lc($cpname);
    $rvcode{'vps'} = RVSInstaller::Process::isVps();
    $rvcode{'license-code'} = RVSInstaller::Process::getAdapterData();
    $rvcode{'rand'} = int(rand(9000)) + 1000; #range: 1000-9999
    
    #serialize data
    return RVSInstaller::Process::URLEncode(RVSInstaller::Process::SerializerData(\%rvcode));
}

sub isVps {
    return '' unless $^O;
    use RVSInstaller::Virtualization;

    my $detector = eval { RVSInstaller::Virtualization->new({verbose => 0}) };
    return '' if( $@ );
    
    my @found = $detector->detect();
    if( @found ) {
        return 1;
    } else {
        return 0;
    }
}

sub getAdapterData {
    #ioncube
    my $page = '';
    my $path = dirname(dirname(realpath(__FILE__)));
    my $inifile = $path.'/include/scripts/php.ini';
    my $phpfile = $path.'/include/scripts/ioncube.php';
    if (-z $inifile && -z $phpfile) {
        my $cmdIoncube = "php -c $inifile $phpfile 2>/dev/null";
        $page = RVSInstaller::Process::callBackticks($cmdIoncube);
    }
    return $page;
}

sub getHomePath{
	my $userLogin = getUserLogin();
	my $homePath = '';
	my $drive = (getpwnam($userLogin))[7];
	if($userLogin eq 'root'){
		$homePath = '/var/cpanel/rvglobalsoft';
		if(!-d $homePath){
			mkdirp($homePath,'0755');
		}
		if(!-d $homePath . '/.rvglobalsoft'){
			mkdirp($homePath . '/.rvglobalsoft' ,'0755');
		}else{
			system('chmod' , '755' , $homePath . '/.rvglobalsoft');
		}
		
	}else{
		$homePath =  $drive ;
	}
	
	return $homePath;
}

sub getUserLogin {
	if (defined $ENV{REMOTE_USER}) {
    	return $ENV{REMOTE_USER};	
	} elsif (defined $ENV{USERNAME}) {
		return $ENV{USERNAME}
	} else {
		my $username = callBackticks('whoami');
		chomp($username);
		return $username;
	}
}

sub getThemeList{
	my(@dirs, @themes);
	opendir my $DIR, '/usr/local/cpanel/base/frontend';
	@dirs = grep {!(/^\./) && -d '/usr/local/cpanel/base/frontend/'.$_} readdir($DIR);
	closedir $DIR;

	foreach my $listdir (@dirs) {
		#ignore some skin
		next if ($listdir eq 'y' || $listdir eq 'NO'  || $listdir eq 'YES'  || $listdir eq 'tree'  || $listdir eq 'x2' || $listdir eq 'xmail' ||
		$listdir eq 'rvblue' || $listdir eq 'rvgreen' || $listdir eq 'rvlightblue' || $listdir eq 'rvlightgreen' || $listdir eq 'rvlightmaroon' || 
		$listdir eq 'rvlightolive' || $listdir eq 'rvlightorange' || $listdir eq 'rvlightteal' || $listdir eq 'rvlightviolet' || 
		$listdir eq 'rvmaroon' || $listdir eq 'rvolive' || $listdir eq 'rvorange' || $listdir eq 'rvteal' || $listdir eq 'rvviolet' ||
		$listdir eq 'mailonly' || $listdir eq 'mime' || $listdir eq 'monsoon' || $listdir eq 'advanced'  || $listdir eq 'default'  || $listdir eq 'iconic' || $listdir eq 'bluelagoon' || $listdir eq 'x3mail');

		if (-d "/usr/local/cpanel/base/frontend/$listdir/rvthemesys") {
			if (-f "/usr/local/cpanel/base/frontend/$listdir/rvthemesys/_themeconf") {
				my %themeConf = ();
				my $iniFile = Cpanel::RvcommonLib::parseIniFile("/usr/local/cpanel/base/frontend/$listdir/rvthemesys/_themeconf");
				foreach my $key(keys %{$iniFile}) {
				    $themeConf{$key} = $iniFile->{$key};
				}				next if ($themeConf{'themeowner'} ne $Cpanel::user && $themeConf{'themeowner'} ne $Cpanel::CPDATA{'OWNER'});
			}
			elsif ($Cpanel::CPDATA{'OWNER'} ne 'root') {
				next;
			}
		}
		if (-e '/usr/local/cpanel/base/frontend/'. $listdir . '/rvskinmanager' || $listdir eq 'x' || $listdir eq 'x3') { 
			push(@themes, $listdir); 
		}
	}
	return @themes;
}

sub parseIniFiles1 {
    my $path = $_[0];
    my %conf = ();
    my @lines = file($path);
    foreach my $array (@lines) {
        next if ($array =~ /^$/);
        my ($keys, $values) = split('=', $array, 2);
        $keys        = trim($keys);
        $values      = trim($values);
        $conf{$keys} = $values;
    } 
    return %conf;
}

sub userAgentConnect {
    my ($host, $params, $type, $sslMode) = @_;
    if (!defined $type || $type eq '') {
        $type = 'get';
    }
    use LWP::UserAgent;
    
    my $protocal = (defined $sslMode && $sslMode ne '')?$sslMode : 'http';
    
    $host = $protocal . '://'.$host;
    my ($obj) = LWP::UserAgent->new;
    $obj->agent('Perl - RV Get Content');
    my $response = {};
    if ($type eq 'post') {
        $response = $obj->post($host, $params);
    } else {
        $response = $obj->get($host);
    }
    my %result = ();
    my $output = '';
    if ($response->is_success) {
        $output = $response->decoded_content;
        $result{'Page'} = $response->{_content};
    } else {
        print STDERR "LWP_get_contents error: ".$response->status_line."\n";
        $result{'socketfail'} = $response->status_line ;
        $result{'Err'} = $response->status_line ;
    }
    
    return %result;
}

sub getcontentbyurl {
	my ($url,$method,$args) = @_;
	
	my ($host,$port,$path) = extracturl($url);
	
	my %OPT = ();
	
	if ($url =~ '^https:\/\/') {
		$OPT{'usessl'} = 1;
	}
	
	$OPT{'host'} = $host;
	$OPT{'port'} = $port;
	$OPT{'request'} = $path;
	$OPT{'args'} = $args;
	$OPT{'method'} = (defined $method && $method ne '')? $method : 'GET';
	my %result= socket2(%OPT);
	
	return %result; 
}

sub extracturl {
	my ($url) = @_;
	my ($host, $port, $path);
	$url =~ s/http:\/\///;
	$url =~ s/https:\/\///;
	$host = $url;
	if ($url =~ /\//) {
		($host, $path) = split(/\//, $url, 2);
		$path = '/' . $path;
		$url =~ s/\/.*//;
	}
	if ($url =~ /:/) {
		($host, $port) = split(/:/, $host, 2);
	}
	
	return ($host, $port, $path);
}

sub socket2 {
	my (%OPT) = @_;

	#prepare vars
	my %result;
	my ($host, $port, $request, $args, $method, $usessl);
	$host    = defined $OPT{'host'}    ? $OPT{'host'}    : '';
	$port    = defined $OPT{'port'}    ? $OPT{'port'}    : '';
	$request = defined $OPT{'request'} ? $OPT{'request'} : '/';
	$args    = defined $OPT{'args'}    ? $OPT{'args'}    : '';
	$method  = defined $OPT{'method'}  ? $OPT{'method'}  : 'GET';
	$usessl  = defined $OPT{'usessl'}  ? $OPT{'usessl'}  : 0;

	my ($authBasic, $user, $password, $accountEncode);

	$authBasic = defined $OPT{'authbasic'} ? $OPT{'authbasic'} : '0';
	$user      = defined $OPT{'user'}      ? $OPT{'user'}      : '';
	$password  = defined $OPT{'password'}  ? $OPT{'password'}  : '';
	$accountEncode = '';
	if ($authBasic) {
		$password =~ s/[\r\n]+//g;
		$accountEncode = "$user:$password";
		$accountEncode = encode_base64_2("$user:$password");
	}
	if ($usessl) {
		_printdebug("## SSL Connect ##");
		
		#print STDERR "## SSL Connect ## \n";
		
		%result = _sslsocket($host, $port, $request, $args, $method, $accountEncode);
	} else {
		
		_printdebug("## None SSL Connect ##");
		#print STDERR "## None SSL Connect ## \n";
		%result =
		  _nonsslsocket($host, $port, $request, $args, $method, $authBasic, $accountEncode);
	}
	return %result;
}
	
sub _nonsslsocket {
	my ($this , $host, $port, $request, $args, $method, $authBasic, $accountEncode) = @_;
	$port = ($port ne '') ? $port : '80';
	my %result;
	my ($sin, $ipaddr, $len, $header);
	socket(SOCKET, PF_INET, SOCK_STREAM, 0);
	$ipaddr = gethostbyname($host);
	if (!defined($ipaddr)) {
		$result{'socketfail'} = "Cannot get protocal by hostname $host";
		return %result;
	}
	$sin = sockaddr_in($port, $ipaddr);
	if (!connect(SOCKET, $sin)) {
		$result{'socketfail'} = "Cannot create socket connection to server `$host`";
		return %result;
	}
	if ($method eq 'GET') {
		if ($args ne '') {
			$request .= "?$args";
		}
		$args = '';
	}
	my $oldfh = select(SOCKET);
	$| = 1;
	select($oldfh);
	my ($referer) = "http://$host$request";
	$len    = length($args);
	$header = "$method $request HTTP/1.0\r\n";
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
	$header .= "Host: $host\r\n";
	$header .= "Content-Length: $len\r\n";
	$header .= "Connection: Keep-Alive\r\n";
	$header .= "Cache-Control: no-cache\r\n";
	$header .= "Referer: $referer\r\n";
	$header .= "\r\n";
	if ($authBasic) {
		$header .= "Authorization: Basic " . $accountEncode . "\r\n";
	}
	$header .= $args;
	print SOCKET $header;
	my ($inheaders) = 1;
	while (<SOCKET>) {
		if ($_ =~ /^\r\n$/) {
			$inheaders = 0;
		}
		my $temp = $_;
		chomp($temp);
		if ($inheaders) {
			$temp =~ s/\n//g;
			$temp =~ s/\s$//g;
			my ($key, $value) = split(/: /, $temp);
			chomp($key);
			chomp($value);
			if ($key =~ /^http\//i) {
				$result{'header'}{'httpresponse'} = $temp;
			}
			$result{'header'}{ lc($key) } = $value;
		} else {
			$result{'Page'} .= $temp;
		}
	}
	close SOCKET;
	return %result;
}

sub _sslsocket {
	my ($host, $port, $request, $args, $method, $accountEncode) = @_;
	my %result;
	my $socketResult = '';
	my $page         = '';
	my $httpresponse = '';
	my %headers;
	$port = ($port ne '') ? $port : '443';
	my $hasNetSSLeay = `perl -e 'eval { require Net::SSLeay; print 1; }' 2>&1`;
	if ($hasNetSSLeay eq '0') {
		$result{'socketfail'} = 'Not support Net::SSLeay';
		return %result;
	}
	if ($method && $method eq 'POST') {
		$socketResult = `perl -e "
        use Net::SSLeay;
        print join\('{RVNL}',Net::SSLeay::post_https\( '$host', '$port', '$request',Net::SSLeay::make_headers\( 'Authorization' => 'Basic $accountEncode', 'Connection' => 'close' \),'$args'\)\);
        " 2>&1`;
	} else {
		if ($args ne '') {
			$request .= "?$args";
		}
		$socketResult = `perl -e "
        use Net::SSLeay;
        print join\('{RVNL}',Net::SSLeay::get_https\( '$host', '$port', '$request',Net::SSLeay::make_headers\( 'Authorization' => 'Basic $accountEncode', 'Connection' => 'close' \)\)\);
        " 2>&1`;
	}
	($page, $httpresponse, %headers) = split('{RVNL}', $socketResult);
	$result{'header'}{'httpresponse'} = $httpresponse;
	foreach my $headkey (keys %headers) {
		$result{'header'}{ lc($headkey) } = $headers{$headkey};
	}
	$result{'Page'} = $page;
	return %result;
}

sub encode_base64_2 {
	my $res = "";
	my $eol = "\n";
	pos($_[0]) = 0;
	while ($_[0] =~ /(.{1,45})/gs) {
		$res .= substr(pack("u", $1), 1);
		chop($res);
	}
	$res =~ tr/` -_/AA-Za-z0-9+\//;
	my $padding = (3 - length($_[0]) % 3) % 3;
	$res =~ s/.{$padding}$/"=" x $padding/e if $padding;
	if (length $eol) {
		$res =~ s/(.{1,76})/$1$eol/g;
	}
	return $res;
}

sub _printdebug {
	my ($msg) = @_ ;
	my $DEBUG;
	print ":: LOG :: $msg\n" if $DEBUG;
}


1;
__END__

Copyright 2K16 - 2K18 Indonesian Hacker Rulez