MOON
Server: Apache/2.2.31 (Unix) mod_ssl/2.2.31 OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4
System: Linux csr818.wilogic.com 2.6.18-419.el5xen #1 SMP Fri Feb 24 22:50:37 UTC 2017 x86_64
User: digitals (531)
PHP: 5.4.45
Disabled: NONE
Upload Files
File: //proc/self/root/scripts.20110531.215904.25158/courierup
#!/usr/bin/perl
# cpanel - courierup                              Copyright(c) 2010 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

BEGIN { unshift @INC, '/usr/local/cpanel', '/scripts'; }

use strict;
use IPC::Open3                   ();
use cPpkgversions                ();
use Cpanel::OSSys                ();
use Cpanel::DataStore            ();
use Cpanel::HttpRequest          ();
use Cpanel::AccessIds::SetUids   ();
use Cpanel::cPServices           ();
use Cpanel::CourierConfig        ();
use Cpanel::SafeRun::Errors      ();
use Cpanel::Logger               ();
use Cpanel::FileUtils::TouchFile ();
use Cpanel::Sys::OS              ();
use Cpanel::Hostname             ();
use Cpanel::SafeFile             ();
use Cpanel::RpmStor              ();
use Cpanel::RpmUtils             ();
use Cpanel::Config::LoadCpConf   ();
use Cpanel::Update               ();

Cpanel::Update::safe_update_environment('courier');
Cpanel::Update::init_UP_update('courier');

my $logger = Cpanel::Logger->new();

my $previous_courierversion = Cpanel::CourierConfig::get_courier_version_from_binary();
my $cpconf_ref              = Cpanel::Config::LoadCpConf::loadcpconf();

# Check that Courier is the configured IMAP server and that system is Maildir format
if ( defined $cpconf_ref->{'mailserver'} && $cpconf_ref->{'mailserver'} ne 'courier' ) {
    print "Courier is not the configured IMAP server.\n";
    print "Use /scripts/setupmailserver to change this setting.\n";
    exit 0;
}

if ( !$cpconf_ref->{'maildir'} ) {
    print "This system is currently configured to use mbox formatted\n";
    print "mailboxes.  Courier support is only available on systems\n";
    print "using the maildir format.\n";
    print "Use /scripts/convert2maildir to change this setting.\n";
    exit 0;
}

my $buildnum = 0;
my $pkg      = 'courier-imap';
my $pkgver;
my $hostname = Cpanel::Hostname::gethostname();
my @PKGLIST;

my $httpClient = Cpanel::HttpRequest->new( 'hideOutput' => 0 );

my ( $system, $nodename, $release, $version, $machine ) = Cpanel::OSSys::uname();
my $arch = $machine;
if ( $machine =~ /i.86/ ) {
    $arch = 'i386';
}

print "$pkg Setup Script Version 1.0\n";
$ENV{'PATH'} = $ENV{'PATH'} . ':/usr/sbin';
$ENV{'HOME'} = ( getpwnam('root') )[7];

my $force    = 0;
my $latest   = 0;
my $src      = 0;
my $verbose  = 0;
my $reconfig = 0;
while ( $#ARGV != -1 ) {
    $_ = $ARGV[0];
    if (/^\-\-/) {
        my $arg = shift(@ARGV);
        $arg =~ s/^\-\-//g;
        $arg =~ tr/[A-Z]/[a-z]/;
        if ( $arg eq 'verbose' )  { $verbose  = 1; }
        if ( $arg eq 'source' )   { $src      = 1; }
        if ( $arg eq 'latest' )   { $latest   = 1; }
        if ( $arg eq 'force' )    { $force    = 1; }
        if ( $arg eq 'reconfig' ) { $reconfig = 1; }
    }
    else {
        last;
    }
}

if ( $ARGV[0] =~ m/source/ ) {
    $src = 1;
}

if ( -e '/etc/gentoo-release' ) {
    die 'Fixme: Gentoo';
}

if ($reconfig) {
    setup_authdaemon_access();
    buildconfig();
    exit;
}

if ( !-e '/var/spool/cpupdates' ) { mkdir( '/var/spool/cpupdates', 0700 ); }

if ( -x '/scripts/precourierup' ) {
    system('/scripts/precourierup');
}

Cpanel::cPServices::servicemod( 'apop3d', 0 );
if ( -e '/etc/xinetd.d/apop3d' ) {
    unlink('/etc/xinetd.d/apop3d');
    system 'killall', '-HUP', 'xinetd';
}
Cpanel::SafeRun::Errors::saferunnoerror( 'killall', '-TERM', 'apop3d' );
Cpanel::SafeRun::Errors::saferunnoerror( 'killall', '-HUP',  'apop3d' );
Cpanel::SafeRun::Errors::saferunnoerror( 'killall', '-9',    'apop3d' );

check_migration();

if ( $system =~ /freebsd/i ) {
    freebsdcourierinstall();
}
else {
    if ( -e '/lib/libc.so.6' ) {
        my $libcv = `/lib/libc.so.6`;
        $libcv =~ /version\s+([\d\.]+)/;
        my $glibcversion = $1;
        if ( $glibcversion && $glibcversion < 2.1 ) {
            $src = 1;
            warn 'Old Glibc library. Rpms will be built from source';
        }
    }
    linuxcourierinstall();

}
setup_authdaemon_access();

if ( -x '/scripts/postcourierup' ) {
    system('/scripts/postcourierup');
}

print "Install Complete\n";

sub buildcourierrpm {
    require Cpanel::SysPkgs;
    my ( $verbose, $pkg, $pkgver, $buildnum ) = @_;
    my (@FILES);

    enablecompilers();

    my $syspkgobj = Cpanel::SysPkgs->new();
    if ( !$syspkgobj ) { die print "Could not create SysPkgs object\n"; }
    my @pkgs = ( 'rpm', 'rpm-build', 'db-devel', 'gdbm-devel', 'db1-devel', 'compat-db', 'ndbm-devel', 'libtool', 'libtool-libs', 'gcc-c++', 'expect', 'gcc-c++-devel' );
    $syspkgobj->install( 'pkglist' => \@pkgs );

    my $rpm = 'rpm';

    if ( -e '/usr/bin/rpmbuild' ) { $rpm = '/usr/bin/rpmbuild'; }

    my $basedir = ( getpwnam('cpanel') )[7];

    my $sleep_count = 0;

    my $pid;
    do {
        $pid = open( KR, '-|' );
        unless ( defined $pid ) {
            warn "cannot fork: $!";
            die 'bailing out' if $sleep_count++ > 6;
            sleep 10;
        }
    } until defined $pid;

    setuprpmbuildroot($basedir);
    system( 'chown', '-R', 'cpanel:cpanel', $basedir . '/rpm-build' );
    if ($pid) {
        print 'Building RPM...';
        while (<KR>) {
            if   ($verbose) { print; }
            else            { print '.'; }
            if (/^Wrote: (\S+)/) {
                my $file = $1;
                if ( $file =~ /.(64|86)\.rpm/ ) {
                    push( @FILES, $file );
                }
            }
        }
        close(KR);
        waitpid( $pid, 0 );
        print "Done\n";
    }
    else {
        my $file = fetchfile( "http://httpupdate.cpanel.net/courierinstall/${pkg}/${pkgver}-${buildnum}/src/${pkg}-${pkgver}-${buildnum}.src.rpm",
                "${basedir}/rpm-build/SRPMS/${pkg}-${pkgver}-${buildnum}.src.rpm" );
        my $compiler_gid = (getgrnam('compiler'))[2];
        Cpanel::AccessIds::SetUids::setuids('cpanel',$compiler_gid);
        $ENV{'HOME'} = $basedir;
        $ENV{'USERNAME'} = $ENV{'USER'} = 'cpanel';
        delete $ENV{'BASH_ENV'};
        open( RNULL, '<', '/dev/null' );
        my $rpid = IPC::Open3::open3( '<&RNULL', '>&STDOUT', '>&STDOUT', $rpm, '--rebuild', $file );
        close(RNULL);
        waitpid( $rpid, 0 );
        exit;
    }

    foreach my $file (@FILES) {
        Cpanel::RpmStor::rpmstor($file);
    }
    return @FILES;
}

sub setuprpmbuildroot {
    my $dir  = shift;
    my $arch = ( Cpanel::OSSys::uname() )[4];
    mkdir( "${dir}/rpm-build",              0700 );
    mkdir( "${dir}/rpm-build/tmp",          0700 );
    mkdir( "${dir}/rpm-build/SOURCES",      0700 );
    mkdir( "${dir}/rpm-build/SPECS",        0700 );
    mkdir( "${dir}/rpm-build/BUILD",        0700 );
    mkdir( "${dir}/rpm-build/SRPMS",        0700 );
    mkdir( "${dir}/rpm-build/RPMS",         0700 );
    mkdir( "${dir}/rpm-build/RPMS/i386",    0700 );
    mkdir( "${dir}/rpm-build/RPMS/${arch}", 0700 );
    open( RPMMACROS, ">", "${dir}/.rpmmacros" );
    print RPMMACROS '%_tmppath  ' . $dir . '/rpm-build/tmp' . "\n";
    print RPMMACROS '%_topdir  ' . $dir . '/rpm-build';
    print RPMMACROS "\n";
    close(RPMMACROS);

    $ENV{'TMP'} = $dir . '/rpm-build/tmp';

}

sub enablecompilers {
    my $user  = 'cpanel';
    my $group = 'compiler';
    if ( -e "/usr/sbin/pw" ) {
        system( "/usr/sbin/pw", "usermod", $user, "-g", $user, "-G", "${group},${user}" );
    }
    else {
        system( "/usr/sbin/usermod", "-g", $user, "-G", "${group},${user}", $user );
    }

}

sub freebsdcourierinstall {
    my @PKGLIST = ( 'gdbm', 'courier-authlib', 'courier-imap' );

    system '/scripts/checkmakeconf';
    system '/scripts/portsup';
    my $result;

    print "This is the $pkg installer for OS FreeBSD\n";

    my $needres  = 0;
    my $complete = 0;

    foreach my $pkg (@PKGLIST) {
        my $result;
        my (@GS) = ( '/scripts/installpkg', '--keepnew', $pkg );
        if ($force) {
            @GS = ( '/scripts/installpkg', '--force', $pkg );
        }
        open( RNULL, "<", "/dev/null" );
        my $pkgpid = IPC::Open3::open3( "<&RNULL", \*INS, \*INS, @GS );
        while (<INS>) {
            print;
            $result .= $_;
        }
        close(INS);
        close(RNULL);
        waitpid( $pkgpid, 0 );

        my $onelineresult = $result;
        $onelineresult =~ s/\n/ /g;

        if (   $result !~ /(^|(?<!Checking if)\s)\s*\S*${pkg}.*\salready\s+installed/m
            && $result !~ /${pkg}.*\sis\s+installed/m
            && $result !~ /${pkg}.*\sis\s+newer/m ) {
            $needres = 1;
        }
    }

    if ( $needres || -e '/etc/xinetd.d/cpimap' ) {

        buildconfig();

        if ( -x '/scripts/postcourierinstall' ) {
            system '/scripts/postcourierinstall';
        }

        rescourier();
    }
    else {
        checksrvd_tcp_check();
        print "No restart required\n";
    }
}

sub buildconfig {
    my $authdir = find_authdir();
    my $imapbin = find_imapbin();

    my $hasfam = Cpanel::SafeRun::Errors::saferunallerrors( 'ldd', $imapbin );

    my $courierversion = Cpanel::CourierConfig::get_courier_version_from_binary();
    my ( $cmajor,     $cminor,     $crelease )     = split( /\./, $courierversion );
    my ( $prevcmajor, $prevcminor, $prevcrelease ) = split( /\./, $previous_courierversion );

    print "Detected Courier Version from binary: MAJOR=$cmajor,MINOR=$cminor,REVISION=$crelease\n";

    my %COURIERCONF = %{ Cpanel::DataStore::fetch_ref('/var/cpanel/courierconfig.yaml') };

    # Disable IDLE functionality, too many problems to use
    $COURIERCONF{'imapd'}{'IMAP_ENHANCEDIDLE'}     = 0;
    $COURIERCONF{'imapd-ssl'}{'IMAP_ENHANCEDIDLE'} = 0;

    if ( !$COURIERCONF{'imapd'}{'MAXPERIP'} )            { $COURIERCONF{'imapd'}{'MAXPERIP'}            = 30; }
    if ( !$COURIERCONF{'imapd'}{'MAXDAEMONS'} )          { $COURIERCONF{'imapd'}{'MAXDAEMONS'}          = 50; }
    if ( !$COURIERCONF{'imapd'}{'IMAPDSTART'} )          { $COURIERCONF{'imapd'}{'IMAPDSTART'}          = 'YES'; }
    if ( !$COURIERCONF{'imapd-ssl'}{'MAXPERIP'} )        { $COURIERCONF{'imapd-ssl'}{'MAXPERIP'}        = 30; }
    if ( !$COURIERCONF{'imapd-ssl'}{'IMAPDSSLSTART'} )   { $COURIERCONF{'imapd-ssl'}{'IMAPDSSLSTART'}   = 'YES'; }
    if ( !$COURIERCONF{'pop3d'}{'MAXPERIP'} )            { $COURIERCONF{'pop3d'}{'MAXPERIP'}            = 30; }
    if ( !$COURIERCONF{'pop3d'}{'MAXDAEMONS'} )          { $COURIERCONF{'pop3d'}{'MAXDAEMONS'}          = 50; }
    if ( !$COURIERCONF{'pop3d'}{'POP3DSTART'} )          { $COURIERCONF{'pop3d'}{'POP3DSTART'}          = 'YES'; }
    if ( !$COURIERCONF{'pop3d-ssl'}{'MAXPERIP'} )        { $COURIERCONF{'pop3d-ssl'}{'MAXPERIP'}        = 30; }
    if ( !$COURIERCONF{'pop3d-ssl'}{'POP3DSSLSTART'} )   { $COURIERCONF{'pop3d-ssl'}{'POP3DSSLSTART'}   = 'YES'; }
    if ( !$COURIERCONF{'pop3d-ssl'}{'TLS_PROTOCOL'} )    { $COURIERCONF{'pop3d-ssl'}{'TLS_PROTOCOL'}    = ( $cmajor > 5 || ( $cmajor == 4 && $cminor >= 2 ) ? 'SSL23' : 'SSL3' ); }
    if ( !$COURIERCONF{'imapd-ssl'}{'TLS_PROTOCOL'} )    { $COURIERCONF{'imapd-ssl'}{'TLS_PROTOCOL'}    = ( $cmajor > 5 || ( $cmajor == 4 && $cminor >= 2 ) ? 'SSL23' : 'SSL3' ); }
    if ( !$COURIERCONF{'pop3d-ssl'}{'TLS_CIPHER_LIST'} ) { $COURIERCONF{'pop3d-ssl'}{'TLS_CIPHER_LIST'} = 'ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:-LOW:-SSLv2:-EXP'; }
    if ( !$COURIERCONF{'imapd-ssl'}{'TLS_CIPHER_LIST'} ) { $COURIERCONF{'imapd-ssl'}{'TLS_CIPHER_LIST'} = 'ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:-LOW:-SSLv2:-EXP'; }
    if ( !$COURIERCONF{'authdaemonrc'}{'daemons'} )      { $COURIERCONF{'authdaemonrc'}{'daemons'}      = 5; }

    if ( $prevcmajor == 4 && $prevcminor < 2 && ( $cmajor > 4 || ( $cmajor == 4 && $cminor >= 2 ) ) ) {
        $COURIERCONF{'pop3d-ssl'}{'TLS_PROTOCOL'} = 'SSL23';
        $COURIERCONF{'imapd-ssl'}{'TLS_PROTOCOL'} = 'SSL23';
    }

    #If courier gets downgraded then set the default
    if ( $prevcmajor == 4 && $prevcminor >= 2 && ( $cmajor < 4 || ( $cmajor == 4 && $cminor < 2 ) ) ) {
        $COURIERCONF{'pop3d-ssl'}{'TLS_PROTOCOL'} = 'SSL3';
        $COURIERCONF{'imapd-ssl'}{'TLS_PROTOCOL'} = 'SSL3';
    }

    foreach my $service (%COURIERCONF) {
        next if ( $service =~ /^auth/ );
        foreach my $configopt ( keys %{ $COURIERCONF{$service} } ) {
            Cpanel::CourierConfig::set_service_config_value( $service, $configopt, $COURIERCONF{$service}{$configopt} );
        }
    }

    if ( -e '/etc/inetd.conf' ) {
        require Cpanel::StringFunc;
        Cpanel::StringFunc::regsrep( '/etc/inetd.conf', '^\s*imap', "" );
    }
    unlink('/etc/xinetd.d/cpimap');
    unlink('/etc/xinetd.d/imap');

    Cpanel::CourierConfig::set_auth_config_value( 'daemons',        $COURIERCONF{'authdaemonrc'}{'daemons'} );
    Cpanel::CourierConfig::set_auth_config_value( 'authmodulelist', '"authpipe"' );
    Cpanel::CourierConfig::set_auth_config_value( 'LOGGEROPTS',     '"-facility=mail"' );
    unless ( -l "${authdir}/authProg" && readlink("${authdir}/authProg") eq '/usr/local/cpanel/bin/courier-auth' ) {
        unlink "${authdir}/authProg";
        symlink( "/usr/local/cpanel/bin/courier-auth", "${authdir}/authProg" );
    }
    system("/usr/local/cpanel/etc/init/startstunnel");
    system("/usr/local/cpanel/etc/init/stopcppop");
    Cpanel::SafeRun::Errors::saferunnoerror( "killall", "-HUP", "inetd" );
    Cpanel::SafeRun::Errors::saferunnoerror( "killall", "-HUP", "xinetd" );

    if ( $cmajor > 4 || $cmajor == 4 && $cminor >= 3 ) {
        if ( $COURIERCONF{'imapd'}{'migrationdone43'} ) {
            return;
        }
        courier_four_three_migration();
    }

}

sub rescourier {
    system( '/scripts/restartsrv', 'courier' );
}

sub linuxcourierinstall {

    my $ises;
    my $xdir;
    my $arch = 'i386';
    my $distro;
    if ( -e '/etc/trustix-release' ) {
        $distro = 'trustix';
        ($version) = Cpanel::Sys::OS::getversionfromfile('/etc/trustix-release');
        $arch = 'i586';
    }
    elsif ( -e '/etc/caos-release' ) {
        $distro = 'caos';
        ($version) = Cpanel::Sys::OS::getversionfromfile('/etc/caos-release');
    }
    elsif ( -e '/etc/SuSE-release' ) {
        $distro = 'suse';
        ($version) = Cpanel::Sys::OS::getversionfromfile('/etc/SuSE-release');
        if ( $version >= 9 ) { $arch = 'i586'; }
    }
    elsif ( -e '/etc/fedora-release' ) {
        $distro = 'fedora';
        ($version) = Cpanel::Sys::OS::getversionfromfile('/etc/fedora-release');
    }
    elsif ( -e '/etc/mandrake-release' ) {
        $distro = 'mandrake';
        ($version) = Cpanel::Sys::OS::getversionfromfile('/etc/mandrake-release');
        $arch = 'i586';
    }
    elsif ( -e '/etc/whitebox-release' ) {
        $distro = 'whitebox';
        ($version) = Cpanel::Sys::OS::getversionfromfile('/etc/whitebox-release');
    }
    elsif ( -e '/etc/redhat-release' ) {
        $distro = 'redhat';
        ( $version, $ises ) = Cpanel::Sys::OS::getversionfromfile('/etc/redhat-release');
    }

    if ( $ises == 1 ) {
        $version = 'AS-' . $version;
    }
    if ( $ises == 2 ) {
        $distro = 'centos';
    }
    if ( $ises == 3 ) {
        $distro = 'whitebox';
    }

    if ( $machine =~ /64/ ) {
        $arch = 'x86_64';
        $xdir .= '/64';
    }

    my $res   = 0;
    my %VINFO = cPpkgversions::getpkgversioninfo('courier');
    foreach my $pkg ( 'courier-authlib', 'courier-imap' ) {
        my $pkgname = $pkg;

        my $pkgver   = $VINFO{$pkgname}{'version'};
        my $buildnum = $VINFO{$pkgname}{'release'};
        my @PKGLIST  = split( /\,/, $VINFO{$pkgname}{'pkgs'} );

        my $courierversion = $pkgver;
        $courierversion =~ s/\.\w+$//g;

        print "This is the $pkg $pkgver installer release number $buildnum\n";

        my (%CVER);
        my $up2date = 1;
        foreach my $subpkg (@PKGLIST) {
            my $subpkgstr = '';
            if ( $subpkg ne '0' ) { $subpkgstr = '-' . $subpkg; }

            last if ($force);
            my $cver = `rpm -q --queryformat "\%{name}-\%{version}-\%{release}" ${pkg}${subpkgstr} 2>/dev/null`;
            chomp($cver);
            $CVER{"${pkg}${subpkgstr}"} = $cver;

            if ( $cver ne "${pkg}${subpkgstr}-${pkgver}-${buildnum}" ) {
                print "${pkg}${subpkgstr} is out of date ($cver != ${pkg}${subpkgstr}-${pkgver}-${buildnum})\n";
                $up2date = 0;
            }
        }
        if ($force) { $up2date = 0; }

        if ($up2date) {
            print "${pkg}-${pkgver} is up to date\n";
        }
        else {
            require Cpanel::SysPkgs;
            my $syspkgobj = Cpanel::SysPkgs->new();
            if ( !$syspkgobj ) { die print "Could not create SysPkgs object\n"; }
            my @pkgs = (
                'gamin',       'gamin-devel', 'libtool',    'libtool-libs',  'expect', 'libdb3.3-devel',
                'db4-devel',   'pam-devel',   'openssl',    'openssl-devel', 'gcc',    'gcc-c++',
                'glibc-devel', 'compat-db',   'zlib-devel', 'rpm-build',     'libtool-libltdl-devel'
            );

            $syspkgobj->install( 'pkglist' => \@pkgs );

            system '/scripts/checklibssl';

            print "Resetting $pkg to cPanel Defaults and Installing the Latest Version\n";

            foreach my $subpkg (@PKGLIST) {
                my $subpkgstr = '';
                if ( $subpkg ne '0' ) { $subpkgstr = '-' . $subpkg; }

                if ($src) { last(); }

                if ( $CVER{ $pkg . $subpkgstr } eq "${pkg}${subpkgstr}-${pkgver}-${buildnum}" && !$force ) {
                    next();
                }

                my $file = fetchfile( "http://httpupdate.cpanel.net/courierinstall/${pkg}/${pkgver}-${buildnum}${xdir}/${distro}/${version}/${pkg}${subpkgstr}-${pkgver}-${buildnum}.${arch}.rpm",
                    "/var/spool/cpupdates/${pkg}${subpkgstr}-${pkgver}-${buildnum}.${arch}.rpm" );

                die "File $file is not valid" if ( $file eq '' );

                if ( ( stat($file) )[7] <= 0 ) {
                    print "Failed to download ${pkg}${subpkgstr}-${pkgver}-${buildnum}.${arch}.rpm .. using source instead\n";
                    $latest = 1;
                    $src    = 1;
                    last;
                }

                $ENV{'RPMINSTALL'} = 1;
                Cpanel::RpmUtils::rpmpreinstall($file);
                system 'rpm', '-Uvh', '--nodeps', '--force', $file;
                unlink $file;
                $ENV{'RPMINSTALL'} = 0;
                chdir '/';

                $res = 1;
            }
            if ($src) {
                my (@FILES) = buildcourierrpm( $verbose, $pkgname, $pkgver, $buildnum );
                if ( $#FILES == -1 ) {
                    die "Rpm failed to build!  Please recall courierup with --source --verbose to find out why";
                }

                $ENV{'RPMINSTALL'} = 1;
                foreach my $file (@FILES) {
                    Cpanel::RpmUtils::rpmpreinstall($file);
                }
                system 'rpm', '-Uvh', '--nodeps', '--force', @FILES;
                unlink(@FILES);
                $ENV{'RPMINSTALL'} = 0;
                chdir("/");
            }

            if ( -x "/scripts/post${pkgname}install" ) {
                system "/scripts/post${pkgname}install";
            }

            $res = 1;
        }
    }
    if ( $res || -e '/etc/xinetd.d/cpimap' ) {
        buildconfig();
        rescourier();
    }
    else {
        checksrvd_tcp_check();
    }
}

sub isvalidfile {
    my $file = shift;
    if ( substr( $file, -4, 4 ) eq '.rpm' ) {
        return ( Cpanel::RpmUtils::checkrpm($file) );
    }
    return 1;
}

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

    if ( ( stat($file) )[7] <= 0 || !isvalidfile($file) ) {
        my $res = $httpClient->download( $url, $file );
    }
    return $file;
}

sub find_imapbin {
    my ($self) = @_;
    my @LOC = ( '/usr/lib/courier-imap/bin/imapd', '/usr/local/sbin/imapd', '/usr/local/bin/imapd' );
    foreach my $loc (@LOC) {
        if ( -x $loc ) { return $loc; }
    }
    return;
}

sub find_authdir {
    my ($self) = @_;
    my @LOC = ( '/etc/authlib', '/usr/etc/authlib', '/usr/local/etc/authlib', '/etc/courier-authlib', '/usr/etc/courier-authlib', '/usr/local/etc/courier-authlib', );
    foreach my $loc (@LOC) {
        if ( -e $loc ) { return $loc; }
    }
    return;
}

sub check_migration {

    my %COURIERCONF = %{ Cpanel::DataStore::fetch_ref('/var/cpanel/courierconfig.yaml') };

    if ( $COURIERCONF{'imapd'}{'migrationdone43'} ) {
        return;
    }

    my $courierversion = Cpanel::CourierConfig::get_courier_version_from_binary();
    my ( $cmajor, $cminor, $crelease ) = split( /\./, $courierversion );

    if ( $cmajor > 4 || $cmajor == 4 && $cminor >= 3 ) {
        courier_four_three_migration();
    }
}

sub has_inotify {
    if ( $system !~ /linux/i ) { return; }
    $release =~ s/\-.*//g;
    $release =~ s/[^\d\.]//g;
    my ( $major, $minor, $rev ) = split( /\./, $release, 3 );
    if ( $major == 2 && $minor > 6 ) { return 1; }
    if ( $major == 2 && $minor == 6 && $rev >= 13 ) { return 1; }
    return 0;
}

sub courier_four_three_migration {
    system '/scripts/mailperm', '--skiplocaldomains';

    Cpanel::CourierConfig::set_service_config_value( 'imapd', 'migrationdone43', 1 );

    # Correct invalid setting - to be removed after Courier 4.3 is in Stable for Linux
    Cpanel::CourierConfig::set_service_config_value( 'imapd', '4.3migrationdone', '' );
}

# When we're not rebuilding the config file this will verify it's possible to pass the chkservd TCP check
sub checksrvd_tcp_check {
    my %COURIERCONF = %{ Cpanel::DataStore::fetch_ref('/var/cpanel/courierconfig.yaml') };
    if ( defined $COURIERCONF{'imapd'}{'IMAPDSTART'} && $COURIERCONF{'imapd'}{'IMAPDSTART'} !~ /YES/i ) {
        Cpanel::FileUtils::TouchFile::touchfile('/var/cpanel/imap_tcp_check_disabled') unless ( -e '/var/cpanel/imap_tcp_check_disabled' );
    }
    else {
        unlink '/var/cpanel/imap_tcp_check_disabled' if ( -e '/var/cpanel/imap_tcp_check_disabled' );
    }
}

sub setup_authdaemon_access {
    my $auth_enabled_file = '/var/cpanel/conf/courier/auth_enabled';
    if ( $system =~ /freebsd/i ) {

        # Add mailnull user to courier group
        my $members = ( getgrnam('courier') )[3];
        if ( $members !~ /\bmailnull\b/ ) {
            my $mod_results = Cpanel::SafeRun::Errors::saferunallerrors( 'pw', 'groupmod', 'courier', '-m', 'mailnull' );
            if ($?) {
                print "Failed to add mailnull to courier group:\n";
                print $mod_results . "\n";
                unlink $auth_enabled_file;
                return 0;
            }
        }
    }
    else {

        # /var/spool/authdaemon/ should be owned by daemon:mail
        my $mailgroupid = ( getgrnam('mail') )[2];
        unless ($mailgroupid) {
            print "Could not determine mail group ID.  Exim integration will be disabled\n";
            unlink $auth_enabled_file;
            return 0;
        }

        my ( $uid, $gid ) = ( stat('/var/spool/authdaemon') )[ 4, 5 ];
        unless ( -d _ ) {
            print "Could not find authdaemon spool directory.  Exim integration will be disabled\n";
            unlink $auth_enabled_file;
            return 0;
        }

        if ( $gid != $mailgroupid ) {
            chown( $uid, $mailgroupid, '/var/spool/authdaemon' );
            if ( ( stat('/var/spool/authdaemon') )[5] != $mailgroupid ) {
                print "Failed to chown authdaemon spool directory.  Exim integration will be disabled\n";
                unlink $auth_enabled_file;
                return 0;
            }
        }
    }

    # Succeeded in providing access to socket directory
    if ( -e $auth_enabled_file ) {
        return 1;
    }

    foreach my $dir ( 'conf', 'conf/courier' ) {
        unless ( -d '/var/cpanel/' . $dir ) {
            mkdir '/var/cpanel/' . $dir;
            chmod 0700, '/var/cpanel/' . $dir;
        }
    }
    if ( open my $enable_fh, '>', $auth_enabled_file ) {
        print $enable_fh time() . "\n";
        close $enable_fh;
        return 1;
    }
    else {
        print "Could not create $auth_enabled_file.  Exim integration will be disabled\n";
        return 0;
    }

}