403 Forbidden


Disable Functions:
Path : /cpanel_installer/
File Upload :
Command :
Current File : //cpanel_installer/install

#!/usr/bin/perl
# cpanel - installd/install                        Copyright 2019 cPanel, L.L.C.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited
package installd::install;

use strict;
use warnings;

# Helper routines for the log.
our $message_caller_depth = 1;

my $log_fh;
my $COLOR_RED    = 31;
my $COLOR_YELLOW = 33;

sub colorize_bold {
    my ( $color, $msg ) = @_;

    return $msg if !defined $color || -e q{/var/cpanel/disable_cpanel_terminal_colors};
    $msg ||= '';

    return chr(27) . '[1;' . $color . 'm' . $msg . chr(27) . '[0;m';
}

# space pad debug messages.
sub DEBUG($) { return _MSG( 'DEBUG', "  " . shift ) }                             ## no critic(ProhibitSubroutinePrototypes)
sub ERROR($) { return _MSG( 'ERROR', colorize_bold( $COLOR_RED, shift ) ) }       ## no critic(ProhibitSubroutinePrototypes)
sub WARN($)  { return _MSG( 'WARN',  colorize_bold( $COLOR_YELLOW, shift ) ) }    ## no critic(ProhibitSubroutinePrototypes)
sub INFO($)  { return _MSG( 'INFO',  shift ) }                                    ## no critic(ProhibitSubroutinePrototypes)
sub FATAL($) { _MSG( 'FATAL', colorize_bold( $COLOR_RED, shift ) ); die "\n"; }   ## no critic(ProhibitSubroutinePrototypes)

use POSIX;
use Socket;
use Sys::Hostname ();
use IO::Handle    ();
use IO::Select    ();
use IPC::Open3    ();
use Cwd           ();
use Getopt::Long  ();

use constant PRODUCT_FULL         => 1;
use constant PRODUCT_DNSONLY      => 64;
use constant PRODUCT_DNSNODE      => 2048;
use constant PRODUCT_MAILNODE     => 4096;
use constant PRODUCT_DATABASENODE => 8192;

use constant PRODUCT_PAID => PRODUCT_FULL | PRODUCT_DNSNODE | PRODUCT_MAILNODE | PRODUCT_DATABASENODE;

my $yumcheck = 0;
my $force;
my $log_file  = '/var/log/cpanel-install.log';
my $lock_file = '/root/installer.lock';

my $skip_apache = -e '/root/skipapache' ? 1 : 0;
my $skip_repo_setup = 0;
my $skip_license_check;
my $collect_output = undef;

my %TIER_CACHE;
my ( $wget_bin, $wget_args );
my $gpg_bin;
my $installstart;

my $original_pid = $$;

our $DEFAULT_MYIP_URL = q[https://myip.cpanel.net/v1.0/];    # default value

exit run(@ARGV) unless caller;

sub run {
    my (@args) = @_;
    my $ret = eval { script(@args) };
    if ($@) {
        chomp $@;
        print STDERR $@;
        return 1;
    }
    return $ret;
}

sub cleanup_lock_file_and_gpg_homedir {
    if ( open my $fh, '<', $lock_file ) {
        my $pid = <$fh>;
        close $fh;

        chomp $pid if ($pid);
        if ( !$pid || $pid == $$ ) {
            print "Removing $lock_file.\n";
            unlink $lock_file;
        }
    }

    if ( -d gpg_homedir() ) {
        opendir( my $dh, gpg_homedir() );
        my @files = readdir($dh);
        closedir($dh);
        @files = map { gpg_homedir() . "/" . $_ } grep { !/^\.{1,2}/ } @files;
        unlink($_) for @files;
        rmdir( gpg_homedir() );
    }

    return;
}

sub script {
    my (@args) = @_;

    local $ENV{'CPANEL_BASE_INSTALL'} = 1;
    local $ENV{'LANG'}                = 'C';
    delete $ENV{'LANGUAGE'};

    local $| = 1;
    umask 022;

    if ( open my $fh, '<', $lock_file ) {
        print "The system detected an installer lock file: ($lock_file)\n";
        print "Make certain that an installer is not already running.\n\n";
        print "You can remove this file and re-run the cPanel installation process after you are certain that another installation is not already in progress.\n\n";
        my $pid = <$fh>;
        if ($pid) {
            chomp $pid;
            print `ps auxwww |grep $pid`;
        }
        else {
            print "Warning: The system could not find pid information in the $lock_file file.\n";
        }
        return 1;
    }

    # Create the lock file.
    if ( open my $fh, '>', $lock_file ) {
        print {$fh} "$$\n";

        close $fh;
    }
    else {
        FATAL("Unable to write lock file $lock_file");

        return 1;
    }

    $original_pid = $$;

    END {
        return if $$ != $original_pid;

        # Required for testing.
        return if $INC{'Test/More.pm'};

        cleanup_lock_file_and_gpg_homedir();
    }

    # Open the install logs for append.
    $installstart = open_logs();

    # Determine local distro and version. Fail if unsupported.
    my ( $distro, $distro_version, $distro_arch ) = check_system_support();
    my $options = {};
    Getopt::Long::GetOptionsFromArray(
        \@args,
        'force'            => \$force,
        'skip-cloudlinux'  => \$options->{'skip-cloudlinux'},
        'skipapache'       => \$skip_apache,
        'skipreposetup'    => \$skip_repo_setup,
        'skiplicensecheck' => \$skip_license_check,
    );
    recommend_version( $distro, $distro_version, $force );

    # Validate hostname is FQDN.
    check_hostname();

    # Validate NetworkManager is off and uninstalled.
    check_network_manager($distro_version);

    # Do the clean install check pause right after
    # network manager so they see the warning since
    # this will pause for 5 seconds
    clean_install_check();

    # Validate that various files are in place.
    check_files();

    # Bootstrap checks.
    INFO "Running health checks prior to start.";
    check_resolv_conf();
    check_yum_works();

    my $ensure_rpms_installed;
    if ( $ensure_rpms_installed = fork() ) {

        #parent
    }
    else {
        $collect_output = '';

        # Must run before bootstrap to install wget if needed
        local $@;
        eval { ensure_rpms_installed( $distro, $distro_version ); };
        print $collect_output;
        undef $collect_output;
        die if $@;

        exit(0);
    }
    {
        # While the ensure is running in the background
        # we show the message warning that they need a clean
        # server
        local $SIG{'INT'} = sub {
            kill( 'TERM', $ensure_rpms_installed );
            WARN("Install terminated by user input");
            exit(0);
        };
        warn_clean_server_needed();
        local $?;
        waitpid( $ensure_rpms_installed, 0 );
        if ( $? != 0 ) {
            die "ensure_rpms_install failed: $?";
        }

    }

    # Assure minimum setup: wget & co
    bootstrap( $distro, $distro_version );

    my $install_version = get_cpanel_version();

    # Install base distro required RPMS and setup YUM
    my $lts = get_lts_version();
    INFO "Installing cPanel & WHM major version ${lts}.";

    # get_cpanel_version must be called before
    # bootstrap_cpanel_perl

    my $bootstrap_cpanel_perl_pid;
    if ( $bootstrap_cpanel_perl_pid = fork() ) {

        # parent
    }
    else {
        # bootstrap cPanel Perl if available - legacy version of WHM would not have/need it
        #   this would allow updatenow to run using cpanel perl instead of system perl
        $collect_output = '';
        local $@;
        eval { bootstrap_cpanel_perl($install_version); };
        print $collect_output;
        undef $collect_output;
        die if $@;

        exit(0);
    }

    do_clock_update();

    # Start nscd if its not running since it will imporve
    # rpm install time
    ssystem("ps -U nscd -h 2>/dev/null || /sbin/service nscd start");

    # Place customer provided cpanel.config in place early in case we need to block on any of the settings.
    mkdir '/var/cpanel';
    chmod 0755, '/var/cpanel';
    my $custom_cpanel_config_file = '/root/cpanel_profile/cpanel.config';
    if ( -e $custom_cpanel_config_file ) {
        INFO("The system is placing the custom cpanel.config file from $custom_cpanel_config_file.");
        unlink '/var/cpanel/cpanel.config';
        system( '/bin/cp', $custom_cpanel_config_file, '/var/cpanel/cpanel.config' );
    }
    create_config_files($options);

    # Look for conditions that require tier manipulation or require us to block the install.
    check_for_install_version_blockers( $distro, $distro_version, $distro_arch, $force );

    check_if_we_can_get_to_httpupdate();

    # Make sure the OS is relatively clean.
    check_no_mysql();

    # Check that we're in runlevel 3.
    check_runlevel($distro_version);

    my $installer_dir = Cwd::getcwd();

    # Do this after sanity checks so that we fail before creating the touch
    # file.
    DEBUG "Parsing command line arguments.";
    get_install_type(@args);    # Set DNSONLY if need be.

    check_license_conflict() unless $skip_license_check;    # need dnsonly file to be set

    # TODO: Get rid of these files and replace them with /var/cpanel/dnsonly
    # Disable services by touching files.
    if ( is_dnsonly() ) {
        my @dnsonlydisable = qw( cpdavd );
        foreach my $dis_service (@dnsonlydisable) {
            ssystem( 'touch', '/etc/' . $dis_service . 'disable' );
        }
    }

    # Set selinux to permissive mode for installation.
    if ( -e '/usr/sbin/setenforce' ) {
        ssystem( '/usr/sbin/setenforce', '0', { ignore_errors => 1 } );
    }

    # Remove rpms and stop unneeded services, we have to do this
    # before any adds as once we remove rpms the rpm db will change out
    # from under yum
    disable_software();

    # Start background rpm download only after disable_software
    # since it does rpm -e
    my $background_rpm_download_pid = background_download_packages_used_during_initial_install();

    # Now software is installed, call rdate in case it couldn't be called earlier in the bootstrap script.
    update_system_clock();

    create_feature_showcase_dir();

    create_slash_scripts_symlink();
    {
        local $?;
        waitpid( $bootstrap_cpanel_perl_pid, 0 );
        if ( $? != 0 ) {
            kill 'TERM', $background_rpm_download_pid if $background_rpm_download_pid;
            die "Bootstrapping cPanel Perl failed: $?";
        }
    }

    # Install cpanel files and directories. TERMINATE if failure.
    updatenow(
        'skipapache'    => $skip_apache     ? 1 : 0,
        'skipreposetup' => $skip_repo_setup ? 1 : 0
    );

    # We used to wait for yum to finish here but
    # that just blocked the installer from downloading
    # rpms so we do the waitpid after

    chmod( 0700, '/usr/local/cpanel/scripts/cpanel_initial_install' );

    system( '/usr/local/cpanel/scripts/cpanel_initial_install', '--skipapache', $skip_apache, '--skipreposetup', $skip_repo_setup, '--installstart', $installstart );

    if ( $? >> 8 != 0 ) {
        kill 'TERM', $background_rpm_download_pid if $background_rpm_download_pid;
        FATAL('The system failed to run the /usr/local/cpanel/scripts/cpanel_initial_install script.');

        return 1;
    }

    # Cleanup before exiting
    waitpid( $background_rpm_download_pid, 0 );
    return 0;
}

sub recommend_version {
    my ( $distro, $version, $force ) = @_;

    return unless $version && $version < 7;

    my $timer          = 5;
    my $days_until_eol = days_until_c6_eol();

    my $notice =
      $force
      ? qq{ Installation will begin in $timer seconds.}
      : qq{ To force the installation on @{[_distro_name($distro)]} version 6, use the --force option.};

    my $advice = <<"END";
On November 30, 2020 @{[_distro_name($distro)]} will stop supporting @{[_distro_name($distro)]} 6 on all systems, including this one. To avoid migrating to a new system at that time, we strongly recommend that you use @{[_distro_name($distro)]} version 7. More information about cPanel, L.L.C. deprecation plan will be forthcoming.

If you do need to use @{[_distro_name($distro)]} 6, anticipate the need to have completed your migration in $days_until_eol days.

$notice
END

    return print_warning_notice( $advice, $force );
}

sub days_until_c6_eol {
    my $c6_eol_epoch   = 1606780799;                                                  # 2020-11-30 23:59:59
    my $day_in_seconds = 86400;
    my $current_day    = time();
    my $days_until_eol = int( ( $c6_eol_epoch - $current_day ) / $day_in_seconds );
    return $days_until_eol;
}

sub create_config_files {
    my ($options) = @_;
    touch('/var/cpanel/nocloudlinux') if $options->{'skip-cloudlinux'};
    return;
}

sub print_warning_notice {
    my ( $advice, $force ) = @_;

    FATAL $advice unless $force;

    do { WARN($_) }
      for split /\n/, $advice;

    five_second_pause();
    print "\n";

    return;
}

sub yum_nohang_ssystem {
    my @cmd = @_;
    $yumcheck = 1;
    my $failcount = 0;
    my $result    = 1;
    while ($result) {    # While yum is failing.
        $result = ssystem(@cmd);
        last if ( !$result );    # yum came back clean. Stop re-trying

        $failcount++;
        if ( $failcount > 5 ) {
            FATAL "yum failed $failcount times. The installation process cannot continue.";
        }
    }
    $yumcheck = 0;
    return;
}

sub ssystem {
    my @cmd = @_;
    my $conf_hr = ref( $cmd[-1] ) eq 'HASH' ? pop(@cmd) : {};

    local $message_caller_depth = $message_caller_depth + 1;    # Set caller depth deeper during this sub so debugging it clearer.
    DEBUG '- ssystem [BEGIN]: ' . join( ' ', @cmd );
    open( my $rnull, '<', '/dev/null' ) or die "Can't open /dev/null: $!";
    my $io = IO::Handle->new;
    my $pid = IPC::Open3::open3( $rnull, $io, $io, @cmd );
    $io->blocking(0);

    my $select = IO::Select->new($io);

    my $exit_status;
    my $buffer                 = '';
    my $buffered_waiting_count = 0;
    while ( !defined $exit_status ) {
        while ( my $line = readline($io) ) {

            # Push the buffer lacking a newline onto the front of this.
            if ($buffer) {
                $line   = $buffer . $line;
                $buffer = '';
            }

            $line =~ s/\r//msg;    # Strip ^M from output for better log output.

            if ( $yumcheck && $line =~ /yum might be hung/ ) {
                kill 15, $pid;
                sleep 2;
                WARN "Yum appears to be hung. The system will now attempt to restart it.";
                ssystem(qw/killall -TERM yum/);
                sleep(20);
                ssystem(qw/killall -TERM yum/);
            }

            # Internally buffer on newlines.
            if ( $line =~ m/\n$/ms ) {
                DEBUG( "  " . $line );
                $buffered_waiting_count = 0;
            }
            else {
                print "." if ( $buffered_waiting_count++ > 1 );
                $buffer = $line;
            }
        }

        # Parse exit status or yield time to the CPU.
        if ( waitpid( $pid, 1 ) == $pid ) {
            $exit_status = $? >> 8;
        }
        else {

            # Watch the file handle for output.
            $select->can_read(0.01);
        }
    }
    ERROR "  - ssystem [EXIT_CODE] '$cmd[0]' exited with $exit_status (ignored)" if $exit_status && !$conf_hr->{'ignore_errors'};

    close($rnull);
    $io->close();

    DEBUG '- ssystem [END]';

    return $exit_status;
}

sub is_dnsonly {
    return -e '/var/cpanel/dnsonly' ? 1 : 0;
}

sub get_install_type {
    my @args = @_;

    # TYPE could be DNSONLY
    my $type = 'standard';
    if (@args) {
        foreach my $val (@args) {
            next if $val =~ m/^--/;
            $type = $val;
            last;
        }
    }

    if ( $type =~ m/dnsonly/i ) {
        INFO "cPanel DNSONLY installation requested.";
        touch('/var/cpanel/dnsonly');
    }

    INFO "Install type: $type\n";
    return;
}

sub touch {
    my ( $file, @data ) = @_;

    open( my $fh, ">>", $file ) or return;
    foreach my $line (@data) {    # concat anything found.
        print {$fh} $line;
    }
    close $fh;
    return;
}

sub get_distro_release_rpm {

    # /etc/redhat-release or /etc/system-release must be present
    my ( $rhel_release, $amazon_release ) = ( '/etc/redhat-release', '/etc/system-release' );

    my $distro_release;

    if ( -e $rhel_release ) {
        $distro_release = $rhel_release;
    }
    elsif ( -e $amazon_release ) {
        $distro_release = $amazon_release;
    }
    else {
        invalid_system("The system could not detect a valid release file for this distribution");
    }

    chomp( my $release_rpm = `rpm -qf $distro_release` );

    return $release_rpm;
}

sub check_system_support {

    # Some of these variables are unused *as of now*. However! some of these values may be useful for 'filling in the blanks' when the RPM check we do fails to provide all required info.
    # For now, only the $system and $machine variables are used, $machine only when Amazon Linux is detected. See https://metacpan.org/pod/POSIX#uname for more info.
    my ( $system, $nodename, $release, $version, $machine ) = POSIX::uname();

    if ( $system =~ m/linux/i ) {

        my $release_rpm = get_distro_release_rpm();

        $release_rpm or invalid_system("RPMs do not manage release file.");

        # We now parse this with our rpm pasrsing code
        # to ensure its reliable
        my $parsed         = parse_rpm_arch($release_rpm);
        my $distro_arch    = $parsed->{'arch'};
        my $distro_version = $parsed->{'version'};
        my $distro_type    = $parsed->{'name'};

        # CentOS uses a hyphen to delimit major/minor.
        $distro_version =~ tr{-}{.};
        if ( index( $distro_version, '.' ) == -1 ) {
            my ($minor_version) = $parsed->{'release'} =~ m{^([0-9]+)\.};
            if ($minor_version) {
                $distro_version .= qq{.$minor_version};
            }
        }
        DEBUG("Detected distro “$distro_type”, version “$distro_version”, arch “$distro_arch”");

        $distro_version or invalid_system("The system found that the unexpected '$release_rpm' RPM manages the release file.");

        # This is required for CloudLinux 5 as they do not set an arch for their rpm. So we want to ignore it.
        $distro_arch ||= '';

        # That RPM must have redhat or centos in the name.
        $distro_type =~ m/centos|redhat|enterprise-release|system-release|cloud/i or invalid_system("The system found that the unexpected '$distro_type' RPM manages the release file.");
        $distro_type =~ s/-release//imsg;

        my $distro;

        if ( $distro_type eq 'enterprise' ) {
            $distro = 'redhat';
        }
        elsif ( $distro_type eq 'system' ) {
            $distro = 'amazon';
            $distro_arch = $machine if $distro_arch eq 'noarch';    # SEE CPANEL-8050
        }
        else {
            $distro = $distro_type;
        }

        INFO _distro_name($distro) . " $distro_version (Linux) detected!";

        # Handle redhat/centos versioning
        if ( $distro ne 'amazon' ) {

            # The version number must be 6 or 7.
            ( int($distro_version) <= 7 && $distro_version >= 6 ) or invalid_system( "cPanel, L.L.C. does not support " . _distro_name($distro) . " version $distro_version." );

            # Supported distros for installer: redhat/red hat enterprise/cloud/centos/amazon
            $distro = ( $distro =~ m/redhat|hat enterprise/i ) ? 'redhat' : ( $distro =~ m/cloud/i ) ? 'cloud' : 'centos';
        }
        else {
            # Support for Amazon Linux introduced in 2015
            ( $distro_version >= 2015 ) or invalid_system( "cPanel, L.L.C. does not support " . _distro_name($distro) . " version $distro_version for new installations." );
        }

        INFO "Checking RAM now...";
        my $total_memory = _get_total_memory();

        my $min_memory_rules = {
            default => 768,      # CentOS 5/6 => in a better world should be 512
            7       => 1_024,    # CentOS 7
        };

        my $minmemory = $min_memory_rules->{$distro_version} || $min_memory_rules->{'default'};

        if ( $total_memory < $minmemory ) {
            ERROR qq{cPanel, L.L.C. requires a minimum of $minmemory MB of RAM for your operating system.};
            FATAL "Increase the server's total amount of RAM, and then reinstall cPanel & WHM.";
        }

        return ( $distro, $distro_version, $distro_arch );
    }
    else {
        invalid_system("Could not detect version for operating system");
    }

    invalid_system("Unknown or unsupported operating system: $system");
    return;
}

sub _get_total_memory {

    # tests on different architectures show that 15 % is safe
    my $tolerance_factor = 1.15;

    # MemTotal: Total usable ram (i.e. physical ram minus a few reserved
    #          bits and the kernel binary code)
    # note, another option would be to use "dmidecode --type 17", or dmesg
    #   but this will require an additional RPM
    #   we just want to be sure that a customer does not install
    #   with 512 when 700 or more is required
    my $meminfo = q{/proc/meminfo};
    if ( open( my $fh, "<", $meminfo ) ) {
        while ( my $line = readline $fh ) {
            if ( $line =~ m{^MemTotal:\s+([0-9]+)\s*kB}i ) {
                return int( int( $1 / 1_024 ) * $tolerance_factor );
            }
        }
    }

    return 0;    # something is wrong
}

sub invalid_system {
    my $message = shift || '';
    chomp $message;
    ERROR "$message";

    ERROR "The system detected an unsupported distribution. cPanel & WHM only supports CentOS 6 and 7, Red Hat Enterprise Linux® 6 and 7, and CloudLinux™ 6 and 7.";
    FATAL "Please reinstall cPanel & WHM from a valid distribution.";
    return;
}

sub check_hostname {
    my $hostname = get_fqdn_hostname();
    INFO "Validating that the system hostname ('$hostname') is a FQDN...";
    if ( $hostname =~ /^www\./ ) {
        FATAL "The installation process detected the following hostname: $hostname\n Hostnames cannot start with www! Use a valid hostname.";
    }

    if ( !is_valid_hostname($hostname) ) {
        ERROR "";
        ERROR "********************* ERROR *********************";
        ERROR "";
        ERROR "Your hostname ($hostname) is invalid, and must be";
        ERROR "set to a fully qualified domain name before installing cPanel.";
        ERROR "";
        ERROR "A fully qualified domain name must contain two dots, and consists of two parts: the hostname and the domain name.";
        ERROR "You can update your hostname by running `hostname your-hostname.example.com`, then re-running the installer.";

        ERROR "********************* ERROR *********************";
        FATAL "Exiting...";
    }
    return;
}

sub check_network_manager() {
    my ($release_version) = @_;

    INFO "Checking for NetworkManager now...";

    if ( $release_version eq 6 ) {
        check_initd_network_manager();
        return;
    }

    check_systemd_network_manager();
    return;
}

sub check_files {
    INFO "Checking for essential system files...";

    unless ( -f '/etc/fstab' ) {
        ERROR "Your system is missing the file /etc/fstab.  This is an";
        ERROR "essential system file that is part of the base system.";
        FATAL "Please ensure the system has been properly installed.";
    }
    return;
}

sub network_manager_report_status {
    my ( $uninstalled, $running, $startup ) = @_;

    if ($uninstalled) {
        INFO "NetworkManager is not installed.";
    }
    elsif ( $running || $startup ) {
        ERROR "********************* ERROR *********************";
        ERROR "NetworkManager is installed and running, or      ";
        ERROR "configured to startup.                           ";
        ERROR "";
        ERROR "cPanel does not support NetworkManager enabled   ";
        ERROR "systems.  The installation cannot proceed.       ";
        ERROR "";
        ERROR "See https://go.cpanel.net/disablenm for more     ";
        ERROR "information on disabling Network Manager.        ";
        ERROR "********************* ERROR *********************";
        ($force) ? WARN "Continuing installation due to force flag..." : FATAL "Exiting...";
    }
    else {
        WARN "NetworkManager is installed, but not active.  Consider removing it.";
    }
    return;
}

sub check_initd_network_manager {
    my $status      = `service NetworkManager status 2>/dev/null`;
    my $uninstalled = !$status;
    my $running;
    my $startup;

    if ($status) {
        my ( $status_service, $verb, $status_state ) = split( ' ', $status );
        $running = $status_state ne 'stopped';
    }

    my $config = `chkconfig NetworkManager --list 2>/dev/null`;
    if ($config) {
        my ( $config_service, $config_runlevels ) = split( ' ', $config, 2 );
        $startup = $config_runlevels =~ m/:on/;
    }

    network_manager_report_status( $uninstalled, $running, $startup );
    return;
}

sub check_systemd_network_manager {
    my $status      = `systemctl --all --no-legend --no-pager list-units NetworkManager.service 2>/dev/null`;
    my $uninstalled = !$status;
    my $running;
    my $startup;

    if ($status) {
        my ( $status_service, $load_state, $active_state, $sub_state, @service_description ) = split( ' ', $status );
        $running = $active_state && $sub_state && $active_state ne 'inactive' && $sub_state ne 'dead';

        # they uninstalled it, but didn't run systemctl daemon-reload
        if ( $load_state eq 'not-found' ) {
            $uninstalled = 1;
        }
    }

    my $config = `systemctl --all --no-legend --no-pager list-unit-files NetworkManager.service 2>/dev/null`;
    if ($config) {
        my ( $config_service, $enabled_state ) = split( ' ', $config );
        $startup = $enabled_state && $enabled_state ne 'disabled' && $enabled_state ne 'masked';
    }

    network_manager_report_status( $uninstalled, $running, $startup );
    return;
}

sub five_second_pause {
    for ( 1 .. 5 ) { print '.'; sleep(1); }
    print "\n";
    return;
}

sub warn_clean_server_needed {
    INFO "cPanel Layer 1 Installer Starting...";
    INFO "Warning !!! Warning !!! WARNING !!! Warning !!! Warning";
    INFO "-------------------------------------------------------";
    INFO "cPanel requires a fresh, clean server!";
    INFO "If you serve websites from this server, this installer";
    INFO "will overwrite all of your configuration files.";
    INFO "Hit Ctrl+C NOW!";
    INFO "If this is a new server, please ignore this message.";
    INFO "-------------------------------------------------------";
    INFO "Warning !!! Warning !!! WARNING !!! Warning !!! Warning";
    INFO "Waiting 5 seconds...";
    INFO "";
    INFO "";
    five_second_pause();
    return;
}

sub clean_install_check {

    INFO 'Checking for any control panels...';
    my @server_detected;
    push @server_detected, 'DirectAdmin' if ( -e '/usr/local/directadmin' );
    push @server_detected, 'Plesk'       if ( -e '/etc/psa' );
    push @server_detected, 'Ensim'       if ( -e '/etc/appliance' || -d '/etc/virtualhosting' );

    #push @server_detected, 'Alabanza'    if ( -e '/etc/mail/mailertable' );
    push @server_detected, 'Zervex' if ( -e '/var/db/dsm' );
    push @server_detected, 'Web Server Director' if ( -e '/bin/rpm' && `/bin/rpm -q ServerDirector` =~ /^ServerDirector/ms );

    # Don't just check for /usr/local/cpanel, as some people will have created
    # that directory as a mount point for the install.
    push @server_detected, 'cPanel & WHM' if -e '/usr/local/cpanel/cpkeyclt';

    return if ( !@server_detected );

    ERROR "The installation process found evidence that the following control panels were installed on this server:";
    ERROR $_ foreach (@server_detected);
    FATAL 'You must install cPanel & WHM on a clean server.';
    return;
}

sub check_no_mysql {

    # This can cause failures if the database is newer than the version we're
    # going to install.
    INFO 'Checking for an existing MySQL or MariaDB instance...';

    my $mysql_dir = '/var/lib/mysql';
    return unless -d $mysql_dir;
    my $nitems = 0;
    if ( opendir( my $dh, $mysql_dir ) ) {
        $nitems = scalar grep { !/\A(?:\.{1,2}|lost\+found)\z/ } readdir $dh;
        closedir($dh);
    }
    return unless $nitems;

    ERROR "The installation process found evidence that MySQL or MariaDB was installed on this server:";
    ERROR "The $mysql_dir directory is present and not completely empty.";
    FATAL 'You must install cPanel & WHM on a clean server.';
    return;
}

sub check_runlevel {
    my ($distro_version) = @_;

    if ( $distro_version && $distro_version >= 7 ) {

        # simply check for multi-user.target on CentOS 7
        # system state and their equivalent runlevel targets
        # graphical.target   <=> runlevel5.target
        # multi-user.target  <=> runlevel2.target, runlevel3.target, runlevel4.target
        # poweroff.target    <=> runlevel0.target
        # reboot.target      <=> runlevel6.target
        # rescue.target      <=> runlevel1.target
        `systemctl is-active multi-user.target >/dev/null 2>&1`;
        return if $? == 0;
        if ($force) {
            WARN 'The installation process detected that the multi-user.target is not active (boot is probably not finished).';
            WARN 'The multi-user.target must be active. Proceeding anyway because --force was specified!';
        }
        else {
            ERROR 'The installation process detected that the multi-user.target is not active (boot is probably not finished).';
            FATAL 'The multi-user.target must be active before the installation can continue.';
        }
    }

    my $runlevel = `runlevel`;
    chomp $runlevel;
    my ( $prev, $curr ) = split /\s+/, $runlevel;

    my $message;

    # runlevel can also return unknown
    if    ( !defined $curr ) { $message = "The installation process could not determine the server's current runlevel."; }
    elsif ( $curr != 3 )     { $message = "The installation process detected that the server was in runlevel $curr."; }
    else                     { return; }

    # the system claims to be in an unsupported runlevel.
    if ($force) {
        WARN $message;
        WARN 'The server must be in runlevel 3. Proceeding anyway because --force was specified!';
        return;
    }
    else {
        ERROR "The installation process detected that the server was in runlevel $curr.";
        FATAL 'The server must be in runlevel 3 before the installation can continue.';
    }

    FATAL 'Runlevel logic failed. This should never happen. The installer cannot continue.';
    return;
}

sub open_logs {
    my $installstart = time();

    if ( my $mtime = ( stat($log_file) )[9] ) {
        my $bu_file = $log_file . '.' . $mtime;
        system( '/bin/cp', $log_file, $bu_file ) unless -e $bu_file;
    }

    my $orig_umask = umask(0077);
    open( $log_fh, '>>', $log_file ) or die "Could not open log: $!";
    $log_fh->autoflush(1);
    umask($orig_umask);

    my $installstarttime = localtime($installstart);
    INFO "cPanel & WHM installation started at: ${installstarttime}!";
    INFO "This installation will require 10-50 minutes, depending on your hardware and network.";
    INFO "Now is the time to go get another cup of coffee/jolt.";
    INFO "The install will log to the /var/log/cpanel-install.log file.";
    INFO "";
    INFO "Beginning Installation v3...";
    return $installstart;
}

# Install fastest mirror plugin for CentOS
sub install_fastest_mirror {
    my ( $distro, $distro_version ) = @_;

    return unless $distro =~ m/centos/;
    return if has_yum_plugin_fastestmirror();

    INFO "Installing the fastest mirror plugin...";
    ssystem( 'yum', 'clean', 'plugins' );
    ssystem( 'yum', '-y',    'install', 'yum-fastestmirror' );
    ssystem( 'yum', 'clean', 'plugins' );

    # We set the number of threads in bootstrap
    #
    #
    #  We used to support 512MB of ram which caused a problem with a high
    #  maxthreads (FB-51412), however this is no longer an issue
    #  https://documentation.cpanel.net/display/78Docs/Installation+Guide+-+System+Requirements
    #
    return;
}

# This is a peared down version of ensure_rpms_installed because we don't yet have cpanel code.
# We also assume centhat 5/6/7 for this code.
sub ensure_rpms_installed {
    my ( $distro, $distro_version ) = @_;

    # Disable rpmforge repos
    if ( glob '/etc/yum.repos.d/*rpmforge*' ) {
        WARN 'DISABLING rpmforge yum repositories.';
        mkdir( '/etc/yum.repos.d.disabled', 0755 );
        ssystem('mv -fv -- /etc/yum.repos.d/*rpmforge* /etc/yum.repos.d.disabled/ 2>/dev/null');
    }

    install_fastest_mirror( $distro, $distro_version );

    # Minimal packages needed to use yum.

    INFO("Installing packages needed to download and run the cPanel initial install.");

    # Assure wget/bzip2/gpg are installed for centhat. These packages are needed prior to sysup
    my @packages_to_install = qw/wget bzip2 gnupg2 rdate xz yum yum-fastestmirror nscd/;

    # Install perl-devel on Redhat installs
    if ( $distro_version < 2015 ) {
        push @packages_to_install, qw{ crontabs sysstat };

        # No need to install perl-CPAN on older versions as install_locallib_loginprofile will
        # do it for us later
    }

    # Remove all excludes from /etc/yum.conf
    ssystem( '/usr/local/cpanel/scripts/checkyum', '--nokernel', '--noperl' ) if ( -e '/usr/local/cpanel/scripts/checkyum' );
    ssystem( 'touch', '/etc/checkyumdisable' );    # Disable checkyum

    # Don't attempt to install kernel-headers on systems with the CentOS Plus kernel headers already installed.
    # We do not need kernel-headers for v70+ since we don't link anything against the kernel anymore
    # if ( !has_kernel_plus_headers() ) {
    #    push @packages_to_install, 'kernel-headers';    # Needed because Cpanel::SysPkgs excludes kernel_version
    #}

    if (@packages_to_install) {
        yum_nohang_ssystem( '/usr/bin/yum', '-y', 'install', @packages_to_install );
    }

    # Make sure all rpms are up to date if we are running
    # an older version that CentOS 7 since we only support
    # Centos 6.5+.
    #
    # Additionally we need Centos 7.4+ to ensure they
    # have the latest version of openssl per
    # CPANEL-25853
    if ( version_lt( $distro_version, 6.5 ) || ( version_gte( $distro_version, 7 ) && version_lt( $distro_version, 7.4 ) ) ) {
        yum_nohang_ssystem( '/usr/bin/yum', '-y', 'update' );
    }

    # Reinstate yum exclusions
    unlink '/etc/checkyumdisable';
    ssystem('/usr/local/cpanel/scripts/checkyum') if ( -e '/usr/local/cpanel/scripts/checkyum' );
    return;
}

sub disable_software {
    my @remove_rpms = qw(
      exim
      mysql
      MySQL
      mysql-max
      MySQL-Max
      mysql-devel
      MySQL-devel
      mysql-client
      MySQL-client
      mysql-ndb-storage
      MySQL-ndb-storage
      mysql-ndb-management
      MySQL-ndb-management
      mysql-ndb-tools
      MySQL-ndb-tools
      mysql-ndb-extra
      MySQL-ndb-extra
      mysql-shared
      MySQL-shared
      mysql-libs
      MySQL-libs
      mysql-bench
      MySQL-bench
      mysql-server
      MySQL-server
      wu-ftpd
      portreserve
      postfix
      sendmail
      smail
      spamassassin
      apache-conf
      mod_perl
      mariadb-libs
      MariaDB-client
      MariaDB-common
      MariaDB-server
      MariaDB-compat
      MariaDB-shared
    );

    INFO 'Ensuring that prelink is disabled...';
    my $prelink_conf = '/etc/sysconfig/prelink';
    if ( open( my $fh, '+<', '/etc/sysconfig/prelink' ) ) {
        my @lines = map { my $s = $_; $s =~ s/^(PRELINKING=)yes(.*)$/$1no$2/; $s } <$fh>;
        seek( $fh, 0, 0 );
        print {$fh} @lines;
        truncate( $fh, tell($fh) );
    }

    INFO 'Ensuring that conflicting services are not installed...';
    my @rpms_to_remove =
      map { ( split( m{-}, $_, 2 ) )[1] }    # split INSTALLED-NAME and take NAME
      grep { rindex( $_, 'INSTALLED-', 0 ) == 0 }    # Only output that starts with INSTALLED- is installed
      split( m{\n}, `rpm -q --nodigest --nosignature --queryformat 'INSTALLED-%{NAME}\n' @remove_rpms` );
    if (@rpms_to_remove) {
        DEBUG " Removing @rpms_to_remove...";
        ssystem( 'rpm', '-e', '--nodeps', @rpms_to_remove, { ignore_errors => 1 } );
    }

    INFO 'Removing conflicting service references from the RPM database (but leaving the services installed)...';
    my @all_pkgs = `rpm -qa --nodigest --nosignature --queryformat '%{name}\n'`;
    @all_pkgs = grep { $_ !~ m/^cpanel-/ } @all_pkgs;    # Don't worry about cpanel RPMS.

    return if ($skip_apache);

    # TODO: Why are we doing --justdb??? Fix this after at least 11.30
    foreach my $rpm ( grep m/http|php|apache|mod_perl/, @all_pkgs ) {
        chomp $rpm;
        DEBUG " Removing $rpm...\n";
        ssystem( 'rpm', '-e', '--justdb', '--nodeps', $rpm, { ignore_errors => 1 } );
    }
    return;
}

sub create_slash_scripts_symlink {

    # Install cPanel files.
    INFO 'Installing /usr/local/cpanel files...';

    DEBUG "HTTPUPDATE is set to " . get_update_source();

    if ( -e '/scripts' && !-l '/scripts' ) {
        if ( !-d '/scripts' ) {
            WARN "The system detected /scripts as a file. Moving it to a new location...";
            ssystem( qw{/bin/mv /scripts}, "/scripts.o.$$" );
        }
        else {
            WARN "The system detected the /scripts directory. Moving its contents to the /usr/local/cpanel/scripts directory...";
            ssystem(qw{mkdir -p /usr/local/cpanel/scripts});
            ssystem('cd / && tar -cf - scripts | (cd /usr/local/cpanel && tar -xvf -)');
            ssystem(qw{/bin/rm -rf /scripts});
        }
    }
    unlink qw{/scripts};
    symlink(qw{/usr/local/cpanel/scripts /scripts}) unless -e '/scripts';

    if ( !-l '/scripts' ) {
        WARN("The /scripts directory must be a symlink to the /usr/local/cpanel/scripts directory. cPanel & WHM does not use the /scripts directory.");
    }
    else {
        DEBUG('/scripts symlink is set to point to /usr/local/cpanel/scripts');
    }

    return;
}

sub bootstrap_cpanel_perl {
    my ($install_version) = @_;

    # Force $install_version to be passed so we know the TIERS
    # file has already been downloaded
    die "bootstrap_cpanel_perl requires the \$install_version" if !$install_version;

    # Install cPanel files.
    INFO "Installing bootstrap cPanel Perl";

    # Download the tar.gz files and extract them instead.

    my $script = 'fix-cpanel-perl';
    my $source = "/cpanelsync/$install_version/cpanel/scripts/${script}.xz";

    unlink $script;

    DEBUG "Retrieving the $script file from $source if available...";

    # download file in current directory (inside the self extracted tarball)
    cpfetch( $source, is_optional => 1 );

    if ( !-e $script ) {
        WARN "Script '$script' is not available for cPanel & WHM version $install_version. Continuing installation...";
        return;
    }

    chmod 0700, $script;

    INFO "Running script $script to bootstrap cPanel Perl.";

    my $exit;

    # Retry a few times if one of the http request failed
    my $max = 3;
    foreach my $iter ( 1 .. $max ) {
        $exit = system("./$script");
        if ( $exit == 0 ) {
            INFO "Successfully installed cPanel Perl minimal version.";
            return;
        }

        WARN "Run #$iter/$max failed to run script $script.";
        last if $iter == $max;
        sleep 5;
    }

    my $signal = $exit % 256;
    $exit = $exit >> 8;

    FATAL "Failed to run script $script to bootstrap cPanel Perl.";
    FATAL("The script $script terminated with the following exit code: $exit ($signal); The cPanel & WHM installation process cannot proceed.");

    return;
}

sub updatenow {
    my (%flags) = @_;

    INFO "Downloading updatenow.static";

    # Download the tar.gz files and extract them instead.

    my $install_version = get_cpanel_version();
    my $source          = "/cpanelsync/$install_version/cpanel/scripts/updatenow.static.bz2";

    DEBUG "Retrieving the updatenow.static file from $source...";

    # download file in current directory (inside the self extracted tarball)
    unlink 'updatenow.static';
    cpfetch($source);
    chmod 0755, 'updatenow.static';
    my $exit;

    my @passed_flags = map { ( "--$_" => $flags{$_} ) } sort keys %flags;

    for ( 1 .. 5 ) {    # Re-try updatenow if it fails.
        INFO("Closing the installation log and passing output control to the updatenow.static file...");

        # close $log_fh so it can be re-opened by updatenow.
        close $log_fh;

        $exit = system( './updatenow.static', '--upcp', '--force', "--log=$log_file", @passed_flags );

        # Re-open the log regardless of success.
        my $log_file = '/var/log/cpanel-install.log';
        open( $log_fh, '>>', $log_file ) or die "Can't open log file: $!";
        $log_fh->autoflush(1);

        return if ( !$exit );

        DEBUG("The installation process detected a failed synchronization. The system will reattempt the synchronization with the updatenow.static file...");
    }

    my $signal = $exit % 256;
    $exit = $exit >> 8;

    FATAL("The installation process was unable to synchronize cPanel & WHM. Verify that your network can connect to httpupdate.cpanel.net and rerun the installer.");
    FATAL("The updatenow.static process terminated with the following exit code: $exit ($signal); The cPanel & WHM installation process cannot proceed.");
    return;
}

# Remote resolvers are required, since we remove local BIND during installation.
sub check_remote_resolvers {
    open my $resolv_conf_fh, '<', '/etc/resolv.conf' or FATAL("Could not open /etc/resolv.conf: $!");

    if ( !grep { m/^\s*nameserver\s+/ && !m/\s+127.0.0.1$/ } <$resolv_conf_fh> ) {
        FATAL("/etc/resolv.conf must be configured with non-local resolvers for installations to complete.");
    }

    return;
}

sub check_resolv_conf {

    check_remote_resolvers();

    INFO "Validating whether the system can look up domains...";
    my @domains = qw(
      httpupdate.cpanel.net
      securedownloads.cpanel.net
    );

    foreach my $domain (@domains) {
        DEBUG "Testing $domain...";
        next if ( gethostbyname($domain) );
        ERROR '!' x 105 . "\n";
        ERROR "The system cannot resolve the $domain domain. Check the /etc/resolv.conf file. The system has terminated the installation process.\n";
        FATAL '!' x 105 . "\n";
    }
    return;
}

sub read_config {
    my $file = shift or die;
    my $config = {};

    open( my $fh, "<", $file ) or return $config;
    while ( my $line = readline $fh ) {
        chomp $line;
        if ( $line =~ m/^\s*([^=]+?)\s*$/ ) {
            my $key = $1 or next;    # Skip loading the key if it's undef or 0
            $config->{$key} = undef;
        }
        elsif ( $line =~ m/^\s*([^=]+?)\s*=\s*(.*?)\s*$/ ) {
            my $key = $1 or next;    # Skip loading the key if it's undef or 0
            $config->{$key} = $2;
        }
    }
    return $config;
}

sub check_if_we_can_get_to_httpupdate {
    return if ( $wget_bin !~ m/wget/ );    # Just skip this check if no wget is avail.

    foreach my $src ( 'index.html', 'modules/index.html' ) {
        my $page = `$wget_bin $wget_args - http://httpupdate.cpanel.net/pub/CPAN/$src`;

        if ( $page =~ m/perl/i && $page =~ m/CPAN/ ) {
            INFO "The system successfully connected to the httpupdate.cpanel.net server.";
            return;
        }
    }
    FATAL "The system cannot currently download from the httpupdate.cpanel.net servers.";
    return;
}

# A tiny version of Cpanel::RpmUtils::checkupdatesystem();
sub check_yum_works {
    local $ENV{'LC_ALL'} = 'C';
    my $out = `yum info glibc 2>&1`;
    return if ( $out =~ m{ (?: Installed | Available) \s+ Packages }xmsi );

    ERROR q{Your operating system's RPM update method } . qq{(yum) could not locate the glibc package. } . q{This is an indication of an improper setup. } . q{You must correct this error before you proceed. };
    FATAL "\n\n";
    return;
}

sub cpfetch {
    my ( $url, %opts ) = @_;

    if ( !$url ) {
        FATAL("The system called the cpfetch process without a URL.");
    }

    my $file = _get_file( $url, %opts );
    return unless defined $file;

    if ( $file =~ /\.bz2$/ ) {
        ssystem( "/usr/bin/bunzip2", $file );
    }

    if ( signatures_enabled() ) {
        $url =~ s/\.bz2$//g;
        $file =~ s/\.bz2$//g;

        my $sig = _get_file("$url.asc");
        _verify_file( $file, $sig, $url );
    }

    # the xz file itself is signed only extract it after checking the signature
    if ( $file =~ /\.xz$/ ) {
        ssystem( "/usr/bin/unxz", $file );
    }

    return;
}

sub _get_file {
    my ( $url, %opts ) = @_;

    $url = 'http://' . get_update_source() . $url;

    my @FILE = split( /\//, $url );
    my $file = pop(@FILE);

    if ( -e $file ) {
        WARN("Warning: Overwriting the $file file...");
        unlink $file;
        FATAL("The system could not remove the $file file.") if ( -e $file );
    }

    DEBUG "Retrieving $url to the $file file...";
    my $out = `$wget_bin $wget_args '$file' $url 2>&1`;

    if ( !-e $file || -z $file ) {
        unlink $file;
        if ( $opts{is_optional} ) {
            WARN "The system could not fetch the optional $file file: $out";
            return;
        }
        FATAL "The system could not fetch the $file file: $out";
    }

    return $file;
}

sub get_update_source {
    my $update_source = 'httpupdate.cpanel.net';
    my $source_file   = '/etc/cpsources.conf';
    if ( -r $source_file && -s $source_file ) {    # pull in from cpsources.conf if it's set.
        open( my $fh, "<", $source_file ) or return $update_source;
        while (<$fh>) {
            next if ( $_ !~ m/^\s*HTTPUPDATE\s*=\s*(\S+)/ );
            $update_source = "$1";
            FATAL("HTTPUPDATE is set to '$update_source' in the $source_file file.") if ( !$update_source );
            last;
        }
    }

    return $update_source;
}

sub get_myip_url {
    my $source_file = '/etc/cpsources.conf';
    my $myip_url    = $DEFAULT_MYIP_URL;
    if ( -r $source_file && -s $source_file ) {    # pull in from cpsources.conf if it's set.
        open( my $fh, "<", $source_file ) or return $myip_url;
        while (<$fh>) {
            next unless m/^\s*MYIP\s*=\s*(\S+)/;
            $myip_url = "$1";
            last;
        }
    }

    DEBUG "Using MyIp URL to detect your IP '$myip_url'.";

    return $myip_url;
}

sub guess_ip {
    my $url = get_myip_url();

    FATAL "No wget binary defined at this stage." unless $wget_bin;

    my $file = q[guess.my.ip];

    my $max = 3;
    foreach my $iter ( 1 .. $max ) {
        unlink $file;
        `$wget_bin $wget_args '$file' $url 2>&1`;
        last if $? == 0;
        if ( $iter == $max ) {
            FATAL "Failed to call URL $url to detect your IP.";
        }
        WARN("Call to $url fails, giving it another try [$iter/$max]");
        sleep 3;
    }

    my $ip;

    {
        open( my $fh, '<', $file ) or FATAL("Cannot read file $file.");
        $ip = readline($fh);
        close($fh);
    }

    chomp($ip) if defined $ip;

    if ( !defined $ip || !length $ip ) {

        # could also use FATAL - be relax for now to avoid false positives
        WARN "Fail to guess your IP using URL $url.";
        return;
    }

    # sanitize the IP - Ipv4 or Ipv6 character set only
    if ( $ip !~ qr{^[0-9a-f\.:]+$}i ) {

        # could also use FATAL - be relax for now to avoid false positives
        WARN "Invalid IP address '$ip' returned by $url";
        return;
    }

    return $ip;
}

sub verify_url {
    my ($ip) = @_;
    $ip ||= '';

    return qq[https://verify.cpanel.net/xml/verifyfeed?ip=$ip];
}

#
#   block cPanel&WHM install when a DNSONLY license is valid for the server
#   block DNSONLY license when a cPanel license is valid for the server
#
sub check_license_conflict {

    my $ip = guess_ip();

    # skip check and continue install if we cannot guess up
    return unless defined $ip;

    INFO "Checking for existing active license linked to IP '$ip'.";

    my $verify_license_xml = q[verify.license.xml];

    my $url = verify_url($ip);

    # check verify.cpanel.net - the xml one...
    _wget_to_file( $url, $verify_license_xml );

    my $active_basepkg = 0;
    my $package        = "";
    {
        open( my $fh, '<', $verify_license_xml ) or FATAL("Cannot read file $verify_license_xml.");
        while ( my $line = <$fh> ) {
            next unless $line =~ m/status="1"/;     # package is active
            next unless $line =~ m/basepkg="1"/;    # package is a base package (skipping packages like kernelcare, cloudlinux & co)
            if ( $line =~ m/producttype="([0-9]+)"/ ) {
                $active_basepkg = $1;

                $line =~ m/package="([^"]+)"/;
                $package = $1;

                last;
            }
        }
    }

    return unless $active_basepkg;

    if ( is_dnsonly() ) {

        # we cannot install dnsonly if a cPanel license exists
        if ( $active_basepkg != 64 ) {

            ERROR "Unexpected license type found for your IP: https://verify.cpanel.net/app/verify?ip=$ip";
            ERROR "Current active package is $package";
            FATAL "Installation aborted. Perhaps you meant to install latest instead of latest-dnsonly? If not please cancel your cPanel license before installing a cPanel DNSONLY server.";
        }
    }
    else {
        # we cannot install cPanel if a dnsonly license exists
        if ( $active_basepkg & PRODUCT_DNSONLY ) {
            ERROR "Unexpected license type found for your IP: https://verify.cpanel.net/app/verify?ip=$ip";
            FATAL "Installation aborted. Perhaps you meant to install latest-dnsonly instead of latest? If not please cancel your DNSONLY license before installing a cPanel & WHM server.";
        }
    }

    # everything is fine at this point
    return;
}

sub _wget_to_file {
    my ( $url, $file ) = @_;

    if ( !defined $wget_bin || !defined $wget_args ) {    # should be performed earlier but easier for testing
        ( $wget_bin, $wget_args ) = get_download_tool_binary();
    }

    my $max = 3;
    foreach my $iter ( 1 .. $max ) {
        unlink $file;
        `$wget_bin $wget_args '$file' $url 2>&1`;
        return 1 if $? == 0;
        if ( $iter == $max ) {
            FATAL "Failed to call URL $url to check your license status.";
        }
        WARN("Call to URL '$url' fails, giving it another try. [$iter/$max]");
        sleep 3;
    }

    return;
}

sub _MSG {
    my $level = shift;
    my $msg = shift || '';
    chomp $msg;

    my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime;
    my ( $package, $filename, $line ) = caller($message_caller_depth);
    my $stamp_msg = sprintf( "%04d-%02d-%02d %02d:%02d:%02d %4s [%d] (%5s): %s\n", $year + 1900, $mon + 1, $mday, $hour, $min, $sec, $line, $$, $level, $msg );

    print {$log_fh} $stamp_msg;
    if ( defined $collect_output ) {
        $collect_output .= $stamp_msg;
    }
    else {
        print $stamp_msg;
    }
    return;
}

# Code previously located in the bootstrap script.
sub bootstrap {
    my ( $distro, $distro_version ) = @_;

    # Confirm perl version.
    if ( $] < 5.008 ) {
        print "This installer requires Perl 5.8.0 or better.\n";
        die "Cannot continue.\n";
    }

    validate_rhn_registration( $distro, $distro_version );
    validate_cloudlinux_registration( $distro, $distro_version );

    ( $wget_bin, $wget_args ) = get_download_tool_binary();
    $gpg_bin = gpg_bin();

    setup_empty_directories($distro);

    # Setup yum/up2date touch files.
    setup_update_config( $distro, $distro_version );

    _fetch_gpg_key_once();
    return;
}

sub do_clock_update {

    # Sync the clock.
    if ( !update_system_clock() ) {
        WARN( "The current system time is set to: " . `date` );
        WARN("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        WARN("The installation process could not verify the system time. The utility to set time from a remote host, rdate, is not installed.");
        WARN("If your system time is incorrect by more than a few hours, source compilations will subtly fail.");
        WARN("This issue may result in an overall installation failure.");
        WARN("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }
    return;
}

sub setup_empty_directories {
    my $distro = shift or die;

    # mkdir some directories.
    INFO 'The installation process will now set up the necessary empty cpanel directories.';

    foreach my $dir (qw{/usr/local/cpanel /usr/local/cpanel/base /usr/local/cpanel/base/frontend /usr/local/cpanel/logs /var/cpanel /var/cpanel/tmp /var/cpanel/version /var/cpanel/perl}) {
        unlink $dir if ( -f $dir || -l $dir );

        if ( !-d $dir ) {
            DEBUG "mkdir $dir";
            mkdir( $dir, 0755 );
        }
    }

    foreach my $dir (qw{/var/cpanel/logs}) {
        unlink $dir if ( -f $dir || -l $dir );

        if ( !-d $dir ) {
            DEBUG "mkdir $dir";
            mkdir( $dir, 0700 );
        }
    }

    return;
}

sub setup_update_config {
    my ( $distro, $distro_version ) = @_;

    # legacy files
    unlink('/var/cpanel/useup2date');
    unlink('/var/cpanel/useyum');
    touch('/var/cpanel/yum_rhn') if $distro eq 'redhat';

    INFO("The installation process will now ensure that GPG is set up properly before it imports keys.");
    system(qw{gpg --list-keys});

    INFO("The installation process will now import GPG keys for yum.");
    if ( -e '/usr/share/rhn/RPM-GPG-KEY' ) {
        system( 'gpg', '--import', '/usr/share/rhn/RPM-GPG-KEY' );
        system( 'rpm', '--import', '/usr/share/rhn/RPM-GPG-KEY' );
    }

    if ( !-e '/etc/yum.conf' && -e '/etc/centos-yum.conf' ) {
        INFO("The system will now set up yum from the /etc/centos-yum.conf file.");
        system(qw{cp -f /etc/centos-yum.conf /etc/yum.conf});
    }
    return;
}

sub validate_registration {
    my ( $distro, $distro_version, $opts ) = @_;

    INFO("Checking the $opts->{'distro_name'} registration for updates...");
    local $ENV{'TERM'} = 'dumb';
    my $registered = `yum list < /dev/null 2>&1`;

    if (   $registered =~ m/not register|Please run rhn_register/ms
        && $registered !~ /is receiving updates/ms ) {
        ERROR("When you use $opts->{'full_distro_name'}, you must register ");
        ERROR("with the $opts->{'distro_name'} Network before you install cPanel & WHM.");
        ERROR("Run the following command to register your server: $opts->{'register_command'} ");
        FATAL("The installation process will now terminate...");
    }
    return;
}

sub validate_cloudlinux_registration {
    my ( $distro, $distro_version ) = @_;

    # Short here if not CloudLinux.
    return if ( $distro ne 'cloud' );

    validate_registration(
        $distro,
        $distro_version,
        {
            distro_name      => _distro_name($distro),
            full_distro_name => _distro_name( $distro, 1 ),
            register_command => '/usr/sbin/clnreg_ks --force',
        }
    );
    return;
}

sub validate_rhn_registration {
    my ( $distro, $distro_version ) = @_;

    # Short here if not redhat
    return if ( $distro ne 'redhat' );

    validate_registration(
        $distro,
        $distro_version,
        {
            distro_name      => _distro_name($distro),
            full_distro_name => _distro_name( $distro, 1 ),
            register_command => '/usr/sbin/rhn_register',
        }
    );

    my @channels = `/usr/bin/yum repolist enabled`;
    INFO("Validating that the system subscribed to the optional RHN channel...");

    # optional channel validated.
    return if grep { m/-optional(?:-\d|-rpms|\/7Server)/ } @channels;

    my $optional_channel;
    foreach my $channel (@channels) {
        chomp $channel;

        # On RHEL 6, this line looks like this:
        # rhel-6-server-rpms                   Red Hat Enterprise Linux 6 Server (RPMs)
        # On RHEL 7, it looks like this:
        # rhel-7-server-rpms/7Server/x86_64                       Red Hat Enterprise Linux 7 Server (RPMs)                                  13,357
        next if ( $channel !~ /^[!*]?(rhel-([\dxi_]+)-server-(\d+|rpms))[\s\/]+.*$/i );
        $channel          = $1;
        $optional_channel = $channel;
        $optional_channel =~ s/-server-6/-server-optional-6/;
        $optional_channel =~ s/-server-rpms/-server-optional-rpms/;
    }
    if ( !$optional_channel ) {
        ERROR("The server is not registered with a known Red Hat base channel.");
        ERROR('$> /usr/bin/yum repolist enabled');
        ERROR(`/usr/bin/yum repolist enabled`);
        exit 8;
    }

    ERROR("cPanel & WHM requires you to subscribe to the RHEL $distro_version optional channel, to get all of the needed packages.");
    ERROR("cPanel & WHM will not function without this channel. Check your subscriptions and then rerun the installer.");
    ERROR(" ");
    ERROR("Please run the following command: /usr/sbin/spacewalk-channel --add --channel=$optional_channel");
    ERROR("Or, for newer versions, run the following command: /usr/sbin/subscription-manager attach --auto");
    ERROR(" ");
    ERROR("You can register to the optional channel at http://rhn.redhat.com.");
    FATAL("Terminating...");
    return;
}

sub get_download_tool_binary {

    for my $bin (qw(/bin/wget /usr/bin/wget /usr/local/bin/wget)) {
        next if ( !-e $bin );
        next if ( !-x _ );
        next if ( -z _ );
        return ( $bin, '-q --no-dns-cache --tries=20 --timeout=60 --dns-timeout=60 --read-timeout=30 --waitretry=1 --retry-connrefused -O' ) if ( `$bin --version` =~ m/GNU\s+Wget\s+\d+\.\d+/ims );
    }

    FATAL "The installation process could not find the wget binary. Install it to a standard location.";
    return;
}

sub gpg_bin {

    for my $bin (qw(/bin/gpg /usr/bin/gpg /usr/local/bin/gpg)) {
        next if ( !-e $bin );
        next if ( !-x _ );
        next if ( -z _ );
        return $bin;
    }

    FATAL "The installation process could not find the gpg binary. Install it to a standard location.";
    return;
}

# This code is somewhat of a duplication of the code for updatenow that blocks updates based on configuration
# settings. It needs to be here also because of the bootstrap level nature for when this needs to run.
sub check_for_install_version_blockers {
    my ( $distro, $distro_version, $distro_arch, $force ) = @_;

    my $lts_version = get_lts_version();
    my $tier        = get_cpanel_tier();
    $lts_version or FATAL("The system could not determine the target version from your tier: $tier");

    if ( $lts_version < 69 ) {
        FATAL("You cannot install versions of cPanel & WHM prior to cPanel & WHM version 70.");
    }

    if ( $distro =~ m/bsd/i ) {
        FATAL "cPanel & WHM does not support BSD.";
    }

    if ( $distro_version < 6 || $distro_arch ne 'x86_64' ) {
        FATAL "Starting with version 57, cPanel & WHM supports 64-bit versions of CentOS 6+, Red Hat Enterprise Linux® 6+, and CloudLinux™ 6+ only.";
    }

    # pull in cpanel.config settings or return if the file's not there (defaults will assert)
    return if ( !-e '/var/cpanel/cpanel.config' );
    my $cpanel_config = read_config('/var/cpanel/cpanel.config');

    if ( defined $cpanel_config->{'mysql-version'} ) {
        my $recommended_mysql_version = _get_recommended_mysql_version($lts_version);
        my $is_mysql_version_good     = $cpanel_config->{'mysql-version'} >= $recommended_mysql_version;
        if ( !$is_mysql_version_good ) {
            FATAL "You must set MySQL® to version $recommended_mysql_version or higher in the /var/cpanel/cpanel.config file for cPanel & WHM version $lts_version.";
        }
    }

    if ( defined $cpanel_config->{'mailserver'} && $cpanel_config->{'mailserver'} =~ m/^courier$/i ) {
        FATAL "You must use 'dovecot' or 'disabled' for the mailserver in the /var/cpanel/cpanel.config file for cPanel & WHM version $lts_version.";
    }

    return;
}

sub update_system_clock {
    my @rdate_bin =
        -x '/usr/bin/rdate'        ? ( '/usr/bin/rdate',        '-s', 'rdate.cpanel.net' )
      : -x '/usr/local/bin/rdate'  ? ( '/usr/local/bin/rdate',  '-s', 'rdate.cpanel.net' )
      : -x '/usr/local/sbin/rdate' ? ( '/usr/local/sbin/rdate', '-s', 'rdate.cpanel.net' )
      : -x '/bin/rdate'            ? ( '/bin/rdate',            '-s', 'rdate.cpanel.net' )
      :                              ();

    # Complain if we don't have an rdate binary.
    if ( !@rdate_bin ) {
        ERROR("The system could not set the system clock because an rdate binary is missing.");
        return;
    }

    # Set the clock
    my $was = time();
    ssystem(@rdate_bin);
    my $now = time();
    INFO( "The system set the clock to: " . localtime($now) );
    my $change = $now - $was;

    # Adjust the start time if it shifted more than 10 seconds.
    if ( abs($change) > 10 ) {
        WARN("The system changed the clock by $change seconds.");
        $installstart += $change;
        WARN( "The system adjusted the starting time to " . localtime($installstart) . "." );
    }
    else {
        INFO("The system changed the clock by $change seconds.");
    }

    return 1;
}

sub guess_version_from_tier {
    my $tier = shift || 'release';

    if ( defined( $TIER_CACHE{$tier} ) ) {
        return $TIER_CACHE{$tier};
    }

    # Support version numbers as tiers.
    if ( $tier =~ /^\s*\d+\.\d+\.\d+\.\d+\s*$/ ) {
        $TIER_CACHE{$tier} = $tier;
        return $tier;
    }

    # Download the file.
    cpfetch('/cpanelsync/TIERS');
    -e 'TIERS' or FATAL('The installation process could not fetch the /cpanelsync/TIERS file from the httpupdate server.');

    # Parse the downloaded TIERS data for our tier. (Stolen from Cpanel::Update)
    open( my $fh, '<', 'TIERS' ) or FATAL("The system could not read the downloaded TIERS file.");
    while ( my $tier_definition = <$fh> ) {
        chomp $tier_definition;
        next if ( $tier_definition =~ m/^\s*#/ );    # Skip commented lines.
        ## e.g. edge:11.29.0 (requires two dots)
        next if ( $tier_definition !~ m/^\s*([^:\s]+)\s*:\s*(\S+)/ );

        my ( $remote_tier, $remote_version ) = ( $1, $2 );
        $TIER_CACHE{$remote_tier} = $remote_version;
    }
    close $fh;

    # Set any disabled tiers to install-fallback if possible.
    foreach my $key ( keys %TIER_CACHE ) {
        next if $key eq 'install-fallback';
        if ( $TIER_CACHE{$key} && $TIER_CACHE{'install-fallback'} && $TIER_CACHE{$key} eq 'disabled' ) {
            $TIER_CACHE{$key} = $TIER_CACHE{'install-fallback'};
        }
    }

    # Fail if the tier is not present.
    if ( !$TIER_CACHE{$tier} ) {
        FATAL("The specified tier ('$tier') in the /etc/cpupdate.conf file is not a valid cPanel & WHM tier.");
    }

    # Fail if the tier is still disabled.
    if ( $TIER_CACHE{$tier} eq 'disabled' ) {
        FATAL("cPanel has temporarily disabled updates on the central httpupdate servers. Please try again later.");
    }

    return $TIER_CACHE{$tier};
}

sub get_cpanel_version {
    my $tier    = get_cpanel_tier();
    my $version = guess_version_from_tier($tier);
    return $version;
}

sub get_cpanel_tier {

    # Pull in cpupdate.conf settings.
    my $cpupdate_conf = read_config('/etc/cpupdate.conf');

    # Determine tier or assume defaults.
    my $tier = $cpupdate_conf->{'CPANEL'} || 'release';

    # version numbers without 11.
    if ( $tier =~ /^\d+/ && $tier !~ /^11\./ ) {
        $tier = '11.' . $tier;
    }

    return $tier;
}

sub get_lts_version {

    my $cpanel_version = get_cpanel_version();
    my ( undef, $lts_version ) = split( qr/\./, $cpanel_version );

    return $lts_version;
}

sub create_feature_showcase_dir {
    return if -e '/var/cpanel/activate/features';
    ssystem( 'mkdir', '-p', '/var/cpanel/activate/features' );
    ssystem( 'chown', '-R', 'root:root', '/var/cpanel/activate' );
    ssystem( 'chmod', '-R', '0700', '/var/cpanel/activate' );
    return;
}

sub _distro_name {
    my ( $distro, $full ) = @_;
    for my $names (
        [ 'centos', 'CentOS',       'CentOS' ],
        [ 'redhat', 'Red Hat',      'Red Hat Enterprise Linux®' ],
        [ 'cloud',  'CloudLinux',   'CloudLinux™' ],
        [ 'amazon', 'Amazon Linux', 'Amazon Linux' ],
    ) {
        return $names->[ $full ? 2 : 1 ] if $distro eq $names->[0];
    }
    return $distro;
}

sub _verify_file {
    my ( $file, $sig, $url ) = @_;

    _fetch_gpg_key_once();

    my @gpg_args = (
        '--logger-fd', '1',
        '--status-fd', '1',
        '--homedir',   gpg_homedir(),
        '--verify',    $sig,
        $file,
    );

    # Verify the validity of the GPG signature.
    # Information on these return values can be found in 'doc/DETAILS' in the GnuPG source.

    my ( %notes, $curnote );
    my ( $gpg_out, $success, $status );
    my $gpg_pid = IPC::Open3::open3( undef, $gpg_out, undef, $gpg_bin, @gpg_args );

    while ( my $line = readline($gpg_out) ) {
        if ( $line =~ /^\[GNUPG:\] VALIDSIG ([A-F0-9]+) (\d+-\d+-\d+) (\d+) ([A-F0-9]+) ([A-F0-9]+) ([A-F0-9]+) ([A-F0-9]+) ([A-F0-9]+) ([A-F0-9]+) ([A-F0-9]+)$/ ) {
            $status  = "Valid signature for $file";
            $success = 1;
        }
        elsif ( $line =~ /^\[GNUPG:\] NOTATION_NAME (.+)$/ ) {
            $curnote = $1;
            $notes{$curnote} = '';
        }
        elsif ( $line =~ /^\[GNUPG:\] NOTATION_DATA (.+)$/ ) {
            $notes{$curnote} .= $1;
        }
        elsif ( $line =~ /^\[GNUPG:\] BADSIG ([A-F0-9]+) (.+)$/ ) {
            $status = "Invalid signature for $file.";
        }
        elsif ( $line =~ /^\[GNUPG:\] NO_PUBKEY ([A-F0-9]+)$/ ) {
            $status = "Could not find public key ($1) in keychain.";
        }
        elsif ( $line =~ /^\[GNUPG:\] NODATA ([A-F0-9]+)$/ ) {
            $status = "Could not find a GnuPG signature in the signature file.";
        }
    }

    waitpid( $gpg_pid, 0 );

    $status ||= "Unknown error from gpg.";
    $status .= " (file:$file, sig:$sig)";

    if ($success) {
        INFO $status;
    }
    else {
        FATAL $status;
    }

    # At this point, the signature should be valid.
    # We now need to check to see if the filename signature notation is correct.

    $url =~ s/\.bz2$//;

    if ( defined( $notes{'filename@gpg.notations.cpanel.net'} ) ) {
        my $file_note = $notes{'filename@gpg.notations.cpanel.net'};
        if ( $file_note ne $url ) {
            FATAL "Filename notation ($file_note) does not match URL ($url).";
        }
    }
    else {
        FATAL "Signature does not contain a filename notation.";
    }

    return;
}

our $_gpg_setup;

sub _fetch_gpg_key_once {

    return if $_gpg_setup;

    my $pub_keys = public_keys();
    _create_gpg_homedir();

    foreach my $key ( @{ keys_to_download() } ) {
        INFO("Downloading GPG public key, $pub_keys->{$key}");
        my $target   = secure_downloads() . $pub_keys->{$key};
        my $dest     = gpg_homedir() . "/" . $pub_keys->{$key};
        my $wget_cmd = $wget_args . " " . $dest . " " . $target;
        my $wget_out = `$wget_bin $wget_cmd`;
        if ( !-e $dest ) {
            FATAL("Could not download GPG public key at $target : $wget_out");
            return;
        }
        INFO("Importing downloaded GPG public key from “$dest”.");
        my $gpg_cmd = $gpg_bin . " -q --homedir " . gpg_homedir() . " --import " . $dest;
        my $output  = `$gpg_cmd 2>&1`;
        if ( $? != 0 ) {
            WARN("Failed to import GPG public key from “$dest”: $output");
        }
    }

    $ENV{'CPANEL_BASE_INSTALL_GPG_KEYS_IMPORTED'} = 1;    # in v82+ fix-cpanel-perl will skip gpg keyimport if set
    $_gpg_setup = 1;

    return;
}

sub _create_gpg_homedir {
    mkdir( gpg_homedir(), 0700 ) if !-e gpg_homedir();
    return;
}

sub signatures_enabled {

    my $config = read_config('/var/cpanel/cpanel.config');
    my $is_enabled = ( defined $config->{'signature_validation'} && $config->{'signature_validation'} eq 'Off' ) ? 0 : 1;

    return $is_enabled;
}

sub keys_to_download {

    my $config   = read_config('/var/cpanel/cpanel.config');
    my $keyrings = gpg_keyrings();

    if ( !defined $config->{'signature_validation'} ) {
        my $mirror = get_update_source();

        if ( $mirror =~ /^(?:.*\.dev|qa-build|next)\.cpanel\.net$/ ) {
            return $keyrings->{'development'};
        }
        else {
            return $keyrings->{'release'};
        }
    }
    elsif ( $config->{'signature_validation'} =~ /^Release and (?:Development|Test) Keyrings$/ ) {
        return $keyrings->{'development'};
    }
    else {
        return $keyrings->{'release'};
    }
}

sub gpg_homedir {
    return '/var/cpanel/.gpgtmpdir';
}

sub public_keys {
    return {
        'release'     => 'cPanelPublicKey.asc',
        'development' => 'cPanelDevelopmentKey.asc',
    };
}

sub secure_downloads {
    return 'https://securedownloads.cpanel.net/';
}

sub gpg_keyrings {
    return {
        'release'     => ['release'],
        'development' => [ 'release', 'development' ],

    };
}

sub has_kernel_plus_headers {
    my $rpm_query = `rpm -q --nodigest --nosignature kernel-plus-headers`;
    return $rpm_query =~ /not installed/ ? 0 : 1;
}

sub has_yum_plugin_fastestmirror {
    my $rpm_query = `rpm -q --nodigest --nosignature yum-plugin-fastestmirror`;
    return $rpm_query =~ /not installed/ ? 0 : 1;
}

sub get_hostname_via_getnameinfo {
    return undef if !Socket->can('getaddrinfo');

    my ( $err, @getaddr ) = Socket::getaddrinfo(
        get_main_ip(),
        undef,
        {
            family   => Socket::AF_UNSPEC(),
            protocol => Socket::IPPROTO_TCP(),
        }
    );

    for my $addr (@getaddr) {
        my ( $err, $host, $service ) = Socket::getnameinfo( $addr->{addr}, Socket::NI_NAMEREQD() );
        if ( defined $host ) {
            return $host;
        }
    }

    return undef;
}

# Copied from Cpanel::DIp::MainIP
sub get_main_ip {
    foreach my $ip ( split( /\n/, `/sbin/ip -4 addr show` ) ) {
        if ( $ip =~ m{ [\s\:] (\d+ [.] \d+ [.] \d+ [.] \d+) }xms ) {
            my $thisip = $1;
            if ( !is_loopback($thisip) ) {
                return $thisip;
            }
        }
    }
    return 0;
}

# Copied from Cpanel::IP::Loopback
sub is_loopback {
    return (
        length $_[0]
          && (
            $_[0] eq 'localhost'                                     #
            || $_[0] eq 'localhost.localdomain'                      #
            || $_[0] eq '0000:0000:0000:0000:0000:0000:0000:0001'    #
            || ( length $_[0] >= 32 && substr( $_[0], 0, 32 ) eq '0000:0000:0000:0000:0000:ffff:7f' )    # ipv4 inside of ipv6 match 127.*
            || ( length $_[0] >= 11 && substr( $_[0], 0, 11 ) eq '::ffff:127.' )                         # ipv4 inside of ipv6 match 127.*
            || ( length $_[0] >= 4  && substr( $_[0], 0, 4 ) eq '127.' )                                 # ipv4 needs to match 127.*
            || $_[0] eq '0:0:0:0:0:0:0:1'                                                                #
            || $_[0] eq ':1'                                                                             #
            || $_[0] eq '::1'                                                                            #
            || $_[0] eq '(null)'                                                                         #
            || $_[0] eq '(null):0000:0000:0000:0000:0000:0000:0000'                                      #
            || $_[0] eq '0000:0000:0000:0000:0000:0000:0000:0000'                                        #
            || $_[0] eq '0.0.0.0'
          )                                                                                              #
    ) ? 1 : 0;
}

# Copied from Cpanel::Sys::Hostname::FQDN
sub get_fqdn_hostname {
    my $hostname_from_sys_hostname = Sys::Hostname::hostname();
    $hostname_from_sys_hostname =~ tr{A-Z}{a-z};

    my $hostname_from_getnameinfo = get_hostname_via_getnameinfo() || "";

    if ( !length $hostname_from_getnameinfo ) {
        return $hostname_from_sys_hostname;
    }

    $hostname_from_getnameinfo =~ tr{A-Z}{a-z};

    if ( index( $hostname_from_getnameinfo, $hostname_from_sys_hostname ) == 0 ) {
        return $hostname_from_getnameinfo;
    }

    return $hostname_from_sys_hostname;
}

# These packages are needed for MySQL later in the install
# By installing them now we do not have to wait for
# download
sub background_download_packages_used_during_initial_install {
    my @sysup_packages_to_install         = qw{python python-devel python-docs python-setuptools quota quota-devel expat expat-devel};
    my @ea4_packages_to_install           = qw{elinks js libssh2 libssh2-devel libvpx nss_compat_ossl scl-utils perl-libwww-perl krb5-devel perl-Compress-Raw-Bzip2 perl-Compress-Raw-Zlib autoconf automake};
    my @mysql_support_packages_to_install = qw{numactl-libs grep shadow-utils coreutils perl-DBI};
    my @packages_to_install               = ( @mysql_support_packages_to_install, @sysup_packages_to_install, @ea4_packages_to_install );
    if ( my $pid = fork() ) {

        # Parent
        return $pid;
    }
    else {
        $collect_output = '';
        my @epel;
        if ( -e "/etc/yum.repos.d/epel.repo" ) {    # for ea4
            @epel = ('--enablerepo=epel');
        }
        local $@;
        eval { yum_nohang_ssystem( '/usr/bin/yum', @epel, '--downloadonly', '-y', 'install', @packages_to_install ); };
        print $collect_output;
        undef $collect_output;
        die if $@;

        exit(0);
    }
    die "Failed to fork to create background rpm download: $!";
}

# Copied from Cpanel::RpmUtils::Parse
sub parse_rpm_arch {
    my ($filename) = @_;

    #
    # Example:
    #
    # cpanel-perl-522-Acme-Bleach-1.150-1.cp1156.x86_64.rpm
    # ea-php70-libc-client-2007f-7.7.1.x86_64
    # glibc-common-2.12-1.192.el6.x86_64.rpm
    #
    $filename =~ s{\.rpm$}{};

    my @rpm_parts = split( /\./, $filename );

    my $arch = pop @rpm_parts;    # x86_64     (glibc-common-2.12-1.192.el6)

    my $name_with_version = join( '.', @rpm_parts );    # glibc-common-2.12-1.192.el6

    my $name_version_parse = parse_rpm($name_with_version);

    return {
        'arch' => $arch,
        %$name_version_parse,
    };
}

# Copied from Cpanel::RpmUtils::Parse
sub parse_rpm {
    my ($name_with_version) = @_;
    my @name_version_parts = split( m{-}, $name_with_version );

    my $release = pop @name_version_parts;    # 1.192.el6  (glibc-common-2.12)
    my $version = pop @name_version_parts;    # 2.12  (glibc-common)

    my $name = join( '-', @name_version_parts );
    $name =~ s/^\d+://;                       # TODO/YAGNI: include epoch (or lack thereof) in results?

    return {
        'release' => $release,
        'version' => $version,
        'name'    => $name
    };
}

sub _get_recommended_mysql_version {
    my $version = shift;
    return ( $version < 79 ) ? 5.5 : 5.6;
}

sub max {
    my ( $a, $b ) = @_;

    return $a > $b ? $a : $b;
}

sub version_cmp {
    my ( $a, $b ) = @_;

    my @parts_a = split /\./, $a;
    my @parts_b = split /\./, $b;

    my $len = max( scalar @parts_a, scalar @parts_b );

    for ( my $i = 0; $i < $len; $i++ ) {
        my $part_a = $parts_a[$i];
        my $part_b = $parts_b[$i];

        return 1  unless defined $part_b;
        return -1 unless defined $part_a;

        my $result = $part_a <=> $part_b;

        return $result unless $result == 0;
    }

    return 0;
}

sub version_lt {
    my ( $a, $b ) = @_;
    return version_cmp( $a, $b ) < 0 ? 1 : 0;
}

sub version_gte {
    my ( $a, $b ) = @_;
    return version_cmp( $a, $b ) > -1 ? 1 : 0;
}

sub is_valid_hostname {
    my $domain = shift;

    if ( !defined $domain ) {
        return;
    }

    # No blank or space characters
    if ( $domain =~ m/\s+/ ) {
        return;
    }

    if ( $domain =~ m/[.]{2,}/ ) {
        return;
    }

    # Can not end with period
    if ( $domain =~ m/[.]$/ ) {
        return;
    }

    # Can not end with minus sign
    if ( $domain =~ m/[-](?=[.]|\z)/ ) {
        return;
    }

    # Must be able to fit in struct utsname
    if ( length $domain > 64 ) {
        return;
    }

    # Can't have an all-numeric TLD or be an IP address
    if ( $domain =~ m/\.\d+\z/ ) {
        return;
    }

    # Must start with alpha numeric, and must have atleast one 'label' part - i.e., label.domain.tld
    if ( $domain =~ /^(?:[a-z0-9][a-z0-9\-]*\.){2,}[a-z0-9][a-z0-9\-]*$/i ) {
        return 1;
    }

    return;
}

1;

404 Not Found
[ LogOut ]